Skip to content

Instantly share code, notes, and snippets.

@rikkix
Created December 28, 2022 11:41
Show Gist options
  • Save rikkix/9516dc34a6b1cbe3481160ca32a6c1ca to your computer and use it in GitHub Desktop.
Save rikkix/9516dc34a6b1cbe3481160ca32a6c1ca to your computer and use it in GitHub Desktop.
convert Telegram Channel to RSS Feed
/*
MIT License
Copyright (c) 2020 Richard Chen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package trss
import (
"fmt"
"net/http"
"time"
"github.com/PuerkitoBio/goquery"
"github.com/gorilla/feeds"
)
// GenerateRSS generates RSS feed from given channel name
// NOTE: arg [name] must NOT contain an "@"
func GenerateRSS(name string) (feeds.Rss, error) {
link := fmt.Sprintf("https://t.me/s/%s", name)
rss := feeds.Rss{
Feed: &feeds.Feed{
Link: &feeds.Link{
Href: link,
},
},
}
resp, err := http.Get(link)
if err != nil {
return feeds.Rss{}, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return feeds.Rss{}, fmt.Errorf("status code error: %d %s", resp.StatusCode, resp.Status)
}
document, err := goquery.NewDocumentFromReader(resp.Body)
if err != nil {
return feeds.Rss{}, err
}
title, err := document.Find(".tgme_header_title").Html()
if err != nil {
return feeds.Rss{}, err
}
rss.Feed.Title = title
document.Find(".js-widget_message").
Each(func(i int, selection *goquery.Selection) {
item := &feeds.Item{}
dateSec := selection.Find(".tgme_widget_message_date")
link, _ := dateSec.Attr("href")
item.Link = &feeds.Link{
Href: link,
}
datetime, _ := dateSec.Find("time").Attr("datetime")
item.Created, err = time.Parse(time.RFC3339, datetime)
if err != nil {
return
}
text, err := selection.Find(".js-message_text").Html()
if err != nil {
return
}
item.Content = text
rss.Add(item)
})
return rss, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment