如何让Python-Telegram-Bot同时处理命令及附带消息内容?
处理Telegram机器人带参数的命令(Python-Telegram-Bot)
方案一:使用CommandHandler(官方推荐,更易用)
CommandHandler是Python-Telegram-Bot中处理标准Telegram命令的常用组件,它会自动提取命令后的参数并通过context.args传递给处理函数。如果参数包含空格,只需将参数列表拼接成字符串即可。
示例代码:
from telegram import Update from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes async def handle_add(update: Update, context: ContextTypes.DEFAULT_TYPE): # 检查是否提供了参数 if not context.args: await update.message.reply_text("请输入要添加的内容,格式:/add [内容]") return # 将参数列表拼接为完整的内容字符串 content = ' '.join(context.args) await update.message.reply_text(f"已收到添加请求:{content}") def main(): # 替换为你的机器人Token app = ApplicationBuilder().token("YOUR_BOT_TOKEN").build() # 注册/add命令的处理器 app.add_handler(CommandHandler("add", handle_add)) app.run_polling() if __name__ == '__main__': main()
当用户输入/add Hello World时,context.args会得到["Hello", "World"],通过' '.join()就能还原成完整的Hello World。
方案二:使用StringCommandHandler
StringCommandHandler用于匹配以指定字符串开头的消息,适合需要自定义命令前缀的场景。你可以通过截取消息文本获取命令后的参数:
示例代码:
from telegram import Update from telegram.ext import ApplicationBuilder, StringCommandHandler, ContextTypes async def handle_add(update: Update, context: ContextTypes.DEFAULT_TYPE): full_text = update.message.text # 去掉命令前缀"/add ",注意末尾的空格 content = full_text[len("/add "):] if not content: await update.message.reply_text("请输入要添加的内容,格式:/add [内容]") return await update.message.reply_text(f"已收到添加请求:{content}") def main(): app = ApplicationBuilder().token("YOUR_BOT_TOKEN").build() # 注册以"/add"开头的消息处理器 app.add_handler(StringCommandHandler("/add", handle_add)) app.run_polling() if __name__ == '__main__': main()
这里StringCommandHandler("/add", ...)会匹配所有以/add开头的消息,包括/addHello(无空格),如果只想匹配带空格的命令,可以把前缀设为"/add "(带空格)。
注意事项
- 如果需要处理带空格的参数,两种方案都能满足需求,优先推荐
CommandHandler,因为它更符合Telegram命令的规范,参数提取更简洁。 - 记得替换代码中的
YOUR_BOT_TOKEN为你从BotFather获取的机器人令牌。
内容的提问来源于stack exchange,提问作者Hoang D Nam
相关产品推荐
相关产品推荐

