Skip to content

Instantly share code, notes, and snippets.

@mnlwldr
Created July 21, 2020 12:46
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 mnlwldr/d9a2d9f6aa68d75444216c4ca62a4699 to your computer and use it in GitHub Desktop.
Save mnlwldr/d9a2d9f6aa68d75444216c4ca62a4699 to your computer and use it in GitHub Desktop.
Simple IRC bot in Golang
package main
import (
"bufio"
"fmt"
"net"
"net/textproto"
"os"
"os/signal"
"strings"
"syscall"
)
func connect() net.Conn {
conn, err := net.Dial("tcp", "irc.freenode.net:6667")
if err != nil {
panic(err)
}
return conn
}
func disconnect(conn net.Conn) {
sendData(conn, "QUIT Bye")
conn.Close()
}
func login(conn net.Conn) {
sendData(conn, "USER TheManWithTheIceCreamVan 8 * :Someone")
sendData(conn, "NICK TheManWithTheIceCreamVan")
}
func pong(conn net.Conn) {
sendData(conn, "PONG")
}
func main() {
conn := connect()
c := make(chan os.Signal)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
disconnect(conn)
}()
login(conn)
tp := textproto.NewReader(bufio.NewReader(conn))
for {
status, err := tp.ReadLine()
if err != nil {
panic(err)
}
fmt.Println(status)
if strings.HasPrefix(status, "PING") {
pong(conn)
}
}
}
func sendData(conn net.Conn, message string) {
fmt.Fprintf(conn, "%s\r\n", message)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment