ChatOps create your IRC bot in Go

21 Feb 2016 · Two minute read · on Gianluca's blog

News! Tech related notes are NOW published to ShippingBytes. See you there! I always felt this was not the right place for me to write consistently about tech and tools. So if you want to read more about that see you at the other side

The infrastructure as a service (IaaS) opened new ways to manage your infrastructure. Use an API to create, destroy and update your virtual machine is one of the biggest revolutions of our sector.

A lot of companies and a lot of DevOps started to create own assistence to increase the automation or to check the status of them infrastructure, in top of all GitHub provided a series of awesome blogpost and tools to describe this approach that it has a name: ChatOps.

IRC is an application layer protocol that facilitates communication. One of the most famouse open IRC server is freenode all most important open source projects use it to chat.

This concept is already applyed it because most projects are your personal bot, for example Zend use Zend\Bot a good assistence written by DASPRiD.

The ChatOps is an assistence oriented to decrease the distance between your infrastacture and your communication channels.

I wrote a low level library to communicate on IRC protocol, we can try to use it to write our dummy bot.

package main

import (
    "log"
    "fmt"
    "regexp"
    "bufio"
    "net/textproto"
    "github.com/gianarb/go-irc"
)

func main(){
    secretary := NewBot(
        "irc.freenode.net",
        "6667",
        "SybilBot",
        "SybilBot",
        "#channel-name",
        "",
    )
    conn, _ := secretary.Connect()
    defer conn.Close()

    reader := bufio.NewReader(bot.conn)
    tp := textproto.NewReader(reader)
    for {
        line, err := tp.ReadLine()
        if err != nil {
            log.Fatal("unable to connect to IRC server ", err)
        }

        isPing, _ := regexp.MatchString("PING", line)
        if isPing  == true {
            bot.Send("PONG");
        }

        fmt.Printf("%s\n", line)
    }
}

With this code you have a bot, in this case her name is SybilBot and at the moment it suppot only the PING PONG flow, without this helth system your bot go down after few time.

You can use the same log to add other actions

yourAction, _ := regexp.MatchString("CheckSomething", line)
if yourAction  == true {
    // Do Something
}

go-irc allow you to communicate over IRC protocol, our but is very stupid I like the idea! If you are working on this topic, in go or in other language please ping me! I am very happy to know your bot!

Something weird with this website? Let me know.