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

Discord.py树命令无法检测用户提及自身的问题求助

问题解决方案:Discord.py树命令判断用户提及自己失效

问题出在你用is运算符比较user和interaction.user——这两个变量对应的是Discord API返回的不同对象实例(即使用户是同一个人),is比较的是对象的内存引用,而非用户本身,所以判断会不生效。

正确的做法是比较用户的唯一ID,因为每个Discord用户的ID是独一无二的,不会因为对象实例不同而出现判断错误。

修改后的关键代码行:

if user.id == interaction.user.id:  # 替换原有的is判断
    await interaction.response.send_message(f"**{interaction.user.mention}**, you are going to bite yourself? Really? -.-")
    return

完整的修改后函数代码:

@bot.tree.command(name="bite", description="Bites a user, yum!")
@app_commands.describe(user = "User")
async def bite(interaction: discord.Interaction, user: discord.Member = None):
   if user is None:
       await interaction.response.send_message(f"**{interaction.user.mention}**, you should specify a user!")
       return
   if user.id == interaction.user.id:  # 此处已修正
       await interaction.response.send_message(f"**{interaction.user.mention}**, you are going to bite yourself? Really? -.-")
       return
   if bot.user == user:
       cembed = discord.Embed(color=0xfacaf5)
       cembed.set_image(url=bgrandomchoice['bite'])
       cembed.add_field(name=f"🍡 Ow! That hurts! ( `ハ ´)", value="")
       await interaction.response.send_message(embed=cembed)
       return
   # 针对其他用户的最终代码段
   embed = discord.Embed(color=0xfacaf5)
   embed.set_image(url=bgrandomchoice['bite'])
   embed.add_field(name=f"🍡 **{interaction.user.name}** has bitten **{user.display_name}**! o.o", value="")
   await interaction.response.send_message(embed=embed)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 00:52:55