public static string GetActiveLocale(ITurnContext context) { if (currentLocale != null) { //the user has specified a different locale so update the bot state if (context.GetConversationState <CurrentUserState>() != null && currentLocale != context.GetConversationState <CurrentUserState>().Locale) { SetLocale(context, currentLocale); } } if (context.Activity.Type == ActivityTypes.Message && context.GetConversationState <CurrentUserState>() != null && context.GetConversationState <CurrentUserState>().Locale != null) { return(context.GetConversationState <CurrentUserState>().Locale); } return("en-us"); }
private static async Task createAndBeginDialogs(ITurnContext context, DialogSet dialogs) { var dialogContext = dialogs.CreateContext(context, context.GetConversationState <EchoState>()); await dialogContext.Continue(); if (!context.Responded) { await dialogContext.Begin("firstRun"); } }
private async void ScheduleRideHandler(ITurnContext turnContext, string carType, string location, string time) { var state = turnContext.GetConversationState <ReservationData>(); var dialogContext = dialogs.CreateContext(turnContext, state); state.CarType = carType; state.Location = location; state.Time = time; await dialogContext.Begin(PromptStep.GatherInfo); }
public async Task OnTurn(ITurnContext context) { var state = context.GetConversationState <ReservationData>(); var dialogContext = _dialogs.CreateContext(context, state); await dialogContext.Continue(); // This bot is only handling Messages if (context.Activity.Type == ActivityTypes.Message) { // Get the conversation state from the turn context // var state = context.GetConversationState<EchoState>(); // Bump the turn count. // state.TurnCount++; // Echo back to the user whatever they typed. // await context.SendActivity($"Turn {state.TurnCount}: You sent '{context.Activity.Text}'"); if (!context.Responded) { var result = context.Services.Get <RecognizerResult>(LuisRecognizerMiddleware.LuisRecognizerResultKey); var topIntent = result?.GetTopScoringIntent(); switch (topIntent != null ? topIntent.Value.intent : null) { case "TodaysSpecialty": // await context.SendActivity($"For today we have the following options: {string.Join(", ", BotConstants.Specialties)}"); await TodaysSpecialtiesHandler(context); break; case "ReserveTable": var amountPeople = result.Entities["AmountPeople"] != null ? (string)result.Entities["AmountPeople"]?.First : null; var time = GetTimeValueFromResult(result); ReservationHandler(dialogContext, amountPeople, time); break; case "GetDiscounts": await GetDiscountsHandler(context); break; default: await context.SendActivity("Sorry, I didn't understand that."); break; } } } else if (context.Activity.Type == ActivityTypes.ConversationUpdate && context.Activity.MembersAdded.FirstOrDefault()?.Id == context.Activity.Recipient.Id) { var msg = "Hi! I'm a restaurant assistant bot. I can help you with your reservation."; await context.SendActivity(msg, _ttsService.GenerateSsml(msg, BotConstants.EnglishLanguage)); } }
/// <summary> /// Every Conversation turn for our EchoBot will call this method. In here /// the bot checks the Activty type to verify it's a message, bumps the /// turn conversation 'Turn' count, and then echoes the users typing /// back to them. /// </summary> /// <param name="context">Turn scoped context containing all the data needed /// for processing this conversation turn. </param> public async Task OnTurn(ITurnContext context) { // This bot is only handling Messages if (context.Activity.Type == ActivityTypes.Message) { // Get the conversation state from the turn context var state = context.GetConversationState <EchoState>(); // Bump the turn count. state.TurnCount++; var input = context.Activity.Text.ToLower(); var output = ""; if (input.Contains("help")) { output += $"TODO: write help definitions\n"; } else { if (input.Contains("hi") || input.Contains("hello")) { output += $"Hello beautiful\n"; } if (input.Contains("suraj")) { output += $"Suraj is pretty standard\n"; } if (input.Contains("galo")) { output += $"Ehhh.. that dudes okay\n"; } if (input.Contains("jesse")) { output += $"Jesse is one of the best programmers I've ever spoken with\n"; } if (input.Contains("love you")) { output += $"I love you too\n"; } if (output == "") { // Echo back to the user whatever they typed. output += $"Turn {state.TurnCount}: You sent '{context.Activity.Text}'\n"; } } await context.SendActivity(output); } }
public async Task OnTurn(ITurnContext context) { var state = context.GetConversationState <Dictionary <string, object> >(); var dialogCtx = dialogs.CreateContext(context, state); switch (context.Activity.Type) { case ActivityTypes.ConversationUpdate: foreach (var newMember in context.Activity.MembersAdded) { if (newMember.Id != context.Activity.Recipient.Id) { await context.SendActivity("Bot says hello"); var quickReplies = MessageFactory.SuggestedActions(new CardAction[] { new CardAction(title: "Yeah!", type: ActionTypes.ImBack, value: "Yes"), new CardAction(title: "Nope!", type: ActionTypes.ImBack, value: "No") }, text: "Do you want to see what I can do?"); Thread.Sleep(1500); await context.SendActivity(quickReplies); } } break; case ActivityTypes.Message: await dialogCtx.Continue(); switch (context.Activity.Text) { case "Yes": await dialogCtx.Begin("initial"); break; case "No": await dialogCtx.Context.SendActivity("Ok, your loss mate!"); break; default: if (!dialogCtx.Context.Responded) { var convo = ConversationState <Dictionary <string, object> > .Get(dialogCtx.Context); await dialogCtx.Context.SendActivity($"I'm ignoring you {convo["Name"]}..."); } break; } break; default: break; } }
public async Task OnTurn(ITurnContext context) { if(context.Activity.Type == ActivityTypes.Message) { var state = context.GetConversationState<AuthenticationState>(); if(state.Authenticated) await context.SendActivity("You are logged in!!"); else await context.SendActivity("You are not logged in"); } else if(context.Activity.Type == ActivityTypes.ConversationUpdate) { await context.SendActivity(new Activity() { Type = "event", Text = context.Activity.From.Id, Name = "authenticate" }); } else if(context.Activity.Type == "event" && context.Activity.Text == "authenticated") { // authentication has taken place // check the state of the user and see if it's been updated var state = context.GetConversationState<AuthenticationState>(); if(state.Authenticated) { await context.SendActivity("You have been authenticated"); } } }
public async Task OnTurn(ITurnContext context) { var state = context.GetConversationState <Dictionary <string, object> >(); var dialogCtx = _dialogs.CreateContext(context, state); if (context.Activity.Type == ActivityTypes.ConversationUpdate) { var newUserName = context.Activity.MembersAdded.FirstOrDefault()?.Name; if (!string.Equals("Bot", newUserName)) { //await dialogCtx.Begin("addUserInfo"); } } if (context.Activity.Type == ActivityTypes.Message) { await dialogCtx.Continue(); var message = context.Activity.Text.Trim(); var indexOfSpace = message.IndexOf(" ", StringComparison.Ordinal); var command = indexOfSpace != -1 ? message.Substring(0, indexOfSpace).ToLower() : message.ToLower(); switch (command) { case "tobase64": context.Activity.Text = indexOfSpace >= 0 ? context.Activity.Text.Substring(indexOfSpace + 1, message.Length - indexOfSpace - 1) : String.Empty; await dialogCtx.Begin("tobase64"); break; case "frombase64": context.Activity.Text = indexOfSpace >= 0 ? context.Activity.Text.Substring(indexOfSpace + 1, message.Length - indexOfSpace - 1) : String.Empty; await dialogCtx.Begin("frombase64"); break; case "cards": context.Activity.Text = indexOfSpace >= 0 ? context.Activity.Text.Substring(indexOfSpace + 1, message.Length - indexOfSpace - 1) : String.Empty; await dialogCtx.Begin("cards"); break; } } }
/// <summary> /// Every Conversation turn for our EchoBot will call this method. In here /// the bot checks the Activty type to verify it's a message, bumps the /// turn conversation 'Turn' count, and then echoes the users typing /// back to them. /// </summary> /// <param name="context">Turn scoped context containing all the data needed /// for processing this conversation turn. </param> public async Task OnTurn(ITurnContext context) { // This bot is only handling Messages if (context.Activity.Type == ActivityTypes.Message) { // Get the conversation state from the turn context var state = context.GetConversationState <BotState>(); // Echo back to the user whatever they typed. await context.SendActivity("Hello world!"); } }
/// <summary> /// Every Conversation turn for our EchoBot will call this method. In here /// the bot checks the Activty type to verify it's a message, bumps the /// turn conversation 'Turn' count, and then echoes the users typing /// back to them. /// </summary> /// <param name="context">Turn scoped context containing all the data needed /// for processing this conversation turn. </param> public async Task OnTurn(ITurnContext context) { // This bot is only handling Messages if (context.Activity.Type == ActivityTypes.Message) { // Get the conversation state from the turn context var state = context.GetConversationState <WillieState>(); // Bump the turn count. state.TurnCount++; IMessageActivity response = null; if (context.Activity.Attachments?.Count > 0) { IList <Attachment> attachments = new List <Attachment>(); foreach (Attachment originalAttachment in context.Activity.Attachments) { HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, originalAttachment.ContentUrl); HttpResponseMessage res = await _httpClient.SendAsync(req); if (res.IsSuccessStatusCode) { using (MemoryStream memStream = new MemoryStream()) { await res.Content.CopyToAsync(memStream); string base64Image = Convert.ToBase64String(memStream.GetBuffer()); Attachment attachment = new Attachment { ContentType = originalAttachment.ContentType, Name = "Echoed Image", ContentUrl = $"data:{originalAttachment.ContentType};base64,{base64Image}" }; attachments.Add(attachment); } } } response = MessageFactory.Carousel(attachments, $"Turn {state.TurnCount}: You sent this"); } else { response = MessageFactory.Text($"Turn {state.TurnCount}: You sent '{context.Activity.Text}'"); } // Echo back to the user whatever they typed. await context.SendActivity(response); } }
public async Task OnTurn(ITurnContext context) { if (context.Activity.Type == ActivityTypes.Message) { var state = context.GetConversationState <SearchState>(); var processor = new QueryProcessor(); var text = await processor.Execute(context.Activity.Text); await context.SendActivity($"### Found the following:\r\n{text}"); } }
private (UserInfo, DialogContext) CreateContext(ITurnContext context) { var dialogs = new DialogSet(); dialogs.AddCatalogDialog(dialogFactory); dialogs.AddCatalogFilterDialog(dialogFactory); var userState = context.GetUserState <UserInfo>(); var state = context.GetConversationState <eShopBotState>(); var dialogCtx = dialogs.CreateContext(context, state); return(userState, dialogCtx); }
public async Task OnTurn(ITurnContext context) { if (context.Activity.Type == ActivityTypes.ConversationUpdate && context.Activity.MembersAdded.FirstOrDefault()?.Id == context.Activity.Recipient.Id) { await context.SendActivity(_greetingMessage); } else if (context.Activity.Type == ActivityTypes.Message) { var userState = context.GetUserState <UserState>(); if (userState.EpisodeInquiries == null) { userState.EpisodeInquiries = new List <EpisodeInquiry>(); } var state = context.GetConversationState <Dictionary <string, object> >(); var dialogContext = dialogs.CreateContext(context, state); var utterance = context.Activity.Text.ToLowerInvariant(); if (utterance == "cancel") { if (dialogContext.ActiveDialog != null) { await context.SendActivity("Ok... Cancelled"); dialogContext.EndAll(); } else { await context.SendActivity("Nothing to cancel."); } } if (!context.Responded) { await dialogContext.Continue(); if (!context.Responded) { var luisResult = context.Services.Get <RecognizerResult>(LuisRecognizerMiddleware.LuisRecognizerResultKey); var(intent, score) = luisResult.GetTopScoringIntent(); var intentResult = score > LUIS_INTENT_THRESHOLD ? intent : "None"; await dialogContext.Begin(intent, new Dictionary <string, object> { { "LuisResult", luisResult } }); } } } }
public async Task OnTurn(ITurnContext context) { // 當收到活動類型為 Messages 的訊息時執行以下程序 if (context.Activity.Type is ActivityTypes.Message) { // 取得儲存在對話狀態中的自訂資訊 var state = context.GetConversationState <EchoState>(); // 增加對話計數器 state.TurnCount++; // 回傳使用者傳送的的對話訊息 await context.SendActivity($"Turn {state.TurnCount}: You sent '{context.Activity.Text}'"); } }
/// <summary> /// Every Conversation turn for our EchoBot will call this method. In here /// the bot checks the Activty type to verify it's a message, bumps the /// turn conversation 'Turn' count, and then echoes the users typing /// back to them. /// </summary> /// <param name="context">Turn scoped context containing all the data needed /// for processing this conversation turn. </param> public async Task OnTurn(ITurnContext context) { // This bot is only handling Messages if (context.Activity.Type == ActivityTypes.Message) { // Get the conversation state from the turn context var state = context.GetConversationState <EchoState>(); // Bump the turn count. state.TurnCount++; // Echo back to the user whatever they typed. await context.SendActivity($"Turn {state.TurnCount}: You sent '{context.Activity.Text}'"); } }
public async Task OnTurn(ITurnContext context) { var state = context.GetConversationState <Dictionary <string, object> >(); var dialogContext = dialogs.CreateContext(context, state); if (context.Activity.Type == ActivityTypes.Message) { await dialogContext.Continue(); if (!context.Responded) { await dialogContext.Begin("cardSelector"); } } }
public async Task Add(ITurnContext context, FavoriteLocation value) { var favorites = await GetFavorites(context); if (favorites.Count >= MaxFavoriteCount) { throw new InvalidOperationException("The max allowed number of favorite locations has already been reached."); } favorites.Add(value); var state = context.GetConversationState <Dictionary <string, object> >(); state[FavoritesKey] = favorites; }
public async Task OnTurn(ITurnContext turnContext) { if (turnContext.Activity.Type == ActivityTypes.Message) { var state = turnContext.GetConversationState <Dictionary <string, object> >(); var dialogCtx = dialogs.CreateContext(turnContext, state); await dialogCtx.Continue(); if (!turnContext.Responded) { await dialogCtx.Begin("mainDialog"); } } }
/// <summary> /// Main bot OnTurn Implementation /// </summary> /// <param name="context">Turn scoped context containing all the data needed for processing this conversation turn. </param> public async Task OnTurn(ITurnContext context) { if (context.Activity.Type == ActivityTypes.ConversationUpdate && context.Activity.MembersAdded.FirstOrDefault()?.Id == context.Activity.Recipient.Id) { await context.SendActivity("Hi! Welcome to the Mcbeev Commerce Bot."); await context.SendActivity("How can we help you today?\n\nWould you like to **Place a new Order**, **Check your Order History** or **Find an Order Tracking Number**? Or is there something else we can help with?"); } else if (context.Activity.Type == ActivityTypes.Message) { var userState = context.GetUserState <UserState>(); var state = context.GetConversationState <Dictionary <string, object> >(); var dialogContext = dialogs.CreateContext(context, state); var utterance = context.Activity.Text.ToLowerInvariant(); if (utterance == "cancel") { if (dialogContext.ActiveDialog != null) { await context.SendActivity("Ok... Cancelled"); dialogContext.EndAll(); } else { await context.SendActivity("Nothing to cancel."); } } if (!context.Responded) { var dialogArgs = new Dictionary <string, object>(); await dialogContext.Continue(); if (!context.Responded) { var luisResult = context.Services.Get <RecognizerResult>(LuisRecognizerMiddleware.LuisRecognizerResultKey); var(intent, score) = luisResult.GetTopScoringIntent(); var intentResult = score > LUIS_INTENT_THRESHOLD ? intent : "None"; dialogArgs.Add("LuisResult", luisResult); await dialogContext.Begin(intent, dialogArgs); } } } }
public async Task OnTurn(ITurnContext turnContext) { var state = turnContext.GetConversationState <BotState>(); var dialogContext = dialogSet.CreateContext(turnContext, state); if (dialogContext.Context.Activity.Type == ActivityTypes.Message) { await dialogContext.Continue(); if (!dialogContext.Context.Responded) { await dialogContext.Begin(Constants.DialogSteps.MainDialog.ToString()); } } }
public override async Task Begin(ITurnContext turnContext) { var state = turnContext.GetConversationState <ImageHuntState>(); if (state.GameId != 0 && state.TeamId != 0) { var warningMessage = $"Le groupe {turnContext.ChatId} a déjà été initialisé!"; await turnContext.ReplyActivity(warningMessage); LogInfo <ImageHuntState>(turnContext, warningMessage); await turnContext.End(); return; } var regEx = new Regex(@"(?i)\/init gameid=(\d*) teamid=(\d*)"); var activityText = turnContext.Activity.Text; if (regEx.IsMatch(activityText)) { var groups = regEx.Matches(activityText); state.GameId = Convert.ToInt32(groups[0].Groups[1].Value); state.TeamId = Convert.ToInt32(groups[0].Groups[2].Value); LogInfo <ImageHuntState>(turnContext, "Init"); state.Game = await _gameWebService.GetGameById(state.GameId); state.Team = await _teamWebService.GetTeamById(state.TeamId); if (state.Game == null || state.Team == null) { LogInfo <ImageHuntState>(turnContext, "Unable to find game"); await turnContext.ReplyActivity($"Impossible de trouver la partie pour l'Id={state.GameId} ou l'équipe pour l'Id={state.TeamId}"); state.GameId = state.TeamId = 0; await turnContext.End(); return; } state.Status = Status.Initialized; } await base.Begin(turnContext); await turnContext.ReplyActivity( $"Le groupe de l'équipe {state.Team.Name} pour la chasse {state.Game.Name} qui débute le {state.Game.StartDate} est prêt, bon jeu!"); await turnContext.End(); }
/// <summary> /// Every Conversation turn for our bot will call this method. In here /// the bot checks the Activity type, and either sends a welcome message, /// a QnA answer, or a LUIS intent response. /// </summary> /// <param name="context">Turn scoped context containing all the data needed /// for processing this conversation turn. </param> public async Task OnTurn(ITurnContext context) { var state = context.GetConversationState <Dictionary <string, object> >(); var dialogContext = dialogs.CreateContext(context, state); switch (context.Activity.Type) { case ActivityTypes.ConversationUpdate: // Send the welcome message when the user is added to the conversation if (context.Activity.MembersAdded.FirstOrDefault()?.Id == context.Activity.Recipient.Id) { await dialogContext.Begin(Greeting.Id); } break; case ActivityTypes.Message: var luisResult = context.Services.Get <RecognizerResult>(LuisRecognizerMiddleware.LuisRecognizerResultKey); // Map each prompt property in the conversation model to LUIS entity results var service = new ConversationModelService(); var conversationModel = service.ConversationModel(); foreach (var entity in conversationModel.Entities) { switch (service.GetMapper(entity).Type) { case MapperTypes.LuisEntityToPropertyMapper: var propertyMapper = new LuisEntityToPropertyMapper(); propertyMapper.Map(service.GetPrompt(entity).PropertyName, entity, state, luisResult); break; default: // TODO: default break; } } await dialogContext.Continue(); if (!context.Responded) { var(intent, score) = luisResult.GetTopScoringIntent(); var intentResult = score > LUIS_INTENT_THRESHOLD ? intent : None.Id; await dialogContext.Begin(intentResult); } break; } }
private async Task HandleMessageAsync(ITurnContext context) { var state = context.GetConversationState <Dictionary <string, object> >(); var dialogContext = _dialogSet.CreateContext(context, state); // Cancel active dialog if user writes 'cancel' var utterance = context.Activity.Text.ToLowerInvariant(); if (utterance == "cancel") { if (dialogContext.ActiveDialog != null) { await context.SendActivity("Alright, just forget it then"); dialogContext.EndAll(); } else { await context.SendActivity("Sorry, I cannot do that Dave"); } } if (!context.Responded) { await dialogContext.Continue(); if (!context.Responded) { var consumed = false; foreach (var flow in _flows) { if (await flow.TryConsumeAsync(dialogContext, utterance)) { consumed = true; break; } } // No flow matches if (!consumed) { await context.SendActivity("Sorry, I didn't understand that."); } } } }
/// <summary> /// Every Conversation turn for our EchoBot will call this method. In here /// the bot checks the Activty type to verify it's a message, bumps the /// turn conversation 'Turn' count, and then echoes the users typing /// back to them. /// </summary> /// <param name="context">Turn scoped context containing all the data needed /// for processing this conversation turn. </param> public async Task OnTurn(ITurnContext context) { try { if (context.Activity.Type == ActivityTypes.Message) { if (context.Activity.Text == null) { GetFileId a = new GetFileId(); // string response="AgADBQAEqDEbptgBVN0ZE1AM9YGXsVHVMgAEORQyLqTyGdCaEQMAAQI"; seriobj ser = JsonConvert.DeserializeObject <seriobj>(context.Activity.ChannelData.ToString()); var response = ser.message.photo[ser.message.photo.Length - 1].file_id; //await context.SendActivity(@"{""file_id"":" + "\"" +"AgADBQAEqDEbptgBVN0ZE1AM9YGXsVHVMgAEORQyLqTyGdCaEQMAAQI"+ "\"}"); //await context.SendActivity(a.PostUrl(response).ToString()); //await context.SendActivity(response); photodownload download = JsonConvert.DeserializeObject <photodownload>(a. PostUrl(response).ToString()); judgeqr b = new judgeqr(); if (b.CodeDecoder(download.result.file_path).ToString() != null) { await context.SendActivity(b.CodeDecoder(download.result.file_path).ToString()); } } else { // Get the conversation state from the turn context var state = context.GetConversationState <EchoState>(); // Bump the turn count. state.TurnCount++; if (context.Activity.Text == "Hey! Welcome!") { await context.SendActivity(@"@test299_bot I received a message from a robot,I am a bot;"); } await context.SendActivity(context.Activity.Text); // Echo back to the user whatever they typed. } } } catch (Exception e) { await context.SendActivity(e.ToString()); } }
public async Task OnTurn(ITurnContext context) { var state = context.GetConversationState <MultiplePromptsState>(); var dialogCtx = dialogs.CreateContext(context, state); switch (context.Activity.Type) { case ActivityTypes.Message: await dialogCtx.Continue(); if (!context.Responded) { await dialogCtx.Begin(PromptStep.GatherInfo); } break; } }
public async Task OnTurn(ITurnContext context) { if (context.Activity.Type == ActivityTypes.Message && !context.Responded) { var state = context.GetConversationState <ClaimStateModel>(); var dialogContext = dialogs.CreateContext(context, state); if (context.Activity.Type == ActivityTypes.Message) { await dialogContext.Continue(); if (!context.Responded) { await dialogContext.Begin(CARD_SELECTOR_ID); } } } }
public async Task <string> CheckLUISandQandAAndGetMostAccurateResult() { var response = string.Empty; var state = _context.GetConversationState <Dictionary <string, object> >(); if (state.Count == 0) { var topIntent = await LuisConnectivity.GetTopIntent(_context.Activity.Text, _configuration); response = await GetResponseForUser(topIntent); } else { await RunDialogContext(); } return(response); }
/// <summary> /// Method to validate that the info was collected from the user. /// If the user's input wasn't valid, the bot will ask again. /// </summary> private async Task CollectStepValidator(ITurnContext context, TextResult result) { // Check to see if info was found in the LUIS entities var state = context.GetConversationState <Dictionary <string, object> >(); var collected = state.TryGetValue(collectSteps[0].PropertyName, out object userInput); if (!collected) { // If not found in the LUIS entities, ask again result.Status = PromptStatus.NotRecognized; await context.SendActivity(collectSteps[0].RetryValue, collectSteps[0].RetryValue, InputHints.ExpectingInput); } else { // If found, remove this step from the dialog collectSteps.Remove(collectSteps[0]); } }
public async Task Delete(ITurnContext context, FavoriteLocation value) { var favorites = await GetFavorites(context); var newFavorites = new List <FavoriteLocation>(); foreach (var favoriteItem in favorites) { if (!AreEqual(favoriteItem.Location, value.Location)) { newFavorites.Add(favoriteItem); } } var state = context.GetConversationState <Dictionary <string, object> >(); state[FavoritesKey] = newFavorites; }
public async Task <ScubaCardResult> GetNextCardText(ITurnContext context, Activity activity) { var userScubaData = context.GetConversationState <UserScubaData>(); var userInput = activity.Text; var jObjectValue = activity.Value as Newtonsoft.Json.Linq.JObject; var cardProvider = _cardHandlers.Value.FirstOrDefault(c => c.ProvidesCard(userScubaData, jObjectValue, userInput)); if (cardProvider != null) { return(await cardProvider.GetCardResult(userScubaData, jObjectValue, activity.Text)); } return(new ScubaCardResult() { ErrorMessage = "I'm sorry, I don't understand. Please rephrase, or use the Adaptive Card to respond." }); }