-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmessage-intercom.js
87 lines (72 loc) · 2.64 KB
/
message-intercom.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
var intercom = require('intercom-client');
var config = require('./environment-config');
var request = require('request');
//incoming from twilio -- send to intercom
exports.execute = function (req, response, callback) {
var token = config.intercom_token.prod;
var client = new intercom.Client({
token: token
});
var from = req.body.From;
var body = req.body.Body;
if(from.substring(0,1) != '+'){
response.setHeader('Content-Type', 'text/plain');
response.end();
return null;
}
client.users.create({
user_id: from
}).then(function (r) {
var userId = r.body.id;
var phoneNum = r.body.user_id;
var headers = {
'Authorization': 'Bearer ' + token,
'Accept': 'application/json',
'Content-Type': 'application/json'
};
request.get(
{
url:"https://api.intercom.io/conversations/?type=user&intercom_user_id=" + userId,
headers:headers
},
function (error, res, bodyResponse) {
var obj = JSON.parse(bodyResponse);
if(obj.conversations == undefined || obj.conversations.length == 0){
var message = {
message_type: "email",
subject: "From Twilio with user phone number: " + phoneNum,
body: body,
from: {
type: "user",
id: userId
}
};
client.messages.create(message);
console.log('create message');
}else{
var postData = {
"intercom_user_id": userId,
"body": body,
"type": "user",
"message_type": "comment"
};
postData = JSON.stringify(postData);
/* send reply to last convo */
request.post(
{
url: 'https://api.intercom.io/conversations/last/reply',
headers: headers,
body: postData
},
function (error, res, body) {
console.log('error ' + error);
}
);
console.log('reply message');
}
response.setHeader('Content-Type', 'text/plain');
response.end();
}
);
});
};