GoBlog/telegram.go

72 lines
1.8 KiB
Go
Raw Normal View History

2020-11-09 18:54:06 +00:00
package main
import (
"bytes"
2021-02-08 17:51:07 +00:00
"log"
2020-11-09 18:54:06 +00:00
"net/url"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
2020-11-09 18:54:06 +00:00
func (a *goBlog) initTelegram() {
a.pPostHooks = append(a.pPostHooks, func(p *post) {
if tg := a.cfg.Blogs[p.Blog].Telegram; tg.enabled() && p.isPublishedSectionPost() {
2021-08-05 06:09:34 +00:00
if html := tg.generateHTML(p.RenderedTitle, a.fullPostURL(p), a.shortPostURL(p)); html != "" {
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
}
var message bytes.Buffer
if title != "" {
message.WriteString(tgbotapi.EscapeText(tgbotapi.ModeHTML, 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(tgbotapi.EscapeText(tgbotapi.ModeHTML, shortURL))
2021-02-08 19:33:48 +00:00
message.WriteString("</a>")
} else {
message.WriteString("<a href=\"" + shortURL + "\">")
message.WriteString(tgbotapi.EscapeText(tgbotapi.ModeHTML, shortURL))
2021-02-08 19:33:48 +00:00
message.WriteString("</a>")
}
return message.String()
2020-11-09 18:54:06 +00:00
}
func (a *goBlog) send(tg *configTelegram, message, mode string) (int, error) {
if !tg.enabled() {
return 0, nil
2021-02-08 19:33:48 +00:00
}
bot, err := tgbotapi.NewBotAPIWithClient(tg.BotToken, tgbotapi.APIEndpoint, a.httpClient)
2020-11-09 18:54:06 +00:00
if err != nil {
return 0, err
2020-11-09 18:54:06 +00:00
}
msg := tgbotapi.MessageConfig{
BaseChat: tgbotapi.BaseChat{
ChannelUsername: tg.ChatID,
},
Text: message,
ParseMode: mode,
2021-03-31 07:29:52 +00:00
}
res, err := bot.Send(msg)
if err != nil {
return 0, err
2020-11-09 18:54:06 +00:00
}
return res.MessageID, nil
2020-11-09 18:54:06 +00:00
}