Making a new command - nortxort/tinybot-rtc GitHub Wiki

This document will describe the steps, in order to creating a new command for the bot.

Bassicly, a command consists of 3 parts. Some only 2 parts:

  1. The command name that will trigger the command method.
  2. The command method that will be called.
  3. An optional call to a API method/function.
What should the command do?

For this guide i will make a rate command. So, a user will do rate someuser and the bot will respond with someuser rated 4/10

Who should be able to use the command?

For now, lets make it a public command. We can always move the command to another user level later, if needed.

So now that we know what the command should do, and we have decided who will be able to use the command, it is time to add some code.

First we find the public commands group in message_handler in tinybot.py starting at line 372. So after the last command in the public commands group add:

# the last command in the public commands group.
elif cmd == prefix + 'flip':
    self.do_flip_coin()

# the new command name.
elif cmd == prefix + 'rate':
    # the call to the command method.
    self.do_rate(cmd_arg)

Next, we define a method that will be called when the command has been recieved. I wont get to much in to explaining how the method works, but bassicly we want to format a string, with 2 variables. The username and a random integer between 1 and 10. Now i could import the random module in to tinybot.py and make it a 2 part command as described above, however, i know that the random module is already used in apis/locals_.py so instead, i make a function in locals_.py and go with a 3 part command.

def rand_int(low=0, high=10):
    return random.randint(low, high)

Next we wrap it up with a method in tinybot.py that will do the actuall sending of the message. Where the method is placed in the code does not matter much, as long as it is part of the TinychatBot class. I like things to be somewhat organized, so i place the method after the do_flip_coin on line 1444

def do_rate(user_name):
    if len(user_name) == 0:
        self.send_chat_msg('Missing user name.')
    else:
	self.send_chat_msg('%s rated %s/10' % (user_name, locals_.rand_int(low=1)))

Although this guide and the methods/functions in it are rather simple, i hope it can be of some help to people wanting to add their own commands to the bot.