简体   繁体   English

从 Discord.py 执行 Python 命令

[英]Executing Python Command from Discord.py

So what I want to do is that I want to create an evaluation command in discord.py.所以我想做的是我想在 discord.py 中创建一个评估命令。 So when the user says所以当用户说

.evaluate print("hi")

I want it to to send the code to python and run it.我希望它将代码发送到 python 并运行它。 I seen ways with subprocess.Popen or os.system or system generally, but it only runs shell commands.我通常看到subprocess.Popenos.systemsystem的方法,但它只运行shell命令。 I was wondering how I do this?我想知道我是怎么做到的?

You can use the python eval() function.您可以使用 python eval() function。 Of course allowing people to execute commands in your script is a security risk, please proceed with extreme caution.当然,允许人们在您的脚本中执行命令是一种安全风险,请格外小心。 Not sure what you are trying to accomplish, this type of activity should be avoided.不确定您要完成什么,应避免此类活动。

Try:尝试:

@client.command()
async def evaluate(ctx, *, cmd=None):
    try:
        eval(cmd)
        await ctx.send(f'Your bot friend executed your command --> {cmd}')
    except:
        print(f'{cmd} is an invalid command')
        await ctx.send(f'Your bot friend could not execute an invalid command --> {cmd}')

Console Output控制台 Output

None is an invalid command
hi
nocommand(junk) is an invalid command

Discord dialog (using a "?" prefix instead of ".": Discord 对话框(使用“?”前缀而不是“.”:

在此处输入图像描述

import contextlib
import io
@bot.command()
async def eval(ctx, *, code):
    str_obj = io.StringIO() #Retrieves a stream of data
    try:
        with contextlib.redirect_stdout(str_obj):
            exec(code)
    except Exception as e:
        return await ctx.send(f"```{e.__class__.__name__}: {e}```")
    await ctx.send(f'```{str_obj.getvalue()}```')

Keep in mind, the example above is very simple, and can be expanded on.请记住,上面的示例非常简单,并且可以扩展。 For example, exec has a globals argument so that you can use global(pre-defined) variables in your eval statements.例如, exec有一个globals参数,以便您可以在 eval 语句中使用全局(预定义)变量。 You can even format your code so that you can include: ```py你甚至可以格式化你的代码,这样你就可以包括:```py

{your code here}``` {你的代码在这里}```

around your eval command.围绕您的 eval 命令。 Whatever you do, make sure no one has access to your eval command but you .无论您做什么,请确保除了您之外没有人可以访问您的 eval 命令 Seriously, they might as well be sitting at your computer if they have access to it.说真的,如果他们可以访问它,他们还不如坐在你的电脑前。

Here is the command being owner only.这是仅作为所有者的命令。

@client.command()
@commands.is_owner()
async def evaluate(ctx, *, cmd=None):
    try:
        eval(cmd)
        await ctx.send(f'Your bot friend executed your command --> {cmd}')
    except:
        print(f'{cmd} is an invalid command')
        await ctx.send(f'Your bot friend could not execute an invalid command --> {cmd}')

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

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