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

如何让pyTelegramBotAPI仅在/start回复问候,未知消息返回‘我不理解’?

解决Telegram机器人回复逻辑错误的问题

你的问题出在条件判断的逻辑错误,以及缺少未匹配内容的处理分支:

问题根源

代码中elif message.text.lower() == 'hello' or 'hi':这一行逻辑有问题,or 'hi'会被视为布尔值True,所以只要前面的条件都不满足,就会进入这个分支,导致任何未定义的消息都触发“Hello”回复,而不是你期望的“抱歉,我不理解”。

修复步骤

  1. 修正hello/hi的判断条件,确保是对message.text.lower()的两种值判断
  2. 在所有条件分支最后添加else块,处理未匹配的消息

修改后的完整代码

import telebot
import webbrowser
from telebot import types

bot = telebot.TeleBot('my_token')

@bot.message_handler(commands=['start'])
def welcome(message):
    bot.send_message(message.chat.id, f'<em>Hello, {message.from_user.first_name}</em>!', parse_mode='HTML')
    markup = types.ReplyKeyboardMarkup()
    btn1 = types.KeyboardButton('Open website')
    btn2 = types.KeyboardButton('Delete')
    btn3 = types.KeyboardButton('Change')
    markup.add(btn1)
    markup.row(btn2, btn3)
    bot.send_message(message.chat.id, "Choose the option:", reply_markup=markup)

@bot.message_handler()
def answers(message): 
    if message.text == 'Open website':
        bot.send_message(message.chat.id, 'The website is open')
    elif message.text == 'Delete':
        bot.send_message(message.chat.id, 'The message is deleted')
    elif message.text == 'Change':
        bot.send_message(message.chat.id, 'The message is changed')
    elif message.text.lower() == 'id':
        bot.reply_to(message, f'ID: {message.from_user.id}')
    elif message.text == '/site':
        webbrowser.open('https://stackoverflow.com/')
    elif message.text == '/help':
        bot.send_message(message.chat.id, 'How can I help you?')
    elif message.text.lower() == 'bye':
        bot.send_message(message.chat.id, f'<em>Bye, {message.from_user.first_name}</em>!', parse_mode='HTML')
    elif message.text.lower() in ['hello', 'hi']:  # 修正此处的条件判断
        bot.send_message(message.chat.id, f'<em>Hello, {message.from_user.first_name}</em>!', parse_mode='HTML')
    else:  # 添加未匹配内容的处理分支
        bot.send_message(message.chat.id, '抱歉,我不理解')

bot.polling(non_stop=True)

内容的提问来源于stack exchange,提问作者ВЕКТС

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 10:12:43