package main import ( "context" "fmt" "strings" "text/template" "git.milar.in/milarin/adverr" "git.milar.in/milarin/anilist" "git.milar.in/milarin/channel" "git.milar.in/milarin/slices" "git.milar.in/nyaanime/logic" "git.milar.in/nyaanime/model" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api" ) var TelegramBot *tgbotapi.BotAPI func InitTelegramBot() error { if TelegramBotToken != "" && TelegramChatID != 0 { bot, err := tgbotapi.NewBotAPI(TelegramBotToken) if err != nil { return err } TelegramBot = bot } return nil } func SendTelegramMessage(text string) { if TelegramBot == nil { return } msg := tgbotapi.NewMessage(TelegramChatID, text) _, err := TelegramBot.Send(msg) if err != nil { adverr.Println(adverr.Wrap("could not send telegram message", err)) } } func SendTelegramAnimeEpMessage(messagePattern *template.Template, animeEp model.AnimeEpisode) { shouldSendMessage, err := CheckSendConditions(animeEp) if err != nil { adverr.Println(adverr.Wrap("could not check telegram message send conditions", err)) } fmt.Println("shouldSendMessage:", shouldSendMessage) if !shouldSendMessage { fmt.Println("do not send message") return } fmt.Println("send message") b := new(strings.Builder) if err := messagePattern.Execute(b, []model.AnimeEpisode{animeEp}); err != nil { adverr.Println(adverr.Wrap("could not send telegram message", err)) } SendTelegramMessage(b.String()) } func CheckSendConditions(animeEp model.AnimeEpisode) (bool, error) { listEntry, err := GetListEntry(animeEp.Anime) if err != nil { return false, err } fmt.Println("listEntry:", listEntry) for _, sendCondition := range AllSendConditions { // check if user configured current sendCondition if !slices.Contains(TelegramOrganizeMessageSendCondition, sendCondition) { fmt.Println("condition not configured", sendCondition) continue } // check if current sendCondition applies for given anime episode if sendCondition.ShouldSend(animeEp, listEntry) { fmt.Println("condition applies", sendCondition) return true, nil } fmt.Println("condition does not apply", sendCondition) } fmt.Println("no condition applies") return false, nil } func GetListEntry(anime *anilist.Media) (*anilist.MediaList, error) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() listEntries, err := logic.GetCurrentlyWatchingAnimesContext(ctx, logic.AllMediaListStatuses...) if err != nil { return nil, err } filteredListEntries := channel.Filter(listEntries, func(a *anilist.MediaList) bool { return a.MediaID == anime.ID }) listEntry := channel.FindFirstAndCancelFlush(filteredListEntries, cancel) // TODO flush working properly? if listEntry == nil { return nil, nil } return *listEntry, nil }