rss_habrbot.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package main
  2. import (
  3. "encoding/xml"
  4. "fmt"
  5. "io/ioutil"
  6. _ "log"
  7. "net/http"
  8. tgbotapi "gopkg.in/telegram-bot-api.v4"
  9. // "github.com/technoweenie/multipartstreamer.go"
  10. )
  11. const (
  12. BotToken = "5630535837:AAGE1huAvwq2FRtlPh2iHVcL0zjznMXWjiY"
  13. WebhookURL = "https://2881-178-204-109-137.eu.ngrok.io"
  14. )
  15. var rss = map[string]string{
  16. "Habr": "https://habrahabr.ru/rss/best/",
  17. }
  18. type RSS struct {
  19. Items []Item `xml:"channel>item"`
  20. }
  21. type Item struct {
  22. URL string `xml:"guid"`
  23. Title string `xml:"title"`
  24. }
  25. func getNews(url string) (*RSS, error) {
  26. resp, err := http.Get(url)
  27. if err != nil {
  28. return nil, err
  29. }
  30. defer resp.Body.Close()
  31. body, _ := ioutil.ReadAll(resp.Body)
  32. rss := new(RSS)
  33. err = xml.Unmarshal(body, rss)
  34. if err != nil {
  35. return nil, err
  36. }
  37. return rss, nil
  38. }
  39. func main() {
  40. bot, err := tgbotapi.NewBotAPI(BotToken)
  41. if err != nil {
  42. panic(err)
  43. }
  44. // bot.Debug = true
  45. fmt.Printf("Authorized on account %s\n", bot.Self.UserName)
  46. _, err = bot.SetWebhook(tgbotapi.NewWebhook(WebhookURL))
  47. if err != nil {
  48. panic(err)
  49. }
  50. updates := bot.ListenForWebhook("/")
  51. go http.ListenAndServe(":8080", nil)
  52. fmt.Println("start listen :8080")
  53. // получаем все обновления из канала updates
  54. for update := range updates {
  55. if url, ok := rss[update.Message.Text]; ok {
  56. rss, err := getNews(url)
  57. if err != nil {
  58. bot.Send(tgbotapi.NewMessage(
  59. update.Message.Chat.ID,
  60. "sorry, error happend",
  61. ))
  62. }
  63. for _, item := range rss.Items {
  64. bot.Send(tgbotapi.NewMessage(
  65. update.Message.Chat.ID,
  66. item.URL+"\n"+item.Title,
  67. ))
  68. }
  69. } else {
  70. bot.Send(tgbotapi.NewMessage(
  71. update.Message.Chat.ID,
  72. `I am Ilshat. There is only Habr feed availible`,
  73. ))
  74. }
  75. }
  76. }