-
Notifications
You must be signed in to change notification settings - Fork 0
/
tamtam.go
222 lines (186 loc) · 5.39 KB
/
tamtam.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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"path"
"time"
)
const (
ttUploadTemplate = "https://botapi.tamtam.chat/uploads?access_token=%s&type=%s"
ttSendMessageTemplate = "https://botapi.tamtam.chat/messages?access_token=%s&chat_id=%d"
ttMaxMessageSendRetries = 10
ttMessageSendRetryDelay = 2
ttFileAttachmentType = "file"
ttImageAttachmentType = "image"
)
type ttMessage struct {
Text string `json:"text"`
Attachments []ttMessageAttachment `json:"attachments"`
Notify bool `json:"notify"`
}
type ttMessageAttachment struct {
Type string `json:"type"`
Payload ttAttachmentPayload `json:"payload"`
}
type ttAttachmentPayload struct {
Token string `json:"token"`
}
func createUploadURL(attachmentType string, token string) (string, error) {
url := fmt.Sprintf(ttUploadTemplate, token, attachmentType)
req, err := http.Post(url, "application/json", nil)
if err != nil {
return "", err
}
defer req.Body.Close()
body, err := ioutil.ReadAll(req.Body)
if err != nil {
return "", err
}
fmt.Println("TT: Get upload URL response body:", string(body))
var response struct {
URL string `json:"url"`
}
err = json.Unmarshal(body, &response)
if err != nil {
return "", err
}
return response.URL, nil
}
func uploadFile(sourceURL string, destinationURL string, isImage bool) (string, error) {
resp, err := http.Get(sourceURL)
if err != nil {
return "", err
}
defer resp.Body.Close()
_, filename := path.Split(sourceURL)
var b bytes.Buffer
w := multipart.NewWriter(&b)
fw, err := w.CreateFormFile("data", filename)
if err != nil {
return "", err
}
_, err = io.Copy(fw, resp.Body)
w.Close()
if err != nil {
return "", err
}
uploadResp, err := http.Post(destinationURL, w.FormDataContentType(), &b)
if err != nil {
return "", err
}
defer uploadResp.Body.Close()
body, err := ioutil.ReadAll(uploadResp.Body)
fmt.Println("TT: Upload attachment response body:", string(body))
var response interface{}
err = json.Unmarshal(body, &response)
if err != nil {
return "", err
}
if isImage {
var response map[string]interface{}
err = json.Unmarshal(body, &response)
if err != nil {
return "", err
}
photos := response["photos"].(map[string]interface{})
for _, value := range photos {
values := value.(map[string]interface{})
token, prs := values["token"]
if prs {
return token.(string), nil
}
}
} else {
var response struct {
Token string `json:"token"`
}
err = json.Unmarshal(body, &response)
if err != nil {
return "", err
}
return response.Token, nil
}
return "", errors.New("Can't extract token from" + string(body))
}
func uploadAttachment(remoteURL string, attachmentType string, token string) (string, error) {
uploadURL, err := createUploadURL(attachmentType, token)
if err != nil {
return "", err
}
uploadToken, err := uploadFile(remoteURL, uploadURL, attachmentType == ttImageAttachmentType)
if err != nil {
return "", err
}
return uploadToken, nil
}
func ttSendMessage(url string, message interface{}, numberOfRetries int) error {
json, err := json.Marshal(message)
if err != nil {
return errors.New("Failed to create message JSON")
}
resp, err := http.Post(url, "application/json", bytes.NewBuffer(json))
if err != nil {
return err
}
defer resp.Body.Close()
fmt.Printf("TT: Post message (%d retries) response status: %d\n", numberOfRetries, resp.StatusCode)
if resp.StatusCode == http.StatusBadRequest {
if numberOfRetries == ttMaxMessageSendRetries {
return errors.New("Max send retries exceed")
}
time.Sleep(ttMessageSendRetryDelay * time.Second)
return ttSendMessage(url, message, numberOfRetries+1)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("Bad response status: %s (%s)", resp.Status, string(body))
}
return nil
}
func ttSendPicture(picture picture, token string, chat int64) error {
fileToken, err := uploadAttachment(picture.FullImageURL, ttFileAttachmentType, token)
if err != nil {
return err
}
if len(fileToken) == 0 {
return errors.New("Empty upload file token")
}
imageToken, err := uploadAttachment(picture.URL, ttImageAttachmentType, token)
if err != nil {
return err
}
if len(imageToken) == 0 {
return errors.New("Empty upload image token")
}
imageAttachment := ttMessageAttachment{Type: ttImageAttachmentType, Payload: ttAttachmentPayload{imageToken}}
fileAttachment := ttMessageAttachment{Type: ttFileAttachmentType, Payload: ttAttachmentPayload{fileToken}}
url := fmt.Sprintf(ttSendMessageTemplate, token, chat)
text := "🌌" + picture.Title + "\n\n" + picture.Explanation + "\n🔗 " + picture.Link
err = ttSendMessage(url, ttMessage{text, []ttMessageAttachment{imageAttachment}, true}, 0)
if err != nil {
return err
}
fileCaption := ""
if len(picture.Copyright) > 0 {
fileCaption = "© " + picture.Copyright
}
err = ttSendMessage(url, ttMessage{fileCaption, []ttMessageAttachment{fileAttachment}, false}, 0)
if err != nil {
return err
}
return nil
}
func ttSendVideo(picture picture, token string, chat int64) error {
url := fmt.Sprintf(ttSendMessageTemplate, token, chat)
text := "🌌" + picture.Title + "\n\n" + picture.Explanation + "\n🔗 " + picture.URL
return ttSendMessage(url, ttMessage{text, []ttMessageAttachment{}, true}, 0)
}