sn-rss2tg/tg.go

56 lines
1.3 KiB
Go

package main
import (
"fmt"
"log"
"net/http"
"net/url"
"github.com/dustin/go-humanize"
"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 {
text := fmt.Sprintf("%s (%s)\n", item.Title, humanize.Time(item.PubDate.Time))
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))
resp, err := http.Get(url)
if err != nil {
err = fmt.Errorf("error during GET %s: %w", url, err)
return err
}
defer resp.Body.Close()
log.Printf("GET %s: %d\n", url, resp.StatusCode)
return nil
}