forked from nyaruka/courier
-
Notifications
You must be signed in to change notification settings - Fork 0
/
telegram.go
349 lines (298 loc) · 10.4 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
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
package telegram
import (
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/buger/jsonparser"
"github.com/go-errors/errors"
"github.com/nyaruka/courier"
"github.com/nyaruka/courier/handlers"
"github.com/nyaruka/courier/utils"
"github.com/nyaruka/gocommon/urns"
)
func init() {
courier.RegisterHandler(NewHandler())
}
type handler struct {
handlers.BaseHandler
}
// NewHandler returns a new TelegramHandler ready to be registered
func NewHandler() courier.ChannelHandler {
return &handler{handlers.NewBaseHandler(courier.ChannelType("TG"), "Telegram")}
}
// Initialize is called by the engine once everything is loaded
func (h *handler) Initialize(s courier.Server) error {
h.SetServer(s)
return s.AddReceiveMsgRoute(h, http.MethodPost, "receive", h.ReceiveMessage)
}
// ReceiveMessage is our HTTP handler function for incoming messages
func (h *handler) ReceiveMessage(channel courier.Channel, w http.ResponseWriter, r *http.Request) ([]courier.ReceiveEvent, error) {
te := &telegramEnvelope{}
err := handlers.DecodeAndValidateJSON(te, r)
if err != nil {
return nil, courier.WriteError(w, r, err)
}
// no message? ignore this
if te.Message.MessageID == 0 {
return nil, courier.WriteIgnored(w, r, "Ignoring request, no message")
}
// create our date from the timestamp
date := time.Unix(te.Message.Date, 0).UTC()
// create our URN
urn := urns.NewTelegramURN(te.Message.From.ContactID, te.Message.From.Username)
// build our name from first and last
name := handlers.NameFromFirstLastUsername(te.Message.From.FirstName, te.Message.From.LastName, te.Message.From.Username)
// our text is either "text" or "caption" (or empty)
text := te.Message.Text
// this is a start command, trigger a new conversation
if text == "/start" {
event := h.Backend().NewChannelEvent(channel, courier.NewConversation, urn).WithContactName(name).WithOccurredOn(date)
err = h.Backend().WriteChannelEvent(event)
if err != nil {
return nil, err
}
return []courier.ReceiveEvent{event}, courier.WriteChannelEventSuccess(w, r, event)
}
// normal message of some kind
if text == "" && te.Message.Caption != "" {
text = te.Message.Caption
}
// deal with attachments
mediaURL := ""
if len(te.Message.Photo) > 0 {
// grab the largest photo less than 100k
photo := te.Message.Photo[0]
for i := 1; i < len(te.Message.Photo); i++ {
if te.Message.Photo[i].FileSize > 100000 {
break
}
photo = te.Message.Photo[i]
}
mediaURL, err = resolveFileID(channel, photo.FileID)
} else if te.Message.Video != nil {
mediaURL, err = resolveFileID(channel, te.Message.Video.FileID)
} else if te.Message.Voice != nil {
mediaURL, err = resolveFileID(channel, te.Message.Voice.FileID)
} else if te.Message.Sticker != nil {
mediaURL, err = resolveFileID(channel, te.Message.Sticker.Thumb.FileID)
} else if te.Message.Document != nil {
mediaURL, err = resolveFileID(channel, te.Message.Document.FileID)
} else if te.Message.Venue != nil {
text = utils.JoinNonEmpty(", ", te.Message.Venue.Title, te.Message.Venue.Address)
mediaURL = fmt.Sprintf("geo:%f,%f", te.Message.Location.Latitude, te.Message.Location.Longitude)
} else if te.Message.Location != nil {
text = fmt.Sprintf("%f,%f", te.Message.Location.Latitude, te.Message.Location.Longitude)
mediaURL = fmt.Sprintf("geo:%f,%f", te.Message.Location.Latitude, te.Message.Location.Longitude)
} else if te.Message.Contact != nil {
phone := ""
if te.Message.Contact.PhoneNumber != "" {
phone = fmt.Sprintf("(%s)", te.Message.Contact.PhoneNumber)
}
text = utils.JoinNonEmpty(" ", te.Message.Contact.FirstName, te.Message.Contact.LastName, phone)
}
// we had an error downloading media
if err != nil {
return nil, courier.WriteError(w, r, errors.WrapPrefix(err, "error retrieving media", 0))
}
// build our msg
msg := h.Backend().NewIncomingMsg(channel, urn, text).WithReceivedOn(date).WithExternalID(fmt.Sprintf("%d", te.Message.MessageID)).WithContactName(name)
if mediaURL != "" {
msg.WithAttachment(mediaURL)
}
// queue our message
err = h.Backend().WriteMsg(msg)
if err != nil {
return nil, err
}
return []courier.ReceiveEvent{msg}, courier.WriteMsgSuccess(w, r, msg)
}
func (h *handler) sendMsgPart(msg courier.Msg, token string, path string, form url.Values) (string, *courier.ChannelLog, error) {
sendURL := fmt.Sprintf("%s/bot%s/%s", telegramAPIURL, token, path)
req, err := http.NewRequest(http.MethodPost, sendURL, strings.NewReader(form.Encode()))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
rr, err := utils.MakeHTTPRequest(req)
// build our channel log
log := courier.NewChannelLogFromRR("Message Sent", msg.Channel(), msg.ID(), rr).WithError("Message Send Error", err)
// was this request successful?
ok, err := jsonparser.GetBoolean([]byte(rr.Body), "ok")
if err != nil || !ok {
return "", log, errors.Errorf("response not 'ok'")
}
// grab our message id
externalID, err := jsonparser.GetInt([]byte(rr.Body), "result", "message_id")
if err != nil {
return "", log, errors.Errorf("no 'result.message_id' in response")
}
return strconv.FormatInt(externalID, 10), log, nil
}
// SendMsg sends the passed in message, returning any error
func (h *handler) SendMsg(msg courier.Msg) (courier.MsgStatus, error) {
confAuth := msg.Channel().ConfigForKey(courier.ConfigAuthToken, "")
authToken, isStr := confAuth.(string)
if !isStr || authToken == "" {
return nil, fmt.Errorf("invalid auth token config")
}
// we only caption if there is only a single attachment
caption := ""
if len(msg.Attachments()) == 1 {
caption = msg.Text()
}
// the status that will be written for this message
status := h.Backend().NewMsgStatusForID(msg.Channel(), msg.ID(), courier.MsgErrored)
// whether we encountered any errors sending any parts
hasError := true
// if we have text, send that if we aren't sending it as a caption
if msg.Text() != "" && caption == "" {
form := url.Values{
"chat_id": []string{msg.URN().Path()},
"text": []string{msg.Text()},
}
externalID, log, err := h.sendMsgPart(msg, authToken, "sendMessage", form)
status.SetExternalID(externalID)
hasError = err != nil
status.AddLog(log)
}
// send each attachment
for _, attachment := range msg.Attachments() {
mediaType, mediaURL := courier.SplitAttachment(attachment)
switch strings.Split(mediaType, "/")[0] {
case "image":
form := url.Values{
"chat_id": []string{msg.URN().Path()},
"photo": []string{mediaURL},
"caption": []string{caption},
}
externalID, log, err := h.sendMsgPart(msg, authToken, "sendPhoto", form)
status.SetExternalID(externalID)
hasError = err != nil
status.AddLog(log)
case "video":
form := url.Values{
"chat_id": []string{msg.URN().Path()},
"video": []string{mediaURL},
"caption": []string{caption},
}
externalID, log, err := h.sendMsgPart(msg, authToken, "sendVideo", form)
status.SetExternalID(externalID)
hasError = err != nil
status.AddLog(log)
case "audio":
form := url.Values{
"chat_id": []string{msg.URN().Path()},
"audio": []string{mediaURL},
"caption": []string{caption},
}
externalID, log, err := h.sendMsgPart(msg, authToken, "sendAudio", form)
status.SetExternalID(externalID)
hasError = err != nil
status.AddLog(log)
default:
status.AddLog(courier.NewChannelLog("Unknown media type: "+mediaType, msg.Channel(), msg.ID(), "", "", courier.NilStatusCode,
"", "", time.Duration(0), fmt.Errorf("unknown media type: %s", mediaType)))
hasError = true
}
}
if !hasError {
status.SetStatus(courier.MsgWired)
}
return status, nil
}
var telegramAPIURL = "https://api.telegram.org"
func resolveFileID(channel courier.Channel, fileID string) (string, error) {
confAuth := channel.ConfigForKey(courier.ConfigAuthToken, "")
authToken, isStr := confAuth.(string)
if !isStr || authToken == "" {
return "", fmt.Errorf("invalid auth token config")
}
fileURL := fmt.Sprintf("%s/bot%s/getFile", telegramAPIURL, authToken)
form := url.Values{}
form.Set("file_id", fileID)
req, err := http.NewRequest(http.MethodPost, fileURL, strings.NewReader(form.Encode()))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
if err != nil {
return "", err
}
rr, err := utils.MakeHTTPRequest(req)
if err != nil {
return "", err
}
// was this request successful?
ok, err := jsonparser.GetBoolean([]byte(rr.Body), "ok")
if err != nil {
return "", errors.Errorf("no 'ok' in response")
}
if !ok {
return "", errors.Errorf("file id '%s' not present", fileID)
}
// grab the path for our file
filePath, err := jsonparser.GetString([]byte(rr.Body), "result", "file_path")
if err != nil {
return "", errors.Errorf("no 'result.file_path' in response")
}
// return the URL
return fmt.Sprintf("%s/file/bot%s/%s", telegramAPIURL, authToken, filePath), nil
}
type telegramFile struct {
FileID string `json:"file_id" validate:"required"`
FileSize int `json:"file_size"`
}
type telegramLocation struct {
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
}
// {
// "update_id": 174114370,
// "message": {
// "message_id": 41,
// "from": {
// "id": 3527065,
// "first_name": "Nic",
// "last_name": "Pottier",
// "username": "nicpottier"
// },
// "chat": {
// "id": 3527065,
// "first_name": "Nic",
// "last_name": "Pottier",
// "type": "private"
// },
// "date": 1454119029,
// "text": "Hello World"
// }
// }
type telegramEnvelope struct {
UpdateID int64 `json:"update_id" validate:"required"`
Message struct {
MessageID int64 `json:"message_id"`
From struct {
ContactID int64 `json:"id"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Username string `json:"username"`
} `json:"from"`
Date int64 `json:"date"`
Text string `json:"text"`
Caption string `json:"caption"`
Sticker *struct {
Thumb telegramFile `json:"thumb"`
} `json:"sticker"`
Photo []telegramFile `json:"photo"`
Video *telegramFile `json:"video"`
Voice *telegramFile `json:"voice"`
Document *telegramFile `json:"document"`
Location *telegramLocation `json:"location"`
Venue *struct {
Location *telegramLocation `json:"location"`
Title string `json:"title"`
Address string `json:"address"`
}
Contact *struct {
PhoneNumber string `json:"phone_number"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
}
} `json:"message"`
}