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 6.5 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
  1. // This loads the environment variables from the .env file
  2. require('dotenv-extended').load();
  3. var builder = require('botbuilder');
  4. var restify = require('restify');
  5. var Swagger = require('swagger-client');
  6. var Promise = require('bluebird');
  7. var url = require('url');
  8. var fs = require('fs');
  9. var util = require('util');
  10. // Swagger client for Bot Connector API
  11. var connectorApiClient = new Swagger(
  12. {
  13. url: 'https://raw.githubusercontent.com/Microsoft/BotBuilder/master/CSharp/Library/Microsoft.Bot.Connector.Shared/Swagger/ConnectorAPI.json',
  14. usePromise: true
  15. });
  16. // Setup Restify Server
  17. var server = restify.createServer();
  18. server.listen(process.env.port || process.env.PORT || 3978, function () {
  19. console.log('%s listening to %s', server.name, server.url);
  20. });
  21. // Create chat bot
  22. var connector = new builder.ChatConnector({
  23. appId: process.env.MICROSOFT_APP_ID,
  24. appPassword: process.env.MICROSOFT_APP_PASSWORD
  25. });
  26. // Listen for messages
  27. server.post('/api/messages', connector.listen());
  28. // Bot Dialogs
  29. var bot = new builder.UniversalBot(connector, [
  30. function (session) {
  31. session.send('Welcome, here you can see attachment alternatives:');
  32. builder.Prompts.choice(session, 'What sample option would you like to see?', Options, {
  33. maxRetries: 3
  34. });
  35. },
  36. function (session, results) {
  37. var option = results.response ? results.response.entity : Inline;
  38. switch (option) {
  39. case Inline:
  40. return sendInline(session, './images/small-image.png', 'image/png', 'BotFrameworkLogo.png');
  41. case Upload:
  42. return uploadFileAndSend(session, './images/big-image.png', 'image/png', 'BotFramework.png');
  43. case External:
  44. var url = 'https://docs.microsoft.com/en-us/bot-framework/media/how-it-works/architecture-resize.png';
  45. return sendInternetUrl(session, url, 'image/png', 'BotFrameworkOverview.png');
  46. }
  47. }]);
  48. var Inline = 'Show inline attachment';
  49. var Upload = 'Show uploaded attachment';
  50. var External = 'Show Internet attachment';
  51. var Options = [Inline, Upload, External];
  52. // Sends attachment inline in base64
  53. function sendInline(session, filePath, contentType, attachmentFileName) {
  54. fs.readFile(filePath, function (err, data) {
  55. if (err) {
  56. return session.send('Oops. Error reading file.');
  57. }
  58. var base64 = Buffer.from(data).toString('base64');
  59. var msg = new builder.Message(session)
  60. .addAttachment({
  61. contentUrl: util.format('data:%s;base64,%s', contentType, base64),
  62. contentType: contentType,
  63. name: attachmentFileName
  64. });
  65. session.send(msg);
  66. });
  67. }
  68. // Uploads a file using the Connector API and sends attachment
  69. function uploadFileAndSend(session, filePath, contentType, attachmentFileName) {
  70. // read file content and upload
  71. fs.readFile(filePath, function (err, data) {
  72. if (err) {
  73. return session.send('Oops. Error reading file.');
  74. }
  75. // Upload file data using helper function
  76. uploadAttachment(
  77. data,
  78. contentType,
  79. attachmentFileName,
  80. connector,
  81. connectorApiClient,
  82. session.message.address.serviceUrl,
  83. session.message.address.conversation.id)
  84. .then(function (attachmentUrl) {
  85. // Send Message with Attachment obj using returned Url
  86. var msg = new builder.Message(session)
  87. .addAttachment({
  88. contentUrl: attachmentUrl,
  89. contentType: contentType,
  90. name: attachmentFileName
  91. });
  92. session.send(msg);
  93. })
  94. .catch(function (err) {
  95. console.log('Error uploading file', err);
  96. session.send('Oops. Error uploading file. ' + err.message);
  97. });
  98. });
  99. }
  100. // Sends attachment using an Internet url
  101. function sendInternetUrl(session, url, contentType, attachmentFileName) {
  102. var msg = new builder.Message(session)
  103. .addAttachment({
  104. contentUrl: url,
  105. contentType: contentType,
  106. name: attachmentFileName
  107. });
  108. session.send(msg);
  109. }
  110. // Uploads file to Connector API and returns Attachment URLs
  111. function uploadAttachment(fileData, contentType, fileName, connector, connectorApiClient, baseServiceUrl, conversationId) {
  112. var base64 = Buffer.from(fileData).toString('base64');
  113. // Inject the connector's JWT token into to the Swagger client
  114. function addTokenToClient(connector, clientPromise) {
  115. // ask the connector for the token. If it expired, a new token will be requested to the API
  116. var obtainToken = Promise.promisify(connector.addAccessToken.bind(connector));
  117. var options = {};
  118. return Promise.all([clientPromise, obtainToken(options)]).then(function (values) {
  119. var client = values[0];
  120. var hasToken = !!options.headers.Authorization;
  121. if (hasToken) {
  122. var authHeader = options.headers.Authorization;
  123. client.clientAuthorizations.add('AuthorizationBearer', new Swagger.ApiKeyAuthorization('Authorization', authHeader, 'header'));
  124. }
  125. return client;
  126. });
  127. }
  128. // 1. inject the JWT from the connector to the client on every call
  129. return addTokenToClient(connector, connectorApiClient).then(function (client) {
  130. // 2. override API client host and schema (https://api.botframework.com) with channel's serviceHost (e.g.: https://slack.botframework.com or http://localhost:NNNN)
  131. var serviceUrl = url.parse(baseServiceUrl);
  132. var serviceScheme = serviceUrl.protocol.split(':')[0];
  133. client.setSchemes([serviceScheme]);
  134. client.setHost(serviceUrl.host);
  135. // 3. POST /v3/conversations/{conversationId}/attachments
  136. var uploadParameters = {
  137. conversationId: conversationId,
  138. attachmentUpload: {
  139. type: contentType,
  140. name: fileName,
  141. originalBase64: base64
  142. }
  143. };
  144. return client.Conversations.Conversations_UploadAttachment(uploadParameters)
  145. .then(function (res) {
  146. var attachmentId = res.obj.id;
  147. var attachmentUrl = serviceUrl;
  148. attachmentUrl.pathname = util.format('/v3/attachments/%s/views/%s', attachmentId, 'original');
  149. return attachmentUrl.format();
  150. });
  151. });
  152. }
Tip!

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

Comments

Loading...