如何检测频道消息的点赞/点踩等用户反应?现有代码无响应求助
问题:无法检测Telegram频道消息的点赞/点踩反应
使用pyTelegramBotAPI 4.14.1版本时,尝试检测用户对频道消息的「点赞」「点踩」反应,但点击频道的点赞按钮后,代码无任何检测结果,相关代码如下:
# pyTelegramBotAPI Version 4.14.1 import telebot from telebot import apihelper from telebot import types from telebot import util from telebot.types import ChatMemberUpdated from telebot.util import update_types ...... @bot.callback_query_handler(func=lambda call: True) def handle_callback_query(call): print(call) if call.data == "like": print("user likes!!!") ..... # in main function: bot.infinity_polling(allowed_updates=update_types)
问题原因与解决方案
核心原因
频道原生的点赞/点踩按钮不属于内联回调按钮(Inline Keyboard Button),不会触发callback_query类型的更新,因此你用@bot.callback_query_handler根本捕获不到这类操作。
正确实现方式
要检测频道消息的反应,需要监听reaction类型的更新,具体步骤如下:
- 确认Bot权限:确保你的Bot是目标频道的管理员,且开启了「读取消息」权限,否则无法获取反应数据。
- 更新允许的更新类型:默认的
update_types不包含reaction,需要手动添加。 - 使用反应专属处理器:用
@bot.message_reaction_handler()装饰器替代回调查询处理器。
修改后的示例代码:
# pyTelegramBotAPI Version 4.14.1 import telebot from telebot import types from telebot.util import update_types # 替换为你的Bot Token bot = telebot.TeleBot("YOUR_BOT_TOKEN") @bot.message_reaction_handler(func=lambda reaction: True) def handle_reaction(reaction): # 打印完整反应对象,方便调试 print(reaction) # 遍历用户添加的所有反应 for user_reaction in reaction.new_reactions: # 判断反应类型 if user_reaction.emoji == "👍": print(f"用户{reaction.user.id}点赞了消息ID: {reaction.message.message_id}") elif user_reaction.emoji == "👎": print(f"用户{reaction.user.id}点踩了消息ID: {reaction.message.message_id}") if __name__ == "__main__": # 合并原有更新类型与reaction类型 allowed_updates = update_types + ["reaction"] bot.infinity_polling(allowed_updates=allowed_updates)
补充说明
MessageReaction对象包含触发反应的用户信息、目标消息信息,以及具体的反应表情,可根据需求进一步处理。- 如果仍无响应,检查频道的隐私设置,确保Bot能正常读取频道内的消息和反应数据。
内容的提问来源于stack exchange,提问作者Kris Xivior
相关产品推荐
相关产品推荐

