Writing a simple bot

In this tutorial, we’ll take the code from the README.md and explain what happens, it is a bot that answers Hello <username>! when someone says !hello in a public message.

The code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from fatbotslim.cli import make_bot, main
from fatbotslim.handlers import CommandHandler, EVT_PUBLIC


class HelloCommand(CommandHandler):
    triggers = {
        u'hello': [EVT_PUBLIC],
    }

    def hello(self, msg):
        self.irc.msg(msg.dst, u"Hello {0}!".format(msg.src.name))


bot = make_bot()
bot.add_handler(HelloCommand)
main(bot)

Explanations

Imports:

The handler:

  • Lines 5-7:

    The triggers attribute is a dict used to define to which commands and on which type of events the bot should react. It consists of command names mapped to a tuple listing events. If we wanted the bot to react to !hello both in public and private messages, the value would have been (‘public’, ‘private’).

  • Lines 9-10:

    This is the method that will be called when the !hello command will be triggered, it must have the same name as defined in triggers and takes two arguments, the first is the instance of the fatbotslim.irc.bot.Message that triggered the command, and the second is an instance of fatbotslim.irc.bot.IRC which is used to communicate back with the server.

Starting the bot:

  • Line 12:

    Nothing to explain here, the fatbotslim.cli.make_bot() function is already described in the imports part.

  • Line 13:

    The previously created handler is instanciated and added to the bot’s handlers.

  • Line 14:

    The bot is passed to the fatbotslim.cli.main() function, which will take care of