Created
March 26, 2014 15:43
-
-
Save trmcnvn/9786328 to your computer and use it in GitHub Desktop.
irc.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package irc | |
import( | |
"net/textproto" | |
"regexp" | |
"time" | |
) | |
var ( | |
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\\.]+)$") | |
) | |
type Client struct { | |
conn *textproto.Conn | |
User string | |
Pass string | |
onMessage func(string, string) | |
} | |
func (client *Client) ConnectTo(server string) error { | |
c, err := textproto.Dial("tcp", server + ":6667") | |
if err != nil { | |
return err | |
} | |
c.Cmd("PASS %s\r\n", client.Pass) | |
c.Cmd("NICK %s\r\n", client.User) | |
c.Cmd("USER %s * * :...\r\n", client.User) | |
client.conn = c | |
return nil | |
} | |
func (client *Client) Join(channel string) { | |
client.conn.Cmd("JOIN %s\r\n", channel) | |
} | |
func (client *Client) OnMessage(cb func(string, string)) { | |
client.onMessage = cb | |
} | |
func (client *Client) Loop() { | |
ch := make(chan string) | |
go func() { | |
for { | |
d, _ := client.conn.ReadLine() | |
ch <- d | |
} | |
}() | |
go func(in <-chan string) { | |
for { | |
d := <-in | |
if m := privmsg.FindStringSubmatch(d); m != nil { | |
go client.onMessage(m[1], m[3]) | |
} | |
if m := ping.FindStringSubmatch(d); m != nil { | |
client.conn.Cmd("PONG :%s\r\n", m[1]) | |
} | |
} | |
}(ch) | |
for { | |
time.Sleep(50 * time.Millisecond) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment