-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathfunction.go
77 lines (59 loc) · 1.75 KB
/
function.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
package investbot
import (
"encoding/json"
"log"
"net/http"
"os"
"strconv"
"investbot/telegram"
"investbot/tinkoff"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
)
var bot *telegram.Bot
func getEnvOrDie(key string) string {
val, ok := os.LookupEnv(key)
if !ok {
log.Fatalf("ENV var %s is not set\n", key)
}
return val
}
func init() {
log.SetFlags(log.LstdFlags | log.Lshortfile | log.Lmicroseconds)
telegramBotToken := getEnvOrDie("TELEGRAM_APITOKEN")
tinkofApiToken := getEnvOrDie("TINKOFF_APITOKEN")
webHookToken := getEnvOrDie("WEBHOOK_TOKEN")
botOwnerId_ := getEnvOrDie("BOT_OWNER_ID")
currencyConvertToken := getEnvOrDie("CURRENCY_API_TOKEN")
botOwnerId, err := strconv.Atoi(botOwnerId_)
if err != nil {
log.Fatalln("Fail to parse bot owner ID:", botOwnerId_)
}
tinkoffApi := tinkoff.New(tinkofApiToken)
if err := tinkoffApi.SetupAccounts(); err != nil {
log.Fatalln("Fail to setup Tinkoff accounts:", err)
}
bot, err = telegram.New(telegramBotToken, webHookToken, currencyConvertToken, botOwnerId, tinkoffApi)
if err != nil {
log.Fatalln("Fail to create Telegram bot:", err)
}
}
func HandleTelegramUpdate(w http.ResponseWriter, r *http.Request) {
webHookToken := r.URL.Query().Get("token")
if webHookToken != bot.WebHookToken {
http.Error(w, "Bad token", http.StatusUnauthorized)
return
}
update := tgbotapi.Update{}
if err := json.NewDecoder(r.Body).Decode(&update); err != nil {
http.Error(w, "Fail to parse JSON body", http.StatusBadRequest)
return
}
log.Printf("New update: %+v\n", update)
if update.Message != nil {
log.Printf("[%s] %s\n", update.Message.From.UserName, update.Message.Text)
if update.Message.IsCommand() {
bot.HandleCommandMessage(&update)
}
}
w.WriteHeader(http.StatusOK)
}