Skip to content

Instantly share code, notes, and snippets.

@jarredkenny
Created January 21, 2014 14:10
Show Gist options
  • Save jarredkenny/8540779 to your computer and use it in GitHub Desktop.
Save jarredkenny/8540779 to your computer and use it in GitHub Desktop.
A simple IRC bot written in Go.
package main
import (
"fmt"
"net/textproto"
"regexp"
)
var (
conn *textproto.Conn
err error
privmsg = regexp.MustCompile("^:([a-zA-Z0-9`_\\-]+)![a-zA-Z0-9/\\\\\\.\\-]+@[a-zA-Z0-9/\\\\\\.\\-]+ PRIVMSG (#[a-zA-Z0-9]+) :(.*)$")
ping = regexp.MustCompile("^PING :([a-zA-Z0-9\\.]+)$")
motd = regexp.MustCompile(":End of /MOTD command\\.$")
)
type PrivMsg struct {
nick string
channel string
message string
}
type Bot struct {
nick string
channel string
host string
port string
}
func (bot Bot) sendMessage(channel, message string){
conn.Cmd("PRIVMSG %s :%s\r\n", channel, message)
}
func (bot Bot) parseLine(line string){
if match := privmsg.FindStringSubmatch(line); match != nil {
pm := new(PrivMsg)
pm.nick, pm.channel, pm.message = match[1], match[2], match[3]
bot.messageHandler(*pm)
}
if match := ping.FindStringSubmatch(line); match != nil {
conn.Cmd("PONG :%s\r\n", match[1])
}
if match := motd.FindStringSubmatch(line); match != nil {
conn.Cmd("JOIN %s\r\n", bot.channel)
}
}
func (bot Bot) messageHandler(pm PrivMsg){
fmt.Printf("%s: %s\n", pm.nick, pm.message)
}
func (bot Bot) start(){
conn, err = textproto.Dial("tcp", bot.host + ":" + bot.port)
if err != nil {
fmt.Printf("%s", err)
}
conn.Cmd("NICK %s\r\n", bot.nick)
conn.Cmd("USER %s 8 * :%s", bot.nick, bot.nick)
for {
text, err := conn.ReadLine()
if err != nil {
fmt.Print("%s", err)
return
}
go bot.parseLine(text)
}
}
func main() {
bot := new(Bot)
bot.nick = "Jaybot"
bot.channel = "#test"
bot.host = "irc.unixhub.net"
bot.port = "6667"
bot.start()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment