GoBlog/telegram.go

228 lines
6.0 KiB
Go
Raw Normal View History

2020-11-09 18:54:06 +00:00
package main
import (
"bytes"
2021-12-07 18:05:43 +00:00
"errors"
2021-02-08 17:51:07 +00:00
"log"
2020-11-09 18:54:06 +00:00
"net/url"
2021-12-07 18:05:43 +00:00
"strconv"
2020-11-09 18:54:06 +00:00
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-12-11 18:43:40 +00:00
tgChat := p.firstParameter("telegramchat")
tgMsg := p.firstParameter("telegrammsg")
if tgChat != "" && tgMsg != "" {
// Already posted
return
}
2021-12-07 18:05:43 +00:00
// Generate HTML
html := tg.generateHTML(p.RenderedTitle, a.fullPostURL(p), a.shortPostURL(p))
if html == "" {
return
}
// Send message
chatId, msgId, err := a.sendTelegram(tg, html, tgbotapi.ModeHTML)
2021-12-07 18:05:43 +00:00
if err != nil {
log.Printf("Failed to send post to Telegram: %v", err)
return
}
if chatId == 0 || msgId == 0 {
// Not sent
return
}
// Save chat and message id to post
err = a.db.replacePostParam(p.Path, "telegramchat", []string{strconv.FormatInt(chatId, 10)})
if err != nil {
log.Printf("Failed to save Telegram chat id: %v", err)
}
err = a.db.replacePostParam(p.Path, "telegrammsg", []string{strconv.Itoa(msgId)})
if err != nil {
log.Printf("Failed to save Telegram message id: %v", err)
}
}
})
a.pUpdateHooks = append(a.pUpdateHooks, func(p *post) {
if tg := a.cfg.Blogs[p.Blog].Telegram; tg.enabled() {
2021-12-07 18:05:43 +00:00
tgChat := p.firstParameter("telegramchat")
tgMsg := p.firstParameter("telegrammsg")
if tgChat == "" || tgMsg == "" {
// Not send to Telegram
return
}
// Parse tgChat to int64
chatId, err := strconv.ParseInt(tgChat, 10, 64)
if err != nil {
log.Printf("Failed to parse Telegram chat ID: %v", err)
return
}
// Parse tgMsg to int
messageId, err := strconv.Atoi(tgMsg)
if err != nil {
log.Printf("Failed to parse Telegram message ID: %v", err)
return
}
// Generate HTML
html := tg.generateHTML(p.RenderedTitle, a.fullPostURL(p), a.shortPostURL(p))
if html == "" {
return
}
// Send update
err = a.updateTelegram(tg, chatId, messageId, html, "HTML")
2021-12-07 18:05:43 +00:00
if err != nil {
log.Printf("Failed to send update to Telegram: %v", err)
2020-11-17 21:10:13 +00:00
}
}
})
a.pDeleteHooks = append(a.pDeleteHooks, func(p *post) {
if tg := a.cfg.Blogs[p.Blog].Telegram; tg.enabled() {
tgChat := p.firstParameter("telegramchat")
tgMsg := p.firstParameter("telegrammsg")
if tgChat == "" || tgMsg == "" {
// Not send to Telegram
return
}
// Parse tgChat to int64
chatId, err := strconv.ParseInt(tgChat, 10, 64)
if err != nil {
log.Printf("Failed to parse Telegram chat ID: %v", err)
return
}
// Parse tgMsg to int
messageId, err := strconv.Atoi(tgMsg)
if err != nil {
log.Printf("Failed to parse Telegram message ID: %v", err)
return
}
// Delete message
err = a.deleteTelegram(tg, chatId, messageId)
if err != nil {
log.Printf("Failed to delete Telegram message: %v", err)
}
// Delete chat and message id from post
err = a.db.replacePostParam(p.Path, "telegramchat", []string{})
if err != nil {
log.Printf("Failed to remove Telegram chat id: %v", err)
}
err = a.db.replacePostParam(p.Path, "telegrammsg", []string{})
if err != nil {
log.Printf("Failed to remove Telegram message id: %v", err)
}
}
})
// TODO: Handle undelete
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) sendTelegram(tg *configTelegram, message, mode string) (int64, int, error) {
if !tg.enabled() {
2021-12-07 18:05:43 +00:00
return 0, 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 {
2021-12-07 18:05:43 +00:00
return 0, 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 {
2021-12-07 18:05:43 +00:00
return 0, 0, err
}
return res.Chat.ID, res.MessageID, nil
}
func (a *goBlog) updateTelegram(tg *configTelegram, chatId int64, messageId int, message, mode string) error {
2021-12-07 18:05:43 +00:00
if !tg.enabled() {
return nil
}
bot, err := tgbotapi.NewBotAPIWithClient(tg.BotToken, tgbotapi.APIEndpoint, a.httpClient)
if err != nil {
return err
}
// Check if chat is still the configured one
2021-12-07 18:05:43 +00:00
chat, err := bot.GetChat(tgbotapi.ChatInfoConfig{
ChatConfig: tgbotapi.ChatConfig{
SuperGroupUsername: tg.ChatID,
},
})
if err != nil {
return err
}
if chat.ID != chatId {
return errors.New("chat id mismatch")
}
// Send update
2021-12-07 18:05:43 +00:00
msg := tgbotapi.EditMessageTextConfig{
BaseEdit: tgbotapi.BaseEdit{
ChatID: chatId,
MessageID: messageId,
},
Text: message,
ParseMode: mode,
}
_, err = bot.Send(msg)
return err
}
func (a *goBlog) deleteTelegram(tg *configTelegram, chatId int64, messageId int) error {
if !tg.enabled() {
return nil
}
bot, err := tgbotapi.NewBotAPIWithClient(tg.BotToken, tgbotapi.APIEndpoint, a.httpClient)
2021-12-07 18:05:43 +00:00
if err != nil {
return err
2020-11-09 18:54:06 +00:00
}
chat, err := bot.GetChat(tgbotapi.ChatInfoConfig{
ChatConfig: tgbotapi.ChatConfig{
SuperGroupUsername: tg.ChatID,
},
})
if err != nil {
return err
}
if chat.ID != chatId {
return errors.New("chat id mismatch")
}
msg := tgbotapi.DeleteMessageConfig{
ChatID: chatId,
MessageID: messageId,
}
_, err = bot.Send(msg)
return err
2020-11-09 18:54:06 +00:00
}