-
Notifications
You must be signed in to change notification settings - Fork 0
/
telebot.go
236 lines (199 loc) · 5.81 KB
/
telebot.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
package telebot
import (
"encoding/json"
"errors"
"fmt"
"github.com/aliforever/go-telegram-bot-api"
"reflect"
"runtime/debug"
log "github.com/sirupsen/logrus"
"github.com/aliforever/go-telegram-bot-api/structs"
)
type Bot struct {
token string
botInterface interface{}
api *tgbotapi.TelegramBot
reflectType reflect.Type
updateHandlers *updateHandlers
rateLimiter RateLimiter
isOfAPIType bool
options *BotOptions
}
func NewBot(token string, app interface{}, options *BotOptions) (bot *Bot, api *tgbotapi.TelegramBot, err error) {
if reflect.ValueOf(app).Kind() == reflect.Ptr {
appName := reflect.ValueOf(app).Elem().Type().Name()
err = errors.New(fmt.Sprintf("pass_app_without_pointer_as_%s{}_not_&%s{}", appName, appName))
return
}
api, err = tgbotapi.New(token)
if err != nil {
return
}
t := reflect.TypeOf(app)
if options == nil {
options = NewOptions()
}
if options.stateStorage == nil {
options.stateStorage = newStateStorage()
}
bot = &Bot{
token: token,
botInterface: app,
api: api,
reflectType: t,
options: options,
}
bot.updateHandlers = updateHandlersFromType(bot, t)
var v = reflect.ValueOf(app)
if reflect.ValueOf(app).Kind() == reflect.Ptr {
v = v.Elem()
}
if v.NumField() > 0 && v.Field(0).Type().AssignableTo(reflect.TypeOf(api).Elem()) {
bot.isOfAPIType = true
}
return
}
// SetUserStateStorage is deprecated
// Pass state storage as an option instead
func (bot *Bot) SetUserStateStorage(storage UserStateStorage) {
}
func (bot *Bot) SetRateLimiter(limiter RateLimiter) {
bot.rateLimiter = limiter // commit
}
func (bot *Bot) updateReplyStateNotExists(update tgbotapi.Update, state string) {
message := update.Message
if message == nil {
message = update.EditedMessage
}
if message != nil {
bot.options.stateStorage.SetUserState(message.Chat.Id, "Welcome")
}
j, _ := json.Marshal(update)
log.Errorf("Handler for State: %s was not found!\n%s", state, string(j))
return
}
func (bot *Bot) updateReplyStateInternalError(update tgbotapi.Update) {
j, _ := json.Marshal(update)
log.Errorf("Error getting user state: %+v. For update: %s", update, string(j))
return
}
func (bot *Bot) newApp() reflect.Value {
app := reflect.New(bot.reflectType)
return app
}
func (bot *Bot) appWithUpdate(app reflect.Value, update *tgbotapi.Update, defaultRecipient *int64) []reflect.Value {
api := *bot.api
if bot.isOfAPIType {
if defaultRecipient != nil {
api.SetRecipientChatId(*defaultRecipient)
}
app.Elem().Field(0).Set(reflect.ValueOf(api))
}
return []reflect.Value{app.Elem(), reflect.ValueOf(update)}
}
func (bot *Bot) newAppWithUpdate(defaultRecipientId *int64, update *tgbotapi.Update) []reflect.Value {
app := reflect.New(bot.reflectType)
api := *bot.api
if defaultRecipientId != nil {
api.SetRecipientChatId(*defaultRecipientId)
}
if bot.isOfAPIType {
app.Elem().Field(0).Set(reflect.ValueOf(api))
}
return []reflect.Value{app.Elem(), reflect.ValueOf(update)}
}
func (bot *Bot) invoke(app reflect.Value, update tgbotapi.Update, method string, isSwitched bool) {
if app.MethodByName(method).Kind() == reflect.Invalid {
bot.updateReplyStateNotExists(update, method)
return
}
values := app.MethodByName(method).Call([]reflect.Value{reflect.ValueOf(&update), reflect.ValueOf(isSwitched)})
if len(values) == 1 {
if val, ok := values[0].Interface().(string); ok {
if val != "" {
bot.options.stateStorage.SetUserState(update.Message.Chat.Id, val)
bot.invoke(app, update, val, true)
}
}
}
}
func (bot *Bot) invokeMiddleware(app reflect.Value, update *tgbotapi.Update) (ignoreUpdate bool) {
middlewareMethod := app.MethodByName("Middleware")
if middlewareMethod.Kind() == reflect.Invalid {
return
}
values := middlewareMethod.Call([]reflect.Value{reflect.ValueOf(update)})
if len(values) == 1 {
ignoreUpdate, _ = values[0].Interface().(bool)
}
return
}
func (bot *Bot) processUpdate(update tgbotapi.Update) {
defer func() {
if err := recover(); err != nil {
// log.Errorf("recovered from panic: %s\n%s", err, debug.Stack())
fmt.Println(err)
fmt.Println(string(debug.Stack()))
}
}()
app := bot.newApp()
api := *bot.api
if update.From() != nil {
api.SetRecipientChatId(update.From().Id)
if bot.options.useStorage != nil {
bot.options.useStorage.Store(update.From())
}
}
app.Elem().Field(0).Set(reflect.ValueOf(api))
if ignoreUpdate := bot.invokeMiddleware(app, &update); ignoreUpdate {
return
}
var message *structs.Message
if update.Message != nil {
message = update.Message
} else if update.EditedMessage != nil {
message = update.EditedMessage
}
if message != nil && message.Chat.Type == "private" {
state, err := bot.options.stateStorage.UserState(message.Chat.Id)
if err != nil {
bot.options.stateStorage.SetUserState(message.Chat.Id, "Welcome")
bot.updateReplyStateInternalError(update)
return
}
// _, exists := bot.reflectType.MethodByName(state)
if app.MethodByName(state).Kind() == reflect.Invalid {
bot.updateReplyStateNotExists(update, state)
return
}
/*api := *bot.api
*/
apiField := app.Elem().Field(0)
api.SetRecipientChatId(message.Chat.Id)
apiField.Set(reflect.ValueOf(api))
bot.invoke(app, update, state, false)
return
}
if bot.updateHandlers == nil {
return
}
bot.updateHandlers.processUpdate(app, update)
return
}
func (bot *Bot) Poll() (err error) {
var allowedUpdates []string = []string{"message", "edited_message"}
if bot.updateHandlers != nil {
allowedUpdates = bot.updateHandlers.allowedUpdates()
}
go bot.api.GetUpdates().SetAllowedUpdates(allowedUpdates).LongPoll()
for update := range bot.api.Updates() {
if err = update.Error(); err != nil {
return
}
if bot.rateLimiter != nil && bot.rateLimiter.ShouldLimitUpdate(&update) {
continue
}
go bot.processUpdate(update)
}
return
}