首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使discord.py命令能够执行ctx.send命令

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

Stack Overflow用户
提问于 2020-10-03 07:16:40
回答 1查看 278关注 0票数 0

现在,我有一个机器人,我希望能够通过Python命令来控制它。下面是我的>execute命令的代码,我想用它来执行Python代码片段。

代码语言:javascript
运行
复制
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!"))

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

代码语言:javascript
运行
复制
>execute await ctx.send("Hello world!")

当我运行这段代码时,它会说:

代码语言:javascript
运行
复制
Error
'await' outside function (<string>, line 1)

但当我在没有等待的情况下运行它时,它会说它运行得很好,但运行该机器人的控制台显示如下:

代码语言:javascript
运行
复制
<string>:1: RuntimeWarning: coroutine 'Messageable.send' was never awaited
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-03 11:19:53

对于异步函数,我使用eval实现了这一点:

代码语言:javascript
运行
复制
arg = arg.replace("```", "")
if arg.startswith("await"):
    await eval(arg.replace("await ", ""))
else:
    exec(arg)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64179222

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档