-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
737 lines (605 loc) · 15 KB
/
main.go
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
package main
import (
"bytes"
"encoding/base64"
"encoding/csv"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"runtime/debug"
"strconv"
"strings"
"time"
"crawshaw.io/sqlite"
"crawshaw.io/sqlite/sqlitex"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
"github.com/hako/durafmt"
"github.com/wcharczuk/go-chart"
)
const (
defaultMonthChartDays = 30
defaultYearChartWeeks = 52
defaultTopCount = 10
minTopCount = 3
maxTopCount = 25
)
//
// Debug
//
const (
debugSendPanicToChat = false
debugChartFilename = "debug.png"
)
// When `debugChartEnabled` is true, the chars are rendered to the local `debug.png`
// and the process exits. See `make debug-chart`.
var debugChartEnabled = os.Getenv("SINCE_BOT_DEBUG_CHART") == "1"
func savePng(content []byte) {
if err := ioutil.WriteFile(debugChartFilename, content, 0644); err != nil {
log.Panic(err)
}
}
func saveRedPng() {
// Red PNG 100x100
pngB64 := "iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAApElEQVR42u3R" +
"AQ0AAAjDMO5fNCCDkC5z0HTVrisFCBABASIgQAQEiIAAAQJEQIAICBABASIgQAREQI" +
"AICBABASIgQAREQIAICBABASIgQAREQIAICBABASIgQAREQIAICBABASIgQAREQIAI" +
"CBABASIgQAREQIAICBABASIgQAREQIAICBABASIgQAREQIAICBABASIgQAQECBAgAg" +
"JEQIAIyPcGFY7HnV2aPXoAAAAASUVORK5CYII="
pngBin, _ := base64.StdEncoding.DecodeString(pngB64)
savePng(pngBin)
}
//
// Utils
//
// Config represents the structure of the config.json file
type Config struct {
Token string `json:"token"`
}
func readConfig() Config {
file, err := os.Open("config.json")
if err != nil {
log.Panic(err)
}
defer file.Close()
bytes, err := ioutil.ReadAll(file)
if err != nil {
log.Panic(err)
}
var config Config
err = json.Unmarshal(bytes, &config)
if err != nil {
log.Panic(err)
}
return config
}
func formatResponse(name string, date int64, prevDate int64) string {
prev := time.Unix(prevDate, 0)
now := time.Unix(date, 0)
duration := durafmt.ParseShort(now.Sub(prev))
return fmt.Sprintf("%s since last '%s'", duration, name)
}
func buildSinceResponse(name string, now int64, userID int64, connection *sqlite.Conn) string {
response := ""
// Get the last event with the same name and format the response
err := sqlitex.Exec(connection,
"SELECT date FROM events "+
"WHERE user = ? AND name = ? "+
"ORDER BY date "+
"DESC LIMIT 1",
func(s *sqlite.Stmt) error {
response = formatResponse(name, now, s.GetInt64("date"))
return nil
},
userID,
name)
if err != nil {
log.Panic(err)
}
return response
}
//
// context
//
type context struct {
message *tgbotapi.Message
db *sqlitex.Pool
bot *tgbotapi.BotAPI
}
func (c context) sendResponse(response string, format string) {
log.Printf("Responding to '%s' in '%s' with '%s'", c.message.From, format, response)
if debugChartEnabled {
saveRedPng()
return
}
message := tgbotapi.NewMessage(c.message.Chat.ID, response)
message.ParseMode = format
_, err := c.bot.Send(message)
if err != nil {
log.Panic(err)
}
}
func (c context) sendText(response string) {
c.sendResponse(response, "")
}
func (c context) sendMarkdown(response string) {
c.sendResponse(response, "Markdown")
}
func (c context) sendImage(filename string, content []byte) {
log.Printf("Sending an image named '%s' to '%s'", filename, c.message.From)
if debugChartEnabled {
saveRedPng()
return
}
image := tgbotapi.FileBytes{Name: filename, Bytes: content}
_, err := c.bot.Send(tgbotapi.NewPhotoUpload(c.message.Chat.ID, image))
if err != nil {
log.Panic(err)
}
}
func (c context) sendFile(filename string, content []byte) {
log.Printf("Sending a file named '%s' to '%s'", filename, c.message.From)
if debugChartEnabled {
saveRedPng()
return
}
file := tgbotapi.FileBytes{Name: filename, Bytes: content}
_, err := c.bot.Send(tgbotapi.NewDocumentUpload(c.message.Chat.ID, file))
if err != nil {
log.Panic(err)
}
}
// This interface unites all the charts
type renderableChart interface {
Render(rp chart.RendererProvider, w io.Writer) error
}
func (c context) sendChart(ch renderableChart) {
// Render
buffer := &bytes.Buffer{}
err := ch.Render(chart.PNG, buffer)
if err != nil {
log.Panic(err)
}
if debugChartEnabled {
// Save locally
savePng(buffer.Bytes())
} else {
// Send as photo
c.sendImage("chart.png", buffer.Bytes())
}
}
func (c context) sendKeyboard(text string, names ...string) {
log.Printf("Sending a keyboard %v to '%s'", names, c.message.From)
if debugChartEnabled {
saveRedPng()
return
}
var markup interface{}
if len(names) > 0 {
keys := []tgbotapi.KeyboardButton{}
for _, n := range names {
keys = append(keys, tgbotapi.NewKeyboardButton(n))
}
keyboard := tgbotapi.NewReplyKeyboard(keys)
keyboard.OneTimeKeyboard = true
markup = keyboard
} else {
markup = tgbotapi.NewRemoveKeyboard(false)
}
message := tgbotapi.NewMessage(c.message.Chat.ID, text)
message.ReplyMarkup = markup
_, err := c.bot.Send(message)
if err != nil {
log.Panic(err)
}
}
//
// Commands
//
func (c context) add(text string) {
if text == "" {
c.sendText("Please provide a name: *name* or /add *name* if you'd like to be formal")
return
}
// DB
connection := c.db.Get(nil)
defer c.db.Put(connection)
// Get stuff out the incoming message
name := text
date := int64(c.message.Date)
// /add is /since + store
response := buildSinceResponse(name, date, int64(c.message.From.ID), connection)
if response == "" {
response = fmt.Sprintf("First time for '%s'", name)
}
// Launch this one in parallel with the database access right bellow this
go c.sendText(response)
// Store the new item in the database
err := sqlitex.Exec(
connection,
"INSERT INTO events (user, name, date) VALUES (?, ?, ?);",
nil,
c.message.From.ID,
name,
date)
if err != nil {
log.Panic(err)
}
}
func (c context) export() {
// DB
connection := c.db.Get(nil)
defer c.db.Put(connection)
// CSV writer
buffer := &bytes.Buffer{}
csv := csv.NewWriter(buffer)
// This is most likely a rarely used command, so we use a non caching version
err := sqlitex.ExecTransient(
connection,
"SELECT name, date FROM events WHERE user = ? ORDER BY date",
func(s *sqlite.Stmt) error {
err := csv.Write([]string{
s.GetText("name"),
time.Unix(s.GetInt64("date"), 0).Format(time.RFC3339),
})
if err != nil {
log.Panic(err)
}
return nil
},
c.message.From.ID)
if err != nil {
log.Panic(err)
}
// Never forget to flush when you're done
csv.Flush()
// There you go
c.sendFile("data.csv", buffer.Bytes())
}
func (c context) help() {
c.sendMarkdown(`
Simply send an event name to log a new event. This is equivalent to the /add command.
Available commands are:
/a, /add *name* - add a new event
/e, /export - get all your data in CSV format
/h, /help - this help message
/m, /month *name* - disply some chart of event activity in the last month
/s, /since *name* - the time since the last event with a given name was logged
/t, /top *[N]* - top 10 or *N* events
/tc, /topchart *[N]* - chart 10 or *N* events
/test - test if the bot works
`)
}
func (c context) month(name string) {
if name == "" {
c.sendMarkdown("Please provide a name: /month *name*")
return
}
// DB
connection := c.db.Get(nil)
defer c.db.Put(connection)
numDays := defaultMonthChartDays
now := int64(c.message.Date)
days := make([]int64, numDays)
done := errors.New("Done")
err := sqlitex.Exec(
connection,
"SELECT date FROM events "+
"WHERE user = ? AND name = ? "+
"ORDER BY date DESC",
func(s *sqlite.Stmt) error {
date := s.GetInt64("date")
daysAgo := int((now - date) / (24 * 60 * 60))
if daysAgo < 0 {
daysAgo = 0
}
if daysAgo >= numDays {
return done
}
days[daysAgo]++
return nil
},
c.message.From.ID,
name)
if err != nil && err != done {
log.Panic(err)
}
maxValue := int64(-1)
for _, day := range days {
if day > maxValue {
maxValue = day
}
}
if maxValue <= 0 {
c.sendMarkdown(fmt.Sprintf("No events named '%s' have been logged in the last %d days", name, numDays))
return
}
values := make([]chart.Value, len(days))
for i, day := range days {
values[len(days)-i-1] = chart.Value{
Value: float64(day),
Style: chart.Style{
Show: true,
StrokeWidth: 1,
StrokeColor: chart.ColorAlternateGreen,
FillColor: chart.ColorAlternateGreen,
},
}
}
// Chart settings
response := chart.BarChart{
Title: fmt.Sprintf("Activity for '%s' in the last %d days", name, numDays),
TitleStyle: chart.StyleShow(),
Background: chart.Style{
Padding: chart.Box{
Top: 40,
},
},
Width: numDays*22 + 80,
Height: 256,
BarWidth: 20,
BarSpacing: 2,
XAxis: chart.StyleShow(),
YAxis: chart.YAxis{
Style: chart.StyleShow(),
ValueFormatter: chart.IntValueFormatter,
Range: &chart.ContinuousRange{Min: 0, Max: float64(maxValue)},
},
Bars: values,
}
c.sendChart(response)
}
func (c context) since(name string) {
if name == "" {
c.sendMarkdown("Please provide a name: /since *name*")
return
}
// DB
connection := c.db.Get(nil)
defer c.db.Put(connection)
response := buildSinceResponse(name, int64(c.message.Date), int64(c.message.From.ID), connection)
if response == "" {
response = fmt.Sprintf("You don't have any events named '%s'", name)
}
c.sendText(response)
}
func (c context) test() {
c.sendText("It works")
}
func (c context) top(args string) {
num := parseTopArgs(args)
response := strings.Builder{}
response.WriteString(fmt.Sprintf("These are your %d most logged events:\n```\n", num))
for _, e := range c.getTopEvents(num) {
response.WriteString(fmt.Sprintf("%s: %d\n", e.name, e.count))
}
response.WriteString("```\n")
c.sendMarkdown(response.String())
}
func (c context) topChart(args string) {
num := parseTopArgs(args)
// Convert values
values := make([]chart.Value, 0, num)
for _, e := range c.getTopEvents(num) {
values = append(values, chart.Value{Label: e.name, Value: float64(e.count)})
}
// Chart settings
response := chart.BarChart{
Title: fmt.Sprintf("Top %d events", num),
TitleStyle: chart.StyleShow(),
Background: chart.Style{
Padding: chart.Box{
Top: 40,
},
},
Width: num * 100,
Height: 512,
BarWidth: 80,
XAxis: chart.StyleShow(),
YAxis: chart.YAxis{
Style: chart.StyleShow(),
ValueFormatter: chart.IntValueFormatter,
Range: &chart.ContinuousRange{Min: 0, Max: values[0].Value},
},
Bars: values,
}
c.sendChart(response)
}
func (c context) year(name string) {
if name == "" {
c.sendMarkdown("Please provide a name: /year *name*")
return
}
// DB
connection := c.db.Get(nil)
defer c.db.Put(connection)
numWeeks := defaultYearChartWeeks
numDays := numWeeks * 7
now := int64(c.message.Date)
days := make([]int, numDays)
done := errors.New("Done")
err := sqlitex.Exec(
connection,
"SELECT date FROM events "+
"WHERE user = ? AND name = ? "+
"ORDER BY date DESC",
func(s *sqlite.Stmt) error {
date := s.GetInt64("date")
daysAgo := int((now - date) / (24 * 60 * 60))
if daysAgo < 0 {
daysAgo = 0
}
if daysAgo >= numDays {
return done
}
days[daysAgo]++
return nil
},
c.message.From.ID,
name)
if err != nil && err != done {
log.Panic(err)
}
today := time.Unix(now, 0)
// Chart settings
response := ActivityChart{
Width: 1200,
XAxis: chart.StyleShow(),
YAxis: chart.StyleShow(),
Legend: chart.StyleShow(),
Days: days,
CurrentDay: (int(today.Weekday()) - 1 + 7) % 7, // Weekday return 0 for Sunday
CurrentMonth: int(today.Month()) - 1, // Month is 1 based
RightToLeft: true,
}
c.sendChart(response)
}
//
// Command utils
//
func clamp(value, min, max int) int {
if value < min {
return min
}
if value > max {
return max
}
return value
}
func parseTopArgs(args string) int {
num, err := strconv.Atoi(args)
if err != nil {
return defaultTopCount
}
return clamp(num, minTopCount, maxTopCount)
}
type topEvent struct {
name string
count int64
}
func (c context) getTopEvents(num int) []topEvent {
// DB
connection := c.db.Get(nil)
defer c.db.Put(connection)
events := make([]topEvent, 0, num)
err := sqlitex.ExecTransient(
connection,
fmt.Sprintf(
"SELECT name, COUNT(name) freq FROM events "+
"WHERE user = ? "+
"GROUP BY name "+
"ORDER BY freq DESC "+
"LIMIT %d",
num),
func(s *sqlite.Stmt) error {
events = append(events, topEvent{name: s.GetText("name"), count: s.GetInt64("freq")})
return nil
},
c.message.From.ID)
if err != nil {
log.Panic(err)
}
return events
}
func reply(message *tgbotapi.Message, db *sqlitex.Pool, bot *tgbotapi.BotAPI) {
// Store all the variables into the context not to pass around all the arguments everywhere
c := context{message: message, db: db, bot: bot}
// TODO: Should we always recover, not only in debug?
if debugSendPanicToChat {
defer func() {
if r := recover(); r != nil {
// When we recover from panic, the runtime doesn't print the callstack
debug.PrintStack()
// Send to the curious user as well
c.sendMarkdown(fmt.Sprintf("*Internal error:*\n```\n%s\n```\n", r))
}
}()
}
if message.IsCommand() {
switch command := message.Command(); command {
case "a", "add":
c.add(message.CommandArguments())
case "e", "export":
c.export()
case "h", "help":
c.help()
case "m", "month":
c.month(message.CommandArguments())
case "s", "since":
c.since(message.CommandArguments())
case "test":
c.test()
case "t", "top":
c.top(message.CommandArguments())
case "tc", "topchart":
c.topChart(message.CommandArguments())
case "y", "year":
c.year(message.CommandArguments())
default:
c.sendText(fmt.Sprintf("Eh? /%s?", command))
}
} else {
c.add(message.Text)
}
}
func openDB() *sqlitex.Pool {
db, err := sqlitex.Open("./since.db", 0, 16)
if err != nil {
log.Panic(err)
}
execSQL(db,
"CREATE TABLE IF NOT EXISTS events ("+
"id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "+
"user INTEGER, "+
"name TEXT, "+
"date INTEGER);")
return db
}
func execSQL(db *sqlitex.Pool, sql string) {
connection := db.Get(nil)
defer db.Put(connection)
err := sqlitex.Exec(connection, sql, nil)
if err != nil {
log.Panic(err)
}
}
func main() {
config := readConfig()
db := openDB()
defer db.Close()
if debugChartEnabled {
c := context{
db: db,
message: &tgbotapi.Message{
Date: int(time.Now().Unix()),
From: &tgbotapi.User{ID: 37121672},
},
}
c.year("commit")
//c.topChart("")
return
}
bot, err := tgbotapi.NewBotAPI(config.Token)
if err != nil {
log.Panic(err)
}
bot.Debug = false
log.Printf("Authorized on account %s", bot.Self.UserName)
updateConfig := tgbotapi.NewUpdate(0)
updateConfig.Timeout = 60
updates, err := bot.GetUpdatesChan(updateConfig)
if err != nil {
log.Panic(err)
}
for update := range updates {
// Ignore any non-Message Updates
if update.Message == nil {
continue
}
log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text)
go reply(update.Message, db, bot)
}
}