/
telegram.go
183 lines (153 loc) · 4.26 KB
/
telegram.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
package proc
import (
"bytes"
"fmt"
"io"
"net/http"
"strings"
"time"
log "github.com/go-pkgz/lgr"
"github.com/microcosm-cc/bluemonday"
"github.com/pkg/errors"
"github.com/tcolgate/mp3"
"golang.org/x/net/html"
tb "gopkg.in/tucnak/telebot.v2"
"github.com/umputun/feed-master/app/feed"
)
// TelegramClient client
type TelegramClient struct {
Bot *tb.Bot
Timeout time.Duration
}
// NewTelegramClient init telegram client
func NewTelegramClient(token, apiURL string, timeout time.Duration) (*TelegramClient, error) {
if timeout == 0 {
timeout = time.Second * 60
}
if token == "" {
return &TelegramClient{
Bot: nil,
Timeout: timeout,
}, nil
}
bot, err := tb.NewBot(tb.Settings{
URL: apiURL,
Token: token,
Client: &http.Client{Timeout: timeout},
})
if err != nil {
return nil, err
}
result := TelegramClient{
Bot: bot,
Timeout: timeout,
}
return &result, err
}
// Send message, skip if telegram token empty
func (client TelegramClient) Send(channelID string, item feed.Item) (err error) {
if client.Bot == nil || channelID == "" {
return nil
}
message, err := client.sendAudio(channelID, item)
if err != nil && strings.HasSuffix(err.Error(), "Request Entity Too Large") {
message, err = client.sendText(channelID, item)
}
if err != nil {
return errors.Wrapf(err, "can't send to telegram for %+v", item.Enclosure)
}
log.Printf("[DEBUG] telegram message sent: \n%s", message.Text)
return nil
}
func (client TelegramClient) sendText(channelID string, item feed.Item) (*tb.Message, error) {
message, err := client.Bot.Send(
recipient{chatID: channelID},
client.getMessageHTML(item, true, false),
tb.ModeHTML,
tb.NoPreview,
)
return message, err
}
func (client TelegramClient) sendAudio(channelID string, item feed.Item) (*tb.Message, error) {
httpBody, err := item.DownloadAudio(client.Timeout)
if err != nil {
return nil, err
}
defer httpBody.Close()
var httpBodyCopy bytes.Buffer
tee := io.TeeReader(httpBody, &httpBodyCopy)
audio := tb.Audio{
File: tb.FromReader(&httpBodyCopy),
FileName: item.GetFilename(),
MIME: "audio/mpeg",
Caption: client.getMessageHTML(item, false, true),
Title: item.Title,
Performer: item.Author,
Duration: client.duration(tee),
}
message, err := audio.Send(
client.Bot,
recipient{chatID: channelID},
&tb.SendOptions{
ParseMode: tb.ModeHTML,
},
)
return message, err
}
// https://core.telegram.org/bots/api#html-style
func (client TelegramClient) tagLinkOnlySupport(htmlText string) string {
p := bluemonday.NewPolicy()
p.AllowAttrs("href").OnElements("a")
return html.UnescapeString(p.Sanitize(htmlText))
}
// getMessageHTML generates HTML message from provided feed.Item
func (client TelegramClient) getMessageHTML(item feed.Item, withMp3Link, trimCaption bool) string {
var header, footer string
title := strings.TrimSpace(item.Title)
if title != "" {
switch {
case item.Link == "":
header = fmt.Sprintf("%s\n\n", title)
case item.Link != "":
header = fmt.Sprintf("<a href=%q>%s</a>\n\n", item.Link, title)
}
}
if withMp3Link {
footer += fmt.Sprintf("\n\n%s", item.Enclosure.URL)
}
description := string(item.Description)
description = strings.TrimPrefix(description, "<![CDATA[")
description = strings.TrimSuffix(description, "]]>")
// apparently bluemonday doesn't remove escaped HTML tags
description = client.tagLinkOnlySupport(html.UnescapeString(description))
description = strings.TrimSpace(description)
// https://limits.tginfo.me/en 1024 symbol limit for caption
if trimCaption && len(header+description+footer) > 1024 {
description = CleanText(description, 1020-len(header+footer))
}
return header + description + footer
}
// duration scans MP3 file from provided io.Reader and returns it's duration in seconds, ignoring possible errors
func (client TelegramClient) duration(r io.Reader) int {
d := mp3.NewDecoder(r)
var f mp3.Frame
var skipped int
var duration float64
var err error
for err == nil {
if err = d.Decode(&f, &skipped); err != nil && err != io.EOF {
return 0
}
duration += f.Duration().Seconds()
}
return int(duration)
}
type recipient struct {
chatID string
}
func (r recipient) Recipient() string {
if !strings.HasPrefix(r.chatID, "@") {
return "@" + r.chatID
}
return r.chatID
}