100 lines
2.2 KiB
Go
100 lines
2.2 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/xml"
|
|
"errors"
|
|
"flag"
|
|
"fmt"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/hamcha/clessy/tg"
|
|
)
|
|
|
|
func assert(err error) {
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
}
|
|
|
|
var chatID *int
|
|
var lastPage string
|
|
var broker *tg.Broker
|
|
var apichat *tg.APIChat
|
|
|
|
const mspaRSS = "http://mspaintadventures.com/rss/rss.xml"
|
|
const timelayout = "Mon, 2 Jan 2006 15:04:05 -0700"
|
|
|
|
type Item struct {
|
|
Title string `xml:"title"`
|
|
Link string `xml:"link"`
|
|
Date string `xml:"pubDate"`
|
|
}
|
|
|
|
type RSS struct {
|
|
Items []Item `xml:"channel>item"`
|
|
}
|
|
|
|
func process(b *tg.Broker, update tg.APIMessage) {
|
|
if update.Chat.ChatID == *chatID && *(update.Text) == "!start" {
|
|
broker = b
|
|
apichat = update.Chat
|
|
broker.SendTextMessage(apichat, "Ok! Aspetto updates..", &update.MessageID)
|
|
}
|
|
}
|
|
|
|
func advert(page Item) {
|
|
date, _ := time.Parse(timelayout, page.Date)
|
|
dateStr := date.Format("15:04:05")
|
|
parts := strings.Split(page.Link, "p=")
|
|
pagen := strings.Trim(parts[1], "0")
|
|
text := "<b>Nuova pagina uscita!</b>\n\n#" + pagen + " - " + dateStr + "\n" + page.Title + "\n\n<a href=\"" + page.Link + "\">Clicca qui per leggerla</a>"
|
|
broker.SendTextMessage(apichat, text, nil)
|
|
}
|
|
|
|
func startPolling(delay int64) {
|
|
panicFn := func(err error) {
|
|
broker.SendTextMessage(apichat, "Errore cercando di leggere l'RSS! @HAMCHA LEGGI LA CONSOLE!", nil)
|
|
panic(err)
|
|
}
|
|
for broker == nil {
|
|
// Wait for broker
|
|
time.Sleep(time.Second)
|
|
}
|
|
for {
|
|
resp, err := http.Get(mspaRSS)
|
|
if err != nil {
|
|
panicFn(err)
|
|
}
|
|
var out RSS
|
|
err = xml.NewDecoder(resp.Body).Decode(&out)
|
|
if err != nil {
|
|
panicFn(err)
|
|
}
|
|
if len(out.Items) < 1 {
|
|
panicFn(errors.New("0 items in the RSS Feed?"))
|
|
}
|
|
if out.Items[0].Link != lastPage {
|
|
fmt.Println("Got new page: " + out.Items[0].Link)
|
|
if lastPage != "" {
|
|
advert(out.Items[0])
|
|
}
|
|
lastPage = out.Items[0].Link
|
|
}
|
|
time.Sleep(time.Second * time.Duration(delay))
|
|
}
|
|
}
|
|
|
|
func main() {
|
|
brokerAddr := flag.String("broker", "localhost:7314", "Broker address:port")
|
|
delay := flag.Int64("delau", 5*60, "How many seconds between each poll")
|
|
chatID = flag.Int("chatid", -68373985, "Telegram Chat ID to count stats for")
|
|
flag.Parse()
|
|
lastPage = ""
|
|
|
|
go startPolling(*delay)
|
|
|
|
err := tg.CreateBrokerClient(*brokerAddr, process)
|
|
assert(err)
|
|
}
|