summaryrefslogtreecommitdiff
path: root/main.go
blob: 021ee123202a2b3effa95e7526670f4a5b85f389 (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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package main

import (
	"crypto/tls"
	"flag"
	"fmt"
	"io"
	"log"
	"sync"

	"dim13.org/bot/internal/feeds"
	"dim13.org/bot/internal/fix"
	"dim13.org/bot/internal/flood"
	"dim13.org/bot/internal/title"
	irc "github.com/fluffle/goirc/client"
)

func limit(s string) string {
	const maxLen = 450
	if len(s) > maxLen {
		return fmt.Sprintf("%.*s...", maxLen-3, s)
	}
	return s
}

type room struct {
	conn   *irc.Conn
	target string
}

func roomWriter(conn *irc.Conn, target string) *room {
	return &room{conn: conn, target: target}
}

func (n *room) Write(p []byte) (int, error) {
	n.conn.Notice(n.target, limit(string(p)))
	return len(p), nil
}

func (n *room) Kick(nick string, message ...string) {
	n.conn.Kick(n.target, nick, message...)
}

func (n *room) Ban(nick string) {
	n.conn.Mode(n.target, "+b", nick+"!*@*")
}

func (n *room) HellBan(nick string) {
	n.conn.Mode(n.target, "+q", nick+"!*@*")
}

type message struct {
	title *title.Titles
	flood *flood.Check
	fix   *fix.Fix
}

type kickWriter interface {
	io.Writer
	flood.Kicker
}

func msgHandler(w kickWriter) *message {
	return &message{
		title: title.New(w),
		flood: flood.New(w),
		fix:   fix.New(w),
	}
}

func (r *message) Handle(conn *irc.Conn, line *irc.Line) {
	text, nick := line.Text(), line.Nick
	// ignore self
	if nick == conn.Me().Nick {
		return
	}
	r.flood.Check(text, nick)
	r.title.Parse(text)
	r.fix.Fix(text, nick)
}

func main() {
	node := flag.String("node", "irc.freenode.org", "IRC server")
	notls := flag.Bool("notls", false, "disable TLS")
	room := flag.String("room", "#lor", "IRC channel")
	name := flag.String("name", "dim13", "bots name")
	flag.Parse()

	conf := irc.NewConfig(*name)
	conf.Server = *node
	if !*notls {
		conf.SSL = true
		conf.SSLConfig = &tls.Config{ServerName: *node}
	}
	conn := irc.Client(conf)

	var wg sync.WaitGroup
	wg.Add(1)

	conn.HandleFunc(irc.DISCONNECTED, func(_ *irc.Conn, _ *irc.Line) {
		wg.Done()
	})

	w := roomWriter(conn, *room)
	conn.HandleFunc(irc.CONNECTED, func(conn *irc.Conn, _ *irc.Line) {
		conn.Join(*room)
		feeds.Watch(w, feeds.Feeds)
	})

	conn.HandleFunc(irc.KICK, func(conn *irc.Conn, _ *irc.Line) {
		conn.Join(*room)
	})

	conn.HandleBG(irc.PRIVMSG, msgHandler(w))

	if err := conn.Connect(); err != nil {
		log.Fatal(err)
	}
	wg.Wait()
}