public
Last active

GoBot, a useless IRC bot in Go

  • Download Gist
gobot.go
Go
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
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)
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.