如何从另一个脚本中调用Discord机器人的函数。Python

huangapple go评论53阅读模式
英文:

How to call a discord bot`s function from another script. Python

问题

I can help you with the translation. Here's the translated content:

我正在尝试创建一个Python脚本该脚本从Telegram频道获取消息并将其发送到Discord服务器的频道我在处理Discord部分时遇到了问题绝对不知道如何让它工作

我已经有了这个主要的脚本

# -*- coding: utf-8 -*-

from telethon.sync import TelegramClient
import config
import validators
from multiprocessing import Pipe
from discord_signal import send_message
import asyncio

api_id = config.API_ID
api_hash = config.API_HASH
phone_number = config.PHONE_NUMBER

BASE_URL = 'https://discord.com/api/v10'
CHANNEL_URL = BASE_URL + '/channels/{channel_id}';

class TelegramWorker:
    def __init__(self):
        self.client = TelegramClient('your_account', api_id, api_hash)
        self.client.connect()
        self.client.start()
        self.dp = self.client.get_entity(config.CHANNEL_T)

    def get_messages(self):
        messages = self.client.get_messages(self.dp, limit=1000000000000)
        a = []
        for item in messages:
            item = item.text
            if item:
                if validators.url(item):
                    a.append(item)
        return a

def main():
    tel = TelegramWorker()
    a = tel.get_messages()
    print(a)

    for item in a:
        send_message(item)

if __name__ == '__main__':
    main()

当我运行这个脚本时Python会导入第二个脚本该脚本使用"discord.py"库运行机器人运行后什么都不会发生

这是第二个脚本

import discord
from discord.ext import commands
import config
import datetime

intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents)

@bot.event
async def on_ready():
    now_time = datetime.datetime.now()
    print(f'机器人已启动。时间:{now_time}')

async def send_message(msg):
    channel = bot.get_channel(id=config.DISCORD_CHANNEL_ID)
    await channel.send(msg)

bot.run(config.DISCORD_TOKEN)
有人可以帮助我吗

I've provided the translated content from your code, excluding the parts that you requested not to translate. If you have any further questions or need assistance with your code, please feel free to ask.

英文:

I am trying to make a python script, that takes messages from a telegram channel and send them to the discord server`s channel. I am stuck with discord. Absolutely cant have an idea how to make it works.

I already have this main scripts:

# -*- coding: utf-8 -*-
from telethon.sync import TelegramClient
import config
import validators
from multiprocessing import Pipe
from discord_signal import send_message
import asyncio
api_id = config.API_ID
api_hash = config.API_HASH
phone_number = config.PHONE_NUMBER
BASE_URL = 'https://discord.com/api/v10'
CHANNEL_URL = BASE_URL + '/channels/{channel_id}'
class TelegramWorker:
def __init__(self):
self.client = TelegramClient('your_account', api_id, api_hash)
self.client.connect()
self.client.start()
self.dp = self.client.get_entity(config.CHANNEL_T)
def get_messages(self):
messages = self.client.get_messages(self.dp, limit=1000000000000)
a = []
for item in messages:
item = item.text
if item:
if validators.url(item):
a.append(item)
return a
def main():
tel = TelegramWorker()
a = tel.get_messages()
print(a)
for item in a:
send_message(item)
if __name__ == '__main__':
main()

When I run this, python import second script, that run bot with library "discord.py". After it run it, nothing happens.

Here is the second script:

import discord
from discord.ext import commands
import config
import datetime
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
now_time = datetime.datetime.now()
print(f'BOT STARTED. TIME: {now_time}')
async def send_message(msg):
channel = bot.get_channel(id=config.DISCORD_CHANNEL_ID)
await channel.send(msg)
bot.run(config.DISCORD_TOKEN)

Can anyone help me?

答案1

得分: 1

请注意,当你导入send_message时,编译器会在bot.run(config.DISCORD_TOKEN)这一行陷入循环,因为这个函数会启动一个无限循环来运行你的 Discord 机器人。换句话说,你的 Telegram 机器人将永远不会启动。

你可以尝试在一个线程中运行你的 Discord 机器人,或者在on_ready事件中插入加载 Telegram 消息的函数。

然而,如果你只是想在 Discord 频道中发送一条消息,你不需要一个机器人。只需为该频道创建一个 Webhook 并复制链接。要将消息发布到 Webhook,你可以使用requestsdiscord.py提供的SyncWebhook

from discord import SyncWebhook

WEBHOOK_URL = ""

def main():
    webhook = SyncWebhook.from_url(WEBHOOK_URL)
    tel = TelegramWorker()
    a = tel.get_messages()
    print(a)

    for item in a:
        webhook.send(a)

这个问题中详细了解如何向 Discord Webhook 发送消息的更多细节。

英文:

Note that when you import send_message, the compiler will get stuck on the bot.run(config.DISCORD_TOKEN) line, as this function starts an infinite loop to run your discord bot. That is, your telegram bot will never start.

You can try running your discord bot in a Thread or insert your function that loads telegram messages in the on_ready event.

However, if you simply want to send a message in a discord channel, you don't need a bot. Just create a Webhook for the channel and copy the link. To post a message to the webhook you can use requests or the SyncWebook provided by discord.py:

from discord import SyncWebhook


WEBHOOK_URL = ""


def main():
    webhook = SyncWebhook.from_url(WEBHOOK_URL)
    tel = TelegramWorker()
    a = tel.get_messages()
    print(a)

    for item in a:
        webhook.send(a)

> Read more details on how to send a message to a discord webhook in this question.

huangapple
  • 本文由 发表于 2023年4月20日 03:10:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76058058.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定