【问题标题】:TypeError: Greedy[str] is invalid - Discord.pyTypeError: Greedy[str] 无效 - Discord.py
【发布时间】:2022-10-23 17:27:46
【问题描述】:

我在 Discord.py 中使用了一个内联转换器,它是贪婪的 (It's Documentation, More Demo Code)

从这些演示代码中可以看出,它也可以接受int 之类的类型,但是当我使用str 时,它会引发此错误

TypeError: Greedy[str] is invalid

命令的代码(顺便说一下,这是一个 Cog 命令)

@commands.command()
async def temp(self, ctx:commands.Context, message:commands.Greedy[str]='None', user:discord.Member=None):
    await ctx.send(f'{message = }, {user.mention}')

目前这只是一个临时命令,但 Greedy[str] 根本不起作用,但它适用于 intdiscord.Member 类型值

我也知道这一点(星形参数方式)

async def function_name(self, ctx, *, arg)

我知道它也一样,但只有当我希望它将所有其余参数值作为字符串传递给一个变量时才有效,但我不想要这个,我想在中间传递参数值像这样

temp temporary text @user

因为以后想对很多命令实现这个方法

有没有办法让它工作?

我在 Replit 中使用 Python v3.8.12 和 Discord.py v1.7.3

编辑:我目前正在使用此代码作为替代

@commands.command()
async def temp(self, ctx: commands.Context, *arg):
    user_id = re.findall(r'(?<=<@)[!&]?(\d{17,22})(?=> *$)', arg[-1])
    if len(user_id ) == 0:
      raise TypeError('Command "temp" missing 1 required positional argument: "user"')
    user = ctx.guild.get_member(int(user_id[0]))
    message = ' '.join(arg[:-1])
    await ctx.send(f'{message = }, {user.mention}')

如果您找到了使用贪心转换器的方法,这将很有帮助

【问题讨论】:

    标签: python-3.x discord.py


    【解决方案1】:

    这是一种方法,但我想会有另一种方法来解决这个问题。

    @commands.command()
    async def temp(self,ctx:commands.Context,*message):
      message=list(message)
      user=message[len(message)-1]
      message.pop()
      await ctx.send(message)
      await ctx.send(user)
    

    以这种方式获取用户值后,您可以检查它是否是成员,然后您可以执行进一步的代码。

    【讨论】:

    • 我实际上有一个更好的版本,但我想使用内置功能,我认为使用 Greedy 会让事情变得更容易
    • 我现在已经发布了我的临时代码,但仍然感谢您的回答
    • 好的,问题是commands.Greedy[str] 实际上不支持你正在尝试的等于*args,因为用户给出的每个输入都是字符串,甚至是discord.Member 对象,它也是一个字符串。所以我们不能像你想的那样使用贪心函数。
    猜你喜欢
    • 2020-08-25
    • 1970-01-01
    • 2020-04-09
    • 2018-12-29
    • 2020-02-03
    • 2016-01-01
    • 2011-10-23
    • 2015-09-01
    • 2020-01-11
    相关资源
    最近更新 更多