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

Telegram匿名消息机器人异常:开发者无法回复用户问题

Telegram匿名消息机器人回复异常问题修复

问题现象

开发的Telegram匿名消息机器人,预期支持用户向开发者发送问题、开发者回复用户,但实际运行时:

  • 用户可正常给开发者发消息
  • 开发者尝试回复用户时,机器人不发送回复,反而提示“No you can't send a message to yourself”

问题原因

  1. 处理器匹配顺序错误:TeleBot的消息处理器按代码顺序匹配,ask_developer的func=lambda message: True会匹配所有消息,包括开发者的回复消息。开发者发消息时先被该处理器捕获,触发错误提示,后续的answer_question处理器无法执行。
  2. 回复逻辑层级错误:原代码中message.reply_to_message.reply_to_message.chat.id调用不成立——开发者收到的是机器人转发的消息,这条转发消息的reply_to_message为空,无法通过它获取用户Chat ID。

修复后的代码

import telebot

# 替换为你的机器人Token和开发者Chat ID
bot = telebot.TeleBot('YOUR_BOT_TOKEN')
developer_chat_id = 'YOUR_DEVELOPER_CHAT_ID'
bot_id = bot.get_me().id  # 获取机器人自身ID

@bot.message_handler(commands=['start'])
def start(message):
    bot.send_message(message.chat.id, '欢迎使用匿名消息机器人,直接发送消息即可给开发者提问!')

# 优先处理开发者的回复消息
@bot.message_handler(func=lambda message: 
    str(message.chat.id) == developer_chat_id 
    and message.reply_to_message is not None 
    and message.reply_to_message.from_user.id == bot_id,
    content_types=['text']
)
def answer_question(message):
    # 从转发消息中提取用户ID并发送回复
    try:
        user_chat_id = message.reply_to_message.text.split('\n')[0].split(': ')[1]
        bot.send_message(user_chat_id, f'开发者回复:{message.text}')
        bot.send_message(developer_chat_id, '回复已发送给用户')
    except IndexError:
        bot.send_message(developer_chat_id, '无法识别用户ID,请确保回复的是机器人转发的用户消息')

# 处理用户发送给开发者的消息
@bot.message_handler(func=lambda message: str(message.chat.id) != developer_chat_id)
def ask_developer(message):
    # 转发消息时附带用户ID,方便后续回复
    bot.send_message(
        developer_chat_id,
        f'User ID: {message.chat.id}\nMessage: {message.text}',
        parse_mode='plaintext'
    )

bot.polling(none_stop=True)

关键修复点

  • 调整处理器顺序:将处理开发者回复的answer_question放在ask_developer前面,确保开发者的回复消息先被正确匹配。
  • 明确附带用户ID:转发用户消息时主动带上用户Chat ID,避免依赖不存在的消息层级。
  • 过滤开发者消息:ask_developer仅处理非开发者发送的消息,避免开发者自身消息触发错误提示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 06:55:27