-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
76 lines (63 loc) · 2.21 KB
/
index.js
File metadata and controls
76 lines (63 loc) · 2.21 KB
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
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
// Basic request handler. Ensures request is a POST request and parses the message body and sender phone number
async function handleRequest(request) {
if (request.method !== 'POST') {
return simpleMessage(200, 'Error: not a POST')
}
const reqBody = await request.formData();
let body = reqBody.get("Body");
let from = reqBody.get("From");
return twilioWebhookHandler(from, body);
}
// Forwards the message to the user if it's from a different phone number
async function twilioWebhookHandler(from, body) {
// Parse the text from the incoming request and log to console
if (from !== MY_NUM) {
return sendMessage(MY_NUM, body);
} else {
// User sends phone number at start of message followed by a semicolon
let recip = body.substring(0, body.indexOf(';'));
//Basic check to ensure length of phone number is valid
if (recip.length < 10 || recip.length > 12) {
return sendMessage(MY_NUM, "invalid phone number specified")
}
let msg = body.substring(body.indexOf(' ') + 1);
return sendMessage(recip, msg);
}
}
//Return a simple JSON response with status code and message
function simpleMessage(statusCode, message) {
let resp = {
message: message,
status: statusCode
};
return new Response(JSON.stringify(resp), {
headers: { 'Content-Type': 'application/json'},
status: statusCode
});
}
//Sends a new message to the specified number
async function sendMessage(numTo, message) {
const requestURL = "https://api.twilio.com/2010-04-01/Accounts/" + ACCOUNT_SID + "/Messages.json";
let encoded = new URLSearchParams();
encoded.append('To', numTo);
encoded.append('From', TWILIO_NUM);
encoded.append('Body', message);
let token = btoa(ACCOUNT_SID + ':' + AUTH_TOKEN);
const request = {
body: encoded,
method: 'POST',
headers: {
'Authorization': `Basic ${token}`,
'Content-Type': 'application/x-www-form-urlencoded',
},
};
await fetch(requestURL, request);
let responseOptions = {
status: 200,
headers: { 'Content-Type': 'text/html'}
};
return new Response('<Response></Response>', responseOptions);
}