This repository has been archived by the owner on Apr 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtwilio-function.js
100 lines (93 loc) · 2.72 KB
/
twilio-function.js
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
/* global Twilio */
const https = require('https')
// Make sure to declare SLACK_WEBHOOK_PATH in your Environment
// variables at
// https://www.twilio.com/console/runtime/functions/configure
exports.handler = (context, event, callback) => {
// Extract the bits of the message we want
const { To, From, Body } = event
const images = []
while (event['MediaUrl' + images.length]) {
images.push(event['MediaUrl' + images.length])
}
const bodyWithImages = [Body].concat(images).join('\n\nAttached media: ')
function encode (field) {
return field.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
}
const encodedBody = encode(bodyWithImages)
const encodedFrom = encode(From)
const encodedTo = encode(To)
// Construct a payload for Slack's incoming webhooks
const slackBody = JSON.stringify({
attachments: [
{
fallback: `${From}: ${encodedBody}`,
text: `Received SMS from ${From}`,
fields: [
{
title: 'Sender',
value: encodedFrom,
short: true
},
{
title: 'Receiver',
value: encodedTo,
short: true
},
{
title: 'Message',
value: '<!here> ' + encodedBody,
short: false
}
],
color: '#5555AA'
}
]
})
// Account for emoji
function byteLength (str) {
// returns the byte length of an utf8 string
let s = str.length
for (let i = str.length - 1; i >= 0; i--) {
const code = str.charCodeAt(i)
if (code > 0x7f && code <= 0x7ff) {
s++
} else if (code > 0x7ff && code <= 0xffff) {
s += 2
}
if (code >= 0xDC00 && code <= 0xDFFF) {
i-- // trail surrogate
}
}
return s
}
const slackBodyLength = byteLength(slackBody)
// Form our request specification
const options = {
host: 'hooks.slack.com',
port: 443,
path: context.SLACK_WEBHOOK_PATH,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': slackBodyLength
}
}
console.log(slackBody, '===', slackBody.length)
// send the request
const post = https.request(options, res => {
// only respond once we're done, or Twilio's functions
// may kill our execution before we finish.
res.on('error', (e) => { console.log('res ERROR:', e) })
res.on('data', (chunk) => { console.log('res CHUNK:', chunk.toString()) })
res.on('end', () => {
// respond with an empty message
callback(null, new Twilio.twiml.MessagingResponse())
})
})
post.on('error', e => { console.log('post ERROR:', e) })
post.on('drain', () => { post.end() })
if (post.write(slackBody)) {
post.end()
}
}