-
-
Notifications
You must be signed in to change notification settings - Fork 42
/
main.go
63 lines (48 loc) · 1.38 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
package main
import (
"context"
"fmt"
"os"
"github.com/mymmrac/telego"
th "github.com/mymmrac/telego/telegohandler"
)
func main() {
botToken := os.Getenv("TOKEN")
// Note: Please keep in mind that default logger may expose sensitive information, use in development only
bot, err := telego.NewBot(botToken, telego.WithDefaultDebugLogger())
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// Get updates channel
updates, _ := bot.UpdatesViaLongPolling(nil)
// Create bot handler and specify from where to get updates
bh, _ := th.NewBotHandler(bot, updates)
// Stop handling updates
defer bh.Stop()
// Stop getting updates
defer bot.StopLongPolling()
// Define a context key
type userID bool
var userIDKey userID
// Apply middleware that will retrieve user ID from update
bh.Use(func(bot *telego.Bot, update telego.Update, next th.Handler) {
// Get initial context
ctx := update.Context()
if update.Message != nil && update.Message.From != nil {
// Set user ID in context
ctx = context.WithValue(ctx, userIDKey, update.Message.From.ID)
}
// Update context
update = update.WithContext(ctx)
next(bot, update)
})
// Handle messages
bh.Handle(func(bot *telego.Bot, update telego.Update) {
ctx := update.Context()
// Retrieve user ID from context
fmt.Println("User ID:", ctx.Value(userIDKey))
}, th.AnyMessage())
// Start handling updates
bh.Start()
}