如何在python-telegram-bot中实现命令并发执行?
问题解决思路及代码修复
先纠正代码里的明显错误
- 你重复定义了
start函数,后面的空实现会覆盖前面的正常逻辑,直接删掉第二个空的start函数。 register函数只在handler里调用了,但没实现,先补上函数定义。
核心问题:为什么设置了block=False还是串行?
block=False只是让handler不会阻塞Dispatcher的线程,但如果你的register函数里有同步阻塞操作(比如用requests.get发同步请求、time.sleep()这类),会直接卡住整个事件循环,导致其他命令(比如complete)必须等它跑完才能执行。
解决方法
把所有同步阻塞的操作换成异步非阻塞的:
- 把
requests换成异步HTTP库aiohttp,用异步请求替代同步请求。 - 如果有
time.sleep(),换成asyncio.sleep()。 - 确保所有耗时操作都不阻塞事件循环。
修改后的示例代码
import logging import asyncio import aiohttp # 换成异步HTTP库 from telegram import Update from telegram.ext import ApplicationBuilder, CallbackContext, CommandHandler logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO ) async def start(update: Update, context: CallbackContext): await context.bot.send_message(chat_id=update.effective_chat.id, text="I'm a bot, please talk to me!") # 实现register函数,用异步操作 async def register(update: Update, context: CallbackContext): # 示例:异步HTTP请求,替代requests.get async with aiohttp.ClientSession() as session: async with session.get('https://example.com') as resp: await resp.text() await context.bot.send_message(chat_id=update.effective_chat.id, text="Register done!") async def complete(update: Update, context: CallbackContext): await context.bot.send_message(chat_id=update.effective_chat.id, text="Complete executed immediately!") if __name__ == '__main__': application = ApplicationBuilder().token('你的BotToken').build() start_handler = CommandHandler('start', start, block=False) application.add_handler(start_handler) register_handler = CommandHandler('register', register, block=False) application.add_handler(register_handler) complete_handler = CommandHandler('complete', complete, block=False) application.add_handler(complete_handler) application.run_polling()
验证逻辑
运行修改后的代码,执行/register hello后立刻发/complete bye,complete的消息会马上发送,不用等register里的异步操作完成。
内容的提问来源于stack exchange,提问作者minhkhoa0502
相关产品推荐
相关产品推荐

