@
@
@pyshvel2021-09-30 17:47:04
Python
@pyshvel, 2021-09-30 17:47:04

How to execute an argument from a command as code?

For example, I type !command await ctx.send('Hello!')
and the bot will do that and send Hello!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
H
Hawchik_dev, 2021-09-30
_

I suggest you make an eval.
the code:

import ast
def insert_returns(body):
  if isinstance(body[-1], ast.Expr):
    body[-1] = ast.Return(body[-1].value)
    ast.fix_missing_locations(body[-1])
    if isinstance(body[-1], ast.If):
      insert_returns(body[-1].body)
      insert_returns(body[-1].orelse)
    if isinstance(body[-1], ast.With):
      insert_returns(body[-1].body)


@bot.command(aliases = ["eval", "exec"])
async def e(ctx, *, cmd):
    if ctx.author.id == 643017747273351179:
      try:
        fn_name = "_eval_expr"
        cmd = cmd.strip("` ")
        cmd = "\n".join(f" {i}" for i in cmd.splitlines())
        body = f"async def {fn_name}():\n{cmd}"
        parsed = ast.parse(body)
        body = parsed.body[0].body
        insert_returns(body)
        env = { "bot": bot, 'discord': discord, 'commands': commands, 'ctx': ctx, '__import__': __import__ }
        exec(compile(parsed, filename="<ast>", mode="exec"), env)
        result = (await eval(f"{fn_name}()", env))
      except Exception as error:
        emb = discord.Embed(title="\❌ Произошла ошибка", description=str(error), color=0xff0000)
        await ctx.send(embed=emb)
    else:
      await ctx.send("Отказано в доступе")

L
LXSTVAYNE, 2021-09-30
@lxstvayne

exec(YOUR_CODE)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question