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
|
package target
import (
"context"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
"os"
"time"
"github.com/microcosm-cc/bluemonday"
cm "go.neonxp.ru/conf/model"
"go.neonxp.ru/pose/internal/model"
)
var (
ErrNoToken = errors.New("no api token")
ErrNoGroup = errors.New("no group")
)
const telegramRequestTimeout = 30 * time.Second
const telegramMaxItemsChan = 32
type Telegram struct {
logger *slog.Logger
apiToken string
group string
client *http.Client
policy *bluemonday.Policy
}
func NewTelegram(cfg cm.Group, logger *slog.Logger) (*Telegram, error) {
token := cfg.Get("token").StringExt("", os.LookupEnv)
if token == "" {
return nil, ErrNoToken
}
group := cfg.Get("group").StringExt("", os.LookupEnv)
if group == "" {
return nil, ErrNoGroup
}
pol := bluemonday.NewPolicy()
pol.AllowAttrs("href").OnElements("a")
pol.AllowAttrs("class").OnElements("span")
pol.AllowElements("p", "br", "b", "strong", "i", "em", "u", "ins", "s", "strike", "del", "code", "pre", "blockquote")
return &Telegram{
logger: logger,
apiToken: token,
group: group,
client: &http.Client{Timeout: telegramRequestTimeout},
policy: pol,
}, nil
}
func (t *Telegram) Send(ctx context.Context) chan<- model.Item {
ch := make(chan model.Item, telegramMaxItemsChan)
go func() {
defer close(ch)
for {
select {
case <-ctx.Done():
return
case item := <-ch:
if err := t.sendMessage(item); err != nil {
t.logger.ErrorContext(ctx, "failed send feed item to telegram", slog.Any("err", err))
continue
}
t.logger.InfoContext(ctx, "send item to telegram", slog.String("id", item.ID))
}
}
}()
return ch
}
func (t *Telegram) sendMessage(it model.Item) error {
sendMessageURL := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", t.apiToken)
message := it.BuildMessage()
message = t.policy.Sanitize(message)
message = processHTML(message)
params := url.Values{}
params.Set("chat_id", t.group)
params.Set("text", message)
params.Set("parse_mode", "HTML")
resp, err := t.client.PostForm(sendMessageURL, params)
if err != nil {
return err
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
msg, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed read error body: %w", err)
}
return fmt.Errorf(
"invalid status code %d (%s): %s",
resp.StatusCode,
resp.Status,
string(msg),
)
}
return nil
}
|