【问题标题】:How do I accept a string as an argument? (discord.py rewrite)如何接受字符串作为参数? (discord.py 重写)
【发布时间】:2022-05-05 09:29:33
【问题描述】:

我正在尝试创建一个接受字符串作为位置参数的 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)
   

【问题讨论】:

    标签: python discord.py arguments


    【解决方案1】:

    这实际上是阅读命令简介时出现的第一件事,here's the link

    还有一个例子

    @bot.command()
    async def foo(ctx, arg):
        await ctx.send(arg)
    
    # To invoke
    # !foo hello
    # >>> hello
    

    【讨论】:

    • 它返回一个错误。 “SyntaxError:无效语法。”
    【解决方案2】:

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

    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)
    

    【讨论】:

      【解决方案3】:

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

      编辑:更新了问题的答案

      【讨论】:

      • 不是命令行,来自在 Discord 中发送的命令的参数。 (为了清楚起见,更新了问题。)
      • 好吧,据我所知,您想要一个程序,当有人在 discord 上对其进行 ping 操作时,它会执行某些操作,对吧?我假设类似@bot play_music Dancing Queen。您能否进一步详细说明您最初的问题?
      • 我有基本的机器人,我尝试从消息中提取字符串作为变量失败。我会详细说明
      • 我看到了您对问题的更新。这些都不能回答我的问题。
      【解决方案4】:

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

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

      如果你想用空格进行参数,

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

      完成。

      【讨论】:

        【解决方案5】:

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

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-07-18
          • 2014-09-14
          • 2020-10-04
          • 2018-06-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多