0

I'm currently new to coding, And I'm planning to make a utility bot. So basically, what I am trying to do here is getting the second argument for my on_message event. But how can I do that? I'm making an auto math module for my bot, without using the prefix. For example: solve 5*5 and the bot was supposed to automatically answer it by reading the second argument.

My Code:


@client.event
async def on_message(message):
    if message.content.startswith('solve'):
        expression = # Where it supposed to read the arguments
        await math(message, expression) # math function
Ruri
  • 139
  • 12
  • Does this answer your question? [Split a string only by first space in python](https://stackoverflow.com/questions/30636248/split-a-string-only-by-first-space-in-python) – TheFungusAmongUs Jun 30 '22 at 16:30
  • You might want to look into `discord.ext.commands` for nicer command handling like this. Also please please please please do *not* use `eval`/`exec`/anything of that sort when evaluating math (what if I did `solve await ctx.send(client.http.token)`?)... to be on the safe side use `ast.literal_eval` – Eric Jin Jul 01 '22 at 00:46
  • @EricJin Yes. I used `eval(expression)` for my math command. But I also used `try/except` which forbids some codes running. I tried it out myself, But thanks for that recommendation. I would use that – Ruri Jul 01 '22 at 13:05
  • You can *never* forbid anyone from doing anything once you already are executing the code directly. There are ways to access things even if the namespace is destroyed. For one, `''.__class__.__bases__[0]` gives you `object` even if you try to disallow that. – Eric Jin Jul 01 '22 at 14:16
  • @EricJin I tried doing `ast.literal_eval` but i ran into some problem: `malformed node or string on line 1: `. I would ask this as question. – Ruri Jul 01 '22 at 15:12
  • Yeah, I don't think bitwise operations are allowed under that. You do have to pay something in exchange for the increased security. – Eric Jin Jul 01 '22 at 15:34

1 Answers1

1

Using message.content.startswith() means you already know that message.content is a string. It is self explanatory that it contains the content of the message that triggered this on_message() event, and you can find the doc here.

Considering that your input message is solve 5*5, you could use the method split() to get a list of the argument of the message.

msg = message.content.split()
# Here msg[0] is "solve"
expression = msg[1]
# Here expression = 5*5
Titouan L
  • 1,182
  • 1
  • 8
  • 24