如何在不阻塞主线程的情况下发送Telegram消息?
解决Telegram异步消息发送不阻塞主线程的问题
你当前代码中使用await send_message_async()会直接阻塞main协程,必须等待消息发送完成才会执行后续代码。要实现非阻塞的需求,无需将所有函数转为异步,以下两种简洁方案可以解决问题:
方案1:同步函数封装异步任务(纯同步主程序结构)
通过线程将异步任务隔离到独立执行环境,主线程调用后可立即继续执行后续逻辑,完全不阻塞:
from telegram import Bot import asyncio import threading TOKEN = "blah" CHAT_ID = 1 async def send_message_async(): message = "This is a test update from the bot!" bot = Bot(token=TOKEN) await bot.send_message(chat_id=CHAT_ID, text=message) print("Message sent successfully!") def send_message(): # 启动独立线程运行异步任务,不占用主线程资源 def run_async_loop(): asyncio.run(send_message_async()) threading.Thread(target=run_async_loop, daemon=True).start() def main(): print("Before sending message...") send_message() print("After sending message...") # 此行会立即执行,无需等待消息发送完成 # 主线程可继续执行其他逻辑,示例中用sleep模拟后续操作 import time time.sleep(3) # 确保异步线程有足够时间完成消息发送 if __name__ == "__main__": main()
注:daemon=True设置线程为守护线程,会随主线程退出自动结束,避免程序无意义挂起。
方案2:异步环境下的任务并行(异步主入口,内部非阻塞)
如果主程序可以接受异步入口,可通过asyncio.create_task将消息发送转为并行任务,当前协程不会被阻塞:
from telegram import Bot import asyncio TOKEN = "blah" CHAT_ID = 1 async def send_message_async(): message = "This is a test update from the bot!" bot = Bot(token=TOKEN) await bot.send_message(chat_id=CHAT_ID, text=message) print("Message sent successfully!") async def main(): print("Before sending message...") # 创建并行任务,不阻塞当前协程 task = asyncio.create_task(send_message_async()) print("After sending message...") # 立即执行后续代码 # 若需确保消息发送完成后再结束程序,可添加此行 # await task # 模拟其他异步业务逻辑 await asyncio.sleep(3) if __name__ == "__main__": asyncio.run(main())
内容的提问来源于stack exchange,提问作者Appaji Chintimi
相关产品推荐
相关产品推荐

