summaryrefslogtreecommitdiff
path: root/internal/client.go
blob: 092504e52032d18be8465a58b536180ed394eeb0 (plain)
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
package irclogs

import (
	"bufio"
	"fmt"
	"log"
	"net"
	"net/textproto"
)

type IRCClient struct {
	Host string
	port int
	nick string
	pass string
	caps []string

	conn net.Conn
}

func NewIRCClient(host string, port int, nick string, pass string, capabilities []string) IRCClient {
	return IRCClient{
		Host: host,
		port: port,
		nick: nick,
		pass: pass,
		caps: capabilities,
	}
}

func (c *IRCClient) Connect() (err error) {
	conn, err := net.Dial("tcp", net.JoinHostPort(c.Host, fmt.Sprintf("%d", c.port)))
	if err != nil {
		return
	}

	c.conn = conn
	c.authorize()

	tp := textproto.NewReader(bufio.NewReader(c.conn))

	for {
		message, err := tp.ReadLine()
		if err != nil {
			log.Panicf("Failed to read a line: %v\n", err)
		}
		log.Printf("IRC message: %s\n", message)
	}
}

func (c *IRCClient) authorize() {
	c.SendRaw(fmt.Sprintf("NICK %s", c.nick))
	c.SendRaw(fmt.Sprintf("PASS %s", c.pass))
	for _, cap := range c.caps {
		c.SendRaw(fmt.Sprintf("CAP REQ :%s", cap))
	}
}

func (c *IRCClient) SendRaw(message string) {
	fmt.Fprintf(c.conn, "%s\r\n", message)
}