forked from nyaruka/courier
-
Notifications
You must be signed in to change notification settings - Fork 0
/
twitter.go
321 lines (275 loc) · 9.43 KB
/
twitter.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
package twitter
import (
"bytes"
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"strconv"
"time"
"github.com/buger/jsonparser"
"github.com/dghubble/oauth1"
"github.com/nyaruka/courier"
"github.com/nyaruka/courier/handlers"
"github.com/nyaruka/courier/utils"
"github.com/nyaruka/gocommon/urns"
"github.com/pkg/errors"
)
// Endpoints we hit
var sendURL = "https://api.twitter.com/1.1/direct_messages/events/new.json"
// DMs can be up to 10,000 characters long
var maxMsgLength = 10000
// Labels in quick replies can't be more than 36 characters
var maxOptionLength = 36
const (
configHandleID = "handle_id"
configAPIKey = "api_key"
configAPISecret = "api_secret"
configAccessToken = "access_token"
configAccessTokenSecret = "access_token_secret"
)
func init() {
courier.RegisterHandler(newHandler())
}
type handler struct {
handlers.BaseHandler
}
func newHandler() courier.ChannelHandler {
return &handler{handlers.NewBaseHandler(courier.ChannelType("TWT"), "Twitter")}
}
// Initialize is called by the engine once everything is loaded
func (h *handler) Initialize(s courier.Server) error {
h.SetServer(s)
err := s.AddHandlerRoute(h, http.MethodPost, "receive", h.Receive)
if err != nil {
return err
}
return s.AddHandlerRoute(h, http.MethodGet, "receive", h.ReceiveVerify)
}
// ReceiveVerify handles Twitter's webhook verification callback
func (h *handler) ReceiveVerify(ctx context.Context, c courier.Channel, w http.ResponseWriter, r *http.Request) ([]courier.Event, error) {
crcToken := r.URL.Query().Get("crc_token")
if crcToken == "" {
return nil, courier.WriteAndLogRequestError(ctx, w, r, c, fmt.Errorf(`missing required 'crc_token' query parameter`))
}
secret := c.StringConfigForKey("api_secret", "")
if secret == "" {
return nil, fmt.Errorf("TWT channel missing required secret in channel config")
}
signature := generateSignature(secret, crcToken)
w.Header().Set("Content-Type", "application/json")
_, err := w.Write([]byte(fmt.Sprintf(`{"response_token": "sha256=%s"}`, signature)))
return nil, err
}
// struct for each user
type twtUser struct {
ID string `json:"id" validate:"required"`
Name string `json:"name" validate:"required"`
ScreenName string `json:"screen_name" validate:"required"`
}
// {
// "direct_message_events": [
// {
// "created_timestamp": "1494877823220",
// "message_create": {
// "message_data": {
// "text": "hello world!",
// },
// "sender_id": "twitterid1",
// "target": {"recipient_id": "twitterid2" }
// },
// "type": "message_create",
// "id": "twitterMsgId"
// }
// ],
// "users": {
// "twitterid1": { "id": "twitterid1", "name": "joe", "screen_name": "joe" },
// "twitterid2": { "id": "twitterid2", "name": "jane", "screen_name": "jane" },
// }
// }
type moEnvelope struct {
DirectMessageEvents []struct {
CreatedTimestamp string `json:"created_timestamp" validate:"required"`
MessageCreate struct {
MessageData struct {
Text string `json:"text"`
Attachment *struct {
Media struct {
MediaURLHTTPS string `json:"media_url_https"`
} `json:"media"`
} `json:"attachment,omitempty"`
} `json:"message_data"`
SenderID string `json:"sender_id" validate:"required"`
Target struct {
RecipientID string `json:"recipient_id" validate:"required"`
} `json:"target"`
} `json:"message_create"`
Type string `json:"type" validate:"required"`
ID string `json:"id" validate:"required"`
} `json:"direct_message_events"`
Users map[string]twtUser `json:"users"`
}
// Receive is our HTTP handler function for incoming messages
func (h *handler) Receive(ctx context.Context, c courier.Channel, w http.ResponseWriter, r *http.Request) ([]courier.Event, error) {
// read our handle id
handleID := c.StringConfigForKey(configHandleID, "")
if handleID == "" {
return nil, fmt.Errorf("Missing handle id config for TWT channel")
}
mo := &moEnvelope{}
err := handlers.DecodeAndValidateJSON(mo, r)
if err != nil {
return nil, courier.WriteAndLogRequestError(ctx, w, r, c, err)
}
// no direct message events? ignore
if len(mo.DirectMessageEvents) == 0 {
return nil, courier.WriteAndLogRequestIgnored(ctx, w, r, c, "ignoring, no direct messages")
}
// the list of messages we read
msgs := make([]courier.Msg, 0, 2)
events := make([]courier.Event, 0, 2)
// for each entry
for _, entry := range mo.DirectMessageEvents {
// not a message create, ignore
if entry.Type != "message_create" {
continue
}
senderID := entry.MessageCreate.SenderID
// ignore this entry if we sent it
if senderID == handleID {
continue
}
// look up the user for this sender
user, found := mo.Users[senderID]
if !found {
return nil, courier.WriteAndLogRequestError(ctx, w, r, c, fmt.Errorf("unable to find user for id: %s", senderID))
}
urn := urns.NewURNFromParts(urns.TwitterIDScheme, user.ID, user.ScreenName)
// create our date from the timestamp (they give us millis, arg is nanos)
ts, err := strconv.ParseInt(entry.CreatedTimestamp, 10, 64)
if err != nil {
return nil, courier.WriteAndLogRequestError(ctx, w, r, c, fmt.Errorf("invalid timestamp: %s", entry.CreatedTimestamp))
}
date := time.Unix(0, ts*1000000).UTC()
// create our message
msg := h.Backend().NewIncomingMsg(c, urn, entry.MessageCreate.MessageData.Text).WithExternalID(entry.ID).WithReceivedOn(date).WithContactName(user.Name)
// if we have an attachment, add that as well
if entry.MessageCreate.MessageData.Attachment != nil {
msg.WithAttachment(entry.MessageCreate.MessageData.Attachment.Media.MediaURLHTTPS)
}
err = h.Backend().WriteMsg(ctx, msg)
if err != nil {
return nil, err
}
msgs = append(msgs, msg)
events = append(events, msg)
}
return events, courier.WriteMsgSuccess(ctx, w, r, msgs)
}
// {
// "event": {
// "type": "message_create",
// "message_create": {
// "target": {
// "recipient_id": "844385345234"
// },
// "message_data": {
// "text": "Hello World!",
// "quick_reply": {
// "type": "options",
// "options": [
// { "label": "Red"}, {"label": "Green"}
// ]
// }
// }
// }
// }
// }
type mtEnvelope struct {
Event struct {
Type string `json:"type"`
MessageCreate struct {
Target struct {
RecipientID string `json:"recipient_id"`
} `json:"target"`
MessageData struct {
Text string `json:"text"`
QuickReply *mtQR `json:"quick_reply,omitempty"`
} `json:"message_data"`
} `json:"message_create"`
} `json:"event"`
}
type mtQR struct {
Type string `json:"type"`
Options []mtQROption `json:"options"`
}
type mtQROption struct {
Label string `json:"label"`
}
func (h *handler) SendMsg(ctx context.Context, msg courier.Msg) (courier.MsgStatus, error) {
apiKey := msg.Channel().StringConfigForKey(configAPIKey, "")
apiSecret := msg.Channel().StringConfigForKey(configAPISecret, "")
accessToken := msg.Channel().StringConfigForKey(configAccessToken, "")
accessSecret := msg.Channel().StringConfigForKey(configAccessTokenSecret, "")
if apiKey == "" || apiSecret == "" || accessToken == "" || accessSecret == "" {
return nil, fmt.Errorf("missing api or tokens for TWT channel")
}
// create our OAuth client that will take care of signing
config := oauth1.NewConfig(apiKey, apiSecret)
token := oauth1.NewToken(accessToken, accessSecret)
client := config.Client(ctx, token)
status := h.Backend().NewMsgStatusForID(msg.Channel(), msg.ID(), courier.MsgErrored)
for i, text := range handlers.SplitMsg(handlers.GetTextAndAttachments(msg), maxMsgLength) {
payload := mtEnvelope{}
payload.Event.Type = "message_create"
payload.Event.MessageCreate.Target.RecipientID = msg.URN().Path()
payload.Event.MessageCreate.MessageData.Text = text
// attach quick replies if we have them
if i == 0 && len(msg.QuickReplies()) > 0 {
qrs := &mtQR{}
qrs.Type = "options"
for _, option := range msg.QuickReplies() {
if len(option) > maxOptionLength {
option = option[:maxOptionLength]
}
qrs.Options = append(qrs.Options, mtQROption{option})
}
payload.Event.MessageCreate.MessageData.QuickReply = qrs
}
jsonBody, err := json.Marshal(payload)
if err != nil {
return status, err
}
req, err := http.NewRequest(http.MethodPost, sendURL, bytes.NewReader(jsonBody))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
rr, err := utils.MakeHTTPRequestWithClient(req, client)
// record our status and log
log := courier.NewChannelLogFromRR("Message Sent", msg.Channel(), msg.ID(), rr).WithError("Message Send Error", err)
status.AddLog(log)
if err != nil {
return status, nil
}
externalID, err := jsonparser.GetString(rr.Body, "event", "id")
if err != nil {
log.WithError("Message Send Error", errors.Errorf("unable to get message_id from body"))
return status, nil
}
// if this is our first message, record the external id
if i == 0 {
status.SetExternalID(externalID)
}
// this was wired successfully
status.SetStatus(courier.MsgWired)
}
return status, nil
}
// hashes the passed in content in sha256 using the passed in secret
func generateSignature(secret string, content string) string {
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(content))
return base64.StdEncoding.EncodeToString(h.Sum(nil))
}