【问题标题】:How to check if a user has permission to use a command? Discordpy如何检查用户是否有权使用命令?不和谐
【发布时间】:2021-08-04 15:25:25
【问题描述】:

我正在创建自定义帮助命令,但遇到了问题。默认的帮助命令可以以某种方式隐藏调用该命令的用户不可用的命令。我到处寻找,但找不到任何解决方案。我尝试使用 command 对象的 hidden 属性,但它不起作用。最好的解决方案是像Member.can_use(command) 这样的方法,它会返回TrueFalse,但在文档中没有类似的东西。或者至少我找不到它。 帮助将不胜感激。

【问题讨论】:

    标签: discord discord.py


    【解决方案1】:

    使用Command.can_run 方法,例如:

    @bot.command()
    async def can_it_run(ctx, command_name: str):
        command = bot.get_command(command_name)
        can_use = await command.can_run(ctx)
        if can_use:
            await ctx.send(f"You can use {command_name}") 
        else:
            await ctx.send(f"You can't use {command_name}") 
    

    遗憾的是,如果检查引发异常(如 commands.guild_only),则异常不会被抑制,如果您想检查其他人(不是调用者)是否可以使用您必须覆盖的命令 @ 987654325@,一个方便的功能是:

    async def can_run(ctx, command_name: str, member: discord.Member=None) -> bool:
        command = bot.get_command(command_name)
        if command is None: # Command doesn't exist / invalid command name
            return False # Or raise an exception
    
        if member is not None: # If a member is passed overwrite the attribute
            ctx.author = member
    
        try:
            return await command.can_run(ctx)
        except Exception:
            return False
    
    @bot.command()
    async def can_it_run(ctx, command_name: str, member: discord.Member=None):
        resp = await can_run(ctx, command_name, member)
        await ctx.send(resp)
    

    【讨论】:

      【解决方案2】:

      您可以通过执行以下操作来检查用户是否计数某个 id:

      if (message.author.id == "WHoever ID1" || message.author.id == "Whoever ID2"):
         #Do Something
      

      如果您想放入一堆 ID,那么只需执行以下操作:

      bool = false;
      arr = ["ID1", "ID2", "ID3"]
      
      for x in arr:
          if(x == message.author.id):
              bool = true;
      
      if(bool):
        #Do stuff
        bool = false;
      

      这是非常模糊的代码,但应该与此类似

      【讨论】:

      • 我知道我可以绕过它并检查 ID 或角色,但我想自动完成。如果我找不到答案,我可能会做这样的事情。
      猜你喜欢
      • 2018-03-17
      • 2021-06-11
      • 2020-02-09
      • 2021-06-11
      • 2021-12-19
      • 1970-01-01
      • 2013-12-09
      • 2011-12-03
      • 2020-03-14
      相关资源
      最近更新 更多