]> git.jsancho.org Git - midgaard_bot.git/blob - telegram.go
3ae6a3ddf50302b0aac9d53fc0dbb3220b6c56b6
[midgaard_bot.git] / telegram.go
1 package main
2
3 import (
4         "context"
5         "log"
6
7         "github.com/go-telegram-bot-api/telegram-bot-api"
8 )
9
10 var sendChannel chan tgbotapi.Chattable
11
12 func initTelegramWorkers(token string, ctx context.Context) error {
13         bot, err := tgbotapi.NewBotAPI(token)
14         if err != nil {
15                 return err
16         }
17
18         bot.Debug = true
19
20         log.Printf("Authorized on account %s", bot.Self.UserName)
21
22         sendChannel = make(chan tgbotapi.Chattable)
23         go sendWorker(bot, sendChannel, ctx)
24         go recvWorker(bot, ctx)
25
26         return nil
27 }
28         
29 func recvWorker(bot *tgbotapi.BotAPI, ctx context.Context) {
30         u := tgbotapi.NewUpdate(0)
31         u.Timeout = 60
32
33         updates, _ := bot.GetUpdatesChan(u)
34
35         for {
36                 select {
37                 case update := <-updates:
38                         session := getSession(update.Message.Chat)
39                         sendToSession(session, update.Message)
40                 case <-ctx.Done():
41                         return
42                 }
43         }
44 }
45
46 func sendWorker(bot *tgbotapi.BotAPI, sendChannel chan tgbotapi.Chattable, ctx context.Context) {
47         for {
48                 select {
49                 case msg := <-sendChannel:
50                         bot.Send(msg)
51                 case <-ctx.Done():
52                         return
53                 }
54         }
55 }
56
57 func sendToTelegram(message tgbotapi.Chattable) {
58         sendChannel <- message
59 }