繁体   English   中英

Discord.py多线输入

[英]Discord.py multi-line input

我正在尝试制作一个接受多行输入的 discord 机器人,以便它可以执行 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

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

b!python a=1;print(a)

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

b!python
a = 1
print(a)

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

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

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

您可以使用仅关键字参数语法discord.py指示您要捕获输入的所有 rest 作为单个参数:

@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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM