/
app.go
85 lines (69 loc) · 1.44 KB
/
app.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
package app
import (
"fmt"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
"log"
"os"
)
type App struct {
token string
dataSource *DataSource
ui *UI
}
type Message struct {
CharID int64
TelegramID int
UserName string
Text string
}
func NewApp() *App {
return &App{}
}
func (a *App) init() {
a.token = os.Getenv("TOKEN")
if a.token == "" {
log.Panic("token is empty!")
}
dataSourcePath := os.Getenv("DB_PATH")
if dataSourcePath == "" {
log.Panic("DB_PATH is empty!")
}
ds, err := NewDataSource(dataSourcePath)
if err != nil {
log.Panic("Invalid DB_PATH. DB does not exist!")
}
a.dataSource = ds
a.ui = NewUI(ds)
}
func (a *App) Start() {
a.init()
bot, err := tgbotapi.NewBotAPI(a.token)
if err != nil {
log.Panic(err)
}
bot.Debug = true
log.Printf("Authorized on account %s", bot.Self.UserName)
u := tgbotapi.NewUpdate(0)
u.Timeout = 60
updates, err := bot.GetUpdatesChan(u)
for update := range updates {
if update.Message == nil {
continue
}
log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text)
if update.CallbackQuery != nil {
fmt.Print(update)
}
userMsg := &Message{
CharID: update.Message.Chat.ID,
TelegramID: update.Message.From.ID,
UserName: update.Message.From.UserName,
Text: update.Message.Text,
}
msg := a.ui.HandleMessage(userMsg)
_, err = bot.Send(msg)
if err != nil {
log.Println(err)
}
}
}