private void OnMessageReceived(object sender, OnMessageReceivedArgs args) { BotMessage message = Bot.ProcessCommand(args.ChatMessage.Username, args.ChatMessage.Message); switch (message) { case { Type: BotMessageType.Error } :
/// <summary> /// Sends the response message with a special markup. /// </summary> /// <param name="response">The response to send.</param> /// <returns>The task that represents the process of sending the response.</returns> private async Task SendResponseWithMarkup(BotMessage response) { var senderId = response.Sender.Id; var responseMarkup = MessageConverter.ConvertMarkup(response.Markup); response.MessageId = await _responder.SendMessageAsync(senderId, response.Text, responseMarkup).ConfigureAwait(false); }
public static async void InitBot() { memoryBot = new Bot(); InitResponses(memoryBot); memoryBot.ConnectionStatusChanged += (bool isConnected) => { if (isConnected) { //Utils.PrintChatHubInfo(); Memory.TestAccord(); SlackChatHub H = new SlackChatHub(); H.ID = "D10DCBHSB"; Console.WriteLine("Connected"); BotMessage ConnectionMessage = new BotMessage(); ConnectionMessage.Text = "hello taylor"; ConnectionMessage.ChatHub = H; memoryBot.Say(ConnectionMessage).Wait(); } }; await memoryBot.Connect("*******************************"); Reminder.StartBrain(); }
public override string ToString() { try { string StockStatus = String.Empty; const string StockStatusOutOfStock = "Нет в наличии"; if (Stock.Count > 0 && Stock.ElementAt(Stock.Count - 1) == null || Stock.Count > 0 && Stock.ElementAt(Stock.Count - 1) != null && Stock.ElementAt(Stock.Count - 1).Balance == 0) { StockStatus = StockStatusOutOfStock; } if (Stock.Count == 0) { StockStatus = StockStatusOutOfStock; } string price = CurrentPrice.ToString(); return("Название: " + Name + BotMessage.NewLine() + "Цена: " + price + " / " + Unit.ShortName + BotMessage.NewLine() + "Описание: " + Text + BotMessage.NewLine() + StockStatus); } catch { return(String.Empty); } }
public void PingdomGetResponseTest() { List <SlackAttachment> attach = new List <SlackAttachment>(); attach.Add(new SlackAttachment() { Title = "ICR:Bug:Critical:Test Jira Ticket. Virtual System is down (#9999)", Text = "ICR:Bug:Critical:Test Jira Ticket. Virtual System is down (#9999)" }); ResponseContext context = new ResponseContext() { Message = new SlackMessage() { Attachments = attach } }; string loc = Assembly.GetExecutingAssembly().Location; string location = Path.GetDirectoryName(loc); ConfigController cfg = new ConfigController(location); if (cfg.LoadConfig()) { SlackBotController sbc = new SlackBotController(cfg); PingdomResponder ping = new PingdomResponder(sbc); BotMessage bm = ping.GetResponse(context); Assert.True(bm.Text.Contains("Jira Ticket")); } }
private async Task SendMessage(ResponseMessage responseMessage) { var chatHub = await this.slackHelper.GetChatHub(responseMessage, this.connection); if (chatHub != null) { if (responseMessage is TypingIndicatorMessage) { this.log.LogDebug($"Indicating typing on channel '{chatHub.Name}'"); await this.connection.IndicateTyping(chatHub); } else { var botMessage = new BotMessage { ChatHub = chatHub, Text = responseMessage.Text, Attachments = this.slackHelper.ConvertAttachmentsToSlackAttachments(responseMessage.Attachments) }; var textTrimmed = botMessage.Text.Length > 50 ? botMessage.Text.Substring(0, 50) + "..." : botMessage.Text; this.log.LogDebug($"Sending message '{textTrimmed}'"); await this.connection.Say(botMessage); } } else { this.log.LogError($"Unable to find channel for message '{responseMessage.Text}'. Message not sent"); } }
public BotMessage Parse(Message message) { BotMessage result = new BotMessage(); BotCommands botCommands; if (message != null) { if (message.Type == Telegram.Bot.Types.Enums.MessageType.Text) { if (message.Text.StartsWith("/")) { botCommands = new BotCommands(_service); result = botCommands.Command(message); } else { botCommands = new BotCommands(_service); result = botCommands.Command(message); } } else { result.Body = "Непонятно о.0"; } } return(result); }
private async Task should_send_message( [Frozen] Mock <IConnectionFactory> connectionFactory, Mock <IChatClient> chatClient, Mock <IWebSocketClient> webSocket, SlackConnection slackConnection) { // given const string slackKey = "key-yay"; var connectionInfo = new ConnectionInformation { WebSocket = webSocket.Object, SlackKey = slackKey }; await slackConnection.Initialise(connectionInfo); connectionFactory .Setup(x => x.CreateChatClient()) .Returns(chatClient.Object); var message = new BotMessage { Text = "some text", ChatHub = new SlackChatHub { Id = "channel-id" }, Attachments = new List <SlackAttachment>() }; // when await slackConnection.Say(message); // then chatClient .Verify(x => x.PostMessage(slackKey, message.ChatHub.Id, message.Text, message.Attachments), Times.Once); }
public override List <IRCResponse> GetResponse(BotMessage message) { if (!Regex.IsMatch(message.Command, "^(r(emove)?tell)$", RegexOptions.IgnoreCase)) { return(null); } if (message.ParameterList.Count == 0) { return new List <IRCResponse>() { new IRCResponse(ResponseType.Say, "You didn't specify a message to remove!", message.ReplyTo) } } ; List <string> keysToRemove = new List <string>(); foreach (string user in Tell.MessageMap.Keys) { List <IRCResponse> response = new List <IRCResponse>(); lock (Tell.tellMapLock) { int index = Tell.MessageMap[user].FindIndex(s => s.From.ToLowerInvariant() == message.User.Name.ToLowerInvariant() && Regex.IsMatch(s.Message, ".*" + message.Parameters + ".*", RegexOptions.IgnoreCase)); if (index < 0) { continue; } response.Add(new IRCResponse(ResponseType.Say, "Message \"" + Tell.MessageMap[user][index].Message + "\", sent on date \"" + Tell.MessageMap[user][index].SentDate + "\" to \"" + user + "\" removed from the message database!", message.ReplyTo)); Tell.MessageMap[user].RemoveAt(index); if (Tell.MessageMap[user].Count == 0) { Tell.MessageMap.Remove(user); } } Tell.WriteMessages(); return(response); } return(new List <IRCResponse>() { new IRCResponse(ResponseType.Say, "No message sent by you containing \"" + message.Parameters + "\" found in the message database!", message.ReplyTo) }); } }
public BotMessage ToBotMessage(RemoteIDEModel model) { var message = new BotMessage() { Text = $"{model.IDEUserIdentity.DisplayName} is doing some coding!" }; var attachment = new SlackAttachment() { ThumbUrl = model.IDEUserIdentity.ImageUrl, AuthorName = model.IDEUserIdentity.DisplayName, AuthorLink = model.IDEUserIdentity.Id, AuthorIcon = model.IDEUserIdentity.ImageUrl, ColorHex = new System.Windows.Media.ColorConverter().ConvertToString(model.IDEUserIdentity.GetUserColour()), Fallback = model.OpenFiles.Count == 0 ? $"{ model.IDEUserIdentity.DisplayName} has no files open." : $"{model.IDEUserIdentity.DisplayName} has {model.OpenFiles.Count} files open in {model.OpenFiles.FirstOrDefault()?.RepoUrl}" }; foreach (var field in GetSlackFields(model).OrderBy(f => f.Title.Count(c => c == '.')).ThenBy(f => f.Title)) { attachment.Fields.Add(field); } message.Attachments.Add(attachment); return(message); }
public override List <IRCResponse> GetResponse(BotMessage message) { if (Regex.IsMatch(message.Command, @"^(goo\.?gl|shorten)$", RegexOptions.IgnoreCase)) { // URL given if (message.ParameterList.Count > 0) { string shortURL = URL.Shorten(message.Parameters); if (shortURL != null) { return(new List <IRCResponse>() { new IRCResponse(ResponseType.Say, shortURL, message.ReplyTo) }); } return(new List <IRCResponse>() { new IRCResponse(ResponseType.Say, "No URL detected in your message.", message.ReplyTo) }); } // No URL given else { return(new List <IRCResponse>() { new IRCResponse(ResponseType.Say, "You didn't give a URL to shorten!", message.ReplyTo) }); } } else { return(null); } }
public void Fire(BaseRtmResponse response) { AllMessages?.Invoke(this, new RtmMessageEventArgs <BaseRtmResponse>(response)); switch (response) { case HelloResponse helloResponse: HelloMessage?.Invoke(this, new RtmMessageEventArgs <HelloResponse>(helloResponse)); break; case PongResponse pongResponse: PongMessage?.Invoke(this, new RtmMessageEventArgs <PongResponse>(pongResponse)); break; case UserTypingResponse userTypingResponse: UserTypingMessage?.Invoke(this, new RtmMessageEventArgs <UserTypingResponse>(userTypingResponse)); break; case BaseMessageResponse messageResponse: switch (messageResponse) { case BotMessageResponse botMessageResponse: BotMessage?.Invoke(this, new RtmMessageEventArgs <BotMessageResponse>(botMessageResponse)); break; default: UserMessage?.Invoke(this, new RtmMessageEventArgs <UserMessageResponse>(messageResponse)); break; } break; default: throw new NotImplementedException(); } }
public override async Task <BotMessage> HandleMessage(BotMessage message) { if (message.Text.ToLowerInvariant().Trim().Trim('?', '!', '.', ';', '-').Equals("what")) { var responses = new List <string>() { "Say what again.", "English m**********r do you speak it!?", "SAY WHAT again! And I dare you, I double dare you m**********r! Say what one more time.", "500 Internal Server Error" }; // Construct an message var counter = message.GetBotPerUserInConversationData <int>("WhatCounter"); message.Response = responses[counter]; // Increment counter message.SetBotPerUserInConversationData("WhatCounter", (counter + 1) % responses.Count); // Handle message message.IsHandled = true; } return(message); }
public async Task <MessageSet> SendMessage(string message) { try { var messageToSend = new BotMessage() { Text = message, ConversationId = _lastConversation.ConversationId }; var contentPost = new StringContent(JsonConvert.SerializeObject(messageToSend), Encoding.UTF8, "application/json"); var conversationUrl = $"{_baseBotEndPointAddress}/api/conversations/{_lastConversation.ConversationId}/messages/"; var response = await _client.PostAsync(conversationUrl, contentPost); var messageInfo = await response.Content.ReadAsStringAsync(); var messagesReceived = await _client.GetAsync(conversationUrl); var messagesReceivedData = await messagesReceived.Content.ReadAsStringAsync(); var messages = JsonConvert.DeserializeObject <MessageSet>(messagesReceivedData); return(messages); } catch (Exception ex) { return(SetExceptionMessage(ex)); } }
public override List <IRCResponse> GetResponse(BotMessage message) { if (Regex.IsMatch(message.Command, "^(nick(name)?|name)$", RegexOptions.IgnoreCase)) { if (message.TargetType == IRCMessage.TargetTypes.CHANNEL && ChannelList.UserIsAnyOp(message.User.Name, message.ReplyTo)) { if (message.ParameterList.Count > 0) { return(new List <IRCResponse>() { new IRCResponse(ResponseType.Raw, "NICK " + message.ParameterList[0], "") }); } else { return(new List <IRCResponse>() { new IRCResponse(ResponseType.Say, "Change my nick to what?", message.ReplyTo) }); } } else { return(new List <IRCResponse>() { new IRCResponse(ResponseType.Say, "You need to be an operator to change my name :P", message.ReplyTo) }); } } else { return(null); } }
internal static BotMessage CreateMessage(string phoneNumber, string message) { var sms = new IncomingSms() { DateReceived = DateTime.UtcNow, DestinationNumber = "00000000000", SourceNumber = phoneNumber, Message = message }; var msg = new BotMessage(); dynamic channelData = new ExpandoObject(); channelData.NotifyMessage = sms; dynamic from = new ExpandoObject(); from.Id = sms.SourceNumber; msg.ChannelData = channelData; msg.From = from; return(msg); }
public override List <IRCResponse> GetResponse(BotMessage message) { if (Regex.IsMatch(message.Command, "^(join)$", RegexOptions.IgnoreCase)) { if (message.ParameterList.Count > 0) { string output = ""; foreach (string parameter in message.ParameterList) { string channel = parameter; if (!channel.StartsWith("#")) { channel = "#" + channel; } output += "JOIN " + channel + "\r\n"; } return(new List <IRCResponse>() { new IRCResponse(ResponseType.Raw, output, "") }); } else { return(new List <IRCResponse>() { new IRCResponse(ResponseType.Say, message.User.Name + ", you didn't say where I should join.", message.ReplyTo) }); } } return(null); }
public override List <IRCResponse> GetResponse(BotMessage message) { if (Regex.IsMatch(message.Command, "^(translate)$", RegexOptions.IgnoreCase)) { if (message.ParameterList.Count > 0) { string translatedString; try { string translateTerm = message.Parameters.Replace('"', ' '); translatedString = Gapi.Language.Translator.Translate(translateTerm, Gapi.Language.Language.English); } catch (Gapi.Core.GapiException ex) { Logger.Write(ex.ToString(), Settings.Instance.ErrorFile); translatedString = "Couldn't work out what language you're using."; } return(new List <IRCResponse>() { new IRCResponse(ResponseType.Say, translatedString, message.ReplyTo) }); } else { return(new List <IRCResponse>() { new IRCResponse(ResponseType.Say, "Translate what?", message.ReplyTo) }); } } else { return(null); } }
public override List <IRCResponse> GetResponse(BotMessage message) { if (Regex.IsMatch(message.Command, "^(leave|gtfo)$", RegexOptions.IgnoreCase)) { if (message.TargetType == IRCMessage.TargetTypes.CHANNEL && ChannelList.UserIsAnyOp(message.User.Name, message.ReplyTo)) { if (message.ParameterList.Count > 0) { return(new List <IRCResponse>() { new IRCResponse(ResponseType.Raw, "PART " + message.ReplyTo + " :" + message.Parameters, "") }); } else { return(new List <IRCResponse>() { new IRCResponse(ResponseType.Raw, "PART " + message.ReplyTo + " :" + Settings.Instance.LeaveMessage, "") }); } } else { return(new List <IRCResponse>() { new IRCResponse(ResponseType.Say, "You need to be an operator to get rid of me :P", message.ReplyTo) }); } } return(null); }
private async Task <IActionResult> GetContact() { int Help_followerId = Argumetns[0]; // id пользователя которой создал заявку var follower = FollowerFunction.GetFollower(Help_followerId); if (follower != null && follower.Telephone != null && follower.Telephone != "") { Contact contact = new Contact { FirstName = follower.FirstName, PhoneNumber = follower.Telephone }; await SendContact(contact); } if (follower != null && follower.UserName != null && follower.UserName != "") { await SendUrl(BotMessage.HrefUrl("https://t.me/" + follower.UserName, follower.UserName)); return(OkResult); } else { return(base.OkResult); } }
/// <summary> /// Отправить список всех пользователей /// </summary> /// <returns></returns> private async Task <IActionResult> SendFollowerList() { if (Argumetns != null && Argumetns.Count > 0) { BotMessage = new FollowerListMessage(Argumetns[0]); } else { BotMessage = new FollowerListMessage(); } var mess = BotMessage.BuildMsg(); if (mess != null) { await EditMessage(mess); } else { await AnswerCallback("Данные отсутствуют", true); } return(OkResult); }
public override List <IRCResponse> GetResponse(BotMessage message) { if (Regex.IsMatch(message.Command, "^(unignore)$", RegexOptions.IgnoreCase)) { if (message.TargetType == IRCMessage.TargetTypes.CHANNEL && ChannelList.UserIsAnyOp(message.User.Name, message.ReplyTo)) { foreach (string parameter in message.ParameterList) { if (Settings.Instance.IgnoreList.Contains(parameter.ToUpper())) { Settings.Instance.IgnoreList.Remove(parameter.ToUpper()); } } return(new List <IRCResponse>() { new IRCResponse(ResponseType.Say, message.Parameters + (message.ParameterList.Count > 1 ? " are " : " is ") + "no longer ignored.", message.ReplyTo) }); } else { return(new List <IRCResponse>() { new IRCResponse(ResponseType.Say, "You need to be an operator to make me unignore people :P", message.ReplyTo) }); } } else { return(null); } }
public override InlineQueryResult[] GetResult() { db = new MarketBotDbContext(); var ProductList = GetProductList().Take(MaxResult).ToList(); InputTextMessageContent[] textcontent = new InputTextMessageContent[ProductList.Count]; InlineQueryResultArticle[] article = new InlineQueryResultArticle[ProductList.Count]; InlineQueryResult[] result = new InlineQueryResult[ProductList.Count]; int i = 0; foreach (Product prod in ProductList) { textcontent[i] = new InputTextMessageContent(); textcontent[i].ParseMode = Telegram.Bot.Types.Enums.ParseMode.Html; textcontent[i].DisableWebPagePreview = true; textcontent[i].MessageText = "/adminproduct" + prod.Id.ToString(); article[i] = new InlineQueryResultArticle(); article[i].HideUrl = true; article[i].Id = prod.Id.ToString(); article[i].Title = prod.Name; article[i].Description = "Категория:" + prod.Category.Name + BotMessage.NewLine() + "Цена:" + prod.CurrentPrice.Value; article[i].ThumbUrl = "https://cdn2.iconfinder.com/data/icons/shop-payment-vol-6/128/shop-07-256.png"; article[i].InputMessageContent = textcontent[i]; result[i] = article[i]; i++; } db.Dispose(); return(result); }
static void SetHeader(this MessageCell cell, NSIndexPath indexPath, BotMessage message) { cell.SetHeader(message.LocalTimeStamp, message.Activity?.From?.Name); cell.ImageView.SetCacheFormat(getCacheFormat(MessageCell.AvatarImageSize)); if (message.Activity.From.Id == "DigitalAgencies") { cell.SetAvatar(indexPath.Row, UIImage.FromBundle("avatar_microsoft")); } else { var avatarUrl = string.IsNullOrEmpty(message.Activity?.From?.Id) ? string.Empty : BotClient.Shared.GetAvatarUrl(message.Activity.From.Id); if (string.IsNullOrEmpty(avatarUrl)) { cell.SetAvatar(indexPath.Row, null); } else { var placeholder = getPlaceholderImage(MessageCell.AvatarImageSize); using (NSUrl url = new NSUrl(avatarUrl)) { cell?.ImageView.SetImage(url, placeholder, (img) => cell.SetAvatar(indexPath.Row, img), (err) => { cell.SetAvatar(indexPath.Row, null); Log.Debug(err.LocalizedDescription); }); } } } }
public override async Task<BotMessage> HandleMessage(BotMessage message) { if (message.Text.ToLowerInvariant().Trim().Trim('?', '!', '.', ';', '-').Equals("what")) { var responses = new List<string>() { "Say what again.", "English m**********r do you speak it!?", "SAY WHAT again! And I dare you, I double dare you m**********r! Say what one more time.", "500 Internal Server Error" }; // Construct an message var counter = message.GetBotPerUserInConversationData<int>("WhatCounter"); message.Response = responses[counter]; // Increment counter message.SetBotPerUserInConversationData("WhatCounter", (counter + 1)%responses.Count); // Handle message message.IsHandled = true; } return message; }
public async Task <MessageSet> SendMessageAsync(string messageText) { try { var messageToSend = new BotMessage { Text = messageText, ConversationId = _lastConversation.ConversationId, From = Constants.MyUserId }; var content = new StringContent(JsonConvert.SerializeObject(messageToSend), Encoding.UTF8, "application/json"); var conversationUrl = "https://directline.botframework.com/api/conversations/" + _lastConversation.ConversationId + "/messages/"; var response = await _client.PostAsync(conversationUrl, content); var messageInfo = await response.Content.ReadAsStringAsync(); // possible error which we'll happily ignore for demo purposes var messagesRecievedResponse = await _client.GetAsync(conversationUrl); var messagesReceivedData = await messagesRecievedResponse.Content.ReadAsStringAsync(); var messages = JsonConvert.DeserializeObject <MessageSet>(messagesReceivedData); return(messages); } catch (Exception) { // poke catch return(null); } }
public async Task SendMessage(ResponseMessage responseMessage) { SlackChatHub chatHub = await GetChatHub(responseMessage); if (chatHub != null) { if (responseMessage is TypingIndicatorMessage) { _log.Info($"Indicating typing on channel '{chatHub.Name}'"); await _connection.IndicateTyping(chatHub); } else { var botMessage = new BotMessage { ChatHub = chatHub, Text = responseMessage.Text, Attachments = GetAttachments(responseMessage.Attachment) }; string textTrimmed = botMessage.Text.Length > 50 ? botMessage.Text.Substring(0, 50) + "..." : botMessage.Text; _log.Info($"Sending message '{textTrimmed}'"); await _connection.Say(botMessage); } } else { _log.Error($"Unable to find channel for message '{responseMessage.Text}'. Message not sent"); } }
internal async Task PublishAsync(BotMessage message) { await ConnectTask; // Wait to be connected first if (SlackClient != null) { var hub = SlackClient.ConnectedHubs.Select(kv => kv.Value).SingleOrDefault(h => h.Name == TeamCodingPackage.Current.Settings.SharedSettings.SlackChannel); if (hub != null) { message.ChatHub = hub; await SlackClient.Say(message).HandleException(); TeamCodingPackage.Current.Logger.WriteInformation("Sent model via Slack"); } else if (string.IsNullOrEmpty(TeamCodingPackage.Current.Settings.SharedSettings.SlackChannel)) { TeamCodingPackage.Current.Logger.WriteInformation($"Slack channel not specified."); } else if (!TeamCodingPackage.Current.Settings.SharedSettings.SlackChannel.StartsWith("#")) { TeamCodingPackage.Current.Logger.WriteInformation($"Slack channel must start with a #. It is set as {TeamCodingPackage.Current.Settings.SharedSettings.SlackChannel}"); } else { TeamCodingPackage.Current.Logger.WriteInformation($"Slack channel {TeamCodingPackage.Current.Settings.SharedSettings.SlackChannel} not found (it doesn't exist, or the bot the API token is for doesn't have access)."); } } else if (!string.IsNullOrEmpty(TeamCodingPackage.Current.Settings.SharedSettings.SlackToken)) { TeamCodingPackage.Current.Logger.WriteInformation("SlackClient == null, didn't send model"); } }
/// <inheritdoc/> public async Task <BotMessage> ProcessAsync(BotMessage message) { try { return(await SubscribeSenderAsync(message).ConfigureAwait(false)); } catch (SubscriberAlreadyExistsException) { return(new BotMessage { Text = "This chat already subscribed." }); } catch (SubscriptionNotAllowedException) { return(new BotMessage { Text = "Failed to subscribe. Invalid subscription key." }); } catch (SubscriberOperationException) { return(new BotMessage { Text = "Failed to subscribe. Try again later." }); } finally { SetSubscriptionCompletedState(); } }
public async Task <PluginResult> Handle(BotMessage message, CommandItems commandItems, CancellationToken token) { var chatId = message.ChatId; StringBuilder result = new(); var user = await _userService.GetUserAsync(chatId, token); if (user == null) { var sourceAdapter = _sourceAdapterFactory.GetAdapter(message.SourceId); var name = await sourceAdapter.GetName(message.ChatId, token); user = await _userService.AddUserAsync(new AddUserRequest { ChatId = chatId, Name = name }, token); result.AppendLine(AccountantText.WelcomeUser(name)); result.AppendLine(); } var balance = await _accountantService.GetBalance(user.Id, token); result.AppendLine(AccountantText.RemainingBalance(balance)); return(PluginResult.Success(result.ToString())); }
public async Task <Activity> Connect() { try { StringContent content = new StringContent("", Encoding.UTF8, "application/json"); string result = await PostAsync(AppSettings.BaseBotEndPointAddress, content); var conversationResponse = JsonConvert.DeserializeObject <Conversation>(result); botUriChat = String.Format(AppSettings.BaseBotUriChat, conversationResponse.ConversationId); Settings.ConversationId = conversationResponse.ConversationId; var activitiesReceived = await Client.GetAsync(botUriChat); var activitiesReceivedData = await activitiesReceived.Content.ReadAsStringAsync(); Conversation = JsonConvert.DeserializeObject <BotMessage>(activitiesReceivedData); var activity = Conversation.Activities.FirstOrDefault(); if (activity != null) { return(activity); } else { return(await Connect()); } } catch (Exception ex) { return(SetExceptionMessage()); } }
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously /// <summary> /// Handles the empty message. /// </summary> /// <param name="message">The message.</param> /// <returns>If message has no content, message is returned to user.</returns> public override async Task<BotMessage> HandleMessage(BotMessage message) #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously { if (!message.HasContent()) { message.Response = "I didn't understand that :/"; message.IsHandled = true; } return message; }
public override async Task<BotMessage> HandleMessage(BotMessage message) { var responses = new List<string>() { $"I'm sorry {message.From.Name}, I'm afraid I can't do that.", "Ah well, there's always hope.", "Did you say something?" }; message.Response = responses[new Random().Next(0, responses.Count)]; return message; }
public override async Task<BotMessage> HandleMessage(BotMessage message) { var luisMessage = message as ILuisMessage; if (luisMessage != null) { var recommendation = luisMessage.Luis.Intents.OrderByDescending(i => i.Score).FirstOrDefault(); if (recommendation?.Intent == "GetTime") { message.Response = $"Over here it's {DateTime.Now.ToShortTimeString()}."; message.IsHandled = true; } } return message; }
public override async Task<BotMessage> HandleMessage(BotMessage message) { var luisMessage = message as LuisMessage; if (luisMessage != null) { var recommendation = luisMessage.Luis.Intents.OrderByDescending(i => i.Score).FirstOrDefault(); if (recommendation?.Intent == "GetStoreAcquisitions") { var response = await this.HandleWindowsStoreAnalyticsQueryAsync(luisMessage); response.IsHandled = true; return response; } } return message; }
/// <summary> /// Populates the specified message with LUIS response data. /// </summary> /// <param name="message">The message.</param> /// <returns>Returns new instance of <see cref="LuisMessage"/> that is populated with LUIS response data.</returns> /// <remarks> /// Access the LUIS response data through <see cref="LuisMessage.Luis"/> property. /// </remarks> private static async Task<LuisMessage> HandleMessageAsync(BotMessage message) { // Translate to LUIS message var luisMessage = BotMessage.Populate<BotMessage, LuisMessage>(message); // Populate LUIS data luisMessage.Luis = await GetLuisResponseAsync(message.Text); // Check if we need to debug the message if (luisMessage.IsDebug && luisMessage.DebugParam == "luis") { luisMessage.Response = JsonConvert.SerializeObject(luisMessage.Luis); luisMessage.IsHandled = true; } return luisMessage; }
/// <summary> /// Handles the bot message. /// This will populate the message with LUIS response data. /// </summary> /// <param name="message">The message.</param> /// <returns>Returns the <see cref="LuisMessage"/> that is populated with LUIS response data.</returns> public override async Task<BotMessage> HandleMessage(BotMessage message) { // Run LUIS task return await HandleMessageAsync(message); }
public virtual async Task<BotMessage> HandleMessage(BotMessage message) { return message; }
public virtual async Task<BotMessage> ResultMessage(BotMessage message) { return message; }