我的程序应该以用户定义的文本回复用户帐户收到的电报消息。可以通过向电报机器人发送消息来更改此文本。对于该机器人,我一直在使用PyTelegramBotAPI,对于从用户帐户发送消息,我一直在使用Telethon。我可以通过调用bot.polling()
来运行机器人,并且效果很好。Telethon Client也可以单独工作,它具有如下方法:
async def run():
self.add_event_handler(self.message_handler, events.NewMessage)
while True:
#(Every Second the while is supposed to be checked)
if(condition):
do_something()
async def message_handler(self, event):
do_another_thing()
并开始运行客户端,我只是:
loop = asyncio.get_event_loop()
loop.run_until_complete(client.run())
但是我不能让它们同时运行。
我尝试过:
asyncio.get_event_loop().run_until_complete(asyncio.gather(
bot.bot.polling(none_stop=True, interval=0.1, timeout=15),
client.run()
))
同时运行它们,但这仅运行机器人。
我也尝试过:
executor = ProcessPoolExecutor(2)
loop = asyncio.get_event_loop()
boo = asyncio.create_task(loop.run_in_executor(executor, bot.bot.polling(none_stop=True, interval=0.5, timeout=15)))
baa = asyncio.create_task(loop.run_in_executor(executor, client.run()))
但是它也不起作用。
您能告诉我如何同时运行机器人和客户端吗?
您应该将此代码放在脚本的末尾。
loop = asyncio.get_event_loop()
loop.create_task(function1())
loop.create_task(function2())
loop.run_forever()