Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

app.js 7.4 KB

You have to be logged in to leave a comment. Sign In
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
  1. var Swagger = require('swagger-client');
  2. var open = require('open');
  3. var rp = require('request-promise');
  4. // Config settings
  5. var directLineSecret = 'DIRECTLINE_SECRET';
  6. // directLineUserId is the field that identifies which user is sending activities to the Direct Line service.
  7. // Because this value is created and sent within your Direct Line client, your bot should not
  8. // trust the value for any security-sensitive operations. Instead, have the user log in and
  9. // store any sign-in tokens against the Conversation or Private state fields. Those fields
  10. // are secured by the conversation ID, which is protected with a signature.
  11. var directLineUserId = 'DirectLineClient';
  12. var useW3CWebSocket = false;
  13. process.argv.forEach(function (val, index, array) {
  14. if (val === 'w3c') {
  15. useW3CWebSocket = true;
  16. }
  17. });
  18. var directLineSpecUrl = 'https://docs.botframework.com/en-us/restapi/directline3/swagger.json';
  19. var directLineClient = rp(directLineSpecUrl)
  20. .then(function (spec) {
  21. // Client
  22. return new Swagger({
  23. spec: JSON.parse(spec.trim()),
  24. usePromise: true
  25. });
  26. })
  27. .then(function (client) {
  28. // Obtain a token using the Direct Line secret
  29. // First, add the Direct Line Secret to the client's auth header
  30. client.clientAuthorizations.add('AuthorizationBotConnector', new Swagger.ApiKeyAuthorization('Authorization', 'Bearer ' + directLineSecret, 'header'));
  31. // Second, request a token for a new conversation
  32. return client.Tokens.Tokens_GenerateTokenForNewConversation().then(function (response) {
  33. // Then, replace the client's auth secret with the new token
  34. var token = response.obj.token;
  35. client.clientAuthorizations.add('AuthorizationBotConnector', new Swagger.ApiKeyAuthorization('Authorization', 'Bearer ' + token, 'header'));
  36. return client;
  37. });
  38. })
  39. .catch(function (err) {
  40. console.error('Error initializing DirectLine client', err);
  41. });
  42. // Once the client is ready, create a new conversation
  43. directLineClient.then(function (client) {
  44. client.Conversations.Conversations_StartConversation()
  45. .then(function (response) {
  46. var responseObj = response.obj;
  47. // Start console input loop from stdin
  48. sendMessagesFromConsole(client, responseObj.conversationId);
  49. if (useW3CWebSocket) {
  50. // Start receiving messages from WS stream - using W3C client
  51. startReceivingW3CWebSocketClient(responseObj.streamUrl, responseObj.conversationId);
  52. } else {
  53. // Start receiving messages from WS stream - using Node client
  54. startReceivingWebSocketClient(responseObj.streamUrl, responseObj.conversationId);
  55. }
  56. });
  57. });
  58. // Read from console (stdin) and send input to conversation using DirectLine client
  59. function sendMessagesFromConsole(client, conversationId) {
  60. var stdin = process.openStdin();
  61. process.stdout.write('Command> ');
  62. stdin.addListener('data', function (e) {
  63. var input = e.toString().trim();
  64. if (input) {
  65. if (input.toLowerCase() === 'exit') {
  66. return process.exit();
  67. }
  68. // Send message
  69. client.Conversations.Conversations_PostActivity(
  70. {
  71. conversationId: conversationId,
  72. activity: {
  73. textFormat: 'plain',
  74. text: input,
  75. type: 'message',
  76. from: {
  77. id: directLineUserId,
  78. name: directLineUserId
  79. }
  80. }
  81. }).catch(function (err) {
  82. console.error('Error sending message:', err);
  83. });
  84. process.stdout.write('Command> ');
  85. }
  86. });
  87. }
  88. function startReceivingWebSocketClient(streamUrl, conversationId) {
  89. console.log('Starting WebSocket Client for message streaming on conversationId: ' + conversationId);
  90. var ws = new (require('websocket').client)();
  91. ws.on('connectFailed', function (error) {
  92. console.log('Connect Error: ' + error.toString());
  93. });
  94. ws.on('connect', function (connection) {
  95. console.log('WebSocket Client Connected');
  96. connection.on('error', function (error) {
  97. console.log("Connection Error: " + error.toString());
  98. });
  99. connection.on('close', function () {
  100. console.log('WebSocket Client Disconnected');
  101. });
  102. connection.on('message', function (message) {
  103. // Occasionally, the Direct Line service sends an empty message as a liveness ping
  104. // Ignore these messages
  105. if (message.type === 'utf8' && message.utf8Data.length > 0) {
  106. var data = JSON.parse(message.utf8Data);
  107. printMessages(data.activities);
  108. // var watermark = data.watermark;
  109. }
  110. });
  111. });
  112. ws.connect(streamUrl);
  113. }
  114. function startReceivingW3CWebSocketClient(streamUrl, conversationId) {
  115. console.log('Starting W3C WebSocket Client for message streaming on conversationId: ' + conversationId);
  116. var ws = new (require('websocket').w3cwebsocket)(streamUrl);
  117. ws.onerror = function () {
  118. console.log('Connection Error');
  119. };
  120. ws.onopen = function () {
  121. console.log('W3C WebSocket Client Connected');
  122. };
  123. ws.onclose = function () {
  124. console.log('W3C WebSocket Client Disconnected');
  125. };
  126. ws.onmessage = function (e) {
  127. // Occasionally, the Direct Line service sends an empty message as a liveness ping
  128. // Ignore these messages
  129. if (typeof e.data === 'string' && e.data.length > 0) {
  130. var data = JSON.parse(e.data);
  131. printMessages(data.activities);
  132. // var watermark = data.watermark;
  133. }
  134. };
  135. }
  136. // Helpers methods
  137. function printMessages(activities) {
  138. if (activities && activities.length) {
  139. // Ignore own messages
  140. activities = activities.filter(function (m) { return m.from.id !== directLineUserId });
  141. if (activities.length) {
  142. process.stdout.clearLine();
  143. process.stdout.cursorTo(0);
  144. // Print other messages
  145. activities.forEach(printMessage);
  146. process.stdout.write('Command> ');
  147. }
  148. }
  149. }
  150. function printMessage(activity) {
  151. if (activity.text) {
  152. console.log(activity.text);
  153. }
  154. if (activity.attachments) {
  155. activity.attachments.forEach(function (attachment) {
  156. switch (attachment.contentType) {
  157. case "application/vnd.microsoft.card.hero":
  158. renderHeroCard(attachment);
  159. break;
  160. case "image/png":
  161. console.log('Opening the requested image ' + attachment.contentUrl);
  162. open(attachment.contentUrl);
  163. break;
  164. }
  165. });
  166. }
  167. }
  168. function renderHeroCard(attachment) {
  169. var width = 70;
  170. var contentLine = function (content) {
  171. return ' '.repeat((width - content.length) / 2) +
  172. content +
  173. ' '.repeat((width - content.length) / 2);
  174. }
  175. console.log('/' + '*'.repeat(width + 1));
  176. console.log('*' + contentLine(attachment.content.title) + '*');
  177. console.log('*' + ' '.repeat(width) + '*');
  178. console.log('*' + contentLine(attachment.content.text) + '*');
  179. console.log('*'.repeat(width + 1) + '/');
  180. }
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...