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

Discord.py 权限校验if语句失效,限定ID指令所有用户均可调用无报错

问题根源

你写的权限判断语句存在Python逻辑运算符优先级错误:

if ctx.message.author == m1 or m2:

这段代码实际执行逻辑等价于:

if (ctx.message.author == m1) or (bool(m2)):

只要你填写的m2用户ID存在(你已经确认ID正确,所以m2永远是非空的用户对象,布尔值为True),整个判断就永远返回True,所以所有用户都能调用指令。

修复方案

方案1:直接修正判断语句

把权限判断改为完整的等值校验即可:

if ctx.message.author == m1 or ctx.message.author == m2:

方案2(更稳定的推荐写法)

直接校验用户ID,避免机器人缓存未加载导致get_user返回None的异常情况,代码也更简洁:

@commands.command()
async def dm(self, ctx, member:discord.Member=None, *, message=None):
    # 提前定义允许使用指令的用户ID集合
    allowed_ids = {775277904481353749, 709295989596356609}
    # 权限校验放到最前面,不符合条件直接返回
    if ctx.author.id not in allowed_ids:
        await ctx.send("You can't use this command!")
        return
    if member == None:
      await ctx.send("You have to mention the user that you want to send a message to!")
      return
    if message == None:
      await ctx.send("You have to type the message that you want to send to the mentioned user!")
      return
    await member.send(message)
    await ctx.send(f"Successfully sent your message to **{member.name}#{member.discriminator}**")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 23:36:02