/
main.go
73 lines (58 loc) · 1.17 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
package main
import (
"context"
"flag"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
"log"
"os"
"os/signal"
"strings"
"syscall"
)
var (
token = flag.String("token", "", "Telegram Bot Token")
)
func main() {
flag.Parse()
*token = strings.TrimSpace(*token)
if *token == "" {
log.Printf("error: empty token")
os.Exit(1)
}
bot, err := tgbotapi.NewBotAPI(*token)
if err != nil {
log.Printf("error: error create bot: %v", err)
os.Exit(1)
}
updateConfig := tgbotapi.UpdateConfig{
Offset: 0,
Limit: 0,
Timeout: 0,
}
ch, err := bot.GetUpdatesChan(updateConfig)
if err != nil {
log.Printf("error: get updates channel: %v", err)
os.Exit(1)
}
ctx, ctxCancel := context.WithCancel(context.Background())
go listen(ctx, ch)
stop := make(chan os.Signal, 1)
signal.Notify(stop, syscall.SIGTERM)
signal.Notify(stop, syscall.SIGINT)
<-stop
ctxCancel()
log.Printf("bye")
}
func listen(ctx context.Context, ch tgbotapi.UpdatesChannel) {
for {
select {
case <-ctx.Done():
return
case mes := <-ch:
if mes.Message == nil {
continue
}
log.Printf("Text '%s' in ChatID %d", mes.Message.Text, mes.Message.Chat.ID)
}
}
}