diff --git a/mspa/main.go b/mspa/main.go new file mode 100644 index 0000000..65a7750 --- /dev/null +++ b/mspa/main.go @@ -0,0 +1,100 @@ +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 := "Nuova pagina uscita!\n\n#" + pagen + " - " + dateStr + "\n" + page.Title + "\n\nClicca qui per leggerla" + 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) +}