ScuttleBot

scuttlebot / internal / bots / scroll / scroll.go
Blame History Raw 316 lines
1
// Package scroll implements the scroll bot — channel history replay via PM.
2
//
3
// Agents or humans send a PM to scroll requesting history for a channel.
4
// scroll fetches from scribe's Store and delivers entries as PM messages,
5
// never posting to the channel itself.
6
//
7
// Command format:
8
//
9
// replay #channel [last=N] [since=<unix_ms>]
10
package scroll
11
12
import (
13
"context"
14
"encoding/json"
15
"fmt"
16
"log/slog"
17
"net"
18
"strconv"
19
"strings"
20
"sync"
21
"time"
22
23
"github.com/lrstanley/girc"
24
25
"github.com/conflicthq/scuttlebot/internal/bots/cmdparse"
26
"github.com/conflicthq/scuttlebot/internal/bots/scribe"
27
"github.com/conflicthq/scuttlebot/pkg/chathistory"
28
"github.com/conflicthq/scuttlebot/pkg/toon"
29
)
30
31
const (
32
botNick = "scroll"
33
defaultLimit = 50
34
maxLimit = 500
35
rateLimitWindow = 10 * time.Second
36
)
37
38
// Bot is the scroll history-replay bot.
39
type Bot struct {
40
ircAddr string
41
password string
42
channels []string
43
store scribe.Store
44
log *slog.Logger
45
client *girc.Client
46
history *chathistory.Fetcher // nil until connected, if CHATHISTORY is available
47
rateLimit sync.Map // nick → last request time
48
}
49
50
// New creates a scroll Bot backed by the given scribe Store.
51
func New(ircAddr, password string, channels []string, store scribe.Store, log *slog.Logger) *Bot {
52
return &Bot{
53
ircAddr: ircAddr,
54
password: password,
55
channels: channels,
56
store: store,
57
log: log,
58
}
59
}
60
61
// Name returns the bot's IRC nick.
62
func (b *Bot) Name() string { return botNick }
63
64
// Start connects to IRC and begins handling replay requests. Blocks until ctx is cancelled.
65
func (b *Bot) Start(ctx context.Context) error {
66
host, port, err := splitHostPort(b.ircAddr)
67
if err != nil {
68
return fmt.Errorf("scroll: parse irc addr: %w", err)
69
}
70
71
c := girc.New(girc.Config{
72
Server: host,
73
Port: port,
74
Nick: botNick,
75
User: botNick,
76
Name: "scuttlebot scroll",
77
SASL: &girc.SASLPlain{User: botNick, Pass: b.password},
78
PingDelay: 30 * time.Second,
79
PingTimeout: 30 * time.Second,
80
SSL: false,
81
SupportedCaps: map[string][]string{
82
"draft/chathistory": nil,
83
"chathistory": nil,
84
},
85
})
86
87
// Register CHATHISTORY batch handlers before connecting.
88
b.history = chathistory.New(c)
89
90
c.Handlers.AddBg(girc.CONNECTED, func(cl *girc.Client, e girc.Event) {
91
cl.Cmd.Mode(cl.GetNick(), "+B")
92
for _, ch := range b.channels {
93
cl.Cmd.Join(ch)
94
}
95
hasCH := cl.HasCapability("chathistory") || cl.HasCapability("draft/chathistory")
96
b.log.Info("scroll connected", "channels", b.channels, "chathistory", hasCH)
97
})
98
99
router := cmdparse.NewRouter(botNick)
100
router.Register(cmdparse.Command{
101
Name: "replay",
102
Usage: "REPLAY [#channel] [count]",
103
Description: "replay recent channel messages",
104
Handler: func(_ *cmdparse.Context, _ string) string { return "not implemented yet" },
105
})
106
router.Register(cmdparse.Command{
107
Name: "search",
108
Usage: "SEARCH [#channel] <term>",
109
Description: "search channel history",
110
Handler: func(_ *cmdparse.Context, _ string) string { return "not implemented yet" },
111
})
112
113
c.Handlers.AddBg(girc.PRIVMSG, func(client *girc.Client, e girc.Event) {
114
if len(e.Params) < 1 || e.Source == nil {
115
return
116
}
117
// Dispatch commands (DMs and channel messages).
118
if reply := router.Dispatch(e.Source.Name, e.Params[0], e.Last()); reply != nil {
119
client.Cmd.Message(reply.Target, reply.Text)
120
return
121
}
122
target := e.Params[0]
123
if strings.HasPrefix(target, "#") {
124
return // channel message, ignore
125
}
126
nick := e.Source.Name
127
text := strings.TrimSpace(e.Last())
128
b.handle(client, nick, text)
129
})
130
131
b.client = c
132
133
errCh := make(chan error, 1)
134
go func() {
135
if err := c.Connect(); err != nil && ctx.Err() == nil {
136
errCh <- err
137
}
138
}()
139
140
select {
141
case <-ctx.Done():
142
c.Close()
143
return nil
144
case err := <-errCh:
145
return fmt.Errorf("scroll: irc connection: %w", err)
146
}
147
}
148
149
// Stop disconnects the bot.
150
func (b *Bot) Stop() {
151
if b.client != nil {
152
b.client.Close()
153
}
154
}
155
156
func (b *Bot) handle(client *girc.Client, nick, text string) {
157
if !b.checkRateLimit(nick) {
158
client.Cmd.Notice(nick, "rate limited — please wait before requesting again")
159
return
160
}
161
162
req, err := ParseCommand(text)
163
if err != nil {
164
client.Cmd.Notice(nick, fmt.Sprintf("error: %s", err))
165
client.Cmd.Notice(nick, "usage: replay #channel [last=N] [since=<unix_ms>] [format=json|toon]")
166
return
167
}
168
169
entries, err := b.fetchHistory(req)
170
if err != nil {
171
client.Cmd.Notice(nick, fmt.Sprintf("error fetching history: %s", err))
172
return
173
}
174
175
if len(entries) == 0 {
176
client.Cmd.Notice(nick, fmt.Sprintf("no history found for %s", req.Channel))
177
return
178
}
179
180
if req.Format == "toon" {
181
toonEntries := make([]toon.Entry, len(entries))
182
for i, e := range entries {
183
toonEntries[i] = toon.Entry{
184
Nick: e.Nick,
185
MessageType: e.MessageType,
186
Text: e.Raw,
187
At: e.At,
188
}
189
}
190
output := toon.Format(toonEntries, toon.Options{Channel: req.Channel})
191
for _, line := range strings.Split(output, "\n") {
192
if line != "" {
193
client.Cmd.Notice(nick, line)
194
}
195
}
196
} else {
197
client.Cmd.Notice(nick, fmt.Sprintf("--- replay %s (%d entries) ---", req.Channel, len(entries)))
198
for _, e := range entries {
199
line, _ := json.Marshal(e)
200
client.Cmd.Notice(nick, string(line))
201
}
202
client.Cmd.Notice(nick, fmt.Sprintf("--- end replay %s ---", req.Channel))
203
}
204
}
205
206
// fetchHistory tries CHATHISTORY first, falls back to scribe store.
207
func (b *Bot) fetchHistory(req *replayRequest) ([]scribe.Entry, error) {
208
if b.history != nil && b.client != nil {
209
hasCH := b.client.HasCapability("chathistory") || b.client.HasCapability("draft/chathistory")
210
if hasCH {
211
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
212
defer cancel()
213
msgs, err := b.history.Latest(ctx, req.Channel, req.Limit)
214
if err == nil {
215
entries := make([]scribe.Entry, len(msgs))
216
for i, m := range msgs {
217
entries[i] = scribe.Entry{
218
At: m.At,
219
Channel: req.Channel,
220
Nick: m.Nick,
221
Kind: scribe.EntryKindRaw,
222
Raw: m.Text,
223
}
224
if m.Account != "" {
225
entries[i].Nick = m.Account
226
}
227
}
228
return entries, nil
229
}
230
b.log.Warn("chathistory failed, falling back to store", "err", err)
231
}
232
}
233
return b.store.Query(req.Channel, req.Limit)
234
}
235
236
func (b *Bot) checkRateLimit(nick string) bool {
237
now := time.Now()
238
if last, ok := b.rateLimit.Load(nick); ok {
239
if now.Sub(last.(time.Time)) < rateLimitWindow {
240
return false
241
}
242
}
243
b.rateLimit.Store(nick, now)
244
return true
245
}
246
247
// ReplayRequest is a parsed replay command.
248
type replayRequest struct {
249
Channel string
250
Limit int
251
Since int64 // unix ms, 0 = no filter
252
Format string // "json" (default) or "toon"
253
}
254
255
// ParseCommand parses a replay command string. Exported for testing.
256
func ParseCommand(text string) (*replayRequest, error) {
257
parts := strings.Fields(text)
258
if len(parts) < 2 || strings.ToLower(parts[0]) != "replay" {
259
return nil, fmt.Errorf("unknown command %q", parts[0])
260
}
261
262
channel := parts[1]
263
if !strings.HasPrefix(channel, "#") {
264
return nil, fmt.Errorf("channel must start with #")
265
}
266
267
req := &replayRequest{Channel: channel, Limit: defaultLimit}
268
269
for _, arg := range parts[2:] {
270
kv := strings.SplitN(arg, "=", 2)
271
if len(kv) != 2 {
272
return nil, fmt.Errorf("invalid argument %q (expected key=value)", arg)
273
}
274
switch strings.ToLower(kv[0]) {
275
case "last":
276
n, err := strconv.Atoi(kv[1])
277
if err != nil || n <= 0 {
278
return nil, fmt.Errorf("invalid last=%q (must be a positive integer)", kv[1])
279
}
280
if n > maxLimit {
281
n = maxLimit
282
}
283
req.Limit = n
284
case "since":
285
ts, err := strconv.ParseInt(kv[1], 10, 64)
286
if err != nil {
287
return nil, fmt.Errorf("invalid since=%q (must be unix milliseconds)", kv[1])
288
}
289
req.Since = ts
290
case "format":
291
switch strings.ToLower(kv[1]) {
292
case "json", "toon":
293
req.Format = strings.ToLower(kv[1])
294
default:
295
return nil, fmt.Errorf("unknown format %q (use json or toon)", kv[1])
296
}
297
default:
298
return nil, fmt.Errorf("unknown argument %q", kv[0])
299
}
300
}
301
302
return req, nil
303
}
304
305
func splitHostPort(addr string) (string, int, error) {
306
host, portStr, err := net.SplitHostPort(addr)
307
if err != nil {
308
return "", 0, fmt.Errorf("invalid address %q: %w", addr, err)
309
}
310
port, err := strconv.Atoi(portStr)
311
if err != nil {
312
return "", 0, fmt.Errorf("invalid port in %q: %w", addr, err)
313
}
314
return host, port, nil
315
}
316

Keyboard Shortcuts

Open search /
Next entry (timeline) j
Previous entry (timeline) k
Open focused entry Enter
Show this help ?
Toggle theme Top nav button