2023-04-28 15:34:26 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
"net/http"
|
2023-04-28 16:24:02 +00:00
|
|
|
"net/url"
|
2023-04-28 15:34:26 +00:00
|
|
|
|
2023-04-28 16:24:02 +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")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-28 16:24:02 +00:00
|
|
|
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))
|
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)
|
2023-04-28 16:24:02 +00:00
|
|
|
return err
|
2023-04-28 15:34:26 +00:00
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
log.Printf("GET %s: %d\n", url, resp.StatusCode)
|
2023-04-28 16:24:02 +00:00
|
|
|
return nil
|
2023-04-28 15:34:26 +00:00
|
|
|
}
|