-
Notifications
You must be signed in to change notification settings - Fork 0
/
sink.go
83 lines (73 loc) · 1.79 KB
/
sink.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
package sink
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
"github.com/rozag/rss-tg-chan/retry"
)
// Sink publishes posts from feeds
type Sink struct {
config *Config
}
// New constructs a new Sink
func New(config *Config) *Sink {
return &Sink{config}
}
// Send publishes the post
func (s Sink) Send(feeds map[string][]Post) uint {
client := &http.Client{
Timeout: 30 * time.Second,
}
cnt := uint(0)
for _, posts := range feeds {
for _, post := range posts {
err := send(client, s.config.TgBotToken, s.config.TgChannel, post)
if err != nil {
log.Printf("[ERROR] Failed sending post: %v", err)
} else {
cnt++
}
}
}
return cnt
}
func send(client *http.Client, tgBotToken, tgChannel string, post Post) error {
// Prepare post's text
text := post.GetPublishableText()
if text == "" {
return fmt.Errorf("Text is empty for the post: %v", post)
}
// Prepare the body
type Body struct {
ChatID string `json:"chat_id"`
ParseMode string `json:"parse_mode"`
Text string `json:"text"`
}
body := Body{tgChannel, "Markdown", text}
bodyBytes, err := json.Marshal(body)
if err != nil {
return err
}
// Send the text
url := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", tgBotToken)
err = retry.Do(3, time.Second, 2, func() error {
resp, err := client.Post(url, "application/json", bytes.NewReader(bodyBytes))
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
bytes, bodyerr := ioutil.ReadAll(resp.Body)
if bodyerr != nil {
return fmt.Errorf("Got status code=%d body=%s", resp.StatusCode, string(bodyBytes))
}
return fmt.Errorf("Got status code=%d respBody=%s body=%s", resp.StatusCode, string(bytes), string(bodyBytes))
}
return nil
})
return err
}