13
"xelbot.com/reprogl/api"
14
"xelbot.com/reprogl/api/backend"
15
"xelbot.com/reprogl/container"
16
"xelbot.com/reprogl/models"
20
Chat int `json:"chat_id"`
21
Text string `json:"text"`
22
ParseMode string `json:"parse_mode"`
23
DisablePreview bool `json:"disable_web_page_preview"`
26
var telegramLocker sync.Mutex
29
app *container.Application,
30
comment *backend.CreatedCommentDTO,
31
article *models.ArticleForComment,
33
text := generateText(comment, article)
34
app.InfoLog.Printf("Telegram notification text:\n%s", text)
36
jsonBody, err := json.Marshal(createMessage(text))
42
request, err := http.NewRequest(
44
"https://api.telegram.org/bot"+container.GetConfig().TelegramToken+"/sendMessage",
45
bytes.NewReader(jsonBody))
51
request.Header.Set("Content-Type", "application/json")
53
resp, err := send(request)
59
defer resp.Body.Close()
60
buf, err := io.ReadAll(resp.Body)
66
app.InfoLog.Printf("Telegram answer:\nStatus: %s\n\n%s", resp.Status, string(buf))
69
func createMessage(text string) message {
71
Chat: container.GetConfig().TelegramAdminID,
73
ParseMode: "MarkdownV2",
79
comment *backend.CreatedCommentDTO,
80
article *models.ArticleForComment,
83
"Кто\\-то оставил [комментарий](%s)\n\n*ID*: %d\n",
84
container.GenerateAbsoluteURL("article", "slug", article.Slug),
87
if len(comment.Name) > 0 {
88
msg += "*Name*: " + escapeMarkdownCharacters(comment.Name)
90
if len(comment.Country) > 0 {
91
msg += " " + comment.Country + "\n"
95
if len(comment.Email) > 0 {
96
msg += "*Email*: " + escapeMarkdownCharacters(comment.Email) + "\n"
98
if len(comment.Website) > 0 {
99
msg += "*Website*: " + escapeMarkdownCharacters(comment.Website) + "\n"
102
msg += "\n" + escapeMarkdownCharacters(stripTags(comment.Text))
107
func stripTags(content string) string {
108
re := regexp.MustCompile(`<(.|\n)*?>`)
110
return re.ReplaceAllString(content, "")
113
func escapeMarkdownCharacters(content string) string {
114
buffer := make([]rune, 0, 2*utf8.RuneCountInString(content))
115
for _, e := range []rune(content) {
117
case '_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!':
118
buffer = append(buffer, '\\', e)
120
buffer = append(buffer, e)
124
return string(buffer)
127
func send(req *http.Request) (*http.Response, error) {
128
telegramLocker.Lock()
129
defer telegramLocker.Unlock()