-
-
Notifications
You must be signed in to change notification settings - Fork 42
/
main.go
85 lines (66 loc) · 1.8 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package main
import (
"context"
"crypto/sha256"
"encoding/hex"
"log"
"os"
"os/signal"
"time"
"github.com/mymmrac/telego"
th "github.com/mymmrac/telego/telegohandler"
tu "github.com/mymmrac/telego/telegoutil"
)
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 {
log.Fatalf("Create bot: %s", err)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Note: Creating a secret token like this is not secure,
// but at least better than having a plain bot token as is in requests
secretBytes := sha256.Sum256([]byte(botToken))
secret := hex.EncodeToString(secretBytes[:])
srv, url := Webhook(ctx, bot, secret)
updates, err := bot.UpdatesViaWebhook(
"/bot",
telego.WithWebhookServer(srv),
telego.WithWebhookSet(tu.Webhook(url+"/bot").WithSecretToken(secret)),
)
if err != nil {
log.Fatalf("Updates via webhoo: %s", err)
}
bh, err := th.NewBotHandler(bot, updates)
if err != nil {
log.Fatalf("Bot handler: %s", err)
}
RegisterHandlers(bh)
done := make(chan struct{}, 1)
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, os.Interrupt)
go func() {
<-sigs
log.Println("Stopping...")
stopCtx, stopCancel := context.WithTimeout(context.Background(), time.Second*10)
defer stopCancel()
err = bot.StopWebhookWithContext(stopCtx)
if err != nil {
log.Println("Failed to stop webhook properly:", err)
}
bh.StopWithContext(stopCtx)
done <- struct{}{}
}()
go bh.Start()
log.Println("Handling updates...")
go func() {
err = bot.StartWebhook(":443")
if err != nil {
log.Fatalf("Failed to start webhook: %s", err)
}
}()
<-done
log.Println("Done")
}