-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.go
529 lines (438 loc) · 20 KB
/
bot.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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
package bot
import (
"fmt"
"log"
"net/http"
"net/url"
"time"
"github.com/d-Rickyy-b/gogeizhalsbot/v2/internal/bot/models"
"github.com/d-Rickyy-b/gogeizhalsbot/v2/internal/bot/userstate"
"github.com/d-Rickyy-b/gogeizhalsbot/v2/internal/config"
"github.com/d-Rickyy-b/gogeizhalsbot/v2/internal/database"
"github.com/d-Rickyy-b/gogeizhalsbot/v2/internal/geizhals"
"github.com/d-Rickyy-b/gogeizhalsbot/v2/internal/prometheus"
"github.com/PaulSonOfLars/gotgbot/v2/ext/handlers/filters/message"
"github.com/PaulSonOfLars/gotgbot/v2"
"github.com/PaulSonOfLars/gotgbot/v2/ext"
"github.com/PaulSonOfLars/gotgbot/v2/ext/handlers"
"github.com/PaulSonOfLars/gotgbot/v2/ext/handlers/filters/callbackquery"
)
var bot *gotgbot.Bot
// startHandler is a message handler for the /start command.
func startHandler(bot *gotgbot.Bot, ctx *ext.Context) error {
// Reset user's state to idle
userID := ctx.EffectiveUser.Id
userstate.UserStates[userID] = userstate.UserState{State: userstate.Idle}
_, err := ctx.EffectiveMessage.Reply(bot, "Was möchtest du tun?", &gotgbot.SendMessageOpts{
ReplyMarkup: gotgbot.InlineKeyboardMarkup{
InlineKeyboard: [][]gotgbot.InlineKeyboardButton{{
{Text: "Neuer Preisagent", CallbackData: "m01_00"},
{Text: "Meine Preisagenten", CallbackData: "m01_01"},
}},
},
})
if err != nil {
return fmt.Errorf("failed to send start message: %w", err)
}
return nil
}
// viewPriceagentsHandler is a callback handler that displays the first sub menu for the m01_01 callback.
func viewPriceagentsHandler(bot *gotgbot.Bot, ctx *ext.Context) error {
cbq := ctx.Update.CallbackQuery
_, err := cbq.Answer(bot, &gotgbot.AnswerCallbackQueryOpts{})
if err != nil {
return fmt.Errorf("failed to answer start callback query: %w", err)
}
markup := gotgbot.InlineKeyboardMarkup{
InlineKeyboard: [][]gotgbot.InlineKeyboardButton{
{
{Text: "📋 Wunschlisten", CallbackData: "m02_00"},
{Text: "📦 Produkte", CallbackData: "m02_01"},
},
{
{Text: "↩️ Zurück", CallbackData: "m00_00"},
},
},
}
_, _, err = cbq.Message.EditText(bot, "Welche Preisagenten möchtest du einsehen?", &gotgbot.EditMessageTextOpts{ReplyMarkup: markup})
if err != nil {
return fmt.Errorf("viewPriceagents: failed to edit message text: %w", err)
}
return nil
}
// showWishlistPriceagents displays the menu with all wishlist priceagents for the m02_00 callback
func showWishlistPriceagents(bot *gotgbot.Bot, ctx *ext.Context) error {
cbq := ctx.Update.CallbackQuery
_, err := cbq.Answer(bot, &gotgbot.AnswerCallbackQueryOpts{})
if err != nil {
return fmt.Errorf("failed to answer start callback query: %w", err)
}
priceagents, _ := database.GetWishlistPriceagentsForUser(ctx.EffectiveUser.Id)
var messageText string
if len(priceagents) == 0 {
messageText = "Du hast noch keine Preisagenten für Wunschlisten angelegt!"
} else {
messageText = "Das sind deine Preisagenten für deine Wunschlisten:"
}
markup := generateEntityKeyboard(priceagents, "m03_00", 2)
_, _, err = cbq.Message.EditText(bot, messageText, &gotgbot.EditMessageTextOpts{ReplyMarkup: markup})
if err != nil {
return fmt.Errorf("showWishlist: failed to edit message text: %w", err)
}
return nil
}
// showProductPriceagents displays the menu with all product priceagents for the m02_01 callback
func showProductPriceagents(bot *gotgbot.Bot, ctx *ext.Context) error {
cbq := ctx.Update.CallbackQuery
if _, err := cbq.Answer(bot, &gotgbot.AnswerCallbackQueryOpts{}); err != nil {
return fmt.Errorf("showProductPriceagents: failed to answer callback query: %w", err)
}
productPriceagents, _ := database.GetProductPriceagentsForUser(ctx.EffectiveUser.Id)
var messageText string
if len(productPriceagents) == 0 {
messageText = "Du hast noch keine Preisagenten für Produkte angelegt!"
} else {
messageText = "Das sind deine Preisagenten für deine Produkte:"
}
markup := generateEntityKeyboard(productPriceagents, "m03_00", 2)
_, _, err := cbq.Message.EditText(bot, messageText, &gotgbot.EditMessageTextOpts{ReplyMarkup: markup})
if err != nil {
return fmt.Errorf("showProduct: failed to edit message text: %w", err)
}
return nil
}
// newPriceagentHandler is a callback handler for the m01_00 callback.
func newPriceagentHandler(bot *gotgbot.Bot, ctx *ext.Context) error {
conf, confErr := config.GetConfig()
if confErr != nil {
return fmt.Errorf("newPriceagentHandler: failed to get config: %w", confErr)
}
cbq := ctx.Update.CallbackQuery
if _, err := cbq.Answer(bot, &gotgbot.AnswerCallbackQueryOpts{}); err != nil {
return fmt.Errorf("failed to answer start callback query: %w", err)
}
// check if user has capacities for a new priceagent
if database.GetPriceAgentCountForUser(ctx.EffectiveUser.Id) >= conf.MaxPriceAgents {
text := fmt.Sprintf("Du hast bereits die maximale Anzahl von %d Preisagenten angelegt. Bitte lösche einen Preisagenten, bevor du einen neuen anlegst.", conf.MaxPriceAgents)
markup := gotgbot.InlineKeyboardMarkup{
InlineKeyboard: [][]gotgbot.InlineKeyboardButton{
{
{Text: "Zu den Preisagenten", CallbackData: "m01_01"},
},
},
}
_, _, err := cbq.Message.EditText(bot, text, &gotgbot.EditMessageTextOpts{ReplyMarkup: markup})
if err != nil {
return fmt.Errorf("newPriceagentHandler: failed to edit message text: %w", err)
}
return nil
}
_, _, err := cbq.Message.EditText(bot, "Bitte sende mir eine URL zu einem Produkt oder einer Wunschliste!", &gotgbot.EditMessageTextOpts{ReplyMarkup: gotgbot.InlineKeyboardMarkup{InlineKeyboard: [][]gotgbot.InlineKeyboardButton{}}})
if err != nil {
return fmt.Errorf("newPriceagent: failed to edit message text: %w", err)
}
// Set user's State
userID := ctx.EffectiveUser.Id
userstate.UserStates[userID] = userstate.UserState{State: userstate.CreatePriceagent}
return nil
}
// mainMenuHandler handles all the back-button calls to the main menu.
// It's basically the same as the start handler, but without sending a new message.
func mainMenuHandler(bot *gotgbot.Bot, ctx *ext.Context) error {
cbq := ctx.Update.CallbackQuery
if _, err := cbq.Answer(bot, &gotgbot.AnswerCallbackQueryOpts{}); err != nil {
return fmt.Errorf("failed to answer start callback query: %w", err)
}
markup := gotgbot.InlineKeyboardMarkup{
InlineKeyboard: [][]gotgbot.InlineKeyboardButton{{
{Text: "Neuer Preisagent", CallbackData: "m01_00"},
{Text: "Meine Preisagenten", CallbackData: "m01_01"},
}},
}
_, _, err := cbq.Message.EditText(bot, "Was möchtest du tun?", &gotgbot.EditMessageTextOpts{ReplyMarkup: markup})
if err != nil {
return fmt.Errorf("mainMenu: failed to edit message text: %w", err)
}
return nil
}
// showPriceagentDetail displays the menu for a single, specific price agent.
func showPriceagentDetail(bot *gotgbot.Bot, ctx *ext.Context) error {
cbq := ctx.Update.CallbackQuery
menu, priceagent, parseErr := parseMenuPriceagent(ctx)
if parseErr != nil {
return fmt.Errorf("showPriceagentDetail: failed to parse callback data: %w", parseErr)
}
var backCallbackData string
switch {
case priceagent.Entity.Type == geizhals.Wishlist:
backCallbackData = "m02_00"
case priceagent.Entity.Type == geizhals.Product:
backCallbackData = "m02_01"
default:
backCallbackData = "invalidType"
}
if _, err := cbq.Answer(bot, &gotgbot.AnswerCallbackQueryOpts{}); err != nil {
return fmt.Errorf("showPriceagentDetail: failed to answer callback query: %w", err)
}
notificationButtonText := fmt.Sprintf("⏰ %s", priceagent.NotificationSettings.String())
linkName := createLink(priceagent.EntityURL(), priceagent.Entity.Name)
price := priceagent.CurrentEntityPrice()
editedText := fmt.Sprintf("%s kostet aktuell %s", linkName, bold(price.String()))
markup := gotgbot.InlineKeyboardMarkup{
InlineKeyboard: [][]gotgbot.InlineKeyboardButton{
{
{Text: notificationButtonText, CallbackData: fmt.Sprintf("m04_00_%d", priceagent.ID)},
{Text: "📊 Preisverlauf", CallbackData: fmt.Sprintf("m05_00_%d", priceagent.ID)},
},
{
{Text: "❌ Löschen", CallbackData: fmt.Sprintf("m04_98_%d", priceagent.ID)},
{Text: "↩️ Zurück", CallbackData: backCallbackData},
},
},
}
switch menu.SubMenu {
case "00":
_, _, err := cbq.Message.EditText(bot, editedText, &gotgbot.EditMessageTextOpts{ReplyMarkup: markup, ParseMode: "HTML"})
if err != nil {
return fmt.Errorf("showPriceagentDetail: failed to edit message text: %w", err)
}
case "01":
bot.DeleteMessage(ctx.EffectiveChat.Id, cbq.Message.MessageId, nil)
_, err := bot.SendMessage(ctx.EffectiveChat.Id, editedText, &gotgbot.SendMessageOpts{ReplyMarkup: markup, ParseMode: "HTML"})
if err != nil {
return fmt.Errorf("showPriceagentDetail: failed to send new message: %w", err)
}
case "02":
_, err := bot.SendMessage(ctx.EffectiveChat.Id, editedText, &gotgbot.SendMessageOpts{ReplyMarkup: markup, ParseMode: "HTML"})
if err != nil {
return fmt.Errorf("showPriceagentDetail: failed to send new message: %w", err)
}
}
return nil
}
// changePriceagentSettingsHandler handles the callbacks for the buttons to change the notification
// settings of a price agent.
func changePriceagentSettingsHandler(bot *gotgbot.Bot, ctx *ext.Context) error {
cbq := ctx.Update.CallbackQuery
_, priceagent, parseErr := parseMenuPriceagent(ctx)
if parseErr != nil {
return fmt.Errorf("changePriceagentSettingsHandler: failed to parse callback data: %w", parseErr)
}
if _, err := cbq.Answer(bot, &gotgbot.AnswerCallbackQueryOpts{}); err != nil {
return fmt.Errorf("changePriceagentSettingsHandler: failed to answer callback query: %w", err)
}
linkName := createLink(priceagent.EntityURL(), priceagent.Entity.Name)
price := priceagent.CurrentEntityPrice()
editedText := fmt.Sprintf("%s\n\nWann möchtest du für %s alarmiert werden?\n\nAktuelle Einstellung: %s\nAktueller Preis: %s", bold("Benachrichtigungseinstellungen"), linkName, bold(priceagent.NotificationSettings.String()), bold(price.String()))
markup := gotgbot.InlineKeyboardMarkup{
InlineKeyboard: [][]gotgbot.InlineKeyboardButton{
{
{Text: "📉 Unter x€", CallbackData: fmt.Sprintf("m04_02_%d", priceagent.ID)},
{Text: "🔔 Immer", CallbackData: fmt.Sprintf("m04_01_%d", priceagent.ID)},
},
{
{Text: "↩️ Zurück", CallbackData: fmt.Sprintf("m03_00_%d", priceagent.ID)},
},
},
}
_, _, err := cbq.Message.EditText(bot, editedText, &gotgbot.EditMessageTextOpts{ReplyMarkup: markup, ParseMode: "HTML"})
if err != nil {
return fmt.Errorf("showPriceagent: failed to edit message text: %w", err)
}
return nil
}
func deletePriceagentConfirmationHandler(bot *gotgbot.Bot, ctx *ext.Context) error {
cbq := ctx.Update.CallbackQuery
_, priceagent, parseErr := parseMenuPriceagent(ctx)
if parseErr != nil {
return fmt.Errorf("deletePriceagentConfirmationHandler: failed to parse callback data: %w", parseErr)
}
if _, err := cbq.Answer(bot, &gotgbot.AnswerCallbackQueryOpts{}); err != nil {
return fmt.Errorf("deletePriceagentConfirmationHandler: failed to answer callback query: %w", err)
}
linkName := createLink(priceagent.EntityURL(), priceagent.Entity.Name)
editedText := fmt.Sprintf("%s\n\nMöchtest du den Preisagenten für %s wirklich löschen?", bold("Löschen bestätigen"), linkName)
markup := gotgbot.InlineKeyboardMarkup{
InlineKeyboard: [][]gotgbot.InlineKeyboardButton{
{
{Text: "❌ Löschen", CallbackData: fmt.Sprintf("m04_99_%d", priceagent.ID)},
{Text: "↩️ Zurück", CallbackData: fmt.Sprintf("m03_00_%d", priceagent.ID)},
},
},
}
_, _, err := cbq.Message.EditText(bot, editedText, &gotgbot.EditMessageTextOpts{ReplyMarkup: markup, ParseMode: "HTML"})
if err != nil {
return fmt.Errorf("deletePriceagentConfirmationHandler: failed to edit message text: %w", err)
}
return nil
}
// deletePriceagentHandler handles all the inline "delete" buttons for priceagents
func deletePriceagentHandler(bot *gotgbot.Bot, ctx *ext.Context) error {
cbq := ctx.Update.CallbackQuery
if _, err := cbq.Answer(bot, &gotgbot.AnswerCallbackQueryOpts{}); err != nil {
return fmt.Errorf("failed to answer start callback query: %w", err)
}
// Get Priceagent from DB
_, priceagent, parseErr := parseMenuPriceagent(ctx)
if parseErr != nil {
ctx.EffectiveMessage.Reply(bot, "Der Preisagent existiert nicht mehr, vielleicht wurde er schon gelöscht?", &gotgbot.SendMessageOpts{})
return fmt.Errorf("deletePriceagentHandler: failed to parse callback data: %w", parseErr)
}
deleteErr := database.DeletePriceAgentForUser(priceagent)
if deleteErr != nil {
ctx.EffectiveMessage.Reply(bot, "Der Preisagent konnte nicht gelöscht werden!", &gotgbot.SendMessageOpts{})
return fmt.Errorf("deletePriceagentHandler: failed to delete priceagent from database: %w", deleteErr)
}
editText := fmt.Sprintf("Preisagent für %s wurde gelöscht!", bold(createLink(priceagent.EntityURL(), priceagent.Entity.Name)))
_, _, err := cbq.Message.EditText(bot, editText, &gotgbot.EditMessageTextOpts{ParseMode: "HTML", DisableWebPagePreview: true})
if err != nil {
return fmt.Errorf("deletePriceagentHandler: failed to edit message text: %w", err)
}
return nil
}
func newUserHandler(_ *gotgbot.Bot, ctx *ext.Context) error {
prometheus.TotalUserInteractions.Inc()
// Create user in databse if they don't exist already
if !ctx.EffectiveSender.IsUser() {
return nil
}
user := models.User{
ID: ctx.EffectiveSender.User.Id,
Username: ctx.EffectiveSender.User.Username,
FirstName: ctx.EffectiveSender.User.FirstName,
LastName: ctx.EffectiveSender.User.LastName,
LangCode: ctx.EffectiveSender.User.LanguageCode,
}
database.CreateUserWithCache(user)
return nil
}
// setCommands sets all the available commands for the bot on Telegram
func setCommands() {
_, setCommandErr := bot.SetMyCommands([]gotgbot.BotCommand{
{Command: "start", Description: "Startmenü des Bots"},
{Command: "stop", Description: "Löscht alle Daten und stoppt den Bot"},
{Command: "help", Description: "Zeigt die Hilfe an"},
{Command: "version", Description: "Zeigt die Version des Bots an"},
}, &gotgbot.SetMyCommandsOpts{
Scope: gotgbot.BotCommandScopeDefault{},
LanguageCode: "",
})
if setCommandErr != nil {
log.Fatalln("Something wrong:", setCommandErr)
}
}
// addMessageHandlers adds all the message handlers to the dispatcher. This tells our bot how to handle updates.
func addMessageHandlers(dispatcher *ext.Dispatcher) {
// Text commands
dispatcher.AddHandler(handlers.NewCommand("start", startHandler))
dispatcher.AddHandler(handlers.NewCommand("stop", stopHandler))
dispatcher.AddHandler(handlers.NewCommand("version", versionHandler))
dispatcher.AddHandler(handlers.NewCommand("help", helpHandler))
// Callback Queries (inline keyboards)
dispatcher.AddHandler(handlers.NewCallback(callbackquery.Equal("m06_02"), stopHandlerCancel))
dispatcher.AddHandler(handlers.NewCallback(callbackquery.Equal("m06_01"), stopHandlerConfirm))
dispatcher.AddHandler(handlers.NewCallback(callbackquery.Prefix("m04_98_"), deletePriceagentConfirmationHandler))
dispatcher.AddHandler(handlers.NewCallback(callbackquery.Prefix("m04_99_"), deletePriceagentHandler))
dispatcher.AddHandler(handlers.NewCallback(callbackquery.Prefix("m05_00_"), showPriceHistoryHandler))
dispatcher.AddHandler(handlers.NewCallback(callbackquery.Prefix("m05_01_"), updatePriceHistoryGraphHandler)) // Graph 1M
dispatcher.AddHandler(handlers.NewCallback(callbackquery.Prefix("m05_03_"), updatePriceHistoryGraphHandler)) // Graph 3M
dispatcher.AddHandler(handlers.NewCallback(callbackquery.Prefix("m05_06_"), updatePriceHistoryGraphHandler)) // Graph 6M
dispatcher.AddHandler(handlers.NewCallback(callbackquery.Prefix("m05_12_"), updatePriceHistoryGraphHandler)) // Graph 12M
dispatcher.AddHandler(handlers.NewCallback(callbackquery.Prefix("m04_02_"), setNotificationBelowHandler))
dispatcher.AddHandler(handlers.NewCallback(callbackquery.Prefix("m04_01_"), setNotificationAlwaysHandler))
dispatcher.AddHandler(handlers.NewCallback(callbackquery.Prefix("m04_00_"), changePriceagentSettingsHandler))
dispatcher.AddHandler(handlers.NewCallback(callbackquery.Prefix("m03_"), showPriceagentDetail))
dispatcher.AddHandler(handlers.NewCallback(callbackquery.Equal("m02_00"), showWishlistPriceagents))
dispatcher.AddHandler(handlers.NewCallback(callbackquery.Equal("m02_01"), showProductPriceagents))
dispatcher.AddHandler(handlers.NewCallback(callbackquery.Equal("m01_01"), viewPriceagentsHandler))
dispatcher.AddHandler(handlers.NewCallback(callbackquery.Equal("m01_00"), newPriceagentHandler))
dispatcher.AddHandler(handlers.NewCallback(callbackquery.Equal("m00_00"), mainMenuHandler))
// Fallback handler for callback queries
dispatcher.AddHandler(handlers.NewCallback(callbackquery.All, fallbackCallbackHandler))
// Unknown commands
dispatcher.AddHandler(handlers.NewMessage(message.Command, fallbackCommandHandler))
// Any kind of text
dispatcher.AddHandler(handlers.NewMessage(message.Text, textHandler))
// Store users if not already in database
dispatcher.AddHandlerToGroup(handlers.NewCallback(callbackquery.All, newUserHandler), -1)
dispatcher.AddHandlerToGroup(handlers.NewMessage(message.Text, newUserHandler), -1)
}
// Start is the main function to start the bot.
func Start(botConfig config.Config) {
var createBotErr error
bot, createBotErr = gotgbot.NewBot(botConfig.BotToken, &gotgbot.BotOpts{
Client: http.Client{},
})
if createBotErr != nil {
log.Println(botConfig)
log.Fatalln("Something wrong:", createBotErr)
}
dispatcher := ext.NewDispatcher(&ext.DispatcherOpts{
Error: func(_ *gotgbot.Bot, ctx *ext.Context, err error) ext.DispatcherAction {
log.Println("an error occurred while handling update:", err.Error())
return ext.DispatcherActionNoop
},
})
updater := ext.NewUpdater(&ext.UpdaterOpts{
ErrorLog: nil,
Dispatcher: dispatcher,
})
addMessageHandlers(updater.Dispatcher)
setCommands()
if botConfig.Webhook.Enabled {
parsedURL, parseErr := url.Parse(botConfig.Webhook.URL)
if parseErr != nil {
log.Fatalln("Can't parse webhook url:", parseErr)
}
log.Printf("Starting webhook on '%s:%d%s'...\n", botConfig.Webhook.ListenIP, botConfig.Webhook.ListenPort, botConfig.Webhook.ListenPath)
// TODO add support for custom certificates
startErr := updater.StartWebhook(bot, parsedURL.Path, ext.WebhookOpts{
ListenAddr: fmt.Sprintf("%s:%d", botConfig.Webhook.ListenIP, botConfig.Webhook.ListenPort),
})
if startErr != nil {
panic("failed to start webhook: " + startErr.Error())
}
_, setWebhookErr := bot.SetWebhook(botConfig.Webhook.URL, &gotgbot.SetWebhookOpts{})
if setWebhookErr != nil {
panic("failed to set webhook: " + setWebhookErr.Error())
}
} else {
log.Println("Start polling...")
_, _ = bot.DeleteWebhook(nil)
err := updater.StartPolling(bot, &ext.PollingOpts{DropPendingUpdates: false})
if err != nil {
panic("failed to start polling: " + err.Error())
}
}
log.Printf("Bot has been started as @%s...\n", bot.User.Username)
if botConfig.Prometheus.Enabled {
// Periodically update the metrics from the database
go func() {
for {
prometheus.TotalUniquePriceagentsValue = database.GetPriceAgentCount()
prometheus.TotalUniqueUsersValue = database.GetUserCount()
prometheus.TotalUniqueWishlistPriceagentsValue = database.GetPriceAgentWishlistCount()
prometheus.TotalUniqueProductPriceagentsValue = database.GetPriceAgentProductCount()
time.Sleep(time.Second * 60)
}
}()
exportAddr := fmt.Sprintf("%s:%d", botConfig.Prometheus.ExportIP, botConfig.Prometheus.ExportPort)
log.Printf("Starting prometheus exporter on %s...\n", exportAddr)
err := prometheus.StartPrometheusExporter(exportAddr)
if err != nil {
panic("failed to start prometheus exporter: " + err.Error())
}
}
updater.Idle()
}
func parseMenuPriceagent(ctx *ext.Context) (models.Menu, models.PriceAgent, error) {
menu, parseMenuErr := models.NewMenu(ctx.CallbackQuery.Data)
if parseMenuErr != nil {
return models.Menu{}, models.PriceAgent{}, fmt.Errorf("invalid callback data: %s", ctx.CallbackQuery.Data)
}
priceAgent, dbErr := database.GetPriceagentForUserByID(ctx.EffectiveUser.Id, menu.PriceAgentID)
if dbErr != nil {
return models.Menu{}, models.PriceAgent{}, fmt.Errorf("invalid callback data: %s", ctx.CallbackQuery.Data)
}
return *menu, priceAgent, nil
}