go_telegram/pkg/service/telegram/telegram.go

86 lines
2.0 KiB
Go
Raw Normal View History

2020-05-17 06:25:29 +00:00
package telegram
import (
"log"
"strings"
2020-05-17 06:25:29 +00:00
"time"
"github.com/mattburchett/go_telegram/pkg/core/config"
"github.com/yanzay/tbot/v2"
)
// Bot contains all the necessary bot and callback information.
type Bot struct {
Client *tbot.Client
Config config.Config
Bot *tbot.Server
CallbackChatID string
CallbackMessageID int
}
// Stat middleware.
func stat(h tbot.UpdateHandler) tbot.UpdateHandler {
return func(u *tbot.Update) {
start := time.Now()
h(u)
log.Printf("Handle time: %v", time.Now().Sub(start))
}
}
2020-05-17 06:25:29 +00:00
// New creates an active telegram bot and loads the handlers.
func (tb *Bot) New(token string) {
tb.Bot = tbot.New(token)
tb.Bot.Use(stat)
tb.Client = tb.Bot.Client()
tb.Handler()
tb.Bot.Start()
}
// Handler creates the active Telegram handlers.
func (tb *Bot) Handler() {
// Bot Healthcheck
tb.Bot.HandleMessage("/ping", func(m *tbot.Message) {
tb.Client.SendMessage(m.Chat.ID, "pong")
})
// telegram/sonar.go
tb.Bot.HandleMessage("/s", tb.sonarrSearch)
2020-05-17 06:25:29 +00:00
tb.Bot.HandleMessage("/admin sonarrStatus", tb.sonarrStatus)
// telegram/testhandler.go
tb.Bot.HandleMessage("/test", tb.testHandler)
// telegram/admin.go
tb.Bot.HandleMessage("/admin myID", tb.myID)
tb.Bot.HandleMessage("/admin chatID", tb.chatID)
2020-05-17 06:28:21 +00:00
// Help
2020-05-17 06:31:17 +00:00
tb.Bot.HandleMessage("/help$", tb.helpHandler)
tb.Bot.HandleMessage("/h$", tb.helpHandler)
2020-05-17 06:28:21 +00:00
2020-05-17 06:25:29 +00:00
// Callback Handler
tb.Bot.HandleCallback(tb.callbackHandler)
}
// callbackHandler handles callbacks.
func (tb *Bot) callbackHandler(cq *tbot.CallbackQuery) {
go func() {
tb.Client.AnswerCallbackQuery(cq.ID, tbot.OptText("Request received."))
tb.Client.DeleteMessage(tb.CallbackChatID, tb.CallbackMessageID)
}()
if strings.Contains(cq.Data, "tv_") {
tb.sonarrAdd(cq)
return
}
2020-05-17 06:25:29 +00:00
tb.Client.SendMessage(tb.CallbackChatID, cq.Data)
2020-05-17 06:25:29 +00:00
}
2020-05-17 06:31:17 +00:00
func (tb *Bot) helpHandler(m *tbot.Message) {
tb.Client.SendMessage(m.Chat.ID, "USAGE:\n\n/movie <Movie Name> or /m <Movie Name>\n/show <TV Show Name> or /s <TV Show Name>\n\nEXAMPLES:\n\n/s The Walking Dead\n/m Avatar")
}