This repository has been archived by the owner on Jul 22, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
69 lines (61 loc) · 2.05 KB
/
index.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
'use strict';
require('dotenv').config();
const { Agent } = require('node-agent-sdk');
const agent = new Agent({
accountId: process.env.LP_ACCOUNT,
username: process.env.LP_USER,
appKey: process.env.LP_APP_KEY,
secret: process.env.LP_SECRET,
accessToken: process.env.LP_ACCESS_TOKEN,
accessTokenSecret: process.env.LP_TOKEN_SECRET
});
let openConvs = {};
agent.on('connected', () => {
console.log('connected...');
agent.setAgentState({ availability: 'AWAY' }); // Do not route me conversations, I'll join by myself.
agent.subscribeExConversations({
'convState': ['OPEN'] // subscribes to all open conversation in the account.
});
});
agent.on('cqm.ExConversationChangeNotification', notificationBody => {
notificationBody.changes.forEach(change => {
if (change.type === 'UPSERT') {
if (!openConvs[change.result.convId]) {
openConvs[change.result.convId] = change.result;
if (!getParticipantInfo(change.result.conversationDetails, agent.agentId)) {
agent.updateConversationField({
'conversationId': change.result.convId,
'conversationField': [{
'field': 'ParticipantsChange',
'type': 'ADD',
'role': 'MANAGER'
}]
}, () => {
agent.publishEvent({
dialogId: change.result.convId,
event: {
type: 'ContentEvent',
contentType: 'text/plain',
message: 'welcome from bot'
}
});
});
}
}
}
else if (change.type === 'DELETE') {
delete openConvs[change.result.convId];
console.log('conversation was closed.\n');
}
});
});
agent.on('error', err => {
console.log('got an error', err);
});
agent.on('closed', data => {
console.log('socket closed', data);
agent.reconnect();//regenerate token for reasons of authorization (data === 4401 || data === 4407)
});
function getParticipantInfo(convDetails, participantId) {
return convDetails.participants.filter(p => p.id === participantId)[0];
}