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

MessagesController.cs 10 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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
  1. namespace SimilarProducts.Controllers
  2. {
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Net.Http;
  10. using System.Net.Http.Headers;
  11. using System.Text.RegularExpressions;
  12. using System.Threading.Tasks;
  13. using System.Web.Http;
  14. using Microsoft.Bot.Connector;
  15. using Services;
  16. [BotAuthentication]
  17. public class MessagesController : ApiController
  18. {
  19. /// <summary>
  20. /// Maximum number of hero cards to be returned in the carousel. If this number is greater than 5, skype throws an exception.
  21. /// </summary>
  22. private const int MaxCardCount = 5;
  23. private readonly IImageSearchService imageService = new BingImageSearchService();
  24. /// <summary>
  25. /// POST: api/Messages
  26. /// Receive a message from a user and reply to it
  27. /// </summary>
  28. public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
  29. {
  30. if (activity.Type == ActivityTypes.Message)
  31. {
  32. var connector = new ConnectorClient(new Uri(activity.ServiceUrl));
  33. string message = null;
  34. bool replied = false;
  35. try
  36. {
  37. var images = await this.GetSimilarImagesAsync(activity, connector);
  38. if (images != null && images.Any())
  39. {
  40. Activity reply = activity.CreateReply("Here are some visually similar products I found");
  41. reply.Type = ActivityTypes.Message;
  42. reply.AttachmentLayout = "carousel";
  43. reply.Attachments = this.BuildImageAttachments(images.Take(MaxCardCount));
  44. await connector.Conversations.ReplyToActivityAsync(reply);
  45. replied = true;
  46. }
  47. else
  48. {
  49. message = "Couldn't find similar products images for this one";
  50. }
  51. }
  52. catch (ArgumentException e)
  53. {
  54. message = "Did you upload an image? I'm more of a visual person. " +
  55. "Try sending me an image or an image URL";
  56. Trace.TraceError(e.ToString());
  57. }
  58. catch (Exception e)
  59. {
  60. message = "Oops! Something went wrong. Try again later.";
  61. Trace.TraceError(e.ToString());
  62. }
  63. if (!replied)
  64. {
  65. Activity reply = activity.CreateReply(message);
  66. await connector.Conversations.ReplyToActivityAsync(reply);
  67. }
  68. }
  69. else
  70. {
  71. await this.HandleSystemMessage(activity);
  72. }
  73. var response = this.Request.CreateResponse(HttpStatusCode.OK);
  74. return response;
  75. }
  76. /// <summary>
  77. /// Gets the image stream.
  78. /// </summary>
  79. /// <param name="connector">The connector.</param>
  80. /// <param name="imageAttachment">The image attachment.</param>
  81. /// <returns></returns>
  82. private static async Task<Stream> GetImageStream(ConnectorClient connector, Attachment imageAttachment)
  83. {
  84. using (var httpClient = new HttpClient())
  85. {
  86. // The Skype attachment URLs are secured by JwtToken,
  87. // you should set the JwtToken of your bot as the authorization header for the GET request your bot initiates to fetch the image.
  88. // https://github.com/Microsoft/BotBuilder/issues/662
  89. var uri = new Uri(imageAttachment.ContentUrl);
  90. if (uri.Host.EndsWith("skype.com") && uri.Scheme == "https")
  91. {
  92. httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await GetTokenAsync(connector));
  93. httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream"));
  94. }
  95. return await httpClient.GetStreamAsync(uri);
  96. }
  97. }
  98. /// <summary>
  99. /// Gets the href value in an anchor element.
  100. /// </summary>
  101. /// Skype transforms raw urls to html. Here we extract the href value from the url
  102. /// <param name="text">Anchor tag html.</param>
  103. /// <param name="url">Url if valid anchor tag, null otherwise</param>
  104. /// <returns>True if valid anchor element</returns>
  105. private static bool TryParseAnchorTag(string text, out string url)
  106. {
  107. var regex = new Regex("^<a href=\"(?<href>[^\"]*)\">[^<]*</a>$", RegexOptions.IgnoreCase);
  108. url = regex.Matches(text).OfType<Match>().Select(m => m.Groups["href"].Value).FirstOrDefault();
  109. return url != null;
  110. }
  111. /// <summary>
  112. /// Gets the JwT token of the bot.
  113. /// </summary>
  114. /// <param name="connector"></param>
  115. /// <returns>JwT token of the bot</returns>
  116. private static async Task<string> GetTokenAsync(ConnectorClient connector)
  117. {
  118. var credentials = connector.Credentials as MicrosoftAppCredentials;
  119. if (credentials != null)
  120. {
  121. return await credentials.GetTokenAsync();
  122. }
  123. return null;
  124. }
  125. /// <summary>
  126. /// Gets a list of visually similar products asynchronously by checking the type of the image (stream vs URL)
  127. /// and calling the appropriate image service method.
  128. /// </summary>
  129. /// <param name="activity">The activity.</param>
  130. /// <param name="connector">The connector.</param>
  131. /// <returns>List of visually similar products' images.</returns>
  132. /// <exception cref="ArgumentException">The activity doesn't contain a valid image attachment or an image URL.</exception>
  133. private async Task<IList<ImageResult>> GetSimilarImagesAsync(Activity activity, ConnectorClient connector)
  134. {
  135. var imageAttachment = activity.Attachments?.FirstOrDefault(a => a.ContentType.Contains("image"));
  136. if (imageAttachment != null)
  137. {
  138. using (var stream = await GetImageStream(connector, imageAttachment))
  139. {
  140. return await this.imageService.GetSimilarProductImagesAsync(stream);
  141. }
  142. }
  143. string url;
  144. if (TryParseAnchorTag(activity.Text, out url))
  145. {
  146. return await this.imageService.GetSimilarProductImagesAsync(url);
  147. }
  148. if (Uri.IsWellFormedUriString(activity.Text, UriKind.Absolute))
  149. {
  150. return await this.imageService.GetSimilarProductImagesAsync(activity.Text);
  151. }
  152. // If we reach here then the activity is neither an image attachment nor an image URL.
  153. throw new ArgumentException("The activity doesn't contain a valid image attachment or an image URL.");
  154. }
  155. private IList<Attachment> BuildImageAttachments(IEnumerable<ImageResult> images)
  156. {
  157. var attachments = new List<Attachment>();
  158. foreach (var image in images)
  159. {
  160. // Construct Card
  161. var heroCard = new HeroCard
  162. {
  163. Title = image.Name,
  164. Subtitle = image.HostPageDisplayUrl,
  165. Images = new List<CardImage>()
  166. };
  167. // Add Card Image
  168. var img = new CardImage { Url = image.ThumbnailUrl };
  169. heroCard.Images.Add(img);
  170. // Add Card Buttons
  171. heroCard.Buttons = new List<CardAction>();
  172. var buyButton = new CardAction();
  173. var searchButton = new CardAction();
  174. // Buy Button
  175. buyButton.Title = "Buy from merchant";
  176. buyButton.Type = "openUrl";
  177. buyButton.Value = image.HostPageUrl;
  178. // Search More button
  179. searchButton.Title = "Find more in Bing";
  180. searchButton.Type = "openUrl";
  181. searchButton.Value = image.WebSearchUrl;
  182. heroCard.Buttons.Add(buyButton);
  183. heroCard.Buttons.Add(searchButton);
  184. attachments.Add(heroCard.ToAttachment());
  185. }
  186. return attachments;
  187. }
  188. /// <summary>
  189. /// Handles the system activity.
  190. /// </summary>
  191. /// <param name="activity">The activity.</param>
  192. /// <returns>Activity</returns>
  193. private async Task<Activity> HandleSystemMessage(Activity activity)
  194. {
  195. switch (activity.Type)
  196. {
  197. case ActivityTypes.DeleteUserData:
  198. // Implement user deletion here
  199. // If we handle user deletion, return a real message
  200. break;
  201. case ActivityTypes.ConversationUpdate:
  202. // Greet the user the first time the bot is added to a conversation.
  203. if (activity.MembersAdded.Any(m => m.Id == activity.Recipient.Id))
  204. {
  205. var connector = new ConnectorClient(new Uri(activity.ServiceUrl));
  206. var response = activity.CreateReply();
  207. response.Text = "Hi! I am SimilarProducts Bot. I can find you similar products." +
  208. " Try sending me an image or an image URL.";
  209. await connector.Conversations.ReplyToActivityAsync(response);
  210. }
  211. break;
  212. case ActivityTypes.ContactRelationUpdate:
  213. // Handle add/remove from contact lists
  214. break;
  215. case ActivityTypes.Typing:
  216. // Handle knowing that the user is typing
  217. break;
  218. case ActivityTypes.Ping:
  219. break;
  220. }
  221. return null;
  222. }
  223. }
  224. }
Tip!

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

Comments

Loading...