lanzafame
2/10/2015 - 8:53 PM

An IRC bot written in Go that provides notification when a RethinkDB cluster experiences issues

An IRC bot written in Go that provides notification when a RethinkDB cluster experiences issues

package main

import (
	"code.google.com/p/gcfg"
	"fmt"
	r "github.com/dancannon/gorethink"
	irc "github.com/fluffle/goirc/client"
	"log"
	"strings"
)

type Config struct {
	IRC struct{ Host, Channel, Nickname string }
	DB  struct{ Host string }
}

type Issue struct {
	Description, Type string
}

type Server struct {
	Name, Status string
}

func main() {
	quit := make(chan bool, 1)

	var config Config
	if err := gcfg.ReadFileInto(&config, "config.gcfg"); err != nil {
		log.Fatal("Couldn't read configuration")
	}

	db, err := r.Connect(r.ConnectOpts{Address: config.DB.Host})
	if err != nil {
		log.Fatal("Database connection failed:", err)
	}

	ircConf := irc.NewConfig(config.IRC.Nickname)
	ircConf.Server = config.IRC.Host
	bot := irc.Client(ircConf)

	bot.HandleFunc("connected", func(conn *irc.Conn, line *irc.Line) {
		log.Println("Connected to IRC server", config.IRC.Host)
		conn.Join(config.IRC.Channel)
	})

	bot.HandleFunc("privmsg", func(conn *irc.Conn, line *irc.Line) {
		log.Println("Received:", line.Nick, line.Text())
		if strings.HasPrefix(line.Text(), config.IRC.Nickname) {
			command := strings.Split(line.Text(), " ")[1]
			switch command {
			case "quit":
				log.Println("Received command to quit")
				quit <- true
			}
		}
	})

	log.Println("Connecting to IRC server", config.IRC.Host)
	if err := bot.Connect(); err != nil {
		log.Fatal("IRC connection failed:", err)
	}

	issues, _ := r.Db("rethinkdb").Table("current_issues").Filter(
		r.Row.Field("critical").Eq(true)).Changes().Field("new_val").Run(db)

	go func() {
		var issue Issue
		for issues.Next(&issue) {
			if issue.Type != "" {
				text := strings.Split(issue.Description, "\n")[0]
				message := fmt.Sprintf("(%s) %s ...", issue.Type, text)
				bot.Privmsg(config.IRC.Channel, message)
			}
		}
	}()

	<-quit
}