如何用pyTelegramBotAPI处理Telegram中的非命令消息
Telegram机器人处理非命令消息解决方案
问题说明
当前开发的Telegram机器人可正常响应/start、/help等命令消息,但无法处理hello、fine这类不以/开头的普通消息,需求是让这类普通消息触发固定回复:This is a static message。
用户现有代码
import os import telebot BOT_TOKEN = os.getenv('BOT_TOKEN') bot = telebot.TeleBot(BOT_TOKEN) @bot.message_handler(commands=['start', 'help']) def send_welcome(message): bot.reply_to(message, "Hello. I am a Bot. How are you doing?") @bot.message_handler(func=lambda message: True) def echo_all(message): initial_message = """ This is a static message """ bot.send_message(message.chat.id, initial_message) print("bot is running") bot.infinity_polling()
修改方案
原代码中第二个消息处理器func=lambda message: True会匹配所有未被前序处理器捕获的消息,但为了更精准地只处理非命令消息,可修改匹配逻辑,明确排除以/开头的文本消息:
import os import telebot BOT_TOKEN = os.getenv('BOT_TOKEN') bot = telebot.TeleBot(BOT_TOKEN) @bot.message_handler(commands=['start', 'help']) def send_welcome(message): bot.reply_to(message, "Hello. I am a Bot. How are you doing?") # 修改匹配逻辑,仅处理不以/开头的文本消息 @bot.message_handler(func=lambda message: message.text and not message.text.startswith('/')) def handle_non_command(message): static_reply = "This is a static message" bot.send_message(message.chat.id, static_reply) print("bot is running") bot.infinity_polling()
说明
message.text and判断用于避免无文本内容的消息(如图片、贴纸)触发报错not message.text.startswith('/')确保仅响应不以/开头的普通文本消息- 处理器按注册顺序匹配,命令消息会被第一个处理器优先捕获,非命令消息则进入第二个处理器
内容的提问来源于stack exchange,提问作者Adrian Botteon
相关产品推荐
相关产品推荐

