【问题标题】:How to manage the parameters by default in the definitions of the discord commandsdiscord命令定义中默认如何管理参数
【发布时间】:2022-01-18 20:42:48
【问题描述】:

事实上,我想用参数:“async def say(ctx, repeat, *phrase) 重复定义的次数,但实际上我想在命令中只指定句子时,通过默认重复次数为 1 并给出: async def say(ctx, repeat = 1, *phrase) 问题是当输入不和谐的命令时,例如:“!say Hello my name is Leo” 它需要 Hello作为重复参数,我真的不知道我是否清楚????

我想让不和谐在“!say hi how are u?”中理解这一点。重复默认为 1,Hi 对应于参数“sentence”,另一方面,在“!say 5 Hi how are u?”中对应。有 5 对应于重复。不知道有没有可能。。

感谢您的回答!

【问题讨论】:

  • 只需检查try: int(args[0]),如果通过则sentence = " ".join(args[1:])rep = int(args[0]) 否则请检查rep = 1sentence = " ".join(args)

标签: python discord.py


【解决方案1】:

discord.py 支持 OptionalUnion 类型提示来解析参数。

您可以将repetition 参数设置为Optional[int],这样如果用户没有提供整数作为第一个参数discord.py 在解析时不会抛出错误。

from typing import Optional

@bot.command()
async def say(ctx, repetition: Optional[int] = 1, *, phrase):
    for _ in range(repetition):
        await ctx.send(phrase)

我还使用了仅关键字参数 (*),因此它已经将 phrase 参数作为字符串,而不是元组。

参考资料:

【讨论】:

    猜你喜欢
    • 2021-08-12
    • 2016-06-08
    • 2021-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    相关资源
    最近更新 更多