sn-rss2tg/tg.go

56 lines
1.4 KiB
Go
Raw Normal View History

2023-04-28 15:34:26 +00:00
package main
import (
"fmt"
"log"
"net/http"
"net/url"
2023-04-28 15:34:26 +00:00
"github.com/dustin/go-humanize"
2023-04-28 15:34:26 +00:00
"github.com/joho/godotenv"
"github.com/namsral/flag"
)
var (
ChatId int
BotToken string
)
func init() {
err := godotenv.Load()
if err != nil {
log.Fatal("error loading .env file")
}
flag.IntVar(&ChatId, "TELEGRAM_CHAT_ID", 0, "Chat id of telegram channel")
flag.StringVar(&BotToken, "TELEGRAM_BOT_TOKEN", "", "Telegram bot token")
flag.Parse()
if ChatId == 0 {
log.Fatal("TELEGRAM_CHAT_ID not set")
}
if BotToken == "" {
log.Fatal("TELEGRAM_BOT_TOKEN not set")
}
}
func SendItemToTelegram(item *Item) error {
2023-08-22 01:35:15 +00:00
text := fmt.Sprintf("%s\n_%s by_ [%s](https://stacker.news/%s)\n", item.Title, humanize.Time(item.PubDate.Time), item.Author.Name, item.Author.Name)
linkItem := item.Link != item.Guid
if linkItem {
text += fmt.Sprintf("[Link](%s) ", item.Link)
}
text += fmt.Sprintf("[Comments](%s)", item.Guid)
return SendTextToTelegram(text)
}
func SendTextToTelegram(text string) error {
url := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage?parse_mode=markdown&disable_web_page_preview=true&chat_id=%d&text=%s", BotToken, ChatId, url.QueryEscape(text))
2023-04-28 15:34:26 +00:00
resp, err := http.Get(url)
if err != nil {
err = fmt.Errorf("error during GET %s: %w", url, err)
return err
2023-04-28 15:34:26 +00:00
}
defer resp.Body.Close()
log.Printf("GET %s: %d\n", url, resp.StatusCode)
return nil
2023-04-28 15:34:26 +00:00
}