X-Git-Url: https://git.jsancho.org/?p=midgaard_bot.git;a=blobdiff_plain;f=telegram.go;fp=telegram.go;h=3ae6a3ddf50302b0aac9d53fc0dbb3220b6c56b6;hp=0000000000000000000000000000000000000000;hb=54d3318115d6fd32364f5993ff67d0461c162aef;hpb=287bb6b379833a10a1eca80a5fbe52422e345c76 diff --git a/telegram.go b/telegram.go new file mode 100644 index 0000000..3ae6a3d --- /dev/null +++ b/telegram.go @@ -0,0 +1,59 @@ +package main + +import ( + "context" + "log" + + "github.com/go-telegram-bot-api/telegram-bot-api" +) + +var sendChannel chan tgbotapi.Chattable + +func initTelegramWorkers(token string, ctx context.Context) error { + bot, err := tgbotapi.NewBotAPI(token) + if err != nil { + return err + } + + bot.Debug = true + + log.Printf("Authorized on account %s", bot.Self.UserName) + + sendChannel = make(chan tgbotapi.Chattable) + go sendWorker(bot, sendChannel, ctx) + go recvWorker(bot, ctx) + + return nil +} + +func recvWorker(bot *tgbotapi.BotAPI, ctx context.Context) { + u := tgbotapi.NewUpdate(0) + u.Timeout = 60 + + updates, _ := bot.GetUpdatesChan(u) + + for { + select { + case update := <-updates: + session := getSession(update.Message.Chat) + sendToSession(session, update.Message) + case <-ctx.Done(): + return + } + } +} + +func sendWorker(bot *tgbotapi.BotAPI, sendChannel chan tgbotapi.Chattable, ctx context.Context) { + for { + select { + case msg := <-sendChannel: + bot.Send(msg) + case <-ctx.Done(): + return + } + } +} + +func sendToTelegram(message tgbotapi.Chattable) { + sendChannel <- message +}