~handlerug/handlebot

ref: 5c3342e9f8fd6f47e7bc4ff496b631441fce047a handlebot/main.go -rw-r--r-- 5.0 KiB
5c3342e9Umar Getagazov Update README.md 3 months ago
                                                                                
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
package main

import (
	"context"
	"flag"
	"io"
	"log"
	"net/http"
	"net/url"
	"os"
	"strings"
	"sync"
	"time"

	"git.sr.ht/~handlerug/girc"
	_ "github.com/mattn/go-sqlite3"
	"mvdan.cc/xurls/v2"

	"git.sr.ht/~handlerug/handlebot/database"
	"git.sr.ht/~handlerug/handlebot/urlpreview"
	"git.sr.ht/~handlerug/handlebot/weather"
	"git.sr.ht/~handlerug/handlebot/wolframalpha"
	"git.sr.ht/~handlerug/handlebot/youtube"
)

const BotName = "handlebot"
const BotVersion = "0.0.7"
const ForgeLink = "https://sr.ht/~handlerug/handlebot"
const UserAgent = BotName + "/" + BotVersion

var urlRegexp = xurls.Strict()

type userAgentTransport struct {
	inner     http.RoundTripper
	userAgent string
}

func (u *userAgentTransport) RoundTrip(req *http.Request) (*http.Response, error) {
	if req.Header.Get("User-Agent") == "" {
		req.Header.Set("User-Agent", u.userAgent)
	}
	return u.inner.RoundTrip(req)
}

func main() {
	cfgPath := flag.String("config", "/etc/wormy.json", "path to the config file")
	flag.Parse()
	cfg := parseConfig(*cfgPath)

	log.Println("handlebot starting")

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)

	db, err := database.NewSqliteDB(cfg.Database)
	if err != nil {
		log.Fatal(err)
	}

	version, newVersion, err := db.Migrate(ctx)
	if err != nil {
		log.Fatal("error migrating: ", err)
	} else if newVersion != version {
		log.Printf("migrated from version %d to %d", version, newVersion)
	}

	cancel()

	var debugWriter io.Writer
	if val, ok := os.LookupEnv("TRACE"); val != "" && ok {
		debugWriter = os.Stdout
	}

	var (
		previewer  *urlpreview.Previewer
		forecaster *weather.Forecaster
		waClient   *wolframalpha.Client
		ytClient   *youtube.Client
	)
	httpClient := &http.Client{
		Transport: &userAgentTransport{
			inner:     http.DefaultTransport,
			userAgent: UserAgent,
		},
	}
	previewer = &urlpreview.Previewer{
		HTTPClient:  httpClient,
		UAOverrides: cfg.UAOverrides,
	}
	if cfg.APIKeys.OpenWeatherMap != "" && cfg.APIKeys.MapQuest != "" {
		forecaster = &weather.Forecaster{
			Credentials: weather.APICredentials{
				OpenWeatherMap: cfg.APIKeys.OpenWeatherMap,
				MapQuest:       cfg.APIKeys.MapQuest,
			},
			HTTPClient: httpClient,
		}
	}
	if cfg.APIKeys.WolframAlpha != "" {
		waClient = &wolframalpha.Client{
			AppID:      cfg.APIKeys.WolframAlpha,
			HTTPClient: httpClient,
		}
	}
	if cfg.APIKeys.YouTube != "" {
		ytClient = &youtube.Client{
			APIKey:     cfg.APIKeys.YouTube,
			HTTPClient: httpClient,
		}
	}

	client := girc.New(girc.Config{
		Server:      cfg.IRC.Server,
		ServerPass:  cfg.IRC.Password,
		SSL:         cfg.IRC.TLS,
		Port:        cfg.IRC.Port,
		Nick:        cfg.IRC.Nick,
		Name:        cfg.IRC.Name,
		User:        cfg.IRC.User,
		Debug:       debugWriter,
		RecoverFunc: girc.DefaultRecoverHandler,
		AllowFlood:  true,
	})

	h := NewHandlers(HandlersOpts{
		Client:     client,
		ServerHost: cfg.IRC.Server,
		CmdPrefix:  cfg.CommandPrefix,
	})

	h.Add("weather", []string{"w"}, HandleWeather, `
		Prints current weather. If location is omitted, the previous location is used.
		Forecasts are not implemented (i.e. only the current weather is shown).
		Examples: ".w amsterdam", ".w" (uses "amsterdam")
	`)

	h.Add("jisho", nil, handleJisho, `
		Runs a Jisho.org search.
		Examples: ".jisho himitsu", ".jisho 秘密"
	`)

	h.Add("wolframalpha", []string{"wa"}, handleWolframAlpha, `
		Queries Wolfram|Alpha.
		Examples: ".wa 2+2", ".wa circumference of the moon"
	`)

	h.Add("bots", nil, handleBots, "")

	ctx = context.Background()
	ctx = database.Context(ctx, db)
	ctx = weather.Context(ctx, forecaster)
	ctx = wolframalpha.Context(ctx, waClient)
	ctx = youtube.Context(ctx, ytClient)

	client.Handlers.Add(girc.CONNECTED, func(c *girc.Client, e girc.Event) {
		log.Println("connected to IRC")
		if cfg.Channel != "" {
			c.Cmd.Join(cfg.Channel)
		}
		if len(cfg.Channels) > 0 {
			for _, channel := range cfg.Channels {
				c.Cmd.Join(channel)
			}
		}
	})

	client.Handlers.AddBg(girc.PRIVMSG, func(c *girc.Client, e girc.Event) {
		ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
		defer cancel()

		// Normal command dispatching
		if h.Handle(ctx, e) {
			return
		}

		// Ensure the message is not a command
		if strings.HasPrefix(e.Last(), cfg.CommandPrefix) {
			return
		}

		// In case no command matched the message, find URLs and parse them
		matches := urlRegexp.FindAllString(e.Last(), -1)
		var wg sync.WaitGroup
		for _, match := range matches {
			u, err := url.Parse(match)
			if err != nil {
				continue
			}
			wg.Add(1)
			go func() {
				defer wg.Done()
				resp, err := previewer.Preview(ctx, u)
				if err != nil {
					log.Printf("error handling %q: %s", u.String(), err.Error())
				} else if resp != "" {
					c.Cmd.Replyf(e, "┗━ %s", ellipsize(resp, 430))
				}
			}()
		}
		wg.Wait()
	})

	for {
		if err := client.Connect(); err != nil {
			log.Printf("error connecting to IRC: %s", err)
			log.Println("reconnecting in 30 seconds...")
			time.Sleep(30 * time.Second)
		} else {
			log.Println("stopped")
			return
		}
	}
}