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

discord.py机器人:用户添加爱心表情时匹配判断失败求助

问题描述

代码原本可正常匹配其他表情,但爱心表情❤无法通过str(emo.emoji) == '❤'判断为true。调试信息如下:

  • print(type(emo.emoji))返回str
  • print(emo.emoji)显示❤
  • print(emo.emoji == '❤')返回False
  • print(str(emo.emoji) == '\u2764')返回False

原始代码:

@bot.event
async def on_reaction_add(emo, user):
    if str(emo.emoji) == '❤':
        await emo.message.add_reaction(emo)
解决办法

问题出在爱心表情的Unicode编码变体上:你输入的❤是基础编码U+2764,但实际收到的表情可能是带变体选择符U+FE0F的版本(显示为❤️,视觉上和❤几乎无差别,但编码是\u2764\ufe0f),两者字符串不相等。

步骤1:确认实际编码

先添加调试代码,打印表情的原始字符串表示,明确具体编码:

print(repr(emo.emoji))

运行后会输出类似'\u2764'或'\u2764\ufe0f'的结果,确定需要匹配的目标编码。

步骤2:修改判断条件

根据实际编码,调整判断逻辑以兼容两种爱心变体:

@bot.event
async def on_reaction_add(emo, user):
    heart_emojis = ('❤', '❤️', '\u2764', '\u2764\ufe0f')
    if str(emo.emoji) in heart_emojis:
        await emo.message.add_reaction(emo)

也可以直接针对调试出的具体编码做精准匹配,比如如果repr输出是'\u2764\ufe0f',就直接判断str(emo.emoji) == '\u2764\ufe0f'。

内容的提问来源于stack exchange,提问作者林雍智

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 12:42:08