【发布时间】:2018-12-11 10:44:50
【问题描述】:
我想使用库 python-telegram-bot 和 discord.py(版本 1.0.0)制作一个在 discord 和 telegram 之间进行通信的机器人。然而问题是 discord.py 使用异步函数和 python-telegram-bot 线程。使用下面的代码,在不和谐中发布的消息一切正常(机器人将它们正确地发送到电报),但是反过来不起作用(机器人从电报中获取消息并将其发送到不和谐)。我以前在尝试在同步函数中运行不和谐channel.send 函数时遇到语法/运行时错误问题(因此要么只返回一个生成器对象,要么抱怨我不能在同步函数中使用await)。然而,与此同时,python-telegram-bot 的MessageHandler 需要一个同步函数,所以当给他一个异步函数时,Python 抱怨说,异步函数从未调用过“await”。
我现在尝试使用 asgiref 库中的 async_to_sync 方法从 MessageHandler 运行我的异步 broadcastMsg,但是代码仍然没有将消息发送到不和谐!它似乎正确调用了该函数,但仅在行 print('I get to here') 之前。没有显示错误,也没有不和谐的消息弹出。我想这与我必须将函数注册为 discord.py 事件循环中的任务这一事实有关,但是注册仅在它发生在 botDiscord.run(TOKENDISCORD) 执行之前才有效,这当然必须在之前发生.
所以把我的问题归结为一个问题:
我如何能够从另一个线程(来自电报MessageHandler)与 discord.py 事件循环进行交互。或者如果这是不可能的:如何在不进入 discord.py 事件循环的情况下使用 discord.py 发送消息?
感谢您的帮助
import asyncio
from asgiref.sync import async_to_sync
from telegram import Message as TMessage
from telegram.ext import (Updater,Filters,MessageHandler)
from discord.ext import commands
import discord
TChannelID = 'someTelegramChannelID'
DChannel = 'someDiscordChannelObject'
#%% define functions / commands
prefix = "?"
botDiscord = commands.Bot(command_prefix=prefix)
discordChannels = {}
async def broadcastMsg(medium,channel,message):
'''
Function to broadcast a message to all linked channels.
'''
if isinstance(message,TMessage):
fromMedium = 'Telegram'
author = message.from_user.username
channel = message.chat.title
content = message.text
elif isinstance(message,discord.Message):
fromMedium = 'Discord'
author = message.author
channel = message.channel.name
content = message.content
# check where message comes from
textToSend = '%s wrote on %s %s:\n%s'%(author,fromMedium,channel,content)
# go through channels and send the message
if 'telegram' in medium:
# transform channel to telegram chatID and send
updaterTelegram.bot.send_message(channel,textToSend)
elif 'discord' in medium:
print('I get to here')
await channel.send(textToSend)
print("I do not get there")
@botDiscord.event
async def on_message(message):
await broadcastMsg('telegram',TChannelID,message)
def on_TMessage(bot,update):
# check if this chat is already known, else save it
# get channels to send to and send message
async_to_sync(broadcastMsg)('discord',DChannel,update.message)
#%% initialize telegram and discord bot and run them
messageHandler = MessageHandler(Filters.text, on_TMessage)
updaterTelegram = Updater(token = TOKENTELEGRAM, request_kwargs={'read_timeout': 10, 'connect_timeout': 10})
updaterTelegram.dispatcher.add_handler(messageHandler)
updaterTelegram.start_polling()
botDiscord.run(TOKENDISCORD)
【问题讨论】:
标签: python-3.x python-asyncio discord.py python-telegram-bot