我如何接受一个字符串作为参数? (discord.py重写)

How do I accept a string as an argument? (discord.py rewrite)

我正在尝试创建一个接受字符串作为位置参数的 discord.py 命令。

如何接受来自 Discord 消息的字符串(以及扩展的布尔值和整数)作为参数?

示例代码

# -- snip --

@bot.command()
async def echo(ctx):
  """
  Example command to return the input of this command.
  """
  # argument name should be called `arg`

  await ctx.respond(arg)
   

您是否查看过有关从 discord 机器人获取消息的其他问题?

编辑:更新了问题的答案

字面意思是看命令介绍首先出现的东西,here's the link

这里还有一个例子

@bot.command()
async def foo(ctx, arg):
    await ctx.send(arg)

# To invoke
# !foo hello
# >>> hello

如果你想传递一个位置参数,你可以这样做:

async def test(ctx, arg):
    await ctx.send(arg)

然后用户可以在调用命令时提供参数: $test foo,其输出为 foo 当你想传递一个中间有空格的参数时,你可以只引用参数:$test "foo bar",它有输出 foo bar 或修改你的命令来处理不确定数量的参数:

@bot.command()
async def test(ctx, *args)

要使用整数和布尔值,您可以使用一些 python 小技巧来实现。要转换其中只有整数的字符串,您只需使用 int() 将字符串转换为整数 - 如果应将字符串转换为布尔值,您可以使用如下比较:

s = "Foo"
#<User puts in a value for s>#
s == "Foo" #Returns a boolean value (True if the string matches, False if it does not)

很简单 如果你想接受一个没有空格的参数,

@bot.command()
async def combinestring(ctx, arg: str):
    #your code

如果要带空格的参数,

@bot.command()
async def combinestring(ctx, *, arg):
    #your code

完成。

例如提醒命令。为此,您可以执行以下操作:

@client.command()
async def reminder(ctx, time: int, *, message: str):

时间为整数,消息为字符串。