go-dette/rss.go

77 lines
1.7 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)
_by %s_
%s
`
func RSSTask(api *echotron.API) {
for {
ParseRSS(api)
time.Sleep(5 * 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
}
text := fmt.Sprintf(text_template,
nechotron.EscapeMd2(item.Title),
item.Link,
nechotron.EscapeMd2(item.Authors[0].Name),
nechotron.EscapeMd2(item.Description),
)
sent := false
for _, chat := range chats {
_, 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)
} else {
sent = true
}
time.Sleep(1 * time.Second)
}
if !sent {
return
}
lastFeed.Published = *item.PublishedParsed
lastFeed.Title = item.Title
feeds.ReplaceItem(ctx, *lastFeed, true)
}
}