-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
110 lines (90 loc) · 2.11 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
package main
import (
"encoding/json"
"github.com/go-telegram-bot-api/telegram-bot-api"
"github.com/spf13/viper"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"log"
)
// Logger and Bot global variables
var (
sugar *zap.SugaredLogger
bot *tgbotapi.BotAPI
)
// Structure for extending
type Update struct {
*tgbotapi.Update
}
// Command handler for logging purposes
func (u Update) Handle(c func(update Update) (*tgbotapi.Message, error)) {
res, err := c(u)
if err != nil {
sugar.Error(err)
}
if res != nil {
b, err := json.MarshalIndent(res, "", "\t")
if err != nil {
sugar.Warn(err)
}
sugar.Debugf("api response: %s", string(b))
}
}
func main() {
// Init and read config file
viper.SetConfigName("config")
viper.AddConfigPath(".")
err := viper.ReadInConfig()
if err != nil {
// sugar isn't initialized yet
log.Fatalf("cannot read config: %v", err)
}
// Configuration defaults
// Log level: INFO (-1 for DEBUG)
viper.SetDefault("log.level", 0)
// Log type: "production" or "development"
viper.SetDefault("log.type", "production")
// Init logger
var loggerConfig zap.Config
if viper.GetString("log.type") == "production" {
loggerConfig = zap.NewProductionConfig()
}
if viper.GetString("log.type") == "development" {
loggerConfig = zap.NewDevelopmentConfig()
}
loggerConfig.Level.SetLevel(zapcore.Level(viper.GetInt("log.level")))
logger, _ := loggerConfig.Build()
defer logger.Sync()
sugar = logger.Sugar()
// Check token
if !viper.IsSet("token") {
sugar.Fatalf("token not specified")
}
bot, err = tgbotapi.NewBotAPI(viper.GetString("token"))
if err != nil {
sugar.Fatalf("bot api init: %v", err)
}
sugar.Infof("authorized on @%s", bot.Self.UserName)
u := tgbotapi.NewUpdate(0)
u.Timeout = 60
updates, err := bot.GetUpdatesChan(u)
for u := range updates {
// Extend update
update := Update{
&u,
}
// Skip images, stickers, etc
if update.Message == nil {
continue
}
// Commands handler
switch update.Message.Command() {
case "start":
go update.Handle(Start)
case "help":
go update.Handle(Help)
default:
go update.Handle(Default)
}
}
}