pythonglobal-variablescounterbotschatroom

How to count messages received with Python


I've been using the code tutorial found here to make a bot for a Chatango chat room. My basic code is as follows:

import ch
import random
import sys

class bot(ch.RoomManager):

  def onInit(self):
    self.setNameColor("000000")
    self.setFontColor("000000")
    self.setFontFace("Ariel")
    self.setFontSize(11)

  def onMessage(self, room, user, message):

    print("[{0}] {1}: {2}".format(room.name, user.name.title(), message.body))

    try:
      cmd, args = message.body.split(" ", 1)
    except:
      cmd, args = message.body, ""

    if cmd[0] == "!":
      prfx = True
      cmd = cmd[1:]
    else:
      prfx = False

rooms = ["room0", "room1"]
username = "username goes here"
password = "password goes here"

bot.easy_start(rooms,username,password)

It's basically what you see on the website I linked above. Having used it the past few days, I know the code works. What I am trying to implement is a method of counting messages as they come in. I have already tried something along the lines of:

import ch
import random
import sys

class bot(ch.RoomManager):

  count = 0

  def onInit(self):
    self.setNameColor("000000")
    self.setFontColor("000000")
    self.setFontFace("Ariel")
    self.setFontSize(11)

  def onMessage(self, room, user, message):

    print("[{0}] {1}: {2}".format(room.name, user.name.title(), message.body))

    global count
    count = count + 1
    print (count)

    try:
      cmd, args = message.body.split(" ", 1)
    except:
      cmd, args = message.body, ""

    if cmd[0] == "!":
      prfx = True
      cmd = cmd[1:]
    else:
      prfx = False

rooms = ["room0", "room1"]
username = "username goes here"
password = "password goes here"

bot.easy_start(rooms,username,password)

I am new to Python, but I can't seem to figure out why this wouldn't print out a proper count every time someone sends a message. How can I make this counter work?


Solution

  • count is member of class object "bot", If u intend to use count declared inside class body then access it as bot.count. I don't see any global count which you are trying to use.