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:¶
Line 1:
We import 2 functions, fatbotslim.cli.make_bot() and fatbotslim.cli.main(), both are useful when dealing with a bot that will connect to only one server.
The fatbotslim.cli.make_bot() function takes care of gathering the command line options, which are used to create a fatbotslim.irc.IRC instance, and then returns it.
The fatbotslim.cli.main() function is there to spawn the bot in a greenlet (see gevent’s documentation for details about this) and run the main loop for you.
Line 2:
Here we import the fatbotslim.handlers.CommandHandler that will be used to make the bot react to the !hello command and the EVT_PUBLIC variable, which is used to define
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