]> git.jsancho.org Git - midgaard_bot.git/blob - midgaard_bot.go
Managing sessions functionality
[midgaard_bot.git] / midgaard_bot.go
1 package main
2
3 import (
4         "context"
5         "log"
6
7         "github.com/go-telegram-bot-api/telegram-bot-api"
8         "github.com/jessevdk/go-flags"
9 )
10
11 var config struct {
12         Token string `short:"t" long:"token" description:"Telegram API Token" required:"true"`
13 }
14
15 func recv_task(bot *tgbotapi.BotAPI, sendChannel chan tgbotapi.Chattable, ctx context.Context) {
16         u := tgbotapi.NewUpdate(0)
17         u.Timeout = 60
18
19         updates, _ := bot.GetUpdatesChan(u)
20
21         for {
22                 select {
23                 case update := <-updates:
24                         log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text)
25
26                         msg := tgbotapi.NewMessage(update.Message.Chat.ID, update.Message.Text)
27                         msg.ReplyToMessageID = update.Message.MessageID
28                         sendChannel <- msg
29                 case <-ctx.Done():
30                         return
31                 }
32         }
33 }
34
35 func send_task(bot *tgbotapi.BotAPI, sendChannel chan tgbotapi.Chattable, ctx context.Context) {
36         for {
37                 select {
38                 case msg := <-sendChannel:
39                         bot.Send(msg)
40                 case <-ctx.Done():
41                         return
42                 }
43         }
44 }
45
46 func main() {
47         _, err := flags.Parse(&config)
48         if err != nil {
49                 log.Panic(err)
50         }
51
52         bot, err := tgbotapi.NewBotAPI(config.Token)
53         if err != nil {
54                 log.Panic(err)
55         }
56
57         bot.Debug = true
58
59         log.Printf("Authorized on account %s", bot.Self.UserName)
60
61         ctx, cancel := context.WithCancel(context.Background())
62         sendChannel := make(chan tgbotapi.Chattable)
63         go send_task(bot, sendChannel, ctx)
64         recv_task(bot, sendChannel, ctx)
65         cancel()
66 }