-
-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathmain.go
More file actions
79 lines (63 loc) · 1.69 KB
/
Copy pathmain.go
File metadata and controls
79 lines (63 loc) · 1.69 KB
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
package main
import (
"context"
"fmt"
"os"
"os/signal"
"time"
"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)
}
// Initialize signal handling
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
defer cancel()
// Get updates
updates, _ := bot.UpdatesViaLongPolling(ctx, nil)
// Create bot handler with stop timeout
bh, _ := th.NewBotHandler(bot, updates)
// Handle updates
bh.Handle(func(ctx *th.Context, update telego.Update) error {
fmt.Println("Processing update:", update.UpdateID)
time.Sleep(time.Second * 15) // Simulate long process time
fmt.Println("Done update:", update.UpdateID)
return nil
})
// Initialize done chan
done := make(chan struct{}, 1)
// Handle stop signal (Ctrl+C)
go func() {
// Wait for stop signal
<-ctx.Done()
fmt.Println("Stopping...")
stopCtx, stopCancel := context.WithTimeout(context.Background(), time.Second*20)
defer stopCancel()
loop:
for len(updates) > 0 {
select {
case <-stopCtx.Done():
break loop
case <-time.After(time.Microsecond * 100):
// Continue
}
}
fmt.Println("Long polling done")
_ = bh.StopWithContext(stopCtx)
fmt.Println("Bot handler done")
// Notify that stop is done
done <- struct{}{}
}()
// Start handling in goroutine
go func() { _ = bh.Start() }()
fmt.Println("Handling updates...")
// Wait for the stop process to be completed
<-done
fmt.Println("Done")
}