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 7.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
178
179
180
181
182
183
184
  1. namespace ImageCaption.Controllers
  2. {
  3. using System;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Net.Http;
  9. using System.Net.Http.Headers;
  10. using System.Text.RegularExpressions;
  11. using System.Threading.Tasks;
  12. using System.Web.Http;
  13. using Microsoft.Bot.Connector;
  14. using Services;
  15. [BotAuthentication]
  16. public class MessagesController : ApiController
  17. {
  18. private readonly ICaptionService captionService = new MicrosoftCognitiveCaptionService();
  19. /// <summary>
  20. /// POST: api/Messages
  21. /// Receive a message from a user and reply to it
  22. /// </summary>
  23. public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
  24. {
  25. if (activity.Type == ActivityTypes.Message)
  26. {
  27. var connector = new ConnectorClient(new Uri(activity.ServiceUrl));
  28. string message;
  29. try
  30. {
  31. message = await this.GetCaptionAsync(activity, connector);
  32. }
  33. catch (ArgumentException e)
  34. {
  35. message = "Did you upload an image? I'm more of a visual person. " +
  36. "Try sending me an image or an image URL";
  37. Trace.TraceError(e.ToString());
  38. }
  39. catch (Exception e)
  40. {
  41. message = "Oops! Something went wrong. Try again later.";
  42. Trace.TraceError(e.ToString());
  43. }
  44. Activity reply = activity.CreateReply(message);
  45. await connector.Conversations.ReplyToActivityAsync(reply);
  46. }
  47. else
  48. {
  49. await this.HandleSystemMessage(activity);
  50. }
  51. var response = this.Request.CreateResponse(HttpStatusCode.OK);
  52. return response;
  53. }
  54. private static async Task<Stream> GetImageStream(ConnectorClient connector, Attachment imageAttachment)
  55. {
  56. using (var httpClient = new HttpClient())
  57. {
  58. // The Skype attachment URLs are secured by JwtToken,
  59. // you should set the JwtToken of your bot as the authorization header for the GET request your bot initiates to fetch the image.
  60. // https://github.com/Microsoft/BotBuilder/issues/662
  61. var uri = new Uri(imageAttachment.ContentUrl);
  62. if (uri.Host.EndsWith("skype.com") && uri.Scheme == "https")
  63. {
  64. httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await GetTokenAsync(connector));
  65. httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream"));
  66. }
  67. return await httpClient.GetStreamAsync(uri);
  68. }
  69. }
  70. /// <summary>
  71. /// Gets the href value in an anchor element.
  72. /// </summary>
  73. /// Skype transforms raw urls to html. Here we extract the href value from the url
  74. /// <param name="text">Anchor tag html.</param>
  75. /// <param name="url">Url if valid anchor tag, null otherwise</param>
  76. /// <returns>True if valid anchor element</returns>
  77. private static bool TryParseAnchorTag(string text, out string url)
  78. {
  79. var regex = new Regex("^<a href=\"(?<href>[^\"]*)\">[^<]*</a>$", RegexOptions.IgnoreCase);
  80. url = regex.Matches(text).OfType<Match>().Select(m => m.Groups["href"].Value).FirstOrDefault();
  81. return url != null;
  82. }
  83. /// <summary>
  84. /// Gets the JwT token of the bot.
  85. /// </summary>
  86. /// <param name="connector"></param>
  87. /// <returns>JwT token of the bot</returns>
  88. private static async Task<string> GetTokenAsync(ConnectorClient connector)
  89. {
  90. var credentials = connector.Credentials as MicrosoftAppCredentials;
  91. if (credentials != null)
  92. {
  93. return await credentials.GetTokenAsync();
  94. }
  95. return null;
  96. }
  97. /// <summary>
  98. /// Gets the caption asynchronously by checking the type of the image (stream vs URL)
  99. /// and calling the appropriate caption service method.
  100. /// </summary>
  101. /// <param name="activity">The activity.</param>
  102. /// <param name="connector">The connector.</param>
  103. /// <returns>The caption if found</returns>
  104. /// <exception cref="ArgumentException">The activity doesn't contain a valid image attachment or an image URL.</exception>
  105. private async Task<string> GetCaptionAsync(Activity activity, ConnectorClient connector)
  106. {
  107. var imageAttachment = activity.Attachments?.FirstOrDefault(a => a.ContentType.Contains("image"));
  108. if (imageAttachment != null)
  109. {
  110. using (var stream = await GetImageStream(connector, imageAttachment))
  111. {
  112. return await this.captionService.GetCaptionAsync(stream);
  113. }
  114. }
  115. string url;
  116. if (TryParseAnchorTag(activity.Text, out url))
  117. {
  118. return await this.captionService.GetCaptionAsync(url);
  119. }
  120. if (Uri.IsWellFormedUriString(activity.Text, UriKind.Absolute))
  121. {
  122. return await this.captionService.GetCaptionAsync(activity.Text);
  123. }
  124. // If we reach here then the activity is neither an image attachment nor an image URL.
  125. throw new ArgumentException("The activity doesn't contain a valid image attachment or an image URL.");
  126. }
  127. /// <summary>
  128. /// Handles the system activity.
  129. /// </summary>
  130. /// <param name="activity">The activity.</param>
  131. /// <returns>Activity</returns>
  132. private async Task<Activity> HandleSystemMessage(Activity activity)
  133. {
  134. switch (activity.Type)
  135. {
  136. case ActivityTypes.DeleteUserData:
  137. // Implement user deletion here
  138. // If we handle user deletion, return a real message
  139. break;
  140. case ActivityTypes.ConversationUpdate:
  141. // Greet the user the first time the bot is added to a conversation.
  142. if (activity.MembersAdded.Any(m => m.Id == activity.Recipient.Id))
  143. {
  144. var connector = new ConnectorClient(new Uri(activity.ServiceUrl));
  145. var response = activity.CreateReply();
  146. response.Text = "Hi! I am ImageCaption Bot. I can understand the content of any image" +
  147. " and try to describe it as well as any human. Try sending me an image or an image URL.";
  148. await connector.Conversations.ReplyToActivityAsync(response);
  149. }
  150. break;
  151. case ActivityTypes.ContactRelationUpdate:
  152. // Handle add/remove from contact lists
  153. break;
  154. case ActivityTypes.Typing:
  155. // Handle knowing that the user is typing
  156. break;
  157. case ActivityTypes.Ping:
  158. break;
  159. }
  160. return null;
  161. }
  162. }
  163. }
Tip!

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

Comments

Loading...