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

Discord.py自定义机器人:ctx.message.mentions判断恒为True问题求助

问题解决:Discord.py Spam命令的@提及检测错误

问题根源

你写的判断条件if ctx.message.mentions != None逻辑错误。因为ctx.message.mentions返回的是用户提及列表,当没有@任何用户时,它是一个空列表[],而不是None。空列表和None不相等,所以这个判断永远为真,导致不管有没有提及都会触发错误提示。另外你提示里提到的是"roles",但原代码只检测了用户提及,没检测角色提及,还要注意@everyone/@here这类全员提及的情况。

修正后的代码

@bot.command()
async def spam(ctx, arg, amount=None):
    # 检测用户提及、角色提及、全员提及(@everyone/@here)
    if ctx.message.mentions or ctx.message.role_mentions or ctx.message.mention_everyone:
        await ctx.channel.send("**Whoops!** Sorry, you can't mention users/roles in spam messages.")
        print(f"{ctx.message.author} attempted to spam with mentions.")
        return
    
    # 处理发送次数,默认5次
    send_amount = 5
    if amount is not None:
        try:
            send_amount = int(amount)
        except ValueError:
            await ctx.channel.send("请输入有效的数字作为发送次数!")
            return
    
    # 执行发送逻辑
    for _ in range(send_amount):
        await ctx.send(arg)

关键说明

  • 直接用if 列表判断:空列表在布尔判断中会被视为False,非空列表则为True,这样就能准确检测是否有提及。
  • ctx.message.role_mentions:专门检测角色提及的列表,和用户提及分开判断。
  • ctx.message.mention_everyone:布尔值,当消息包含@everyone或@here时为True,需要额外检测。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 01:27:23