如何将Pyrogram Client作为事件监听器运行并解决handler未触发问题
解决Pyrogram MessageHandler不触发的问题
你的推测完全正确,问题就出在while True循环里的time.sleep(1)——这是同步阻塞函数,会把整个异步事件循环卡死,导致Pyrogram根本没机会处理消息事件。下面是几种正确的实现方式:
方法1:用异步睡眠替代同步睡眠
直接把time.sleep(1)换成异步的asyncio.sleep(1),这样不会阻塞事件循环,Pyrogram的消息处理器就能正常工作了:
import asyncio from pyrogram import Client, filters from pyrogram.handlers import MessageHandler async def handle(client, message): await message.reply("收到消息啦") async def run_tele(): app.add_handler(MessageHandler(handle, filters=filters.text)) await app.start() while True: # 这里写你的逻辑 print("后台任务运行中...") await asyncio.sleep(1) # 关键:用异步睡眠替代同步睡眠 await app.stop() if __name__ == '__main__': app = Client("my_account") # 假设你已完成Client初始化 app.run(run_tele())
方法2:把耗时同步任务放到线程池
如果你的# do something here是耗时的同步代码(比如CPU密集型操作),不能直接用异步睡眠,就把同步任务丢到线程池里执行,避免阻塞事件循环:
import asyncio import time from pyrogram import Client, filters from pyrogram.handlers import MessageHandler def sync_task(): # 这里写你的同步耗时逻辑 print("执行同步任务...") time.sleep(1) async def handle(client, message): await message.reply("收到消息啦") async def run_tele(): app.add_handler(MessageHandler(handle, filters=filters.text)) await app.start() while True: # 把同步任务放到线程池执行(Python3.9+可用) await asyncio.to_thread(sync_task) # 兼容更低版本可替换为:await app.loop.run_in_executor(None, sync_task) await app.stop() if __name__ == '__main__': app = Client("my_account") app.run(run_tele())
方法3:用后台任务并行运行
如果你的后台逻辑不需要和主循环绑定,还可以把它做成独立的异步任务,让Pyrogram的事件循环单独运行,更贴合框架设计习惯:
import asyncio from pyrogram import Client, filters from pyrogram.handlers import MessageHandler async def background_task(): while True: print("后台任务运行中...") await asyncio.sleep(1) async def handle(client, message): await message.reply("收到消息啦") async def run_tele(): app.add_handler(MessageHandler(handle, filters=filters.text)) # 创建后台并行任务 asyncio.create_task(background_task()) # 让Pyrogram持续运行直到主动停止(比如Ctrl+C) await app.run_until_disconnected() if __name__ == '__main__': app = Client("my_account") app.run(run_tele())
内容的提问来源于stack exchange,提问作者Khalil
相关产品推荐
相关产品推荐

