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

如何用Python TeleBot库检测Telegram频道帖子的表情反应?

解决pyTelegramBotAPI中无法获取消息反应的问题

需求:使用Python的telebot库实现Telegram机器人,识别频道帖子的表情反应并在控制台输出反应类型(如爱心、点赞、点踩)。
问题:尝试通过message.reaction获取反应时触发错误:AttributeError: 'Message' object has no attribute 'reaction'. Did you mean: 'caption'?
原代码示例:

import telebot

bot = telebot.TeleBot('token')


@bot.message_handler(func=lambda message: True)
    def handle_reaction(message):
        print(message.reaction)


bot.polling()

问题原因

  • 普通Message对象本身不包含reaction属性,消息反应属于独立的后续更新事件,并非消息初始创建时的属性。
  • 旧版本的pyTelegramBotAPI可能未实现消息反应相关的API支持。

解决方案

1. 升级pyTelegramBotAPI到最新版本

先确保使用的库是最新版,避免因版本缺失功能:

pip install --upgrade pyTelegramBotAPI

2. 使用专门的消息反应处理器

替换普通的message_handler为message_reaction_handler,正确处理MessageReaction对象:

import telebot

# 替换为你的机器人Token
bot = telebot.TeleBot('YOUR_BOT_TOKEN')

@bot.message_reaction_handler(func=lambda reaction: True)
def handle_message_reaction(reaction):
    # 遍历所有反应类型
    for react in reaction.reaction:
        emoji = react.emoji
        count = react.count
        print(f"反应表情: {emoji}, 参与人数: {count}")
        
        # 根据表情判断反应类型
        if emoji == "❤️":
            print("→ 识别到爱心反应")
        elif emoji == "👍":
            print("→ 识别到点赞反应")
        elif emoji == "👎":
            print("→ 识别到点踩反应")

# 启动机器人时指定接收消息反应更新
bot.polling(allowed_updates=["message_reaction"])

3. 确保机器人权限与配置

  • 将机器人添加到目标频道,并授予至少能读取消息的权限(建议设为频道管理员)。
  • allowed_updates参数用于指定机器人接收的更新类型,添加message_reaction确保能捕获反应事件;也可以用allowed_updates=telebot.util.update_types接收所有更新类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 02:17:53