/
main.go
82 lines (65 loc) · 1.68 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
package main
import (
"errors"
"flag"
"log"
"time"
"github.com/bluele/gcache"
"github.com/boltdb/bolt"
"github.com/davidmz/mustbe"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
)
var (
StatesBucket = []byte("States")
ErrNotFound = errors.New("Not Found")
)
func main() {
defer mustbe.Catched(func(err error) { log.Fatalln("Fatal error:", err) })
var (
botToken string
apiHost string
dbFileName string
userAgent string
)
flag.StringVar(&botToken, "token", "", "telegram bot token")
flag.StringVar(&apiHost, "apihost", "freefeed.net", "backend API host")
flag.StringVar(&dbFileName, "dbfile", "", "database file name")
flag.StringVar(&userAgent, "ua", "", "User-Agent for backend requests")
flag.Parse()
if botToken == "" || dbFileName == "" {
flag.Usage()
return
}
db := mustbe.OKVal(bolt.Open(dbFileName, 0600, &bolt.Options{Timeout: 1 * time.Second})).(*bolt.DB)
defer db.Close()
mustbe.OK(db.Update(func(tx *bolt.Tx) error {
mustbe.OKVal(tx.CreateBucketIfNotExists(StatesBucket))
return nil
}))
bot := mustbe.OKVal(tgbotapi.NewBotAPI(botToken)).(*tgbotapi.BotAPI)
u := tgbotapi.NewUpdate(0)
u.Timeout = 60
updates, err := bot.GetUpdatesChan(u)
if err != nil {
log.Fatalln("Can not get update chan:", err)
return
}
log.Println("Starting bot", bot.Self.UserName)
app := &App{
db: db,
apiHost: apiHost,
userAgent: userAgent,
outbox: make(chan tgbotapi.Chattable, 0),
rts: make(map[TgUserID]*Realtime),
cache: gcache.New(1000).ARC().Build(),
}
app.LoadRT()
for {
select {
case update := <-updates:
go app.HandleMessage(update.Message)
case msg := <-app.outbox:
bot.Send(msg)
}
}
}