Reputation: 142
So what I want to do is that I want to create an evaluation command in discord.py. So when the user says
.evaluate print("hi")
I want it to to send the code to python and run it. I seen ways with subprocess.Popen
or os.system
or system
generally, but it only runs shell
commands. I was wondering how I do this?
Upvotes: 1
Views: 6042
Reputation: 101
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}')
Upvotes: 0
Reputation: 2540
You can use the 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
None is an invalid command
hi
nocommand(junk) is an invalid command
Discord dialog (using a "?" prefix instead of ".":
Upvotes: 1
Reputation: 122
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. You can even format your code so that you can include: ```py
{your code here}```
around your eval command. Whatever you do, make sure no one has access to your eval command but you. Seriously, they might as well be sitting at your computer if they have access to it.
Upvotes: 1