如何让Telegram机器人识别并处理单独发送的动态表情?
问题
我是一个拥有约800名成员的Telegram公群管理员,近期遇到用户发送篮球、足球、老虎机等动态表情刷屏的问题。我用Python的Telebot库写了一个机器人自动删除这类消息,但单独发送的动态表情(比如🎲)无法被处理。
当前代码如下:
import telebot from telebot import types print('Starting the bot...') # Getting the bot token bot = telebot.TeleBot('edited') print('Getting the bot API token...') print('Bot started succefully!') @bot.message_handler(commands=['ping']) def test_message(message): bot.send_message(message.chat.id, 'pong') @bot.message_handler(content_types=['text', 'sticker']) def handle_text(message): print("Received message:", message.text) if '🎲' in message.text: print('Banned emoji in message: deleting message') bot.delete_message(message.chat.id, message.message_id) bot.polling()
最初用content_types=['text']时,单独发送的动态表情无法被识别;添加sticker后问题依旧,普通静态表情单独发送能被正常捕获。请问怎么让机器人处理这些单独发送的动态表情?
解决方案
这类动态表情属于Telegram的动画表情(Animated Emoji)或骰子类表情,它们既不属于普通文本,也不属于贴纸(Sticker),而是对应animation或dice类型的消息。你需要调整代码以覆盖这些类型:
- 扩展消息类型范围:在
content_types中加入animation和dice,确保能捕获到目标消息 - 针对不同类型做表情判断:
- 文本消息:直接检查
message.text中的表情 - 动画表情:通过
message.animation.emoji获取对应表情符号 - 骰子类表情:通过
message.dice.emoji获取对应表情符号
- 文本消息:直接检查
修改后的完整代码:
import telebot from telebot import types print('Starting the bot...') # 替换为你的机器人token bot = telebot.TeleBot('your_bot_token_here') print('Bot started successfully!') @bot.message_handler(commands=['ping']) def test_message(message): bot.send_message(message.chat.id, 'pong') # 覆盖需要处理的消息类型 @bot.message_handler(content_types=['text', 'sticker', 'animation', 'dice']) def handle_banned_emojis(message): # 定义需要拦截的表情列表 banned_emojis = ['🎲', '🏀', '⚽'] # 处理文本消息 if message.content_type == 'text': if any(emoji in message.text for emoji in banned_emojis): bot.delete_message(message.chat.id, message.message_id) print(f"Deleted text message with banned emoji: {message.text}") # 处理动画表情 elif message.content_type == 'animation': emoji = message.animation.emoji if emoji in banned_emojis: bot.delete_message(message.chat.id, message.message_id) print(f"Deleted animated emoji: {emoji}") # 处理骰子类动态表情 elif message.content_type == 'dice': emoji = message.dice.emoji if emoji in banned_emojis: bot.delete_message(message.chat.id, message.message_id) print(f"Deleted dice emoji: {emoji}") bot.polling()
- 额外注意事项:
- 确保机器人在群聊中拥有删除消息的权限(在群聊设置中开启对应权限)
- 可根据需要扩展
banned_emojis列表,加入其他需要拦截的动态表情 - 部分特殊动态表情可能仅属于其中一种类型,覆盖
animation和dice可解决绝大多数场景
内容的提问来源于stack exchange,提问作者wxnzks
相关产品推荐
相关产品推荐

