protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken) { var replyText = $"My Complexity Says: {turnContext.Activity.Text}"; await turnContext.SendActivityAsync(MessageFactory.Text(replyText, replyText), cancellationToken); }
/// <summary> /// Attempts to recognize the user's input. /// </summary> /// <param name="turnContext">Context for the current turn of conversation with the user.</param> /// <param name="state">Contains state for the current instance of the prompt on the dialog stack.</param> /// <param name="options">A prompt options object constructed from the options initially provided /// in the call to <see cref="DialogContext.PromptAsync(string, PromptOptions, CancellationToken)"/>.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects /// or threads to receive notice of cancellation.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> /// <remarks>If the task is successful, the result describes the result of the recognition attempt.</remarks> protected override Task <PromptRecognizerResult <T> > OnRecognizeAsync(ITurnContext turnContext, IDictionary <string, object> state, PromptOptions options, CancellationToken cancellationToken = default(CancellationToken)) { if (turnContext == null) { throw new ArgumentNullException(nameof(turnContext)); } var result = new PromptRecognizerResult <T>(); if (turnContext.Activity.Type == ActivityTypes.Message) { var message = turnContext.Activity.AsMessageActivity(); var culture = turnContext.Activity.Locale ?? DefaultLocale ?? English; var results = RecognizeNumberWithUnit(message.Text, culture); if (results.Count > 0) { // Try to parse value based on type string text = string.Empty; // Try to parse value based on type var valueResolution = results[0].Resolution["value"]; if (valueResolution != null) { text = valueResolution.ToString(); } if (typeof(T) == typeof(float)) { if (float.TryParse(text, NumberStyles.Any, new CultureInfo(culture), out var value)) { result.Succeeded = true; result.Value = (T)(object)value; } } else if (typeof(T) == typeof(int)) { if (int.TryParse(text, NumberStyles.Any, new CultureInfo(culture), out var value)) { result.Succeeded = true; result.Value = (T)(object)value; } } else if (typeof(T) == typeof(long)) { if (long.TryParse(text, NumberStyles.Any, new CultureInfo(culture), out var value)) { result.Succeeded = true; result.Value = (T)(object)value; } } else if (typeof(T) == typeof(double)) { if (double.TryParse(text, NumberStyles.Any, new CultureInfo(culture), out var value)) { result.Succeeded = true; result.Value = (T)(object)value; } } else if (typeof(T) == typeof(decimal)) { if (decimal.TryParse(text, NumberStyles.Any, new CultureInfo(culture), out var value)) { result.Succeeded = true; result.Value = (T)(object)value; } } } } return(Task.FromResult(result)); }
public virtual async Task <T> RecognizeAsync <T>(ITurnContext turnContext, CancellationToken cancellationToken) where T : IRecognizerConvert, new() => await _recognizer.RecognizeAsync <T>(turnContext, cancellationToken);
// Called when the task module from an action messaging extension is submitted public async Task <MessagingExtensionActionResponse> HandleMessagingExtensionSubmitActionAsync(ITurnContext turnContext, CancellationToken cancellationToken, MessagingExtensionAction action) { var val = JObject.FromObject(action.Data); // turnContext.Activity.Value as JObject; var payload = val.ToObject <AddToProjectConfirmationCard.AddToProjectCardActionValue>(); var submitData = val["msteams"]["value"]; payload.submissionId = submitData.Value <string>("submissionId"); payload.command = submitData.Value <string>("command"); payload.monthZero = submitData.Value <string>("monthZero"); payload.monthOne = submitData.Value <string>("monthOne"); payload.monthTwo = submitData.Value <string>("monthTwo"); // FROM SAMPLE dynamic Data = JObject.Parse(action.Data.ToString()); var response = new MessagingExtensionActionResponse { ComposeExtension = new MessagingExtensionResult { Type = "botMessagePreview", ActivityPreview = MessageFactory.Attachment(new Attachment { Content = await AddToProjectConfirmationCard.GetCardAsync(turnContext, payload), ContentType = AdaptiveCard.ContentType }) as Activity }, }; return(response); }
public static async Task <EntitiDetails> ExecuteLuisQuery(IConfiguration configuration, ILogger logger, ITurnContext turnContext, CancellationToken cancellationToken) { var entitiDetails = new EntitiDetails(); try { // Create the LUIS settings from configuration. var luisApplication = new LuisApplication( configuration["LuisAppId"], configuration["LuisAPIKey"], "https://" + configuration["LuisAPIHostName"] ); var recognizer = new LuisRecognizer(luisApplication); // The actual call to LUIS var recognizerResult = await recognizer.RecognizeAsync(turnContext, cancellationToken); var(intent, score) = recognizerResult.GetTopScoringIntent(); entitiDetails.Intent = intent; entitiDetails.Score = score; //if(score<0.3) // return await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { Prompt = MessageFactory.Text("which Acronyn details would you like to have") }, cancellationToken) if (intent == "Trigger_Service" || intent == "Build_Deployment") { // We need to get the result from the LUIS JSON which at every level returns an array. //entitiDetails.Project = recognizerResult.Entities["service"]?.FirstOrDefault()?["Tag"]?.FirstOrDefault()?.FirstOrDefault()?.ToString(); if (recognizerResult.Entities["service"] != null) { entitiDetails.Project = recognizerResult.Entities["service"].First().ToString().Replace("[\r\n \"", string.Empty).Replace("\"\r\n]", string.Empty); } if (recognizerResult.Entities["Tag"] != null) { entitiDetails.Tag = recognizerResult.Entities["Tag"].First().ToString().Replace("[\r\n \"", string.Empty).Replace("\"\r\n]", string.Empty); } if (recognizerResult.Entities["Var"] != null) { entitiDetails.Buildwar = recognizerResult.Entities["Var"].First().ToString().Replace("[\r\n \"", string.Empty).Replace("\"\r\n]", string.Empty); } if (recognizerResult.Entities["Portfolio"] != null) { entitiDetails.Portfolio = recognizerResult.Entities["Portfolio"].First().ToString().Replace("[\r\n \"", string.Empty).Replace("\"\r\n]", string.Empty); } if (recognizerResult.Entities["Environment"] != null) { entitiDetails.Environment = recognizerResult.Entities["Environment"].First().ToString().Replace("[\r\n \"", string.Empty).Replace("\"\r\n]", string.Empty); } entitiDetails.TravelDate = recognizerResult.Entities["datetime"]?.FirstOrDefault()?["timex"]?.FirstOrDefault()?.ToString(); } else if (intent == "Acronym") { entitiDetails.Acronym = recognizerResult.Entities["Word"].First().ToString().Replace("[\r\n \"", string.Empty).Replace("\"\r\n]", string.Empty); } } catch (Exception e) { logger.LogWarning($"LUIS Exception: {e.Message} Check your LUIS configuration."); } return(entitiDetails); }
protected override Task OnRepromptDialogAsync(ITurnContext turnContext, DialogInstance instance, CancellationToken cancellationToken = default(CancellationToken)) => base.OnRepromptDialogAsync(turnContext, instance, cancellationToken);
// Called when the messaging extension query is entered public async Task <MessagingExtensionResponse> HandleMessagingExtensionQueryAsync(ITurnContext turnContext, MessagingExtensionQuery query) { var queryText = ""; queryText = query?.Parameters.FirstOrDefault(p => p.Name == "queryText").Value as string; var consultingDataService = new ConsultingDataService(); var projects = await consultingDataService.GetProjects(queryText); var attachments = new List <MessagingExtensionAttachment>(); foreach (var project in projects) { var resultCard = ProjectResultsCard.GetCard(project, getMapUrl(project.Client)); var previewCard = ProjectPreviewCard.GetCard(project); attachments.Add(resultCard.ToAttachment().ToMessagingExtensionAttachment(previewCard.ToAttachment())); } return(new MessagingExtensionResponse { ComposeExtension = new MessagingExtensionResult() { Type = "result", AttachmentLayout = "list", Attachments = attachments } }); }
public async Task OnTurn(ITurnContext context) { // Welcome message when user or agent joins conversation if (context.Activity.Type == ActivityTypes.ConversationUpdate) { if (context.Activity.MembersAdded.Any(m => m.Id != context.Activity.Recipient.Id)) { string msg = IsAgent(context) ? "Say 'list' to list pending users, or say a user ID to connect to" : "Say 'agent' to connect to an agent"; await context.SendActivity(msg); return; } } // Ignore non-message activities if (context.Activity.Type != ActivityTypes.Message) { return; } // If connected, forward activity ConversationReference self = TurnContext.GetConversationReference(context.Activity); ConversationReference connectedTo = connectionManager.ConnectedTo(self); if (connectedTo != null) { await ForwardTo(context, connectedTo); return; } // Agent code if (IsAgent(context)) { IList <Connection> pending = connectionManager.GetWaitingConnections(); if (context.Activity.Text == "list") { // Send agent a list of pending users var pendingStrs = pending.Select(c => $"{c.References.Ref0.User.Name} ({c.References.Ref0.User.Id})"); await context.SendActivity(pendingStrs.Count() > 0?string.Join("\n\n", pendingStrs) : "No users waiting"); return; } else { // Assume the agent said a pending user's id. Find that user // TODO: this is kind of messy b/c Connection is a value type Connection conn = pending.FirstOrDefault(p => p.References.Ref0.User.Id == context.Activity.Text); if (conn.References.Ref0 == null) { await context.SendActivity($"No pending user with id {context.Activity.Text}"); return; } // Connect to the pending user connectionManager.CompleteConnection(conn.References.Ref0, self); // Send message to both user and agent await SendTo(context, $"You are connected to {context.Activity.From.Name}", conn.References.Ref0); await context.SendActivity($"You are connected to {conn.References.Ref0.User.Name}"); return; } } // User code else { if (context.Activity.Text == "agent") { // Start waiting for an agent connectionManager.StartConnection(self); await context.SendActivity("Waiting for an agent... say 'stop' to stop waiting"); return; } else if (context.Activity.Text == "stop") { // Stop waiting for an agent connectionManager.RemoveConnection(self); await context.SendActivity("Stopped waiting"); return; } else { // Echo bot await context.SendActivity($"You said: {context.Activity.Text}"); return; } } }
protected override async Task OnMembersAddedAsync(IList <ChannelAccount> membersAdded, ITurnContext <IConversationUpdateActivity> turnContext, CancellationToken cancellationToken) { foreach (var member in membersAdded) { // Greet anyone that was not the target (recipient) of this message. // To learn more about Adaptive Cards, see https://aka.ms/msbot-adaptivecards for more details. if (member.Id != turnContext.Activity.Recipient.Id) { var welcomeCard = CreateAdaptiveCardAttachment(); var response = CreateResponse(turnContext.Activity, welcomeCard); await turnContext.SendActivityAsync(response, cancellationToken); } } }
private bool IsAgent(ITurnContext context) { return(context.Activity.From.Id == "default-agent"); }
private Task ForwardTo(ITurnContext context, ConversationReference to) { return(SendTo(context, context.Activity, to)); }
protected override async Task OnMembersAddedAsync(IList <ChannelAccount> membersAdded, ITurnContext <IConversationUpdateActivity> turnContext, CancellationToken cancellationToken) { foreach (var member in membersAdded) { // Greet anyone that was not the target (recipient) of this message. // To learn more about Adaptive Cards, see https://aka.ms/msbot-adaptivecards for more details. if (member.Id != turnContext.Activity.Recipient.Id) { //var welcomeCard = CreateAdaptiveCardAttachment(); //var response = MessageFactory.Attachment(welcomeCard, ssml: "Welcome to Bot Framework!"); ///await turnContext.SendActivityAsync(response, cancellationToken); await Dialog.RunAsync(turnContext, ConversationState.CreateProperty <DialogState>("DialogState"), cancellationToken); } } }
public Task <string> Generate(ITurnContext turnContext, string template, object data) { return(Task.FromResult(template)); }
protected override async Task OnMembersAddedAsync(IList <ChannelAccount> membersAdded, ITurnContext <IConversationUpdateActivity> turnContext, CancellationToken cancellationToken) { var welcomeText = "Checking how to deal with complexity?!"; foreach (var member in membersAdded) { if (member.Id != turnContext.Activity.Recipient.Id) { await turnContext.SendActivityAsync(MessageFactory.Text(welcomeText, welcomeText), cancellationToken); } } }
/// <summary> /// Deletes an existing activity in the conversation. /// </summary> /// <param name="context">The context object for the turn.</param> /// <param name="reference">Conversation reference for the activity to delete.</param> /// <returns>A task that represents the work queued to execute.</returns> /// <remarks>The <see cref="ConversationReference.ActivityId"/> of the conversation /// reference identifies the activity to delete.</remarks> /// <seealso cref="ITurnContext.OnDeleteActivity(DeleteActivityHandler)"/> public override async Task DeleteActivity(ITurnContext context, ConversationReference reference) { var connectorClient = context.Services.Get <IConnectorClient>(); await connectorClient.Conversations.DeleteActivityAsync(reference.Conversation.Id, reference.ActivityId).ConfigureAwait(false); }
public async Task <QueryResult[]> GetAnswersAsync(ITurnContext turnContext, IMessageActivity messageActivity, QnAMakerOptions options) { var result = await this.GetAnswersRawAsync(turnContext, messageActivity, options).ConfigureAwait(false); return(result.Answers); }
protected override Task OnEndDialogAsync(ITurnContext context, DialogInstance instance, DialogReason reason, CancellationToken cancellationToken = default(CancellationToken)) => base.OnEndDialogAsync(context, instance, reason, cancellationToken);
public override Task <ResourceResponse> UpdateActivityAsync(ITurnContext turnContext, Activity activity, CancellationToken cancellationToken) { throw new NotSupportedException(); }
public async Task <MessagingExtensionActionResponse> OnTeamsMessagingExtensionBotMessagePreviewEditAsync( ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken) { return(await HandleMessagingExtensionFetchTaskAsync(turnContext, action)); }
public override Task DeleteActivityAsync(ITurnContext turnContext, ConversationReference reference, CancellationToken cancellationToken) { throw new NotSupportedException(); }
// Called when the task module is fetched for an action public async Task <MessagingExtensionActionResponse> HandleMessagingExtensionFetchTaskAsync(ITurnContext turnContext, MessagingExtensionAction query) { var emptyRequest = new ConsultingRequestDetails(); ConsultingDataService dataService = new ConsultingDataService(); emptyRequest.possibleProjects = await dataService.GetProjects(""); IEnumerable <TeamsChannelAccount> members = await TeamsInfo.GetMembersAsync(turnContext); emptyRequest.possiblePersons = members.Select((w) => new Person { name = w.Name, email = w.Email }) .ToList(); var card = await AddToProjectCard.GetCardAsync(turnContext, emptyRequest); var response = new Microsoft.Bot.Schema.Teams.TaskModuleContinueResponse() { Type = "continue", Value = new TaskModuleTaskInfo() { Title = "Select a sample", Card = card.ToAttachment() } }; return(new MessagingExtensionActionResponse { Task = response }); }
protected override Task <MessagingExtensionResponse> OnTeamsAppBasedLinkQueryAsync(ITurnContext <IInvokeActivity> turnContext, AppBasedLinkQuery query, CancellationToken cancellationToken) { var heroCard = new ThumbnailCard { Title = "Thumbnail Card", Text = query.Url, Images = new List <CardImage> { new CardImage("https://raw.githubusercontent.com/microsoft/botframework-sdk/master/icon.png") }, }; var attachments = new MessagingExtensionAttachment(HeroCard.ContentType, null, heroCard); var result = new MessagingExtensionResult("list", "result", new[] { attachments }); return(Task.FromResult(new MessagingExtensionResponse(result))); }
/// <summary> /// Every conversation turn for our Echo Bot will call this method. /// There are no dialogs used, since it's "single turn" processing, meaning a single /// request and response. /// </summary> /// <param name="turnContext">A <see cref="ITurnContext"/> containing all the data needed /// for processing this conversation turn. </param> /// <param name="cancellationToken">(Optional) A <see cref="CancellationToken"/> that can be used by other objects /// or threads to receive notice of cancellation.</param> /// <returns>A <see cref="Task"/> that represents the work queued to execute.</returns> /// <seealso cref="BotStateSet"/> /// <seealso cref="ConversationState"/> /// <seealso cref="IMiddleware"/> public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken)) { Reference = turnContext.Activity.GetConversationReference(); // Handle Message activity type, which is the main activity type for shown within a conversational interface // Message activities may contain text, speech, interactive cards, and binary or unknown attachments. // see https://aka.ms/about-bot-activity-message to learn more about the message and other activity types if (turnContext.Activity.Type == ActivityTypes.Message) { //This should be sent out of form your backend responsbile for generating proactive message requests //Bellow you can find examples of supported content for proactive message by this sample if (turnContext.Activity.Text.ToLower().StartsWith("proactive")) { var card = new HeroCard { Text = "You can upload an image or select one of the following choices", Buttons = new List <CardAction>() { new CardAction(ActionTypes.ImBack, title: "1. Inline Attachment", value: "1"), new CardAction(ActionTypes.ImBack, title: "2. Internet Attachment", value: "2"), new CardAction(ActionTypes.ImBack, title: "3. Uploaded Attachment", value: "3"), } }; var sa = new SuggestedActions() { Actions = new List <CardAction>() { new CardAction() { Title = "Red", Type = ActionTypes.ImBack, Value = "Red" }, new CardAction() { Title = "Yellow", Type = ActionTypes.ImBack, Value = "Yellow" }, new CardAction() { Title = "Blue", Type = ActionTypes.ImBack, Value = "Blue" }, } }; var message = new ProactiveMessageRequestBody() { ConversationReference = await _accessors.ConversationReferenceState.GetAsync(turnContext), Message = "Hello", Attachments = new List <Attachment>() { card.ToAttachment(), card.ToAttachment() }, SuggestedActions = sa }; var localProactiveEndpoint = "http://localhost:3978/api/proactive"; await turnContext.SendActivityAsync("Proactive message incoming..."); // send the conversation reference and message to the bot's proactive endpoint var messageContent = JsonConvert.SerializeObject(message); //In production this would be implemented on the side of backend service, which initiates proactive messages using (var client = new HttpClient()) { var buffer = System.Text.Encoding.UTF8.GetBytes(messageContent); var byteContent = new ByteArrayContent(buffer); byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var result = await client.PostAsync(localProactiveEndpoint, byteContent); } } else { // Get the conversation state from the turn context. var state = await _accessors.CounterState.GetAsync(turnContext, () => new CounterState()); // Bump the turn count for this conversation. state.TurnCount++; // Set the property using the accessor. await _accessors.CounterState.SetAsync(turnContext, state); // Save the new turn count into the conversation state. await _accessors.ConversationState.SaveChangesAsync(turnContext); // Echo back to the user whatever they typed. var responseMessage = $"Turn {state.TurnCount}: You sent '{turnContext.Activity.Text}'\n"; await turnContext.SendActivityAsync(responseMessage); } } else { if (turnContext.Activity.MembersAdded.Count > 0) { foreach (var m in turnContext.Activity.MembersAdded) { if (m.Id != turnContext.Activity.Recipient.Id) { // store the conversation reference for the newly added user // in production scenario you want to store conversation reference in an external store e.g. Cosmos DB, Table Storage etc. await _accessors.ConversationReferenceState.SetAsync(turnContext, turnContext.Activity.GetConversationReference()); await _accessors.ConversationState.SaveChangesAsync(turnContext); } } await turnContext.SendActivityAsync($"{turnContext.Activity.Type} event detected"); } } }
protected override async Task <MessagingExtensionResponse> OnTeamsMessagingExtensionQueryAsync(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionQuery query, CancellationToken cancellationToken) { //Note: The Teams manifest.json for this sample also inclues a Search Query, in order to enable installing from App Studio. var text = query?.Parameters?[0]?.Value as string ?? string.Empty; switch (query.CommandId) { // These commandIds are defined in the Teams App Manifest. case "searchQuery": var card = new HeroCard { Title = "This is a Link Unfurling Sample", Subtitle = "It will unfurl links from *.BotFramework.com", Text = "This sample demonstrates how to handle link unfurling in Teams. Please review the readme for more information.", }; return(new MessagingExtensionResponse { ComposeExtension = new MessagingExtensionResult { AttachmentLayout = "list", Type = "result", Attachments = new List <MessagingExtensionAttachment> { new MessagingExtensionAttachment { Content = card, ContentType = HeroCard.ContentType, Preview = card.ToAttachment(), }, }, }, }); default: throw new NotImplementedException($"Invalid CommandId: {query.CommandId}"); } }
/// <summary> /// /// </summary> /// <param name="state"></param> /// <param name="turnContext"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public async Task StartConversation(MindshopperUserState state, ITurnContext turnContext, CancellationToken cancellationToken) { /* * IConversationUpdateActivity update = turnContext.Activity; * * if (update.MembersAdded != null && update.MembersAdded.Any()) * { * foreach (var newMember in update.MembersAdded) * { * if (newMember.Id != turnContext.Activity.Recipient.Id) * { * if (turnContext.Activity.From.Properties["userId"] != null) * { * state.UserId = turnContext.Activity.From.Properties["userId"].ToString(); * } * * if (turnContext.Activity.From.Properties["cartId"] != null) * { * state.CartId = turnContext.Activity.From.Properties["cartId"].ToString(); * } * * if (turnContext.Activity.From.Properties["name"] != null) * { * state.Name = turnContext.Activity.From.Properties["name"].ToString(); * } * * state.TurnCount = State.CHOOSE_CATEGORY; * * await _accessors.MindshopperUserState.SetAsync(turnContext, state); * await _accessors.ConversationState.SaveChangesAsync(turnContext); * * * string hello = $"Hello, '{state.Name}'. I am your personal shopping assistant and I will guide you during the shopping process." + * $"\n" + * $"\n Please select what you want to buy:" + * $"\n\t\t1) Tobacco" + * $"\n\t\t2) Food" + * $"\n\t\t3) Perfumes & Cosmetics" + * $"\n\t\t4) Liquor"; * * await turnContext.SendActivityAsync(hello); * } * } * }*/ if (turnContext.Activity.From.Properties["userId"] != null) { state.UserId = turnContext.Activity.From.Properties["userId"].ToString(); } if (turnContext.Activity.From.Properties["cartId"] != null) { state.CartId = turnContext.Activity.From.Properties["cartId"].ToString(); } if (turnContext.Activity.From.Properties["name"] != null) { state.Name = turnContext.Activity.From.Properties["name"].ToString(); } state.TurnCount = State.CHOOSE_CATEGORY; await _accessors.MindshopperUserState.SetAsync(turnContext, state); await _accessors.ConversationState.SaveChangesAsync(turnContext); string hello = $"Hello, '{state.Name}'. I am your personal shopping assistant and I will guide you during the shopping process." + $"\n" + $"\n Please select what you want to buy:" + $"\n\t\t1) Tobacco" + $"\n\t\t2) Food" + $"\n\t\t3) Perfumes & Cosmetics" + $"\n\t\t4) Liquor"; await turnContext.SendActivityAsync(hello); }
/// <summary> /// Sends activities to the conversation. /// </summary> /// <param name="context">The context object for the turn.</param> /// <param name="activities">The activities to send.</param> /// <returns>A task that represents the work queued to execute.</returns> /// <remarks>If the activities are successfully sent, the task result contains /// an array of <see cref="ResourceResponse"/> objects containing the IDs that /// the receiving channel assigned to the activities.</remarks> /// <seealso cref="ITurnContext.OnSendActivities(SendActivitiesHandler)"/> public override async Task <ResourceResponse[]> SendActivities(ITurnContext context, Activity[] activities) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (activities == null) { throw new ArgumentNullException(nameof(activities)); } if (activities.Length == 0) { throw new ArgumentException("Expecting one or more activities, but the array was empty.", nameof(activities)); } var responses = new ResourceResponse[activities.Length]; /* * NOTE: we're using for here (vs. foreach) because we want to simultaneously index into the * activities array to get the activity to process as well as use that index to assign * the response to the responses array and this is the most cost effective way to do that. */ for (var index = 0; index < activities.Length; index++) { var activity = activities[index]; var response = default(ResourceResponse); if (activity.Type == ActivityTypesEx.Delay) { // The Activity Schema doesn't have a delay type build in, so it's simulated // here in the Bot. This matches the behavior in the Node connector. int delayMs = (int)activity.Value; await Task.Delay(delayMs).ConfigureAwait(false); // No need to create a response. One will be created below. } else if (activity.Type == "invokeResponse") // Aligning name with Node { context.Services.Add <Activity>(InvokeReponseKey, activity); // No need to create a response. One will be created below. } else if (activity.Type == ActivityTypes.Trace && activity.ChannelId != "emulator") { // if it is a Trace activity we only send to the channel if it's the emulator. } else if (!string.IsNullOrWhiteSpace(activity.ReplyToId)) { var connectorClient = context.Services.Get <IConnectorClient>(); response = await connectorClient.Conversations.ReplyToActivityAsync(activity).ConfigureAwait(false); } else { var connectorClient = context.Services.Get <IConnectorClient>(); response = await connectorClient.Conversations.SendToConversationAsync(activity).ConfigureAwait(false); } // If No response is set, then defult to a "simple" response. This can't really be done // above, as there are cases where the ReplyTo/SendTo methods will also return null // (See below) so the check has to happen here. // Note: In addition to the Invoke / Delay / Activity cases, this code also applies // with Skype and Teams with regards to typing events. When sending a typing event in // these _channels they do not return a RequestResponse which causes the bot to blow up. // https://github.com/Microsoft/botbuilder-dotnet/issues/460 // bug report : https://github.com/Microsoft/botbuilder-dotnet/issues/465 if (response == null) { response = new ResourceResponse(activity.Id ?? string.Empty); } responses[index] = response; } return(responses); }
public virtual async Task <RecognizerResult> RecognizeAsync(ITurnContext turnContext, CancellationToken cancellationToken) => await _recognizer.RecognizeAsync(turnContext, cancellationToken);
/// <summary> /// Replaces an existing activity in the conversation. /// </summary> /// <param name="context">The context object for the turn.</param> /// <param name="activity">New replacement activity.</param> /// <returns>A task that represents the work queued to execute.</returns> /// <remarks>If the activity is successfully sent, the task result contains /// a <see cref="ResourceResponse"/> object containing the ID that the receiving /// channel assigned to the activity. /// <para>Before calling this, set the ID of the replacement activity to the ID /// of the activity to replace.</para></remarks> /// <seealso cref="ITurnContext.OnUpdateActivity(UpdateActivityHandler)"/> public override async Task <ResourceResponse> UpdateActivity(ITurnContext context, Activity activity) { var connectorClient = context.Services.Get <IConnectorClient>(); return(await connectorClient.Conversations.UpdateActivityAsync(activity).ConfigureAwait(false)); }
/// <summary> /// Return results of the analysis (Suggested actions and intents), using the turn context. This is missing a dialog id used for telemetry.. /// </summary> /// <param name="context">Context object containing information for a single turn of conversation with a user.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>The LUIS results of the analysis of the current message text in the current turn's context activity.</returns> public async Task <RecognizerResult> RecognizeAsync(ITurnContext context, CancellationToken cancellationToken = default(CancellationToken)) { return(await RecognizeInternalAsync(context, null, cancellationToken)); }
protected override async Task OnMembersAddedAsync(IList <ChannelAccount> membersAdded, ITurnContext <IConversationUpdateActivity> turnContext, CancellationToken cancellationToken) { foreach (var member in membersAdded) { if (member.Id != turnContext.Activity.Recipient.Id) { //await turnContext.SendActivityAsync($"Hi there - @{member.Name}. Welcome to the channel", cancellationToken: cancellationToken); } else { await turnContext.SendActivityAsync("I have arrived!"); } } }