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 5.0 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
  1. /*-----------------------------------------------------------------------------
  2. An image caption bot for the Microsoft Bot Framework.
  3. -----------------------------------------------------------------------------*/
  4. // This loads the environment variables from the .env file
  5. require('dotenv-extended').load();
  6. var builder = require('botbuilder'),
  7. needle = require('needle'),
  8. restify = require('restify'),
  9. url = require('url'),
  10. validUrl = require('valid-url'),
  11. captionService = require('./caption-service');
  12. //=========================================================
  13. // Bot Setup
  14. //=========================================================
  15. // Setup Restify Server
  16. var server = restify.createServer();
  17. server.listen(process.env.port || process.env.PORT || 3978, function () {
  18. console.log('%s listening to %s', server.name, server.url);
  19. });
  20. // Create chat bot
  21. var connector = new builder.ChatConnector({
  22. appId: process.env.MICROSOFT_APP_ID,
  23. appPassword: process.env.MICROSOFT_APP_PASSWORD
  24. });
  25. server.post('/api/messages', connector.listen());
  26. // Gets the caption by checking the type of the image (stream vs URL) and calling the appropriate caption service method.
  27. var bot = new builder.UniversalBot(connector, function (session) {
  28. if (hasImageAttachment(session)) {
  29. var stream = getImageStreamFromMessage(session.message);
  30. captionService
  31. .getCaptionFromStream(stream)
  32. .then(function (caption) { handleSuccessResponse(session, caption); })
  33. .catch(function (error) { handleErrorResponse(session, error); });
  34. } else {
  35. var imageUrl = parseAnchorTag(session.message.text) || (validUrl.isUri(session.message.text) ? session.message.text : null);
  36. if (imageUrl) {
  37. captionService
  38. .getCaptionFromUrl(imageUrl)
  39. .then(function (caption) { handleSuccessResponse(session, caption); })
  40. .catch(function (error) { handleErrorResponse(session, error); });
  41. } else {
  42. session.send('Did you upload an image? I\'m more of a visual person. Try sending me an image or an image URL');
  43. }
  44. }
  45. });
  46. //=========================================================
  47. // Bots Events
  48. //=========================================================
  49. //Sends greeting message when the bot is first added to a conversation
  50. bot.on('conversationUpdate', function (message) {
  51. if (message.membersAdded) {
  52. message.membersAdded.forEach(function (identity) {
  53. if (identity.id === message.address.bot.id) {
  54. var reply = new builder.Message()
  55. .address(message.address)
  56. .text('Hi! I am ImageCaption Bot. I can understand the content of any image and try to describe it as well as any human. Try sending me an image or an image URL.');
  57. bot.send(reply);
  58. }
  59. });
  60. }
  61. });
  62. //=========================================================
  63. // Utilities
  64. //=========================================================
  65. function hasImageAttachment(session) {
  66. return session.message.attachments.length > 0 &&
  67. session.message.attachments[0].contentType.indexOf('image') !== -1;
  68. }
  69. function getImageStreamFromMessage(message) {
  70. var headers = {};
  71. var attachment = message.attachments[0];
  72. if (checkRequiresToken(message)) {
  73. // The Skype attachment URLs are secured by JwtToken,
  74. // you should set the JwtToken of your bot as the authorization header for the GET request your bot initiates to fetch the image.
  75. // https://github.com/Microsoft/BotBuilder/issues/662
  76. connector.getAccessToken(function (error, token) {
  77. var tok = token;
  78. headers['Authorization'] = 'Bearer ' + token;
  79. headers['Content-Type'] = 'application/octet-stream';
  80. return needle.get(attachment.contentUrl, { headers: headers });
  81. });
  82. }
  83. headers['Content-Type'] = attachment.contentType;
  84. return needle.get(attachment.contentUrl, { headers: headers });
  85. }
  86. function checkRequiresToken(message) {
  87. return message.source === 'skype' || message.source === 'msteams';
  88. }
  89. /**
  90. * Gets the href value in an anchor element.
  91. * Skype transforms raw urls to html. Here we extract the href value from the url
  92. * @param {string} input Anchor Tag
  93. * @return {string} Url matched or null
  94. */
  95. function parseAnchorTag(input) {
  96. var match = input.match('^<a href=\"([^\"]*)\">[^<]*</a>$');
  97. if (match && match[1]) {
  98. return match[1];
  99. }
  100. return null;
  101. }
  102. //=========================================================
  103. // Response Handling
  104. //=========================================================
  105. function handleSuccessResponse(session, caption) {
  106. if (caption) {
  107. session.send('I think it\'s ' + caption);
  108. }
  109. else {
  110. session.send('Couldn\'t find a caption for this one');
  111. }
  112. }
  113. function handleErrorResponse(session, error) {
  114. session.send('Oops! Something went wrong. Try again later.');
  115. console.error(error);
  116. }
Tip!

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

Comments

Loading...