Communicating bots using Slack

We have commented in the past about my tests with a chatbot (notice that we are not talking here about artificial intelligence, nor natural language processing: we are just thinking about a set of pre-defined commands). You can visit, for example, My second bot. I’m more a believer of the chatbot as a personal assistant than a public-service oriented thing (in Spanish: Un chatbot como asistente personal). For these developments I’m using the Errbot project. They provide a chatbot infrastructure developed in Python, with a friendly community, and a multi-channel approach.

But there is a problem (the world is not perfect): one must choose just a communication channel and that’s all. The developers did not consider the possibility for one bot to be present in several channels. My first attempts tested the XMPP channel but clients for XMPP don’t feel very comfortable and I switched to the Telegram backend: there are apps for several devices, the computer, and so on.
Sometimes I’d prefer to send instructions via a textual interface (maybe the command line) and, for this reason, I decided to test the IRC backend.
Some of us have asked for the multi-channel approach: multibackend, Support multiple backends in one instance but these proposals have not enough supporters.

One solution could be to have two replicated bots listening in two different channels and let them live isolated. But I wanted to try another approach, trying to coordinate bots in some way: we can add a forward command (fw for a shorter version) and then, when I’m in a channel whose bot does not understand some command, I can request it to forward to another bot (which can live in a different channel). For example, if I wanted to know the state of another bot, I could ask to the one I’m communicating to forward the status instruction (for now I have two bots which can understand instrucions starting with ‘!’ and ‘,’, respectively):

!fw ,status

The following step was to implement these ideas in some way. We coul try to communicate bots directly, but this could be a problem if one of them was inactive.
So, why not to try to use a command and control like mechanism by means of some common channel and let the bots read and write there?

We can define a language and let the fw command write to the channel. The bots can read it, and then decide whether the command is for them and execute the commands or not. If some result is obtained, they can write the reply in the channel in order the original requester can read and send it to the user who asked for it.

As a proof of concept I’ve developed err-forward, (link to the version when this post is written. It is a live project and it can evolve in the future). We can see also a video of bots interacting by means of a common channel:

For the development we have used:

  • the plugins mechanism of Errbot
  • the scheduling mechanism of Errbot
  • a common channel for reading and writing commands

Many of us have seen command and control systems based on email, IRC, Twitter,… So, we had to decide one for our bot. I’m not a big supporter of Slack, but I wanted to give it a chance on some project. It has an API, some Python modules (slackclient), so I decided to try it.

We have decided to use three types of messages:

  • Msg for text messages (‘Hello’, ‘Good bye’ and so on)
  • Cmd for commands
  • Rep for replies

The bot needs now the following methods:

  • Activation and initialization: when the bot starts it connects to the channel and sends a ‘Hello’ message
  • Writing: the bot can write a message of any of the types defined before
  • Reading: the bot can read messages posted in the channel and it can identify which ones it can interpret, and act on them. This can produce some writing, when there are replies

We won’t discuss here the details but when a bot has to read and write in a Slack channel, it needs an authorization token in order to use the Slack Web API.
Following previous developments, we will store it in a file called ‘~/.rssSlack‘, with the following format:

[Slack]
api-key:......

On activation, we will use the module configparser, we will connect to the channel and we will send the first message. The channel is a configuration parameter that will be accessed by means of:

    self._check_config('channel') 

We will store the operating system, and the IP of the machine hosting the bot. They will be used in order to send information, when needed. The ‘Hello’ message will include this infomation:

self['sc'] = SlackClient(slack_token)
self['chan'] = str(self._check_config('channel'))
self['userName'] = pwd.getpwuid(os.getuid())[0]
self['userHost'] = os.uname()[1]

self.publishSlack(typ = 'Msg', args = 'Hello! from %s' % self.getMyIP())

We have used the ‘publickSlack‘ method (we will comment on in later).

Then we start the ‘poller’, which will read in an scheduled way the channel in order to see if we can find commands for the bot.

    self.start_poller(60, self.readSlack)

Here we are using the ‘readSlack‘ method (we will comment on it later). In this configuration, the poller is executed each 60 seconds.

The ‘publishSlack‘ method is quite simple, it just prepares the message and posts it on the channel:

 msg = {'userName': usr, 'userHost': host,
            'frm': str(frm), 'typ': typ, 'cmd': cmd, 'args': args }

It includes the username, the host, a ‘frm‘ field which is used by Errbot, a type (‘typ‘) as explained above, and the ‘cmd‘ and ‘args‘ fields that are also used by Errbot (command and arguments). The message is quoted in order to avoid its interpretation as HTML, and it is trasnformed to JSON in order to make it easier to interpret it later. Then it is published on the channel.

    chan = self['chan']
    self['sc'].api_call( "chat.postMessage", channel = chan, text = msgJ)

The reading method ‘readSlack‘ is a bit more complicated: it reads the channel, it needs to decide whether the command is for the bot or not, and then interpret it, execute it, and so on…

Reading the list of messages is easy:

    chan = self.normalizedChan(self._check_config('channel'))
    history = self['sc'].api_call("channels.history", channel=chan)

The we need to see all of them and act on them, if needed:

for msg in history['messages']:
     msgJ = self.extractArgs(msg)
     if ('typ' in msgJ):
         if msgJ['typ'] == 'Cmd':
             # It's a command 
             self.manageCommand(chan, msgJ, msg)
         elif msgJ['typ'] == 'Rep':
             # It's a reply 
             self.manageReply(chan, msgJ, msg)

For this you can see we are using some extra methods.

The ‘extractArgs‘ method is devoted to extract the info from the JSON string. If it is not a message (messages are ignored, for now), it unquotes the arguments (no HTML interpretation):

if msgJ['args'] and (msgJ['typ'] != 'Msg'):
    # Unquoting the args
    self.log.debug("Reply args before: %s " % msgJ['args'])
    tmpJ = urllib.parse.unquote(msgJ['args'])
    msgJ['args'] = tmpJ

The ‘manageCommand‘ method decides if it is a command for our bot and tries to execute it:

listCommands = self._bot.all_commands
if msgJ['cmd'].startswith(self._bot.bot_config.BOT_PREFIX):
    cmd = msgJ['cmd'][len(self._bot.bot_config.BOT_PREFIX):]

    self.log.debug("Cmd: %s"% cmd)
    if cmd in listCommands:

That is, it gets the list of commands available in the bot, it checks if the command starts with the adequate character, and then it verifies if it is a command for the bot. The it executes it. For this, it gets the adequate method:

    method = listCommands[cmd]

The execution is as follows:

    replies = method("", msgJ['args'])

Depending of wheter it is a generator or not, the management is slightly different.
In both cases it stores the replies as a text in order to write it in an adequate way:

   self.publishSlack(typ = 'Rep', usr= msgJ['userName'],
       host=msgJ['userHost'], frm = msgJ['frm'], args = txtR)

In some cases there can be templates for the replies, so we need to apply them:

    txtR = txtR + tenv().get_template(method._err_command_template+'.md').render(reply)

After this, the bot deletes the command from the channel (Slack uses for this an identificator, which is based on the posting time).

    self.deleteSlack(chan, msg['ts'])

Finally, the message could be a reply. For this we have the method ‘manageReply‘. This method needs to identify if the reply is for our bot:

if ((msgJ['userName'] == self['userName'])
        and (msgJ['userHost'] == self['userHost'])):
    # It's for me
    self.log.info("Yes. It's for me")
    replies = msgJ['args']

And send it back to the user who sent the command:

    self.send(msgTo, replies)

Finally, it deletes the reply:

    self.deleteSlack(chan, msg['ts'])

We have still a command pending: the ‘forwardCmd‘ method. A command can have arguments, so we need to split them:

if args.find(' ') >= 0:
     cmd, argsS = args.split()
</code>

It publishes the message in the channel:


self.publishSlack(mess=mess,
        usr=self['userName'], host= self['userHost'],
        typ = 'Cmd' , cmd = cmd, args = argsS)

We have defined two aliases, ‘fw‘, and ‘forward‘.

In order to use this plugin we can load it from the GitHub repo for each bot:


!repos install https://github.com/fernand0/err-forward

We need to define a channel in Slack and then we can configure it in the bots:


!plugin config ErrForward {'channel': the name}

Some final thougths:

  • We are proposing here Slack but any channel could be used, with adequate modifications. Maybe there are better options.
  • It would be nice to have different channels available. We could improve the plugin and we could allow to select the channel by means of a configuration parameter. Maybe it would be overkill to establish another plugin infrastructure in Errbot in order to have several channels available. Anyway, it would be nice to see improvements over these ideas, or code for other forwarders.
  • The forwarding is done by writing the complete instrucion (‘!’, ‘,’ including the bot character). We could avoid it, but it has not been our objective here
  • It there are several bots able to execute some instruction, they can do it. There is no locking mechanism. This could be a problem when the second one would try to delete the message.
  • We have succesfully tested this with several bots (two) which have been able to execute commands and establish some communication
  • We have learnt some internalities of Errbot which allow for the execution of commands, apply templates, and so on

I’ve been trying this for several weeks and it seems to be working for my plugins (one bot is listening on Telegram, and the other one is listening in an IRC channel). It seems to be robust for these plugins, which can be found at my repos (fernand0’s GitHub). All my modules’ name start with ‘err-‘.

This post was written originally in Spanish, you can read it at: Comunicación de bots con Slack. As my English is far from perfect, you can contact me if you need some assistance.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s