-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
69 lines (56 loc) · 1.43 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
package main
import (
"context"
"encoding/json"
"net/http"
"os"
"github.com/kbgod/lumex"
"github.com/kbgod/lumex/router"
)
type handler struct {
botRouter *router.Router
bots map[string]*lumex.Bot
}
// webhookHandler for different bots
// Possible to use mini_app/bot builders
func (h *handler) webhookHandler(rw http.ResponseWriter, req *http.Request) {
upd := &lumex.Update{}
err := json.NewDecoder(req.Body).Decode(upd)
if err != nil {
http.Error(rw, "failed to decode request body", http.StatusBadRequest)
return
}
defer req.Body.Close()
// inject bot to context
ctx := context.WithValue(req.Context(), router.BotContextKey, h.bots["bot"])
if err := h.botRouter.HandleUpdate(ctx, upd); err != nil {
http.Error(rw, "failed to handle update", http.StatusInternalServerError)
return
}
}
func main() {
bot, err := lumex.NewBot(os.Getenv("BOT_TOKEN"), nil)
if err != nil {
panic(err)
}
if ok, err := bot.SetWebhook(os.Getenv("WEBHOOK_URL"), nil); err != nil || !ok {
panic(err)
}
h := &handler{
botRouter: makeRouter(),
bots: map[string]*lumex.Bot{"bot": bot},
}
http.HandleFunc("/webhook", h.webhookHandler)
if err := http.ListenAndServe(":8080", nil); err != nil {
panic(err)
}
}
// makeRouter for different bots
// router doesn't have passed bot
func makeRouter() *router.Router {
r := router.New(nil)
r.OnStart(func(ctx *router.Context) error {
return ctx.ReplyVoid("Hello, world!")
})
return r
}