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
6
  • Does this answer your question? Split a string only by first space in python Commented Jun 30, 2022 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 Commented Jul 1, 2022 at 0: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 Commented Jul 1, 2022 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. Commented Jul 1, 2022 at 14:16
  • @EricJin I tried doing ast.literal_eval but i ran into some problem: malformed node or string on line 1: <ast.BinOp object at 0x760ceb4310>. I would ask this as question. Commented Jul 1, 2022 at 15:12

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.