【问题标题】:Get user id from mention in discord.py从 discord.py 中的提及中获取用户 ID
【发布时间】:2021-09-12 06:17:36
【问题描述】:

当我尝试使用以下代码运行命令$getUserId @user 时,它按预期工作,但在尝试传递参数时发送$getUserId 123 之类的内容时会出错。 我想要一个不会出错的机器人。

import discord

client = commands.Bot(command_prefix = "$")

@client.command()
async def getUserId(ctx, *user: discord.User):
if not arg:
    userId = ctx.author.id
else:
    userId = arg.id
await ctx.send(userId)

如果给出$getUserId 命令,我将如何处理:将提到的用户作为参数并处理所有异常?

有没有更简单的方法从提及中获取用户 ID?必须有一个简单的方法来做到这一点,对吧? 无论如何,非常感谢所有帮助。

【问题讨论】:

    标签: python discord discord.py


    【解决方案1】:

    如果是问题或代码中的错误,但您的缩进被弄乱了,并且 arg 不存在,请确认

    
    def convert_mention_to_id(mention):
        return int(mention[1:][:len(mention)-2].replace("@","").replace("!",""))
    
    @client.command(name="getUserId")
    async def getUserId(ctx ,*arg):
        if not arg:
            await ctx.send(ctx.author.id)
        else:
            try:
                await ctx.send({i:convert_mention_to_id(arg[i]) for i in arg})
            except ValueError:
                await ctx.send("Invalid ID")
    
    

    convert_mention_to_id 是一个实用函数,提及以<@!id> 格式传递,该函数只是从中获取 id。

    ID 在 Discord API 中用作 int,因此在传递无效 id 时会在引发值错误的函数中进行转换

    您可以使用client.get_user() 获取提到的用户,但它需要成员意图是真实的

    【讨论】:

      【解决方案2】:

      您的代码有一些问题。

      1. 使用 arg:您没有在您提供的代码中的任何地方定义 arg。而是将 arg 替换为 user。
      2. 如果不是用户:如果您将用户留空,则会引发错误,例如“用户是缺少的必需参数”。解决此问题的一种方法是将其默认为 None

      您可以在下面的代码以及测试示例中查看上述观察结果。

      @client.command()
      async def getUserId(ctx, user: discord.User=None): # defaults user to None if nothing is passed
          if not user: # you are not using an arg variable, you're using user
              userId = ctx.author.id
          else:
              userId = user.id # same as previous
          await ctx.send(userId)
      

      【讨论】:

        猜你喜欢
        • 2019-04-01
        • 2023-04-04
        • 2020-09-07
        • 1970-01-01
        • 2021-07-18
        • 2021-05-07
        • 1970-01-01
        • 1970-01-01
        • 2021-09-06
        相关资源
        最近更新 更多