forked from microsoft/BotBuilder-Samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
215 lines (185 loc) · 7.39 KB
/
app.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
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
var Swagger = require('swagger-client');
var open = require('open');
var rp = require('request-promise');
// Config settings
var directLineSecret = 'DIRECTLINE_SECRET';
// directLineUserId is the field that identifies which user is sending activities to the Direct Line service.
// Because this value is created and sent within your Direct Line client, your bot should not
// trust the value for any security-sensitive operations. Instead, have the user log in and
// store any sign-in tokens against the Conversation or Private state fields. Those fields
// are secured by the conversation ID, which is protected with a signature.
var directLineUserId = 'DirectLineClient';
var useW3CWebSocket = false;
process.argv.forEach(function (val, index, array) {
if (val === 'w3c') {
useW3CWebSocket = true;
}
});
var directLineSpecUrl = 'https://docs.botframework.com/en-us/restapi/directline3/swagger.json';
var directLineClient = rp(directLineSpecUrl)
.then(function (spec) {
// Client
return new Swagger({
spec: JSON.parse(spec.trim()),
usePromise: true
});
})
.then(function (client) {
// Obtain a token using the Direct Line secret
return rp({
url: 'https://directline.botframework.com/v3/directline/tokens/generate',
method: 'POST',
headers: {
'Authorization': 'Bearer ' + directLineSecret
},
json: true
}).then(function (response) {
// Then, replace the client's auth secret with the new token
var token = response.token;
client.clientAuthorizations.add('AuthorizationBotConnector', new Swagger.ApiKeyAuthorization('Authorization', 'Bearer ' + token, 'header'));
return client;
});
})
.catch(function (err) {
console.error('Error initializing DirectLine client', err);
throw err;
});
// Once the client is ready, create a new conversation
directLineClient.then(function (client) {
client.Conversations.Conversations_StartConversation()
.then(function (response) {
var responseObj = response.obj;
// Start console input loop from stdin
sendMessagesFromConsole(client, responseObj.conversationId);
if (useW3CWebSocket) {
// Start receiving messages from WS stream - using W3C client
startReceivingW3CWebSocketClient(responseObj.streamUrl, responseObj.conversationId);
} else {
// Start receiving messages from WS stream - using Node client
startReceivingWebSocketClient(responseObj.streamUrl, responseObj.conversationId);
}
});
});
// Read from console (stdin) and send input to conversation using DirectLine client
function sendMessagesFromConsole(client, conversationId) {
var stdin = process.openStdin();
process.stdout.write('Command> ');
stdin.addListener('data', function (e) {
var input = e.toString().trim();
if (input) {
if (input.toLowerCase() === 'exit') {
return process.exit();
}
// Send message
client.Conversations.Conversations_PostActivity(
{
conversationId: conversationId,
activity: {
textFormat: 'plain',
text: input,
type: 'message',
from: {
id: directLineUserId,
name: directLineUserId
}
}
}).catch(function (err) {
console.error('Error sending message:', err);
});
process.stdout.write('Command> ');
}
});
}
function startReceivingWebSocketClient(streamUrl, conversationId) {
console.log('Starting WebSocket Client for message streaming on conversationId: ' + conversationId);
var ws = new (require('websocket').client)();
ws.on('connectFailed', function (error) {
console.log('Connect Error: ' + error.toString());
});
ws.on('connect', function (connection) {
console.log('WebSocket Client Connected');
connection.on('error', function (error) {
console.log("Connection Error: " + error.toString());
});
connection.on('close', function () {
console.log('WebSocket Client Disconnected');
});
connection.on('message', function (message) {
// Occasionally, the Direct Line service sends an empty message as a liveness ping
// Ignore these messages
if (message.type === 'utf8' && message.utf8Data.length > 0) {
var data = JSON.parse(message.utf8Data);
printMessages(data.activities);
// var watermark = data.watermark;
}
});
});
ws.connect(streamUrl);
}
function startReceivingW3CWebSocketClient(streamUrl, conversationId) {
console.log('Starting W3C WebSocket Client for message streaming on conversationId: ' + conversationId);
var ws = new (require('websocket').w3cwebsocket)(streamUrl);
ws.onerror = function () {
console.log('Connection Error');
};
ws.onopen = function () {
console.log('W3C WebSocket Client Connected');
};
ws.onclose = function () {
console.log('W3C WebSocket Client Disconnected');
};
ws.onmessage = function (e) {
// Occasionally, the Direct Line service sends an empty message as a liveness ping
// Ignore these messages
if (typeof e.data === 'string' && e.data.length > 0) {
var data = JSON.parse(e.data);
printMessages(data.activities);
// var watermark = data.watermark;
}
};
}
// Helpers methods
function printMessages(activities) {
if (activities && activities.length) {
// Ignore own messages
activities = activities.filter(function (m) { return m.from.id !== directLineUserId });
if (activities.length) {
process.stdout.clearLine();
process.stdout.cursorTo(0);
// Print other messages
activities.forEach(printMessage);
process.stdout.write('Command> ');
}
}
}
function printMessage(activity) {
if (activity.text) {
console.log(activity.text);
}
if (activity.attachments) {
activity.attachments.forEach(function (attachment) {
switch (attachment.contentType) {
case "application/vnd.microsoft.card.hero":
renderHeroCard(attachment);
break;
case "image/png":
console.log('Opening the requested image ' + attachment.contentUrl);
open(attachment.contentUrl);
break;
}
});
}
}
function renderHeroCard(attachment) {
var width = 70;
var contentLine = function (content) {
return ' '.repeat((width - content.length) / 2) +
content +
' '.repeat((width - content.length) / 2);
}
console.log('/' + '*'.repeat(width + 1));
console.log('*' + contentLine(attachment.content.title) + '*');
console.log('*' + ' '.repeat(width) + '*');
console.log('*' + contentLine(attachment.content.text) + '*');
console.log('*'.repeat(width + 1) + '/');
}