go-dette/rss.go

89 lines
2.0 KiB
Go

package main
import (
"context"
"fmt"
"log"
"time"
"git.nefrace.ru/nefrace/nechotron"
"git.nefrace.ru/nefrace/tongo"
"github.com/NicoNex/echotron/v3"
"github.com/mmcdole/gofeed"
)
var text_template = `
[*%s*](%s)
_%s_
%s
`
func RSSTask(api *echotron.API) {
for {
ParseRSS(api)
time.Sleep(20 * time.Minute)
}
}
func ParseRSS(api *echotron.API) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
feedChats := tongo.NewStore[FeedChat](db)
feeds := tongo.NewStore[Feeds](db)
lastFeed, err := feeds.GetOne(ctx)
if err != nil || lastFeed == nil {
lastFeed = &Feeds{
Item: tongo.NewID(),
}
feeds.ReplaceItem(ctx, *lastFeed, true)
}
fp := gofeed.NewParser()
feed, err := fp.ParseURL("https://godotengine.org/rss.xml")
if err != nil {
log.Println("Can't get feed: ", err)
return
}
item := feed.Items[0]
if lastFeed.Published.Compare(*item.PublishedParsed) == -1 {
chats, _ := feedChats.GetMany(ctx)
if len(chats) == 0 {
return
}
title := item.Title
author := "by " + item.Author.Name
desc := item.Description
translator := InitTranslator()
translates, err := translator.Translate("ru", item.Title, item.Description)
if err == nil {
title = translates[0]
desc = translates[1]
}
text := fmt.Sprintf(text_template,
nechotron.EscapeMd2(title),
item.Link,
nechotron.EscapeMd2(author),
nechotron.EscapeMd2(desc),
)
sent := false
for _, chat := range chats {
res, err := api.SendPhoto(echotron.NewInputFileURL(item.Custom["image"]), chat.ChatID, nechotron.NewOptions().MarkdownV2().Caption(text).PhotoOptions())
if err != nil {
log.Println("Can't send message to", chat.Title, ": ", err)
if res.ErrorCode == 403 {
feedChats.DeleteByID(ctx, chat.Id)
}
} else {
sent = true
}
time.Sleep(1 * time.Second)
}
if !sent {
return
}
lastFeed.Published = *item.PublishedParsed
lastFeed.Title = item.Title
feeds.ReplaceItem(ctx, *lastFeed, true)
}
}