Writing a multi-server bot

In this tutorial, we’ll take the code from the “simple bot” tutorial, and make it run on multiple servers.

The code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
from fatbotslim.irc.bot import IRC, run_bots
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))


servers = [
    {
        'server': 'irc.rizon.net',
        'port': 6697,
        'ssl': True,
        'nick': 'fatbotslim',
        'realname': 'fatbotslim',
        'channels': ['#testbot']
    },
    {
        'server': 'irc.freenode.net',
        'port': 6697,
        'ssl': True,
        'nick': 'fatbotslim',
        'realname': 'fatbotslim',
        'channels': ['#testbot']
    }
]

bots = []
for server in servers:
    bot = IRC(server)
    bot.add_handler(HelloCommand)
    bots.append(bot)

run_bots(bots)

Explanations

Imports

Configuration

  • Lines 12-29:

    Instead of having our settings passed via the command line, we create a dict for each server our bot will connect to.

Running the bots

  • Lines 31-35:

    Here we create a list to hold our fatbotslim.irc.bot.IRC instances. We loop over each server configuration, and use them in our bots instanciations.

  • Line 37:

    The fatbotslim.irc.bot.run_bots() function takes a list of bots as argument, and launches each one’s main loop in a greenlet.