Skip to content

Instantly share code, notes, and snippets.

@fluffle
Created February 27, 2015 22:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fluffle/7258acc2e15b10cd97d0 to your computer and use it in GitHub Desktop.
Save fluffle/7258acc2e15b10cd97d0 to your computer and use it in GitHub Desktop.
Simple GoIRC client that prints the number of users on #go-nuts every 5 seconds. go run client-test.go --logtostderr
package main
import (
"bufio"
"flag"
"fmt"
irc "github.com/fluffle/goirc/client"
"github.com/fluffle/goirc/logging"
"github.com/fluffle/goirc/logging/glog"
"os"
"strings"
"time"
)
var host *string = flag.String("host", "irc.freenode.net", "IRC server")
var channel *string = flag.String("channel", "#go-nuts", "IRC channel")
func main() {
flag.Parse()
glog.Init()
// create new IRC connection
c := irc.SimpleClient("GoTest", "gotest")
c.EnableStateTracking()
c.HandleFunc("connected",
func(conn *irc.Conn, line *irc.Line) { conn.Join(*channel) })
// Set up a handler to notify of disconnect events.
quit := make(chan bool)
c.HandleFunc("disconnected",
func(conn *irc.Conn, line *irc.Line) { quit <- true })
// Set up a handler for 315 ENDOFWHO
kill315 := make(chan struct{})
c.HandleFunc("315", func(conn *irc.Conn, line *irc.Line) {
if line.Args[1] != *channel {
logging.Info("315 for unexpected channel %s", line.Args[1])
return
}
go func() {
tick := time.NewTicker(5*time.Second)
for {
select {
case <-tick.C:
ch := c.StateTracker().GetChannel(*channel)
logging.Info("%s has %d nicks on it.",
ch.Name, len(ch.Nicks))
case <-kill315:
tick.Stop()
return
}
}
}()
})
// set up a goroutine to read commands from stdin
in := make(chan string, 4)
reallyquit := false
go func() {
con := bufio.NewReader(os.Stdin)
for {
s, err := con.ReadString('\n')
if err != nil {
// wha?, maybe ctrl-D...
close(in)
break
}
// no point in sending empty lines down the channel
if len(s) > 2 {
in <- s[0 : len(s)-1]
}
}
}()
// set up a goroutine to do parsey things with the stuff from stdin
go func() {
for cmd := range in {
if cmd[0] == ':' {
switch idx := strings.Index(cmd, " "); {
case cmd[1] == 'd':
fmt.Printf(c.String())
case cmd[1] == 'f':
if len(cmd) > 2 && cmd[2] == 'e' {
// enable flooding
c.Config().Flood = true
} else if len(cmd) > 2 && cmd[2] == 'd' {
// disable flooding
c.Config().Flood = false
}
for i := 0; i < 20; i++ {
c.Privmsg("#", "flood test!")
}
case idx == -1:
continue
case cmd[1] == 'q':
reallyquit = true
c.Quit(cmd[idx+1 : len(cmd)])
case cmd[1] == 'j':
c.Join(cmd[idx+1 : len(cmd)])
case cmd[1] == 'p':
c.Part(cmd[idx+1 : len(cmd)])
case cmd[1] == 's':
kill315 <- struct{}{}
}
} else {
c.Raw(cmd)
}
}
}()
for !reallyquit {
// connect to server
if err := c.ConnectTo(*host); err != nil {
fmt.Printf("Connection error: %s\n", err)
return
}
// wait on quit channel
<-quit
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment