Search code examples
pythonbotsircinstant-messagingpayload

This python code is not solving equations


I have a chat bot for an Instant messenger and I am trying to make a math solver for it but it can't send the solution of equation to the Instant messenger, it sends equation instead.

If someone from Instant messenger sends "solve: 2+2", this program should send them "4" not "2+2".

Main problem:

if (parser.getPayload().lower()[:6]=="solve:"):
                    parser.sendGroupMessage(parser.getTargetID(), str(parser.getPayload()[7:]))

output:

it's sending same input again not the answer of equation

Test: I tested something and that's working properly. If I add this code, program will send solution of equation:

if (parser.getPayload().lower()=="test"):
                    parser.sendGroupMessage(parser.getTargetID(), str(2 + 2 -3 + 8 * 7))

Output: Working perfectly


Solution

  • What you need to do this evaluating math expressions in string form.

    However, user inputs are dangerous if you are just eval things whatever they give you. Security of Python's eval() on untrusted strings?

    You can use ast.literal_eval to lower the risk.

    Or you can use a evaluator from answers of following question Evaluating a mathematical expression in a string