bot.go 1.6 KB

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