【问题标题】:Discord.py multi-line inputDiscord.py 多行输入
【发布时间】:2020-10-11 20:29:35
【问题描述】:

我正在尝试制作一个接受多行输入的不和谐机器人,以便它可以执行 python 代码。我的代码如下:

@bot.command(name="python", help="executes python script")
async def python(ctx, *args):
    try:
        with Capturing() as output: #Capture output
            exec(" ".join(args).replace('"', "'"))
        # send captured output to thread
    except Exception as e:
        await ctx.send("```\n{}\n```".format(e)) # Send error message

问题是这个函数只能接受一行输入,比如:

b!python a=1;print(a)

但是,我想让 discord.py 机器人接受这种类型的消息: 完整消息的示例如下:

b!python
a = 1
print(a)

我想接受多行输入并将其分配给我的代码中的变量并执行它:

code = """a = 1
print(a)
"""
exec(message)

我见过一些机器人执行类似的 python 代码,但我不知道如何在不使用 *args 的情况下执行它,在这种情况下它只接受一行代码。有没有办法接受多行输入?

【问题讨论】:

  • 您希望机器人如何知道输入结束的位置?
  • 当消息结束时,我猜。

标签: python discord.py


【解决方案1】:

您可以使用keyword-only argument syntaxdiscord.py 表明您希望将所有其余输入捕获为单个参数:

@bot.command(name="python", help="executes python script")
async def python(ctx, *, arg):
    try:
        exec(arg)
    except Exception as e:
        await ctx.send("```\n{}\n```".format(e)) # Send error message

【讨论】:

    猜你喜欢
    • 2021-05-14
    • 2023-01-13
    • 2020-11-01
    • 1970-01-01
    • 2021-04-09
    • 1970-01-01
    • 2021-09-03
    • 2018-04-14
    • 1970-01-01
    相关资源
    最近更新 更多