You need to enable JavaScript to run this app. discord.py 如何检测命令提及对象为Bot并返回对应回复
优惠活动
大模型
产品
解决方案
定价
更多

discord.py 如何检测命令提及对象为Bot并返回对应回复

实现命令中被@对象的Bot身份校验逻辑

你使用的discord.py库中,所有discord.Member类实例自带bot布尔属性,该属性会自动通过Discord接口识别目标账号是否为Bot类型(无论是否为当前运行的Bot自身),可直接用于实现你需要的校验逻辑。

需要注意你现有代码存在一个变量覆盖问题:当前代码一开始就把传入的member(Member类实例)直接赋值为mention字符串,后续会丢失对象自带的所有属性,根本无法完成Bot身份判断。

核心调整内容:

  • 调整代码执行顺序:先完成Bot身份校验,再将Member对象转换为mention字符串做后续文案拼接
  • 用内置的member.bot属性替换你预留的判断占位符,校验命中时直接发送对应提示并终止逻辑,不执行后续随机文案分支

修正后的完整可运行代码如下:

@client.command(aliases=['Noob', 'NOOB'])
async def noob(ctx, member: discord.Member):
    # 优先做Bot身份校验,此时member仍为原始Member类实例
    if member.bot:
        await ctx.send('sorry, i will not betray my kind :pensive:')
        # 校验命中直接终止函数,无需执行后续逻辑
        return
    # 校验完成后再转换为mention字符串用于文案拼接
    member = member.mention
    text = [ f'{member} is a certified Noob:tm:',
               f'{member} is a noob!!',
               ctx.author.mention + f' calls {member} a noob, but they use a Uno reverse card',
               ctx.author.mention + f' attemts to call {member} a noob, but fails.',
               f'{member} is the biggest noob there is!!!',
               f'{member} is a noob, but a really cool one tbh :eyes:',
               ctx.author.mention + f' *thinks* {member} is a noob']
    await ctx.send(random.choice(text))

补充说明:这里的member.bot属性为Discord API内置返回字段,无论是@其他第三方Bot、还是@当前运行的Bot自身,判断逻辑都会精准命中,不需要额外添加冗余的身份判断逻辑。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.21 22:36:05