You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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()

说明

  1. message.text and判断用于避免无文本内容的消息(如图片、贴纸)触发报错
  2. not message.text.startswith('/')确保仅响应不以/开头的普通文本消息
  3. 处理器按注册顺序匹配,命令消息会被第一个处理器优先捕获,非命令消息则进入第二个处理器

内容的提问来源于stack exchange,提问作者Adrian Botteon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 16:52:42