如何用asyncio.gather运行Pyrogram?消息处理函数失效求助
问题解决:Pyrogram消息处理函数无响应
问题原因
你当前的代码中,app.start()仅完成客户端的初始化启动,执行后就会结束,不会让客户端持续运行以监听消息事件。而@app.on_message装饰的joining函数需要客户端处于持续运行状态,才能捕获到消息并触发执行。
解决方案
需要让客户端保持运行状态来监听消息,Pyrogram提供了app.idle()方法,它会让客户端进入空闲循环,持续处理收到的更新和事件,直到客户端被停止。修改main函数并调整相关逻辑即可解决问题:
修改后的完整代码
from pyrogram import Client, filters import asyncio app = Client("Myapi") async def heart_beat(): while True: await asyncio.sleep(30) await beat_function() async def beat_function(): await app.send_message("@my_bot_test_grou_p", "I am Alive..!") @app.on_message(filters.chat(-1001798384649)) async def joining(client, message): print("triggering") if message.entities: for entity in message.entities: if entity.type == "URL": if entity.url: try: await app.join_chat(entity.url) except Exception as e: print(f"加入聊天失败: {e}") else: chat_link = message.text[entity.offset : entity.offset + entity.length] try: await app.join_chat(chat_link) except Exception as e: print(f"加入聊天失败: {e}") async def main(): await app.start() try: await asyncio.gather(heart_beat(), app.idle()) finally: await app.stop() asyncio.run(main())
关键改动说明
- 先执行
await app.start()完成客户端初始化,这是一次性启动操作 - 在
asyncio.gather中加入app.idle(),让客户端保持运行状态以监听消息事件 - 添加
try...finally块,确保程序退出时能正常调用app.stop()清理客户端资源 - 优化异常处理:捕获具体异常并打印错误信息,方便排查问题;修正URL类型判断方式,避免属性访问错误
内容的提问来源于stack exchange,提问作者Sanmay
相关产品推荐
相关产品推荐

