-
Notifications
You must be signed in to change notification settings - Fork 5
/
session_example_test.go
80 lines (66 loc) · 1.55 KB
/
session_example_test.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
package tgbot_test
import (
"context"
"flag"
"log"
"os"
tgbot "github.com/olebedev/go-tgbot"
"github.com/olebedev/go-tgbot/client/messages"
"github.com/olebedev/go-tgbot/models"
"app" // you application
)
type Session struct {
User *app.User
Billing *app.UserBillingInfo
}
func ExampleNew_session() {
token := flag.String("token", "", "telegram bot token")
flag.Parse()
r := tgbot.New(context.Background(), *token)
// setup global middleware
r.Use(tgbot.Recover)
r.Use(tgbot.Logger(os.Stdout))
r.Use(func(c *tgbot.Context) error {
s, err := app.GetSession(c.From)
if err != nil {
return nil, err
}
c.Set("session", s)
if !s.Billing.Active {
c.Path = "/pay_first~" + c.Path
}
err = c.Next()
if err != nil {
return err
}
// finalize session if needed
})
// Bind handlers
// middleware for users who have not paid
r.Bind(`^/pay_first~.*`, func(c *tgbot.Context) error {
s := c.MustGet("session").(*Session)
// business logic
return r.Route(c.Update)
})
r.Bind(`^/message/-/private/text/start\sstart$`, func(c *tgbot.Context) error {
log.Println(c.Update.Message.Text)
// send greeting message back
message := "hi there what's up"
resp, err := r.Messages.SendMessage(
messages.NewSendMessageParams().WithBody(&models.SendMessageBody{
Text: &message,
ChatID: c.Update.Message.Chat.ID,
}),
)
if err != nil {
return err
}
if resp != nil {
log.Println(resp.Payload.MessageID)
}
return nil
})
if err := r.Poll(ctx, models.AllowedUpdateMessage); err != nil {
log.Fatal(err)
}
}