-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcamerabot.go
98 lines (76 loc) · 1.93 KB
/
camerabot.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
package camerabot
import (
"fmt"
"log"
"sync"
"time"
"github.com/VictoriaMetrics/metrics"
"github.com/cooldarkdryplace/camerabot/telegram"
)
const fallbackTimeout = 20 * time.Second
var (
// MainChatID refers to chat where camerabot will send error reports.
MainChatID int64
// CacheDir is a path to dorectory where last photos are stored.
CacheDir string
mu sync.Mutex
lastUpdateID int64
commandsTotal = metrics.NewCounter("commands_total")
)
// Handlers implement commands that are executed by bot. Unknown commands ignored.
var Handlers = make(map[string]Handler)
// Handler processes command sent to bot.
type Handler interface {
// Command name supported by handler.
Command() string
// Handle supported command.
Handle(chatID int64) error
// Help message. Help handler will show it.
Help() string
}
func command(u telegram.Update) string {
if len(u.Message.Entities) == 0 {
return ""
}
if u.Message.Entities[0].Type == "bot_command" {
return u.Message.Text
}
return ""
}
func trackLastUpdateID(ID int64) {
mu.Lock()
log.Printf("Last update ID: %d, incoming update ID: %d", lastUpdateID, ID)
if lastUpdateID < ID {
lastUpdateID = ID
}
mu.Unlock()
}
func handleUpdates(updates []telegram.Update) {
for _, u := range updates {
trackLastUpdateID(u.ID)
cmd := command(u)
chatID := u.Message.Chat.ID
if cmd == "" {
continue
}
if h, exists := Handlers[cmd]; exists {
commandsTotal.Inc()
h.Handle(chatID)
continue
}
log.Printf("Unknown command: %q in chat: %d ignored", cmd, u.Message.Chat.ID)
}
}
// ListenAndServe gets updates and processes them.
func ListenAndServe() {
telegram.SendTextMessage(MainChatID, "Hi there.")
for {
updates, err := telegram.GetUpdates(lastUpdateID + 1)
if err != nil {
telegram.SendTextMessage(MainChatID, fmt.Sprintf("Failed getting updates: %v", err))
time.Sleep(fallbackTimeout)
}
log.Print("Polling...")
handleUpdates(updates)
}
}