1

I have the following code:

import ch
import re
import sys

def doMath(desIn):
  desOut = desIn+2
  return desOut

class bot(ch.RoomManager):
  def onMessage(self, room, user, message):
    try:
      cmd, args = message.body.split(" ", 1)
    except:
      cmd, args = message.body, ""

    if cmd=="!math":
      doMath(3)
      print(desOut)

I am using ch.py to run a bot in a Chatango chat room. It is designed to perform a certain task when a user sends out a specific message. In this case when a user sends the message of "!math", I would like for it to call the doMath function with an input (desIn), perform the math operation I coded, and then return an output (desOut). In this case, it should return 5. My code runs all the way through, but it does not seem to print the last line that I wrote. Is it possible to return the output into the bot class I have?

By request, why does this not work?

def doMath(desIn):
  desOut = desIn+2
  return desOut

class A:
  doMath(3)
  print(desOut)
Patr3xion
  • 122
  • 2
  • 15
  • 1
    Is that story really relevant to the question in the title? Could you come up with a minimal example that does not rely on these specific modules in order to isolate the nature of the actual problem? – timgeb Apr 10 '16 at 16:36

2 Answers2

2

Your desOut variable is a local variable to the doMath function, which means it won't be accessible to the onMessage method. If you want your code to actually print the output of your doMath function, you have to either:

  • Save it in a variable. That's useful if you want to use the same value somewhere else in the onMessage function:
if cmd == '!math':
    math_output = doMath(3)
    print(math_output)
  • Just print the returned value directly:
if cmd == '!math':
    print(doMath(3))

You can read more details in this SO question or even more details here.

Community
  • 1
  • 1
ursan
  • 2,228
  • 2
  • 14
  • 21
0

You can also use print(doMath(int(3))). I just added int xD. If you want it to be a game, then:

if cmd == "!math":
    if args: room.message(doMath(int(args)))
    else: room.message(doMath(int(3)))

it would be like this:

>>> !math 5
>>> 7
>>> !math
>>> 5
Kakkoiikun
  • 41
  • 6