如何使discord.py命令能够执行ctx.send命令

时间:2020-10-02 23:16:39

标签: python async-await discord.py

现在,我有一个机器人,希望能够使用Python命令进行控制。这是我的> execute命令的代码,我想用它执行Python代码段。

async def execute(ctx, *, arg):
    if ctx.author.id == 645264167623983124:
        try:
            exec(arg.replace("```", ""))
            await ctx.send(embed=msg(title="Execution complete!", desc="The code ran successfully."))
        except Exception as e:
            await ctx.send(embed=msg(title="Error", desc=str(e)))
    else:
        await ctx.send(embed=msg(title="Nuh Uh Uhh", desc="You are not allowed to use this command!"))

但是,我也想使用此命令来发送测试消息,如下所示:

>execute await ctx.send("Hello world!")

当我运行它时,它说:

Error
'await' outside function (<string>, line 1)

但是当我在没有等待的情况下运行它时,它说运行正常,但是运行该机器人的控制台却说:

<string>:1: RuntimeWarning: coroutine 'Messageable.send' was never awaited
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

1 个答案:

答案 0 :(得分:0)

我使用eval代替异步功能来工作:

arg = arg.replace("```", "")
if arg.startswith("await"):
    await eval(arg.replace("await ", ""))
else:
    exec(arg)