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 6.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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
  1. namespace SpeechToText.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.Threading.Tasks;
  11. using System.Web.Http;
  12. using Microsoft.Bot.Connector;
  13. using Services;
  14. [BotAuthentication]
  15. public class MessagesController : ApiController
  16. {
  17. private readonly MicrosoftCognitiveSpeechService speechService = new MicrosoftCognitiveSpeechService();
  18. /// <summary>
  19. /// POST: api/Messages
  20. /// Receive a message from a user and reply to it
  21. /// </summary>
  22. public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
  23. {
  24. if (activity.Type == ActivityTypes.Message)
  25. {
  26. var connector = new ConnectorClient(new Uri(activity.ServiceUrl));
  27. string message;
  28. try
  29. {
  30. var audioAttachment = activity.Attachments?.FirstOrDefault(a => a.ContentType.Equals("audio/wav") || a.ContentType.Equals("application/octet-stream"));
  31. if (audioAttachment != null)
  32. {
  33. var stream = await GetAudioStream(connector, audioAttachment);
  34. var text = await this.speechService.GetTextFromAudioAsync(stream);
  35. message = ProcessText(text);
  36. }
  37. else
  38. {
  39. message = "Did you upload an audio file? I'm more of an audible person. Try sending me a wav file";
  40. }
  41. }
  42. catch (Exception e)
  43. {
  44. message = "Oops! Something went wrong. Try again later.";
  45. Trace.TraceError(e.ToString());
  46. }
  47. Activity reply = activity.CreateReply(message);
  48. await connector.Conversations.ReplyToActivityAsync(reply);
  49. }
  50. else
  51. {
  52. await this.HandleSystemMessage(activity);
  53. }
  54. var response = this.Request.CreateResponse(HttpStatusCode.OK);
  55. return response;
  56. }
  57. private static string ProcessText(string text)
  58. {
  59. string message = "You said : " + text + ".";
  60. if (!string.IsNullOrEmpty(text))
  61. {
  62. var wordCount = text.Split(' ').Count(x => !string.IsNullOrEmpty(x));
  63. message += "\n\nWord Count: " + wordCount;
  64. var characterCount = text.Count(c => c != ' ');
  65. message += "\n\nCharacter Count: " + characterCount;
  66. var spaceCount = text.Count(c => c == ' ');
  67. message += "\n\nSpace Count: " + spaceCount;
  68. var vowelCount = text.ToUpper().Count("AEIOU".Contains);
  69. message += "\n\nVowel Count: " + vowelCount;
  70. }
  71. return message;
  72. }
  73. private static async Task<Stream> GetAudioStream(ConnectorClient connector, Attachment audioAttachment)
  74. {
  75. using (var httpClient = new HttpClient())
  76. {
  77. // The Skype attachment URLs are secured by JwtToken,
  78. // you should set the JwtToken of your bot as the authorization header for the GET request your bot initiates to fetch the image.
  79. // https://github.com/Microsoft/BotBuilder/issues/662
  80. var uri = new Uri(audioAttachment.ContentUrl);
  81. if (uri.Host.EndsWith("skype.com") && uri.Scheme == "https")
  82. {
  83. httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await GetTokenAsync(connector));
  84. httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream"));
  85. }
  86. return await httpClient.GetStreamAsync(uri);
  87. }
  88. }
  89. /// <summary>
  90. /// Gets the JwT token of the bot.
  91. /// </summary>
  92. /// <param name="connector"></param>
  93. /// <returns>JwT token of the bot</returns>
  94. private static async Task<string> GetTokenAsync(ConnectorClient connector)
  95. {
  96. var credentials = connector.Credentials as MicrosoftAppCredentials;
  97. if (credentials != null)
  98. {
  99. return await credentials.GetTokenAsync();
  100. }
  101. return null;
  102. }
  103. /// <summary>
  104. /// Handles the system activity.
  105. /// </summary>
  106. /// <param name="activity">The activity.</param>
  107. /// <returns>Activity</returns>
  108. private async Task<Activity> HandleSystemMessage(Activity activity)
  109. {
  110. switch (activity.Type)
  111. {
  112. case ActivityTypes.DeleteUserData:
  113. // Implement user deletion here
  114. // If we handle user deletion, return a real message
  115. break;
  116. case ActivityTypes.ConversationUpdate:
  117. // Greet the user the first time the bot is added to a conversation.
  118. if (activity.MembersAdded.Any(m => m.Id == activity.Recipient.Id))
  119. {
  120. var connector = new ConnectorClient(new Uri(activity.ServiceUrl));
  121. var response = activity.CreateReply();
  122. response.Text = "Hi! I am SpeechToText Bot. I can understand the content of any audio and convert it to text. Try sending me a wav file.";
  123. await connector.Conversations.ReplyToActivityAsync(response);
  124. }
  125. break;
  126. case ActivityTypes.ContactRelationUpdate:
  127. // Handle add/remove from contact lists
  128. break;
  129. case ActivityTypes.Typing:
  130. // Handle knowing that the user is typing
  131. break;
  132. case ActivityTypes.Ping:
  133. break;
  134. }
  135. return null;
  136. }
  137. }
  138. }
Tip!

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

Comments

Loading...