GoBlog/telegram.go

84 lines
2.1 KiB
Go
Raw Normal View History

2020-11-09 18:54:06 +00:00
package main
import (
"bytes"
"errors"
2021-02-08 17:51:07 +00:00
"fmt"
2021-03-31 07:29:52 +00:00
"io"
2021-02-08 17:51:07 +00:00
"log"
2020-11-09 18:54:06 +00:00
"net/http"
"net/url"
2021-02-08 19:33:48 +00:00
"strings"
2020-11-09 18:54:06 +00:00
)
const telegramBaseURL = "https://api.telegram.org/bot"
func (a *goBlog) initTelegram() {
a.pPostHooks = append(a.pPostHooks, func(p *post) {
if tg := a.cfg.Blogs[p.Blog].Telegram; tg.enabled() && p.isPublishedSectionPost() {
if html := tg.generateHTML(p.Title(), a.fullPostURL(p), a.shortPostURL(p)); html != "" {
2021-06-19 06:37:16 +00:00
if err := a.send(tg, html, "HTML"); err != nil {
log.Printf("Failed to send post to Telegram: %v", err)
}
2020-11-17 21:10:13 +00:00
}
}
})
2020-11-17 21:10:13 +00:00
}
func (tg *configTelegram) enabled() bool {
2020-11-17 21:10:13 +00:00
if tg == nil || !tg.Enabled || tg.BotToken == "" || tg.ChatID == "" {
return false
}
return true
}
func (tg *configTelegram) generateHTML(title, fullURL, shortURL string) string {
if !tg.enabled() {
return ""
2020-11-09 18:54:06 +00:00
}
2021-02-08 19:33:48 +00:00
replacer := strings.NewReplacer("<", "&lt;", ">", "&gt;", "&", "&amp;")
2020-11-09 18:54:06 +00:00
var message bytes.Buffer
if title != "" {
2021-02-08 19:33:48 +00:00
message.WriteString(replacer.Replace(title))
2020-11-09 18:54:06 +00:00
message.WriteString("\n\n")
}
2021-02-08 19:33:48 +00:00
if tg.InstantViewHash != "" {
message.WriteString("<a href=\"https://t.me/iv?rhash=" + tg.InstantViewHash + "&url=" + url.QueryEscape(fullURL) + "\">")
message.WriteString(replacer.Replace(shortURL))
2021-02-08 19:33:48 +00:00
message.WriteString("</a>")
} else {
message.WriteString("<a href=\"" + shortURL + "\">")
message.WriteString(replacer.Replace(shortURL))
2021-02-08 19:33:48 +00:00
message.WriteString("</a>")
}
return message.String()
2020-11-09 18:54:06 +00:00
}
2021-06-19 06:37:16 +00:00
func (a *goBlog) send(tg *configTelegram, message, mode string) error {
if !tg.enabled() {
return nil
}
2020-11-09 18:54:06 +00:00
params := url.Values{}
params.Add("chat_id", tg.ChatID)
2021-02-08 19:33:48 +00:00
params.Add("text", message)
if mode != "" {
params.Add("parse_mode", mode)
}
tgURL, err := url.Parse(telegramBaseURL + tg.BotToken + "/sendMessage")
2020-11-09 18:54:06 +00:00
if err != nil {
return errors.New("failed to create Telegram request")
}
tgURL.RawQuery = params.Encode()
req, _ := http.NewRequest(http.MethodPost, tgURL.String(), nil)
2021-06-19 06:37:16 +00:00
resp, err := a.httpClient.Do(req)
2021-02-08 17:51:07 +00:00
if err != nil {
return err
2021-03-31 07:29:52 +00:00
}
defer resp.Body.Close()
_, _ = io.Copy(io.Discard, resp.Body)
if resp.StatusCode != http.StatusOK {
2021-02-08 17:51:07 +00:00
return fmt.Errorf("failed to send Telegram message, status code %d", resp.StatusCode)
2020-11-09 18:54:06 +00:00
}
return nil
}