Skip to content

Instantly share code, notes, and snippets.

@kaimallea
Created August 3, 2011 18:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save kaimallea/1123352 to your computer and use it in GitHub Desktop.
Save kaimallea/1123352 to your computer and use it in GitHub Desktop.
GoBot, a useless IRC bot in Go
package main
import (
"fmt"
"net/textproto"
"regexp"
"strings"
"os"
)
type PrivMsg struct {
nick, channel, text string
}
var (
conn *textproto.Conn
err os.Error
ping = regexp.MustCompile("^PING :([a-zA-Z0-9\\.]+)$")
motd = regexp.MustCompile(":End of /MOTD command\\.$")
privmsg = regexp.MustCompile("^:([a-zA-Z0-9`_\\-]+)![a-zA-Z0-9/\\\\\\.\\-]+@[a-zA-Z0-9/\\\\\\.\\-]+ PRIVMSG (#[a-zA-Z0-9]+) :(.*)$")
)
func talk(channel, msg string) {
conn.Cmd("PRIVMSG " + channel + " :" + msg)
}
func handlePing(auth string) {
conn.Cmd("PONG :" + auth)
fmt.Printf("PONG :%s\n", auth)
}
func handlePrivmsg(pm *PrivMsg) {
if strings.Contains(pm.text, "MrGoBot") {
talk(pm.channel, "Hello, " + pm.nick + "!")
}
}
func handleMotd() {
conn.Cmd("JOIN #GoBot")
fmt.Println("JOIN #GoBot")
}
func parseLine(line string) {
// Channel activity
if match := privmsg.FindStringSubmatch(line); match != nil {
pm := new(PrivMsg)
pm.nick, pm.channel, pm.text = match[1], match[2], match[3]
handlePrivmsg(pm)
return
}
// Server PING
if match := ping.FindStringSubmatch(line); match != nil {
handlePing(match[1])
return
}
// End of MOTD (successful login to IRC server)
if match := motd.FindString(line); match != "" {
handleMotd()
return
}
}
func main() {
conn, err = textproto.Dial("tcp", "chat.freenode.net:6667")
if err != nil {
fmt.Printf("%s", err)
return
}
conn.Cmd("NICK MrGoBot\n\rUSER mrgobot 8 * :MrGoBot")
for {
text, err := conn.ReadLine()
if err != nil {
fmt.Printf("%s", err)
return
}
go parseLine(text)
fmt.Println(text)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment