Skip to content

Instantly share code, notes, and snippets.

@christianchristensen
Forked from kaimallea/gobot.go
Last active December 10, 2015 11:59
Show Gist options
  • Save christianchristensen/4431170 to your computer and use it in GitHub Desktop.
Save christianchristensen/4431170 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"net/textproto"
"regexp"
"strings"
)
type PrivMsg struct {
nick, channel, text string
}
var (
conn *textproto.Conn
err 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