示例#1
0
 protected override async Task OnMembersAddedAsync(IList <ChannelAccount> membersAdded, ITurnContext <IConversationUpdateActivity> turnContext, CancellationToken cancellationToken) =>
 await turnContext.SendActivityAsync("Bem-vindo(a) ao Hotel! Sou o seu atendente virtual!");
        /// <summary>
        /// Every conversation turn calls this method.
        /// </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"/>
        public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
        {
            // use state accessor to extract the didBotWelcomeUser flag
            var didBotWelcomeUser = await _welcomeUserStateAccessors.WelcomeUserState.GetAsync(turnContext, () => new WelcomeUserState());

            // 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)
            {
                if (didBotWelcomeUser.DidBotWelcomeUser == false)
                {
                    didBotWelcomeUser.DidBotWelcomeUser = true;
                    await _welcomeUserStateAccessors.WelcomeUserState.SetAsync(turnContext, didBotWelcomeUser);

                    await _welcomeUserStateAccessors.UserState.SaveChangesAsync(turnContext);

                    var userName = turnContext.Activity.From.Name;
                    await turnContext.SendActivityAsync($"You are seeing this message because this was your first message ever to this bot.", cancellationToken : cancellationToken);

                    await turnContext.SendActivityAsync($"It is a good practice to welcome the user and provide personal greeting. For example, welcome {userName}.", cancellationToken : cancellationToken);
                }
                else
                {
                    // This example hardcodes specific utterances. You should use LUIS or QnA for more advance language understanding.
                    var text = turnContext.Activity.Text.ToLowerInvariant();
                    switch (text)
                    {
                    case "hello":
                    case "hi":
                        await turnContext.SendActivityAsync($"You said {text}.", cancellationToken : cancellationToken);

                        break;

                    case "intro":
                    case "help":
                        await SendIntroCardAsync(turnContext, cancellationToken);

                        break;

                    default:
                        await turnContext.SendActivityAsync(WelcomeMessage, cancellationToken : cancellationToken);

                        break;
                    }
                }
            }
            else if (turnContext.Activity.Type == ActivityTypes.ConversationUpdate)
            {
                if (turnContext.Activity.MembersAdded != null)
                {
                    // Iterate over all new members added to the conversation
                    foreach (var member in turnContext.Activity.MembersAdded)
                    {
                        // Greet anyone that was not the target (recipient) of this message
                        // the 'bot' is the recipient for events from the channel,
                        // turnContext.Activity.MembersAdded == turnContext.Activity.Recipient.Id indicates the
                        // bot was added to the conversation.
                        if (member.Id != turnContext.Activity.Recipient.Id)
                        {
                            await turnContext.SendActivityAsync($"Hi there - {member.Name}. {WelcomeMessage}", cancellationToken : cancellationToken);

                            await turnContext.SendActivityAsync(InfoMessage, cancellationToken : cancellationToken);

                            await turnContext.SendActivityAsync(PatternMessage, cancellationToken : cancellationToken);
                        }
                    }
                }
            }
            else
            {
                // Default behavior for all other type of activities.
                await turnContext.SendActivityAsync($"{turnContext.Activity.Type} activity detected");
            }

            // save any state changes made to your state objects.
            await _welcomeUserStateAccessors.UserState.SaveChangesAsync(turnContext);
        }
示例#3
0
 public static async Task ReplyWithHelp(ITurnContext context)
 {
     await context.SendActivityAsync($"I can search for pictures, share pictures and order prints of pictures.");
 }
示例#4
0
        // Handle message activity in 1:1 chat
        private async Task OnMessageActivityInPersonalChatAsync(IMessageActivity message, ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            if (!string.IsNullOrEmpty(message.ReplyToId) && (message.Value != null) && ((JObject)message.Value).HasValues)
            {
                this.telemetryClient.TrackTrace("Card submit in 1:1 chat");
                await this.OnAdaptiveCardSubmitInPersonalChatAsync(message, turnContext, cancellationToken);

                return;
            }

            string text = (message.Text ?? string.Empty).Trim().ToLower();

            switch (text)
            {
            case AskAnExpert:
                this.telemetryClient.TrackTrace("Sending user ask an expert card");
                await turnContext.SendActivityAsync(MessageFactory.Attachment(AskAnExpertCard.GetCard()));

                break;

            case ShareFeedback:
                this.telemetryClient.TrackTrace("Sending user feedback card");
                await turnContext.SendActivityAsync(MessageFactory.Attachment(ShareFeedbackCard.GetCard()));

                break;

            case TakeATour:
                this.telemetryClient.TrackTrace("Sending user tour card");
                var userTourCards = TourCarousel.GetUserTourCards(this.appBaseUri);
                await turnContext.SendActivityAsync(MessageFactory.Carousel(userTourCards));

                break;

            default:
                this.telemetryClient.TrackTrace("Sending input to QnAMaker");
                var queryResult = await this.GetAnswerFromQnAMakerAsync(text, turnContext, cancellationToken);

                if (queryResult != null)
                {
                    this.telemetryClient.TrackTrace("Sending user QnAMaker card");
                    await turnContext.SendActivityAsync(MessageFactory.Attachment(ResponseCard.GetCard(queryResult.Questions[0], queryResult.Answer, text)));
                }
                else
                {
                    var tileList = await this.MatchTagsWithMessageAsync(text);

                    if (tileList != null)
                    {
                        this.telemetryClient.TrackTrace("Sending user tags card");
                        await turnContext.SendActivityAsync(SuggestedLinkCard.GetTagsCarouselCards(text, tileList, Resource.CustomMessage));
                    }
                    else
                    {
                        this.telemetryClient.TrackTrace("Sending user with no matched tags result");
                        await turnContext.SendActivityAsync(MessageFactory.Attachment(UnrecognizedInputCard.GetCard(text, Resource.NoMatchedTagsMessage)));
                    }
                }

                break;
            }
        }
示例#5
0
        // Handle adaptive card submit in channel
        // Updates the ticket status based on the user submission
        private async Task OnAdaptiveCardSubmitInChannelAsync(IMessageActivity message, ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            var payload = ((JObject)message.Value).ToObject <ChangeTicketStatusPayload>();

            this.telemetryClient.TrackTrace($"Received submit: ticketId={payload.TicketId} action={payload.Action}");

            // Get the ticket from the data store
            var ticket = await this.ticketsProvider.GetTicketAsync(payload.TicketId);

            if (ticket == null)
            {
                this.telemetryClient.TrackTrace($"Ticket {payload.TicketId} was not found in the data store");
                await turnContext.SendActivityAsync(MessageFactory.Text($"Ticket {payload.TicketId} was not found in the data store"));

                return;
            }

            // Update the ticket based on the payload
            switch (payload.Action)
            {
            case ChangeTicketStatusPayload.ReopenAction:
                ticket.Status             = (int)TicketState.Open;
                ticket.DateAssigned       = null;
                ticket.AssignedToName     = null;
                ticket.AssignedToObjectId = null;
                ticket.DateClosed         = null;
                break;

            case ChangeTicketStatusPayload.CloseAction:
                ticket.Status     = (int)TicketState.Closed;
                ticket.DateClosed = DateTime.UtcNow;
                break;

            case ChangeTicketStatusPayload.AssignToSelfAction:
                ticket.Status             = (int)TicketState.Open;
                ticket.DateAssigned       = DateTime.UtcNow;
                ticket.AssignedToName     = message.From.Name;
                ticket.AssignedToObjectId = message.From.AadObjectId;
                ticket.DateClosed         = null;
                break;

            default:
                this.telemetryClient.TrackTrace($"Unknown status command {payload.Action}", SeverityLevel.Warning);
                await turnContext.SendActivityAsync(MessageFactory.Text($"Unknown status command {payload.Action}"));

                return;
            }

            ticket.LastModifiedByName     = message.From.Name;
            ticket.LastModifiedByObjectId = message.From.AadObjectId;

            await this.ticketsProvider.SaveOrUpdateTicketAsync(ticket);

            this.telemetryClient.TrackTrace($"Ticket {ticket.TicketId} updated to status ({ticket.Status}, {ticket.AssignedToObjectId}) in store");

            // Update the card in the SME team
            var updateCardActivity = new Activity(ActivityTypes.Message)
            {
                Id           = ticket.SmeCardActivityId,
                Conversation = new ConversationAccount {
                    Id = ticket.SmeThreadConversationId
                },
                Attachments = new List <Attachment> {
                    new SmeTicketCard(ticket).ToAttachment(message.LocalTimestamp)
                },
            };
            var updateResponse = await turnContext.UpdateActivityAsync(updateCardActivity, cancellationToken);

            this.telemetryClient.TrackTrace($"Card for ticket {ticket.TicketId} updated to status ({ticket.Status}, {ticket.AssignedToObjectId}), activityId = {updateResponse.Id}");

            // Post update to user and SME team thread
            string           smeNotification  = null;
            IMessageActivity userNotification = null;

            switch (payload.Action)
            {
            case ChangeTicketStatusPayload.ReopenAction:
                smeNotification = string.Format(Resource.SMEOpenedStatus, message.From.Name);

                userNotification         = MessageFactory.Attachment(new UserNotificationCard(ticket).ToAttachment(Resource.ReopenedTicketUserNotification, message.LocalTimestamp));
                userNotification.Summary = Resource.ReopenedTicketUserNotification;
                break;

            case ChangeTicketStatusPayload.CloseAction:
                smeNotification = string.Format(Resource.SMEClosedStatus, ticket.LastModifiedByName);

                userNotification         = MessageFactory.Attachment(new UserNotificationCard(ticket).ToAttachment(Resource.ClosedTicketUserNotification, message.LocalTimestamp));
                userNotification.Summary = Resource.ClosedTicketUserNotification;
                break;

            case ChangeTicketStatusPayload.AssignToSelfAction:
                smeNotification = string.Format(Resource.SMEAssignedStatus, ticket.AssignedToName);

                userNotification         = MessageFactory.Attachment(new UserNotificationCard(ticket).ToAttachment(Resource.AssignedTicketUserNotification, message.LocalTimestamp));
                userNotification.Summary = Resource.AssignedTicketUserNotification;
                break;
            }

            if (smeNotification != null)
            {
                var smeResponse = await turnContext.SendActivityAsync(smeNotification);

                this.telemetryClient.TrackTrace($"SME team notified of update to ticket {ticket.TicketId}, activityId = {smeResponse.Id}");
            }

            if (userNotification != null)
            {
                userNotification.Conversation = new ConversationAccount {
                    Id = ticket.RequesterConversationId
                };
                var userResponse = await turnContext.Adapter.SendActivitiesAsync(turnContext, new Activity[] { (Activity)userNotification }, cancellationToken);

                this.telemetryClient.TrackTrace($"User notified of update to ticket {ticket.TicketId}, activityId = {userResponse.FirstOrDefault()?.Id}");
            }
        }
 public async Task HandleStatusRequest(ITurnContext context, string messageText, NextDelegate next, CancellationToken cancellationToken)
 {
     await context.SendActivityAsync("I am great.");
 }
 public async Task HandleThanks(ITurnContext context, string messageText, NextDelegate next, CancellationToken cancellationToken)
 {
     await context.SendActivityAsync("You're welcome.");
 }
示例#8
0
        /// <summary>
        /// Handle adaptive card submit in channel.
        /// Updates the ticket status based on the user submission.
        /// </summary>
        /// <param name="message">A message in a conversation.</param>
        /// <param name="turnContext">Context object containing information cached for a single turn of conversation with a user.</param>
        /// <param name="ticketDetailStorageProvider">Provider to store ticket details to Azure Table Storage.</param>
        /// <param name="cardConfigurationStorageProvider">Provider to search card configuration details in Azure Table Storage.</param>
        /// <param name="logger">Sends logs to the Application Insights service.</param>
        /// <param name="appBaseUrl">Represents the Application base Uri.</param>
        /// <param name="localizer">The current cultures' string localizer.</param>
        /// /// <param name="cancellationToken">Propagates notification that operations should be canceled.</param>
        /// <returns>A task that represents the work queued to execute.</returns>
        internal static async Task OnAdaptiveCardSubmitInChannelAsync(
            IMessageActivity message,
            ITurnContext <IMessageActivity> turnContext,
            ITicketDetailStorageProvider ticketDetailStorageProvider,
            ICardConfigurationStorageProvider cardConfigurationStorageProvider,
            ILogger logger,
            string appBaseUrl,
            IStringLocalizer <Strings> localizer,
            CancellationToken cancellationToken)
        {
            string             smeNotification;
            IMessageActivity   userNotification;
            ChangeTicketStatus payload = ((JObject)message.Value).ToObject <ChangeTicketStatus>();

            payload.Action = payload.RequestType == null ? payload.Action : RequestTypeText;
            logger.LogInformation($"Received submit:  action={payload.Action} ticketId={payload.TicketId}");

            // Get the ticket from the data store.
            TicketDetail ticketData = await ticketDetailStorageProvider.GetTicketAsync(payload.TicketId);

            if (ticketData == null)
            {
                await turnContext.SendActivityAsync($"Ticket {payload.TicketId} was not found in the data store");

                logger.LogInformation($"Ticket {payload.TicketId} was not found in the data store");
                return;
            }

            // Update the ticket based on the payload.
            switch (payload.Action)
            {
            case ChangeTicketStatus.ReopenAction:
                ticketData.TicketStatus       = (int)TicketState.Unassigned;
                ticketData.AssignedToName     = null;
                ticketData.AssignedToObjectId = null;
                ticketData.ClosedOn           = null;
                smeNotification  = localizer.GetString("SmeUnassignedStatus", message.From.Name);
                userNotification = MessageFactory.Text(localizer.GetString("ReopenedTicketUserNotification", ticketData.TicketId));
                break;

            case ChangeTicketStatus.CloseAction:
                ticketData.TicketStatus = (int)TicketState.Closed;
                ticketData.ClosedByName = message.From.Name;
                ticketData.ClosedOn     = message.From.AadObjectId;
                smeNotification         = localizer.GetString("SmeClosedStatus", message.From.Name);
                userNotification        = MessageFactory.Text(localizer.GetString("ClosedTicketUserNotification", ticketData.TicketId));
                break;

            case ChangeTicketStatus.AssignToSelfAction:
                ticketData.TicketStatus       = (int)TicketState.Assigned;
                ticketData.AssignedToName     = message.From.Name;
                ticketData.AssignedToObjectId = message.From.AadObjectId;
                ticketData.ClosedOn           = null;
                smeNotification  = localizer.GetString("SmeAssignedStatus", message.From.Name);
                userNotification = MessageFactory.Text(localizer.GetString("AssignedTicketUserNotification", ticketData.TicketId));
                break;

            case ChangeTicketStatus.RequestTypeAction:
                ticketData.Severity    = (int)(TicketSeverity)Enum.Parse(typeof(TicketSeverity), payload.RequestType);
                ticketData.RequestType = payload.RequestType;
                logger.LogInformation($"Received submit:  action={payload.RequestType} ticketId={payload.TicketId}");
                smeNotification  = localizer.GetString("SmeSeverityStatus", ticketData.RequestType, message.From.Name);
                userNotification = MessageFactory.Text(localizer.GetString("RequestActionTicketUserNotification", ticketData.TicketId));
                break;

            default:
                logger.LogInformation($"Unknown status command {payload.Action}", SeverityLevel.Warning);
                return;
            }

            ticketData.LastModifiedByName     = message.From.Name;
            ticketData.LastModifiedByObjectId = message.From.AadObjectId;
            ticketData.LastModifiedOn         = DateTime.UtcNow;

            await ticketDetailStorageProvider.UpsertTicketAsync(ticketData);

            logger.LogInformation($"Ticket {ticketData.TicketId} updated to status ({ticketData.TicketStatus}, {ticketData.AssignedToObjectId}) in store");

            // Get card item element mappings
            var cardElementMapping = await cardConfigurationStorageProvider.GetCardItemElementMappingAsync(ticketData.CardId);

            // Update the card in the SME team.
            Activity updateCardActivity = new Activity(ActivityTypes.Message)
            {
                Id           = ticketData.SmeTicketActivityId,
                Conversation = new ConversationAccount {
                    Id = ticketData.SmeConversationId
                },
                Attachments = new List <Attachment> {
                    new SmeTicketCard(ticketData).GetTicketDetailsForSMEChatCard(cardElementMapping, ticketData, appBaseUrl, localizer)
                },
            };
            ResourceResponse updateResponse = await turnContext.UpdateActivityAsync(updateCardActivity, cancellationToken);

            logger.LogInformation($"Card for ticket {ticketData.TicketId} updated to status ({ticketData.TicketStatus}, {ticketData.AssignedToObjectId}), activityId = {updateResponse.Id}");

            // Post update to user and SME team thread.
            if (!string.IsNullOrEmpty(smeNotification))
            {
                ResourceResponse smeResponse = await turnContext.SendActivityAsync(smeNotification);

                logger.LogInformation($"SME team notified of update to ticket {ticketData.TicketId}, activityId = {smeResponse.Id}");
            }

            if (userNotification != null)
            {
                userNotification.Conversation = new ConversationAccount {
                    Id = ticketData.RequesterConversationId
                };
                ResourceResponse[] userResponse = await turnContext.Adapter.SendActivitiesAsync(turnContext, new Activity[] { (Activity)userNotification }, cancellationToken);

                logger.LogInformation($"User notified of update to ticket {ticketData.TicketId}, activityId = {userResponse.FirstOrDefault()?.Id}");
            }
        }
示例#9
0
        /// <summary>
        /// Method Handle adaptive card submit in 1:1 chat and Send new ticket details to SME team.
        /// </summary>
        /// <param name="message">Message activity of bot.</param>
        /// <param name="turnContext">Context object containing information cached for a single turn of conversation with a user.</param>
        /// <param name="ticketGenerateStorageProvider">Provider to get ticket id to Azure Table Storage.</param>
        /// <param name="ticketDetailStorageProvider">Provider to store ticket details to Azure Table Storage.</param>
        /// <param name="cardConfigurationStorageProvider">Provider to search card configuration details in Azure Table Storage.</param>
        /// <param name="microsoftAppCredentials">Microsoft Application credentials for Bot/ME.</param>
        /// <param name="logger">Sends logs to the Application Insights service.</param>
        /// <param name="appBaseUrl">Represents the Application base Uri.</param>
        /// <param name="localizer">The current cultures' string localizer.</param>
        /// <param name="cancellationToken">Propagates notification that operations should be canceled.</param>
        /// <returns>A task that handles submit action in 1:1 chat.</returns>
        internal static async Task OnAdaptiveCardSubmitInPersonalChatAsync(
            IMessageActivity message,
            ITurnContext <IMessageActivity> turnContext,
            ITicketIdGeneratorStorageProvider ticketGenerateStorageProvider,
            ITicketDetailStorageProvider ticketDetailStorageProvider,
            ICardConfigurationStorageProvider cardConfigurationStorageProvider,
            MicrosoftAppCredentials microsoftAppCredentials,
            ILogger logger,
            string appBaseUrl,
            IStringLocalizer <Strings> localizer,
            CancellationToken cancellationToken)
        {
            IMessageActivity endUserUpdateCard;

            switch (message.Text.ToUpperInvariant())
            {
            case Constants.SendRequestAction:
                TicketDetail newTicketDetail = JsonConvert.DeserializeObject <TicketDetail>(message.Value?.ToString());
                if (TicketHelper.ValidateRequestDetail(newTicketDetail))
                {
                    AdaptiveCardAction cardDetail = ((JObject)message.Value).ToObject <AdaptiveCardAction>();
                    logger.LogInformation("Adding new request with additional details.");
                    var ticketTd = await ticketGenerateStorageProvider.GetTicketIdAsync();

                    // Update new request with additional details.
                    var userDetails = await GetUserDetailsInPersonalChatAsync(turnContext, cancellationToken);

                    newTicketDetail.TicketId = ticketTd.ToString(CultureInfo.InvariantCulture);
                    newTicketDetail          = TicketHelper.GetNewTicketDetails(turnContext: turnContext, ticketDetail: newTicketDetail, ticketAdditionalDetails: message.Value?.ToString(), cardId: cardDetail.CardId, member: userDetails);
                    bool result = await ticketDetailStorageProvider.UpsertTicketAsync(newTicketDetail);

                    if (!result)
                    {
                        logger.LogError("Error in storing new ticket details in table storage.");
                        await turnContext.SendActivityAsync(localizer.GetString("AzureStorageErrorText"));

                        return;
                    }

                    logger.LogInformation("New request created with ticket Id:" + newTicketDetail.TicketId);

                    // Get card item element mappings
                    var carditemElementMapping = await cardConfigurationStorageProvider.GetCardItemElementMappingAsync(cardDetail?.CardId);

                    endUserUpdateCard = MessageFactory.Attachment(TicketCard.GetTicketDetailsForPersonalChatCard(carditemElementMapping, newTicketDetail, localizer, false));
                    await CardHelper.SendRequestCardToSMEChannelAsync(turnContext : turnContext, ticketDetail : newTicketDetail, logger : logger, ticketDetailStorageProvider : ticketDetailStorageProvider, applicationBasePath : appBaseUrl, cardElementMapping : carditemElementMapping, localizer, teamId : cardDetail?.TeamId, microsoftAppCredentials : microsoftAppCredentials, cancellationToken : cancellationToken);

                    await CardHelper.UpdateRequestCardForEndUserAsync(turnContext, endUserUpdateCard);

                    await turnContext.SendActivityAsync(MessageFactory.Text(localizer.GetString("EndUserNotificationText", newTicketDetail.TicketId)));
                }
                else
                {
                    // Update card with validation message.
                    newTicketDetail.AdditionalProperties = CardHelper.ValidateAdditionalTicketDetails(message.Value?.ToString(), timeSpan: turnContext.Activity.Timestamp.Value.Offset);
                    CardConfigurationEntity cardTemplateJson = await cardConfigurationStorageProvider.GetConfigurationAsync();

                    endUserUpdateCard = MessageFactory.Attachment(TicketCard.GetNewTicketCard(cardConfiguration: cardTemplateJson, localizer: localizer, showValidationMessage: true, ticketDetail: newTicketDetail));
                    await CardHelper.UpdateRequestCardForEndUserAsync(turnContext, endUserUpdateCard);
                }

                break;

            case Constants.WithdrawRequestAction:
                var payload = ((JObject)message.Value).ToObject <AdaptiveCardAction>();
                endUserUpdateCard = MessageFactory.Attachment(WithdrawCard.GetCard(payload.PostedValues, localizer));

                // Get the ticket from the data store.
                TicketDetail ticketDetail = await ticketDetailStorageProvider.GetTicketAsync(payload.PostedValues);

                if (ticketDetail.TicketStatus == (int)TicketState.Closed)
                {
                    await turnContext.SendActivityAsync(localizer.GetString("WithdrawErrorMessage"));

                    return;
                }

                ticketDetail.LastModifiedByName     = message.From.Name;
                ticketDetail.LastModifiedByObjectId = message.From.AadObjectId;
                ticketDetail.TicketStatus           = (int)TicketState.Withdrawn;
                bool success = await ticketDetailStorageProvider.UpsertTicketAsync(ticketDetail);

                if (!success)
                {
                    logger.LogError("Error in updating ticket details in table storage.");
                    await turnContext.SendActivityAsync(localizer.GetString("AzureStorageErrorText"));

                    return;
                }

                logger.LogInformation("Withdrawn the ticket:" + ticketDetail.TicketId);
                IMessageActivity smeWithdrawNotification = MessageFactory.Text(localizer.GetString("SmeWithdrawNotificationText", ticketDetail.RequesterName));
                var itemElementMapping = await cardConfigurationStorageProvider.GetCardItemElementMappingAsync(ticketDetail?.CardId);

                await CardHelper.UpdateSMECardAsync(turnContext, ticketDetail, smeWithdrawNotification, appBaseUrl, itemElementMapping, localizer, logger, cancellationToken);

                await CardHelper.UpdateRequestCardForEndUserAsync(turnContext, endUserUpdateCard);

                break;
            }
        }
 public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default) => await turnContext.SendActivityAsync(MessageFactory.Text("do.not.go.gentle.into.that.good.night"));
示例#11
0
 private async Task BotCallback(ITurnContext turnContext, CancellationToken cancellationToken)
 {
     await turnContext.SendActivityAsync("proactive hello");
 }
示例#12
0
        /// <summary>
        /// Every conversation turn for our LUIS Bot will call this method.
        /// There are no dialogs used, the sample only uses "single turn" processing,
        /// meaning a single request and response, with no stateful conversation.
        /// </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>
        public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (turnContext.Activity.Type == ActivityTypes.Message)
            {
                // Check LUIS model
                var recognizerResult = await _services.LuisServices[LuisKey].RecognizeAsync(turnContext, cancellationToken);

                var topIntent = recognizerResult?.GetTopScoringIntent();
                if (topIntent != null && topIntent.HasValue && topIntent.Value.intent != "None")
                {
                    await turnContext.SendActivityAsync($"==>LUIS Top Scoring Intent: {topIntent.Value.intent}, Score: {topIntent.Value.score}\n");

                    //var listOfEntities = recognizerResult?.Entities.First["$instance"]["DayName"]["text"];
                    //var listOfEntities = recognizerResult?.Entities.First.ToString();
                    //var listOfEntities = recognizerResult?.Entities.First.ToString();

                    //dynamic data = JsonConvert.DeserializeObject(recognizerResult?.Entities.Last);
                    var listOfEntities = recognizerResult?.Entities.Last.ToString();

                    //dynamic dyn = JsonConvert.DeserializeObject(listOfEntities);
                    //foreach (var obj in dyn.DayName)
                    //{
                    //    for
                    //};


                    var stringEntities = recognizerResult?.Entities.ToString();
                    await turnContext.SendActivityAsync($"Entities: {stringEntities} \n");


                    //
                    //var customEntityData = CustomEntityData.FromJson(jsonString);
                    var customEntityData = CustomEntityData.FromJson(stringEntities);
                    var sundayWord       = customEntityData.DayName[0][0].ToString();
                    await turnContext.SendActivityAsync($"Entities: {sundayWord} \n");

                    var dateTimeClass  = DateTimeClass.FromJson(stringEntities);
                    var dateTimeString = dateTimeClass.Datetime[0].Timex[0].ToString();
                    await turnContext.SendActivityAsync($"Entities: {dateTimeString} \n");

                    var dateAndTimeClass        = DateAndTimeClass.FromJson(stringEntities);
                    var dateAndTimeClassTheDate = dateTimeClass.Datetime[0].Timex[0].ToString();
                    var dateAndTimeClassTheTime = dateTimeClass.Datetime[1].Timex[0].ToString();
                    await turnContext.SendActivityAsync($"Entities: {dateAndTimeClassTheDate} and {dateAndTimeClassTheTime} \n");

                    var dateAndDateTimeClass        = DateAndDateTimeClass.FromJson(stringEntities);
                    var dateAndDateTimeClassTheDate = dateAndDateTimeClass.Datetime[0].Timex[0].ToString();

                    var dateAndDateTimeClassTheDateTime = dateAndDateTimeClass.Datetime[1].Timex[0].ToString();

                    //var input = "2018-10-28";
                    ////var input = "2018-10-28T4";
                    //var format = "yyyy-MM-dd";
                    ////var format = "yyyy-MM-ddThh:mm:ss";



                    //DateTime parsed;
                    //string parsedString;
                    //                    if (DateTime.TryParseExact(input, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed))
                    ////if (DateTime.TryParse(dateAndDateTimeClassTheDateTime, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed))


                    ////if (DateTime.TryParse(input, CultureInfo.InvariantCulture , DateTimeStyles.None, out parsed))
                    //{
                    //    parsedString = parsed.ToString();
                    //    // Do whatever you want with "parsed"
                    //    await turnContext.SendActivityAsync($"Parsed: {parsedString} \n");
                    //}

                    //WORKS
                    //var input = "2012-05-28 11:35:00Z";
                    //var format = "yyyy-MM-dd HH:mm:ssZ";
                    //if (DateTime.TryParseExact(input, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed))


                    var input = "2018-10-28T11:35:00";
                    //var format = "yyyy-MM-dd";
                    var format = "yyyy-MM-ddThh:mm:ss";

                    DateTime parsed;
                    string   parsedString;

                    try
                    {
                        await turnContext.SendActivityAsync($"Input: {input} Format: {format} \n");

                        DateTime.TryParseExact(input, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed);
                    }
                    catch (Exception ex)
                    {
                        await turnContext.SendActivityAsync($"Parsed: {ex.ToString()} \n");
                    }

                    //if (DateTime.TryParse(dateAndDateTimeClassTheDateTime, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed))


                    //if (DateTime.TryParse(input, CultureInfo.InvariantCulture , DateTimeStyles.None, out parsed))


                    var input1  = "2018-10-28T11:35:00";
                    var format1 = "yyyy-MM-ddThh:mm:ss";

                    if (DateTime.TryParseExact(input1, format1, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed))
                    {
                        parsedString = parsed.ToString();
                        // Do whatever you want with "parsed"
                        await turnContext.SendActivityAsync($"Parsed 1: {parsedString} \n");

                        await turnContext.SendActivityAsync($"Input: {input1} Format: {format1} \n");
                    }
                    else
                    {
                        await turnContext.SendActivityAsync($"FAILED 1: Input: {input1} Format: {format1} \n");
                    }

                    var input2  = "2018-10-28T11:35:00";
                    var format2 = "yyyy-MM-ddTHH:mm:ss";

                    if (DateTime.TryParseExact(input2, format2, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed))
                    {
                        parsedString = parsed.ToString();
                        // Do whatever you want with "parsed"
                        await turnContext.SendActivityAsync($"Parsed 2: {parsedString} \n");

                        await turnContext.SendActivityAsync($"Input: {input2} Format: {format2} \n");
                    }
                    else
                    {
                        await turnContext.SendActivityAsync($"FAILED 2: Input: {input2} Format: {format2} \n");
                    }

                    var input3  = "2018-10-28T04:35:00";
                    var format3 = "yyyy-MM-ddThh:mm:ss";

                    if (DateTime.TryParseExact(input3, format3, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed))
                    {
                        parsedString = parsed.ToString();
                        // Do whatever you want with "parsed"
                        await turnContext.SendActivityAsync($"Parsed 3: {parsedString} \n");

                        await turnContext.SendActivityAsync($"Input: {input3} Format: {format3} \n");
                    }
                    else
                    {
                        await turnContext.SendActivityAsync($"FAILED 3: Input: {input3} Format: {format3} \n");
                    }

                    var input4  = "2018-10-28T04:35:00";
                    var format4 = "yyyy-MM-ddTHH:mm:ss";

                    if (DateTime.TryParseExact(input4, format4, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed))
                    {
                        parsedString = parsed.ToString();
                        // Do whatever you want with "parsed"
                        await turnContext.SendActivityAsync($"Parsed 4: {parsedString} \n");

                        await turnContext.SendActivityAsync($"Input: {input4} Format: {format4} \n");
                    }
                    else
                    {
                        await turnContext.SendActivityAsync($"FAILED 4: Input: {input4} Format: {format4} \n");
                    }


                    var input5  = "2018-10-28T4:35:00";
                    var format5 = "yyyy-MM-ddTh:mm:ss";

                    if (DateTime.TryParseExact(input5, format5, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed))
                    {
                        parsedString = parsed.ToString();
                        // Do whatever you want with "parsed"
                        await turnContext.SendActivityAsync($"Parsed 5: {parsedString} \n");

                        await turnContext.SendActivityAsync($"Input: {input5} Format: {format5} \n");
                    }
                    else
                    {
                        await turnContext.SendActivityAsync($"FAILED 5: Input: {input5} Format: {format5} \n");
                    }

                    var input6  = "2018-10-28T4:35:00";
                    var format6 = "yyyy-MM-ddTH:mm:ss";

                    if (DateTime.TryParseExact(input6, format6, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed))
                    {
                        parsedString = parsed.ToString();
                        // Do whatever you want with "parsed"
                        await turnContext.SendActivityAsync($"Parsed 6: {parsedString} \n");

                        await turnContext.SendActivityAsync($"Input: {input6} Format: {format6} \n");
                    }
                    else
                    {
                        await turnContext.SendActivityAsync($"FAILED 6: Input: {input6} Format: {format6} \n");
                    }


                    //THIS DOES NOT WORK
                    var input7  = "2018-10-28T4:35:00";
                    var format7 = "yyyy-MM-ddThh:mm:ss";

                    if (DateTime.TryParseExact(input7, format7, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed))
                    {
                        //THIS DOES NOT WORK
                        parsedString = parsed.ToString();
                        await turnContext.SendActivityAsync($"Parsed 7: {parsedString} \n");

                        await turnContext.SendActivityAsync($"Input: {input7} Format: {format7} \n");
                    }
                    else
                    {
                        await turnContext.SendActivityAsync($"FAILED 7: Input: {input7} Format: {format7} \n");
                    }


                    //THIS DOES NOT WORK
                    var input8  = "2018-10-28T4:35:00";
                    var format8 = "yyyy-MM-ddTHH:mm:ss";

                    if (DateTime.TryParseExact(input8, format8, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed))
                    {
                        //THIS DOES NOT WORK
                        parsedString = parsed.ToString();
                        await turnContext.SendActivityAsync($"Parsed 8: {parsedString} \n");

                        await turnContext.SendActivityAsync($"Input: {input8} Format: {format8} \n");
                    }
                    else
                    {
                        await turnContext.SendActivityAsync($"FAILED 8: Input: {input8} Format: {format8} \n");
                    }

                    var input9  = "2018-10-28T11:35:00";
                    var format9 = "yyyy-MM-ddTh:mm:ss";

                    if (DateTime.TryParseExact(input9, format9, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed))
                    {
                        parsedString = parsed.ToString();
                        // Do whatever you want with "parsed"
                        await turnContext.SendActivityAsync($"Parsed 9: {parsedString} \n");

                        await turnContext.SendActivityAsync($"Input: {input9} Format: {format9} \n");
                    }
                    else
                    {
                        await turnContext.SendActivityAsync($"FAILED 9: Input: {input9} Format: {format9} \n");
                    }

                    var input10  = "2018-10-28T11:35:00";
                    var format10 = "yyyy-MM-ddTH:mm:ss";

                    if (DateTime.TryParseExact(input10, format10, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed))
                    {
                        parsedString = parsed.ToString();
                        await turnContext.SendActivityAsync($"Parsed 10: {parsedString} \n");

                        await turnContext.SendActivityAsync($"Input: {input10} Format: {format10} \n");
                    }
                    else
                    {
                        await turnContext.SendActivityAsync($"FAILED 10: Input: {input10} Format: {format10} \n");
                    }

                    //NOW DOING 14 HOUR FORMAT AS RETURNED BY LUIS

                    var input11  = "2018-10-28T14:35:00";
                    var format11 = "yyyy-MM-ddThh:mm:ss";

                    if (DateTime.TryParseExact(input11, format11, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed))
                    {
                        //THIS DOES NOT WORK
                        parsedString = parsed.ToString();
                        await turnContext.SendActivityAsync($"Parsed 11: {parsedString} \n");

                        await turnContext.SendActivityAsync($"Input: {input11} Format: {format11} \n");
                    }
                    else
                    {
                        await turnContext.SendActivityAsync($"FAILED 11: Input: {input11} Format: {format11} \n");
                    }

                    //THIS DOES NOT WORK
                    var input12  = "2018-10-28T14:35:00";
                    var format12 = "yyyy-MM-ddTHH:mm:ss";

                    if (DateTime.TryParseExact(input12, format12, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed))
                    {
                        //THIS DOES NOT WORK
                        parsedString = parsed.ToString();
                        await turnContext.SendActivityAsync($"Parsed 12: {parsedString} \n");

                        await turnContext.SendActivityAsync($"Input: {input12} Format: {format12} \n");
                    }
                    else
                    {
                        await turnContext.SendActivityAsync($"FAILED 12: Input: {input12} Format: {format12} \n");
                    }

                    var input13  = "2018-10-28T14:35:00";
                    var format13 = "yyyy-MM-ddTh:mm:ss";

                    if (DateTime.TryParseExact(input13, format13, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed))
                    {
                        parsedString = parsed.ToString();
                        // Do whatever you want with "parsed"
                        await turnContext.SendActivityAsync($"Parsed 13: {parsedString} \n");

                        await turnContext.SendActivityAsync($"Input: {input13} Format: {format13} \n");
                    }
                    else
                    {
                        await turnContext.SendActivityAsync($"FAILED 13: Input: {input13} Format: {format13} \n");
                    }

                    var input14  = "2018-10-28T14:35:00";
                    var format14 = "yyyy-MM-ddTH:mm:ss";

                    if (DateTime.TryParseExact(input14, format14, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed))
                    {
                        parsedString = parsed.ToString();
                        await turnContext.SendActivityAsync($"Parsed 14: {parsedString} \n");

                        await turnContext.SendActivityAsync($"Input: {input14} Format: {format14} \n");
                    }
                    else
                    {
                        await turnContext.SendActivityAsync($"FAILED 14: Input: {input14} Format: {format14} \n");
                    }
                    ///////////////////////////

                    var input15  = "2018-10-28T14:35";
                    var format15 = "yyyy-MM-ddTH:mm";

                    if (DateTime.TryParseExact(input15, format15, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed))
                    {
                        parsedString = parsed.ToString();
                        await turnContext.SendActivityAsync($"Parsed 15: {parsedString} \n");

                        await turnContext.SendActivityAsync($"Input: {input15} Format: {format15} \n");
                    }
                    else
                    {
                        await turnContext.SendActivityAsync($"FAILED 15: Input: {input15} Format: {format15} \n");
                    }

                    var input15a  = "2018-10-28T14";
                    var format15a = "yyyy-MM-ddTH:mm";

                    if (DateTime.TryParseExact(input15a, format15a, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed))
                    {
                        parsedString = parsed.ToString();
                        await turnContext.SendActivityAsync($"Parsed 15a: {parsedString} \n");

                        await turnContext.SendActivityAsync($"Input: {input15a} Format: {format15a} \n");
                    }
                    else
                    {
                        await turnContext.SendActivityAsync($"FAILED 15a: Input: {input15a} Format: {format15a} \n");
                    }

                    var input16  = "2018-10-28T14";
                    var format16 = "yyyy-MM-ddTH";

                    if (DateTime.TryParseExact(input16, format16, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed))
                    {
                        parsedString = parsed.ToString();
                        await turnContext.SendActivityAsync($"Parsed 16: {parsedString} \n");

                        await turnContext.SendActivityAsync($"Input: {input16} Format: {format16} \n");
                    }
                    else
                    {
                        await turnContext.SendActivityAsync($"FAILED 16: Input: {input16} Format: {format16} \n");
                    }

                    //////////////////////////////
                    ///

                    var input17 = "2018-10-28 14:00:00Z";
                    //var format16 = "yyyy-MM-ddTH";

                    if (DateTime.TryParse(input17, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed))

                    //                        if (DateTime.TryParseExact(input16, format16, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed))
                    {
                        parsedString = parsed.ToString();
                        await turnContext.SendActivityAsync($"Parsed 17: {parsedString} \n");

                        await turnContext.SendActivityAsync($"Input: {input17} Format: NO FORMAT \n");
                    }
                    else
                    {
                        await turnContext.SendActivityAsync($"FAILED 17: Input: {input17} Format: NO FORMAT \n");
                    }

                    var input18 = "2018-10-28 14:00Z";
                    //var format16 = "yyyy-MM-ddTH";

                    if (DateTime.TryParse(input18, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed))

                    //                        if (DateTime.TryParseExact(input16, format16, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed))
                    {
                        parsedString = parsed.ToString();
                        await turnContext.SendActivityAsync($"Parsed 18: {parsedString} \n");

                        await turnContext.SendActivityAsync($"Input: {input18} Format: NO FORMAT \n");
                    }
                    else
                    {
                        await turnContext.SendActivityAsync($"FAILED 18: Input: {input18} Format: NO FORMAT \n");
                    }

                    var input19 = "2018-10-28 14Z";
                    //var format16 = "yyyy-MM-ddTH";

                    if (DateTime.TryParse(input19, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed))

                    //                        if (DateTime.TryParseExact(input16, format16, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed))
                    {
                        parsedString = parsed.ToString();
                        await turnContext.SendActivityAsync($"Parsed 19: {parsedString} \n");

                        await turnContext.SendActivityAsync($"Input: {input19} Format: NO FORMAT \n");
                    }
                    else
                    {
                        await turnContext.SendActivityAsync($"FAILED 19: Input: {input19} Format: NO FORMAT \n");
                    }

                    var input20  = "03-15";
                    var format20 = "MM-dd";

                    if (DateTime.TryParseExact(input20, format20, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed))
                    {
                        parsedString = parsed.ToString();
                        await turnContext.SendActivityAsync($"Parsed 20: {parsedString} \n");

                        await turnContext.SendActivityAsync($"Input: {input20} Format: {format20} \n");
                    }
                    else
                    {
                        await turnContext.SendActivityAsync($"FAILED 20: Input: {input20} Format: {format20} \n");
                    }

                    var input21  = "XXXX-03-15";
                    var format21 = "MM-dd";

                    if (DateTime.TryParseExact(input21, format21, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed))
                    {
                        parsedString = parsed.ToString();
                        await turnContext.SendActivityAsync($"Parsed 21: {parsedString} \n");

                        await turnContext.SendActivityAsync($"Input: {input21} Format: {format21} \n");
                    }
                    else
                    {
                        await turnContext.SendActivityAsync($"FAILED 21: Input: {input21} Format: {format21} \n");
                    }

                    var input22  = "XXXX-03-15";
                    var format22 = "MM-dd";

                    if (input22.Contains("XXXX-") & !input22.Contains("XXXX-W"))
                    {
                        input22 = input22.Replace("XXXX-", "");
                    }

                    if (DateTime.TryParseExact(input22, format22, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed))
                    {
                        parsedString = parsed.ToString();

                        parsedString = parsedString.Replace(" 12:00:00 AM", "");

                        await turnContext.SendActivityAsync($"Parsed 22: {parsedString} \n");

                        await turnContext.SendActivityAsync($"Input: {input22} Format: {format22} \n");
                    }
                    else
                    {
                        await turnContext.SendActivityAsync($"FAILED 22: Input: {input22} Format: {format22} \n");
                    }

                    var input23  = "XXXX-03";
                    var format23 = "MM";

                    if (input23.Contains("XXXX-") & !input23.Contains("XXXX-W"))
                    {
                        input23 = input23.Replace("XXXX-", "");
                    }

                    if (DateTime.TryParseExact(input23, format23, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed))
                    {
                        parsedString = parsed.ToString();

//                        parsedString = parsedString.Replace(" 12:00:00 AM", "");

                        await turnContext.SendActivityAsync($"Parsed 23: {parsedString} \n");

                        await turnContext.SendActivityAsync($"Input: {input23} Format: {format23} \n");
                    }
                    else
                    {
                        await turnContext.SendActivityAsync($"FAILED 23: Input: {input23} Format: {format23} \n");
                    }


                    var input24  = "XXXX-03";
                    var format24 = "MM";

                    if (input24.Contains("XXXX-") & !input24.Contains("XXXX-W"))
                    {
                        input24 = input24.Replace("XXXX-", "");
                    }

                    var formattedDateMonthOnly = MonthByStringNumber(input24);
                    await turnContext.SendActivityAsync($"Parsed 24: through Methods and Formatted: {formattedDateMonthOnly} \n");

                    var input25 = "XXXX-XX-15";
                    //var format25 = "MM";

                    if (input25.Contains("XXXX-XX-") & !input25.Contains("XXXX-W"))
                    {
                        input25 = input25.Replace("XXXX-XX-", "");
                    }

                    var formattedDayNumber = DayNumberByStringNumber(input25);

                    //InvariantCulture
                    var createdDateTimeString = DateTime.Now.ToString("yyyy-MM-", new CultureInfo("en-US"));


                    //CreatedDateTimeString = DateTime.Now.ToString("MMM d h:mm tt", new CultureInfo("en-US")),
                    //    CreatedDateTime = DateTimeOffset.UtcNow,

                    await turnContext.SendActivityAsync($"Parsed 25: through Methods and Formatted: {formattedDayNumber} \n");

                    await turnContext.SendActivityAsync($"Parsed 25b: through Methods and Formatted: {createdDateTimeString} \n");

                    var combinedDateString = createdDateTimeString + formattedDayNumber;

                    await turnContext.SendActivityAsync($"Parsed 25c: through Methods and Formatted: {combinedDateString} \n");

                    ///////////////////////////
                    ///

                    var input26 = "XXXX-03-15T17:30";

                    //InvariantCulture
                    var createdDateTimeString26 = DateTime.Now.ToString("yyyy-", new CultureInfo("en-US"));

                    if (input26.Contains("XXXX-") & !input26.Contains("XXXX-XX-") & !input26.Contains("XXXX-W"))
                    {
                        input26 = input26.Replace("XXXX-", createdDateTimeString26);
                    }

                    //Format-26
                    var dateAndDateTimeClassTheDatePostFormatted26 = FormattingHoursWithOrWithoutMinutes(input26);
                    var formattedTime26 = FormatDateTimeBasedOnTHmm(dateAndDateTimeClassTheDatePostFormatted26);
                    await turnContext.SendActivityAsync($"Entities Through Methods and Formatted: 2. {formattedTime26}\n");

//                  await turnContext.SendActivityAsync($"Parsed 25c: through Methods and Formatted: {combinedDateString} \n");

                    //if (DateTime.TryParseExact(input24, format24, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed))
                    //{
                    //    parsedString = parsed.ToString();

                    //    //                        parsedString = parsedString.Replace(" 12:00:00 AM", "");

                    //    await turnContext.SendActivityAsync($"Parsed 24: {parsedString} \n");
                    //    await turnContext.SendActivityAsync($"Input: {input24} Format: {format24} \n");
                    //}
                    //else
                    //{
                    //    await turnContext.SendActivityAsync($"FAILED 24: Input: {input24} Format: {format24} \n");
                    //}



                    /////////////////////////////////////////////////////////////

                    var inputSystematic  = "2018-10-28T14";
                    var formatSystematic = "yyyy-MM-ddTH:mm";

                    if (!inputSystematic.Contains(":"))
                    {
                        inputSystematic = inputSystematic + ":00";
                    }

                    if (DateTime.TryParseExact(inputSystematic, formatSystematic, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed))
                    {
                        parsedString = parsed.ToString();
                        await turnContext.SendActivityAsync($"Parsed Systematic: {parsedString} \n");

                        await turnContext.SendActivityAsync($"Input Systematic: {inputSystematic} Format: {formatSystematic} \n");
                    }
                    else
                    {
                        await turnContext.SendActivityAsync($"FAILED Systematic: Input: {inputSystematic} Format: {formatSystematic} \n");
                    }
                    /////////////////////////////
                    ///
                    var dayOfWeek = "XXXX-WXX-7";

                    if (dayOfWeek.Contains("XXXX-WXX-"))
                    {
                        dayOfWeek = dayOfWeek.Replace("XXXX-WXX-", "");
                        //var newItem = dayOfWeek;
                    }

                    await turnContext.SendActivityAsync($"Day of week via XXXX-WXX- : {dayOfWeek} \n");

                    var dayOfWeekPlusHours = " XXXX-WXX-7T17";

                    string justTheHours = "";

                    if (dayOfWeekPlusHours.Contains("T"))
                    {
                        if (!dayOfWeekPlusHours.Contains(":"))
                        {
                            dayOfWeekPlusHours = dayOfWeekPlusHours + ":00";
                        }

                        //count number of characters
                        //count position of T
                        //grab after T to final

                        var lengthOfString = dayOfWeekPlusHours.Length;
                        var positionOfT    = dayOfWeekPlusHours.LastIndexOf("T");
                        justTheHours       = dayOfWeekPlusHours.Substring(positionOfT, lengthOfString - positionOfT);
                        dayOfWeekPlusHours = dayOfWeekPlusHours.Replace(justTheHours, "");
                    }

                    if (dayOfWeekPlusHours.Contains("XXXX-WXX-"))
                    {
                        dayOfWeekPlusHours = dayOfWeekPlusHours.Replace("XXXX-WXX-", "");
                        //var newItem = dayOfWeek;
                    }

                    string nameDayOfWeekPlusHourPostFormat = DayOfWeekByStringNumber(dayOfWeek);
                    await turnContext.SendActivityAsync($"Entities DayOfWeekPlusHours. {nameDayOfWeekPlusHourPostFormat}\n");

////////////////////////////////////////////////////////////////////
                    var formatDayOfWeekPlusHoursTheHours = "TH:mm";

                    DateTime parsedFormatDayOfWeekPlusHoursTheHours;
                    string   parsedStringFormatDayOfWeekPlusHoursTheHours;

                    if (DateTime.TryParseExact(justTheHours, formatDayOfWeekPlusHoursTheHours, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedFormatDayOfWeekPlusHoursTheHours))
                    {
                        parsedStringFormatDayOfWeekPlusHoursTheHours = parsed.ToString();
                        //return parsedStringFormatDayOfWeekPlusHoursTheHours;
                        await turnContext.SendActivityAsync($"Entities DayOfWeekPlusHours: {parsedStringFormatDayOfWeekPlusHoursTheHours}\n");
                    }

                    //Unformatted
                    await turnContext.SendActivityAsync($"Entities: {dateAndDateTimeClassTheDate} and {dateAndDateTimeClassTheDateTime} \n");

                    //Format-1
                    string nameDayOfWeekPostFormat = DayOfWeekByStringNumber(dateAndDateTimeClassTheDate);
                    await turnContext.SendActivityAsync($"Entities Through Methods and Formatted: 1. {nameDayOfWeekPostFormat}\n");

                    //Format-2
                    var dateAndDateTimeClassTheDatePostFormatted = FormattingHoursWithOrWithoutMinutes(dateAndDateTimeClassTheDateTime);
                    var formattedTime = FormatDateTimeBasedOnTHmm(dateAndDateTimeClassTheDatePostFormatted);
                    await turnContext.SendActivityAsync($"Entities Through Methods and Formatted: 2. {formattedTime}\n");


                    //Format-3
                    var formattedDate = FormatDateTimeBasedOnYMD(dateAndDateTimeClassTheDateTime);
                    await turnContext.SendActivityAsync($"Entities Through Methods and Formatted: 3. {formattedDate}\n");

                    //Format-4
                    var formattedDateTryParse = FormatDateTimeTryParse(dateAndDateTimeClassTheDateTime);
                    await turnContext.SendActivityAsync($"Entities Through Methods and Formatted: 4. {formattedDateTryParse}\n");

                    //Format-5
                    var formattedDateWithoutYear = FormatDateTimeWithoutYear(dateAndDateTimeClassTheDateTime);
                    await turnContext.SendActivityAsync($"Entities Through Methods and Formatted: 5. {formattedDateWithoutYear} \n");

                    //Formatted
                    await turnContext.SendActivityAsync($"Entities Through Methods and Formatted: 1. {nameDayOfWeekPostFormat} and 2. {formattedTime} and 3. {formattedDate} and 4. {formattedDateTryParse}\n");

                    //string nameDayOfWeek = DayOfWeekByStringNumber(dayOfWeek);
                    //await turnContext.SendActivityAsync($"Entity formatted by XXXX-WXX- from 'dateAndDateTimeClassTheDate': {nameDayOfWeek} \n");

                    //await turnContext.SendActivityAsync($"Entities: {dateAndDateTimeClassTheDate} and {dateAndDateTimeClassTheDateTime} \n");
                }
                else
                {
                    var msg = @"No LUIS intents were found.
                            This sample is about identifying two user intents:
                            'Calendar.Add'
                            'Calendar.Find'
                            Try typing 'Add Event' or 'Show me tomorrow'.";
                    await turnContext.SendActivityAsync(msg);
                }
            }
            else if (turnContext.Activity.Type == ActivityTypes.ConversationUpdate)
            {
                // Send a welcome message to the user and tell them what actions they may perform to use this bot
                await SendWelcomeMessageAsync(turnContext, cancellationToken);
            }
            else
            {
                await turnContext.SendActivityAsync($"{turnContext.Activity.Type} event detected", cancellationToken : cancellationToken);
            }
        }
示例#13
0
        /// <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))
        {
            // 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)
            {
                // 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.


                if (turnContext.Activity.Text == "Help" || turnContext.Activity.Text == "help")
                {
                    var HelpMes = $" Menu '\n" + $"Order '\n";
                    await turnContext.SendActivityAsync(HelpMes);
                }
                var contentMessage = $"1. --------> All T-shorts" +
                                     $"'\n" + $"2. --------> All Fresh" +
                                     $"'\n";


                if (turnContext.Activity.Text == "Меню" || turnContext.Activity.Text == "Menu" || turnContext.Activity.Text == "меню" || turnContext.Activity.Text == "menu")
                {
                    await turnContext.SendActivityAsync(contentMessage);
                }

                if (turnContext.Activity.Text == "1")
                {
                    var shorts = $"1. Sharkasm '\n" + $"2.  Sobaka '\n " + $"3. Slozhna '\n" + $"4. ╰☆╮";
                    await turnContext.SendActivityAsync(shorts);

                    if (turnContext.Activity.Label == "1" || turnContext.Activity.Label == "2" || turnContext.Activity.Label == "3" || turnContext.Activity.Label == "4")
                    {
                        var added = $"Добавлено ✔ ";
                    }
                }
                else if (turnContext.Activity.Text == "2")
                {
                    var fresh = $"1. Mellon '\n" + $"2. WaterMellon '\n";
                    await turnContext.SendActivityAsync(fresh);

                    if (turnContext.Activity.Label == "1" || turnContext.Activity.Label == "2")
                    {
                        var addedf = $"Добавлено ✔";
                    }
                }
                if (turnContext.Activity.Text == "Order" || turnContext.Activity.Text == "Заказ" || turnContext.Activity.Text == "order" || turnContext.Activity.Text == "заказ")
                {
                    var order = $"Корзина not work :(";
                    await turnContext.SendActivityAsync(order);
                }
            }
            else
            {
                await turnContext.SendActivityAsync($"  Hello, I'm Bot, if you need help, write [Help]");
            }
        }
示例#14
0
 protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
 {
     AddConversationReference(turnContext.Activity as Activity);
     var replyText = $"Echo: {turnContext.Activity.Text}";
     await turnContext.SendActivityAsync(MessageFactory.Text(replyText, replyText), cancellationToken);
 }
示例#15
0
 protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
 {
     await turnContext.SendActivityAsync(CreateActivityWithTextAndSpeak($"Echo: {turnContext.Activity.Text}"), cancellationToken);
 }
示例#16
0
        protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            await turnContext.SendActivityAsync(MessageFactory.Text($"Echo: {turnContext.Activity.Text}"), cancellationToken);

            // Get the state properties from the turn context.

            var conversationStateAccessors = _conversationState.CreateProperty <ConversationData>(nameof(ConversationData));
            var conversationData           = await conversationStateAccessors.GetAsync(turnContext, () => new ConversationData());

            var userStateAccessors = _userState.CreateProperty <UserProfile>(nameof(UserProfile));
            var userProfile        = await userStateAccessors.GetAsync(turnContext, () => new UserProfile());

            ////////////////////////////////////////////////////////////////////////
            ///METHOD 1

            ////Get the conversation state from the turn context.
            //var oldStateMethod1 = conversationData.CounterData;

            //// Bump the turn count for this conversation.
            //var newStateMethod1 = new CounterData { TurnCount = oldStateMethod1.TurnCount + 1 };

            //conversationData.CounterData= newStateMethod1;

            //// Echo back to the user whatever they typed.
            //var responseMessage = $"Turn {newStateMethod1.TurnCount}: You sent '{turnContext.Activity.Text}'\n";
            //await turnContext.SendActivityAsync(responseMessage);

            ////////////////////////////////////////////////////////////////////////
            ///METHOD 2

            // Get the conversation state from the turn context.
            var oldStateMethod2 = conversationData.CounterData;   //.GetAsync(turnContext, () => new CounterState());

            // Bump the turn count for this conversation.
            var newStateMethod2 = new CounterData {
                TurnCount = oldStateMethod2.TurnCount + 1
            };

            conversationData.CounterData = newStateMethod2;

            await conversationStateAccessors.SetAsync(turnContext, conversationData);

            // Echo back to the user whatever they typed.
            var responseMessage2 = $"Turn {newStateMethod2.TurnCount}: You sent '{turnContext.Activity.Text}'\n";
            await turnContext.SendActivityAsync(responseMessage2);

            ////////////////////////////////////////////////////////////////////////
            ///METHOD 3
            ///

            ////Give counter state it's own property
            //var counterStateAccessorsMethod3 = _counterState.CreateProperty<CounterData>(nameof(CounterData));
            //var counterStateMethod3 = await counterStateAccessorsMethod3.GetAsync(turnContext, () => new CounterData());

            //var oldStateMethod3 = counterStateMethod3;

            //// Bump the turn count for this conversation.
            //var newStateMethod3 = new CounterData { TurnCount = oldStateMethod3.TurnCount + 1 };

            //await counterStateAccessorsMethod3.SetAsync(turnContext, newStateMethod3);

            //// Echo back to the user whatever they typed.
            //var responseMessageMethod3 = $"Turn {newStateMethod3.TurnCount}: You sent '{turnContext.Activity.Text}'\n";
            //await turnContext.SendActivityAsync(responseMessageMethod3);

            ////////////////////////////////////////////////////////////////////////////////////////////////////



            if (string.IsNullOrEmpty(userProfile.Name))
            {
                // First time around this is set to false, so we will prompt user for name.
                if (conversationData.PromptedUserForName)
                {
                    // Set the name to what the user provided.
                    userProfile.Name = turnContext.Activity.Text?.Trim();

                    // Acknowledge that we got their name.
                    await turnContext.SendActivityAsync($"Thanks {userProfile.Name}. To see conversation data, type anything.");

                    // Reset the flag to allow the bot to go though the cycle again.
                    conversationData.PromptedUserForName = false;
                }
                else
                {
                    // Prompt the user for their name.
                    await turnContext.SendActivityAsync($"What is your name?");

                    // Set the flag to true, so we don't prompt in the next turn.
                    conversationData.PromptedUserForName = true;
                }
            }
            else
            {
                // Add message details to the conversation data.
                // Convert saved Timestamp to local DateTimeOffset, then to string for display.
                var messageTimeOffset = (DateTimeOffset)turnContext.Activity.Timestamp;
                var localMessageTime  = messageTimeOffset.ToLocalTime();
                conversationData.Timestamp = localMessageTime.ToString();
                conversationData.ChannelId = turnContext.Activity.ChannelId.ToString();

                // Display state data.
                await turnContext.SendActivityAsync($"{userProfile.Name} sent: {turnContext.Activity.Text}");

                await turnContext.SendActivityAsync($"Message received at: {conversationData.Timestamp}");

                await turnContext.SendActivityAsync($"Message received from: {conversationData.ChannelId}");
            }
        }
 public async Task HandleGreeting(ITurnContext context, string messageText, NextDelegate next, CancellationToken cancellationToken)
 {
     await context.SendActivityAsync("Well hello there. What can I do for you today?");
 }
        protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            string _channel = "";

            //this is how you can notice that this message is coming from MessageBird WhatsApp Adapter
            if (turnContext.Activity.ChannelId.StartsWith("whatsapp"))
            {
                _channel = "whatsapp";
            }

            switch (turnContext.Activity.Text.ToLower())
            {
            case "location":
            {
                var reply = MessageFactory.Text("Location");
                reply.Entities = new List <Entity>()
                {
                    new GeoCoordinates()
                    {
                        Latitude = 41.0572, Longitude = 29.0433
                    }
                };
                await turnContext.SendActivityAsync(reply);

                break;
            }

            case "file":
            {
                var        reply      = MessageFactory.Text("File");
                Attachment attachment = new Attachment();
                attachment.ContentType = "file";
                attachment.ContentUrl  = "https://qconlondon.com/london-2017/system/files/presentation-slides/microsoft_bot_framework_best_practices.pdf";
                attachment.Name        = "Microsoft Bot Framework Best Practices";
                reply.Attachments      = new List <Attachment>()
                {
                    attachment
                };
                await turnContext.SendActivityAsync(reply);

                break;
            }

            case "image":
            {
                var        reply      = MessageFactory.Text("Image");
                Attachment attachment = new Attachment();
                attachment.Name        = "Bot Framework Arcitecture";
                attachment.ContentType = "image";
                attachment.ContentUrl  = "https://docs.microsoft.com/en-us/bot-framework/media/how-it-works/architecture-resize.png";
                reply.Attachments      = new List <Attachment>()
                {
                    attachment
                };
                await turnContext.SendActivityAsync(reply);

                break;
            }

            default:
            {
                var replyText = $"Echo: {turnContext.Activity.Text}";
                await turnContext.SendActivityAsync(MessageFactory.Text(replyText, replyText), cancellationToken);

                StringBuilder sb = new StringBuilder();
                sb.AppendLine($"Hello. Type the message you want to receive.\r\n");
                sb.AppendLine($"*location* for location\r\n");
                sb.AppendLine($"*file* for file\r\n");
                sb.AppendLine($"*image* for image\r\n");
                sb.AppendLine($"anything else to echo back!\r\n");

                var reply = MessageFactory.Text(sb.ToString());
                await turnContext.SendActivityAsync(reply);

                break;
            }
            }
        }
        public async Task HandleGoodbye(ITurnContext context, string messageText, NextDelegate next, CancellationToken cancellationToken)
        {
            await context.SendActivityAsync("Bye");

            await next(cancellationToken);
        }
        private static async Task <DialogTurnResult> InnerRunAsync(ITurnContext turnContext, string dialogId, DialogContext dialogContext, CancellationToken cancellationToken)
        {
            // Handle EoC and Reprompt event from a parent bot (can be root bot to skill or skill to skill)
            if (IsFromParentToSkill(turnContext))
            {
                // Handle remote cancellation request from parent.
                if (turnContext.Activity.Type == ActivityTypes.EndOfConversation)
                {
                    if (!dialogContext.Stack.Any())
                    {
                        // No dialogs to cancel, just return.
                        return(new DialogTurnResult(DialogTurnStatus.Empty));
                    }

                    var activeDialogContext = GetActiveDialogContext(dialogContext);

                    // Send cancellation message to the top dialog in the stack to ensure all the parents are canceled in the right order.
                    return(await activeDialogContext.CancelAllDialogsAsync(true, cancellationToken : cancellationToken).ConfigureAwait(false));
                }

                // Handle a reprompt event sent from the parent.
                if (turnContext.Activity.Type == ActivityTypes.Event && turnContext.Activity.Name == DialogEvents.RepromptDialog)
                {
                    if (!dialogContext.Stack.Any())
                    {
                        // No dialogs to reprompt, just return.
                        return(new DialogTurnResult(DialogTurnStatus.Empty));
                    }

                    await dialogContext.RepromptDialogAsync(cancellationToken).ConfigureAwait(false);

                    return(new DialogTurnResult(DialogTurnStatus.Waiting));
                }
            }

            // Continue or start the dialog.
            var result = await dialogContext.ContinueDialogAsync(cancellationToken).ConfigureAwait(false);

            if (result.Status == DialogTurnStatus.Empty)
            {
                result = await dialogContext.BeginDialogAsync(dialogId, null, cancellationToken).ConfigureAwait(false);
            }

            await SendStateSnapshotTraceAsync(dialogContext, cancellationToken).ConfigureAwait(false);

            // Skills should send EoC when the dialog completes.
            if (result.Status == DialogTurnStatus.Complete || result.Status == DialogTurnStatus.Cancelled)
            {
                if (SendEoCToParent(turnContext))
                {
                    // Send End of conversation at the end.
                    var code     = result.Status == DialogTurnStatus.Complete ? EndOfConversationCodes.CompletedSuccessfully : EndOfConversationCodes.UserCancelled;
                    var activity = new Activity(ActivityTypes.EndOfConversation)
                    {
                        Value = result.Result, Locale = turnContext.Activity.Locale, Code = code
                    };
                    await turnContext.SendActivityAsync(activity, cancellationToken).ConfigureAwait(false);
                }
            }

            return(result);
        }
示例#21
0
 protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
 {
     var replyText = $"You sent: {turnContext.Activity.Text}";
     await turnContext.SendActivityAsync(MessageFactory.Text(replyText, replyText), cancellationToken);
 }
示例#22
0
        protected async Task Quiz(ConvoState convoState, UserAnswers userAnswers, ITurnContext turnContext)
        {
            string input = turnContext.Activity.Text;

            if (convoState.IsOnConvo)
            {
                switch (convoState.LastConvState)
                {
                case ConvoState.ConversationState.None:
                    var quizMenu = MessageFactory.Text("Ingin Kuis Mode Apa?");
                    quizMenu.SuggestedActions = new SuggestedActions
                    {
                        Actions = new List <CardAction>()
                        {
                            new CardAction {
                                Title = "Tebak Lagu", Type = ActionTypes.ImBack, Value = "Tebak lagu"
                            },
                            new CardAction {
                                Title = "Lengkapi lirik", Type = ActionTypes.ImBack, Value = "Lengkapi lirik"
                            },
                        },
                    };
                    await turnContext.SendActivityAsync(quizMenu);

                    convoState.LastConvState = ConvoState.ConversationState.Menu;
                    break;

                case ConvoState.ConversationState.Menu:
                    if (input.Equals("Tebak lagu"))
                    {
                        convoState.LastConvState = ConvoState.ConversationState.TebakLirikQuestiion;
                        await turnContext.SendActivityAsync("Ketik OK kalau kamu sudah siap");
                    }
                    else if (input.Equals("Lengkapi lirik"))
                    {
                        convoState.LastConvState = ConvoState.ConversationState.IsiLirikQuestion;
                        await turnContext.SendActivityAsync("Ketik OK kalau kamu sudah siap");
                    }
                    else if (input.Equals("Mulai kuis"))
                    {
                        var menu = MessageFactory.Text("Ingin Kuis Mode Apa?");
                        menu.SuggestedActions = new SuggestedActions
                        {
                            Actions = new List <CardAction>()
                            {
                                new CardAction {
                                    Title = "Tebak Lagu", Type = ActionTypes.ImBack, Value = "Tebak lagu"
                                },
                                new CardAction {
                                    Title = "Lengkapi lirik", Type = ActionTypes.ImBack, Value = "Lengkapi lirik"
                                },
                            },
                        };
                        await turnContext.SendActivityAsync(menu);

                        convoState.LastConvState = ConvoState.ConversationState.Menu;
                    }

                    break;

                case ConvoState.ConversationState.IsiLirikQuestion:

                    SongMeta song = GetHardcodedSongList()[(new Random()).Next(GetHardcodedSongList().Count)];
                    convoState.QuestionItemNumber++;
                    if (convoState.QuestionItemNumber < 6)
                    {
                        if (convoState.QuestionItemNumber > 1)
                        {
                            if (input.ToLower().Equals(convoState.LastQuestionAsked.LyricAnswer))
                            {
                                userAnswers.CorrectAnswer++;
                                await turnContext.SendActivityAsync("Benaar!!");
                            }
                            else
                            {
                                await turnContext.SendActivityAsync("Jawabanmu Salah");
                            }
                            if (convoState.QuestionItemNumber < 5)
                            {
                                await turnContext.SendActivityAsync("Pertanyaan selanjutnya...");
                            }
                        }
                        else
                        {
                            await turnContext.SendActivityAsync("Ok bersiaplah. ");

                            await turnContext.SendActivityAsync("Pertanyaan pertama");
                        }
                        CompleteTheLyricQuestion question = LyricGenerator.Instance.GenerateCompleteTheLyricQuestion(song.Artist, song.Song);
                        convoState.LastQuestionAsked = question;
                        await turnContext.SendActivityAsync(question.LyricQuestion);

                        await turnContext.SendActivityAsync("Isilah kata pada lirik yang hilang");
                    }
                    else
                    {
                        if (input.ToLower().Equals(convoState.LastQuestionAsked.LyricAnswer.ToLower()))
                        {
                            userAnswers.CorrectAnswer++;
                            await turnContext.SendActivityAsync("Benaar!!");
                        }
                        else
                        {
                            await turnContext.SendActivityAsync("Jawabanmu Salah");
                        }
                        await turnContext.SendActivityAsync("Kuis sudah selesai");

                        await turnContext.SendActivityAsync($"Kamu menjawab benar sebanyak {userAnswers.CorrectAnswer} dari {convoState.QuestionItemNumber-1}");

                        convoState.LastConvState = ConvoState.ConversationState.Result;
                    }
                    break;

                case ConvoState.ConversationState.TebakLirikQuestiion:
                    break;

                case ConvoState.ConversationState.Result:
                    break;
                }
            }
        }
示例#23
0
        // Handle adaptive card submit in 1:1 chat
        // Submits the question or feedback to the SME team
        private async Task OnAdaptiveCardSubmitInPersonalChatAsync(IMessageActivity message, ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            Attachment   smeTeamCard = null;    // Notification to SME team
            Attachment   userCard    = null;    // Acknowledgement to the user
            TicketEntity newTicket   = null;    // New ticket

            switch (message.Text)
            {
            case AskAnExpert:
            {
                this.telemetryClient.TrackTrace("Sending user ask an expert card (from answer)");

                var responseCardPayload = ((JObject)message.Value).ToObject <ResponseCardPayload>();
                await turnContext.SendActivityAsync(MessageFactory.Attachment(AskAnExpertCard.GetCard(responseCardPayload)));

                break;
            }

            case ShareFeedback:
            {
                this.telemetryClient.TrackTrace("Sending user share feedback card (from answer)");

                var responseCardPayload = ((JObject)message.Value).ToObject <ResponseCardPayload>();
                await turnContext.SendActivityAsync(MessageFactory.Attachment(ShareFeedbackCard.GetCard(responseCardPayload)));

                break;
            }

            case AskAnExpertCard.AskAnExpertSubmitText:
            {
                this.telemetryClient.TrackTrace($"Received question for expert");

                var askAnExpertPayload = ((JObject)message.Value).ToObject <AskAnExpertCardPayload>();

                // Validate required fields
                if (string.IsNullOrWhiteSpace(askAnExpertPayload.Title))
                {
                    var updateCardActivity = new Activity(ActivityTypes.Message)
                    {
                        Id           = turnContext.Activity.ReplyToId,
                        Conversation = turnContext.Activity.Conversation,
                        Attachments  = new List <Attachment> {
                            AskAnExpertCard.GetCard(askAnExpertPayload)
                        },
                    };
                    await turnContext.UpdateActivityAsync(updateCardActivity, cancellationToken);

                    return;
                }

                var userDetails = await this.GetUserDetailsInPersonalChatAsync(turnContext, cancellationToken);

                newTicket = await this.CreateTicketAsync(message, askAnExpertPayload, userDetails);

                smeTeamCard = new SmeTicketCard(newTicket).ToAttachment(message.LocalTimestamp);
                userCard    = new UserNotificationCard(newTicket).ToAttachment(Resource.NotificationCardContent, message.LocalTimestamp);
                break;
            }

            case ShareFeedbackCard.ShareFeedbackSubmitText:
            {
                this.telemetryClient.TrackTrace($"Received app feedback");

                var shareFeedbackPayload = ((JObject)message.Value).ToObject <ShareFeedbackCardPayload>();

                // Validate required fields
                if (!Enum.TryParse(shareFeedbackPayload.Rating, out FeedbackRating rating))
                {
                    var updateCardActivity = new Activity(ActivityTypes.Message)
                    {
                        Id           = turnContext.Activity.ReplyToId,
                        Conversation = turnContext.Activity.Conversation,
                        Attachments  = new List <Attachment> {
                            ShareFeedbackCard.GetCard(shareFeedbackPayload)
                        },
                    };
                    await turnContext.UpdateActivityAsync(updateCardActivity, cancellationToken);

                    return;
                }

                var userDetails = await this.GetUserDetailsInPersonalChatAsync(turnContext, cancellationToken);

                smeTeamCard = SmeFeedbackCard.GetCard(shareFeedbackPayload, userDetails);
                await turnContext.SendActivityAsync(MessageFactory.Text(Resource.ThankYouTextContent));

                break;
            }

            default:
                this.telemetryClient.TrackTrace($"Unexpected text in submit payload: {message.Text}", SeverityLevel.Warning);
                break;
            }

            // Send message to SME team
            if (smeTeamCard != null)
            {
                var channelId = await this.configurationProvider.GetSavedEntityDetailAsync(ConfigurationEntityTypes.TeamId);

                var resourceResponse = await this.SendCardToTeamAsync(turnContext, smeTeamCard, channelId, cancellationToken);

                // If a ticket was created, update the ticket with the conversation info
                if (newTicket != null)
                {
                    newTicket.SmeCardActivityId       = resourceResponse.ActivityId;
                    newTicket.SmeThreadConversationId = resourceResponse.Id;
                    await this.ticketsProvider.SaveOrUpdateTicketAsync(newTicket);
                }
            }

            // Send acknowledgment to the user
            if (userCard != null)
            {
                await turnContext.SendActivityAsync(MessageFactory.Attachment(userCard), cancellationToken);
            }
        }
示例#24
0
        /// <summary>
        /// Run every turn of the conversation. Handles orchestration of messages.
        /// </summary>
        /// <param name="turnContext">Bot Turn Context.</param>
        /// <param name="cancellationToken">Task CancellationToken.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken)
        {
            var activity = turnContext.Activity;

            // Create a dialog context
            var dc = await Dialogs.CreateContextAsync(turnContext);

            if (activity.Type == ActivityTypes.Message)
            {
                // Perform a call to LUIS to retrieve results for the current activity message.
                var luisResults = await _services.LuisServices[LuisConfiguration].RecognizeAsync(dc.Context, cancellationToken);

                // If any entities were updated, treat as interruption.
                // For example, "no my name is tony" will manifest as an update of the name to be "tony".
                var topScoringIntent = luisResults?.GetTopScoringIntent();

                var topIntent = topScoringIntent.Value.intent;

                // update greeting state with any entities captured
                await UpdateGreetingState(luisResults, dc.Context);

                // Handle conversation interrupts first.
                var interrupted = await IsTurnInterruptedAsync(dc, topIntent);

                if (interrupted)
                {
                    // Bypass the dialog.
                    // Save state before the next turn.
                    await _conversationState.SaveChangesAsync(turnContext);

                    await _userState.SaveChangesAsync(turnContext);

                    return;
                }

                // Continue the current dialog
                var dialogResult = await dc.ContinueDialogAsync();

                // See if LUIS found and used an entity to determine user intent.
                var entityFound = ParseLuisForEntities(luisResults);

                // if no one has responded,
                if (!dc.Context.Responded)
                {
                    // examine results from active dialog
                    switch (dialogResult.Status)
                    {
                    case DialogTurnStatus.Empty:
                        switch (topIntent)
                        {
                        case GreetingIntent:
                            //await dc.BeginDialogAsync(nameof(GreetingDialog));
                            break;

                        case NoneIntent:
                        default:
                            // Help or no intent identified, either way, let's provide some help.
                            // to the user
                            await dc.Context.SendActivityAsync("I didn't understand what you just said to me.");

                            break;

                        case BuyIntent:
                            //await dc.Context.SendActivityAsync(topIntent);

                            // Inform the user if LUIS used an entity.
                            if (entityFound.ToString() != string.Empty)
                            {
                                string[] cutEntity = entityFound.Split("|SEP|");
                                //await turnContext.SendActivityAsync($"==>LUIS String: {entityFound}\n");
                                int  count       = 0;
                                bool entityCheck = false;
                                foreach (var cutEntityValue in cutEntity)
                                {
                                    if (cutEntityValue != string.Empty)
                                    {
                                        count++;
                                        if (count == 3)
                                        {
                                            entityCheck = true;
                                        }
                                    }
                                }

                                if (entityCheck)
                                {
                                    /*
                                     * foreach (var cutEntityValue in cutEntity)
                                     * {
                                     *  await turnContext.SendActivityAsync($"==>LUIS Entity: {cutEntityValue}\n");
                                     * }
                                     * await turnContext.SendActivityAsync($"==>LUIS Entity Found: {entityFound}\n");
                                     */
                                    /*
                                     * // 카드는 html에서 출력
                                     * var buyCard = CreateBuyCardAttachment(@".\Dialogs\BuyIntent\Resources\buyCard.json", entityFound);
                                     * var response = CreateResponse(activity, buyCard);
                                     * await dc.Context.SendActivityAsync(response);
                                     */

                                    // html에 인텐트+엔티티 전달
                                    Activity buyReply = activity.CreateReply();
                                    buyReply.Type  = ActivityTypes.Event;
                                    buyReply.Name  = "buystock";
                                    buyReply.Value = entityFound.ToString();
                                    await dc.Context.SendActivityAsync(buyReply);
                                }
                                else
                                {
                                    await turnContext.SendActivityAsync($"종목, 수량, 단가를 모두 입력해주세요.\n(예시:\"신한지주 1주 현재가로 매수해줘\")");
                                }
                            }
                            else
                            {
                                await turnContext.SendActivityAsync($"종목, 수량, 단가를 모두 입력해주세요.\n(예시:\"신한지주 1주 현재가로 매수해줘\")");
                            }



                            break;

                        case SellIntent:
                            //await dc.Context.SendActivityAsync(topIntent);

                            // Inform the user if LUIS used an entity.
                            if (entityFound.ToString() != string.Empty)
                            {
                                string[] cutEntity = entityFound.Split("|SEP|");
                                //await turnContext.SendActivityAsync($"==>LUIS Count: {cutEntity.Length}\n");
                                foreach (var cutEntityValue in cutEntity)
                                {
                                    //await turnContext.SendActivityAsync($"==>LUIS Entity: {cutEntityValue}\n");
                                }
                                //await turnContext.SendActivityAsync($"==>LUIS Entity Found: {entityFound}\n");

                                /*
                                 * // 카드는 html에서 출력
                                 * var sellCard = CreateSellCardAttachment(@".\Dialogs\BuyIntent\Resources\buyCard.json", entityFound);
                                 * var sell_response = CreateResponse(activity, sellCard);
                                 * await dc.Context.SendActivityAsync(sell_response);
                                 */

                                // html에 인텐트+엔티티 전달
                                Activity sellReply = activity.CreateReply();
                                sellReply.Type  = ActivityTypes.Event;
                                sellReply.Name  = "sellstock";
                                sellReply.Value = entityFound.ToString();
                                await dc.Context.SendActivityAsync(sellReply);
                            }
                            else
                            {
                                await turnContext.SendActivityAsync($"종목, 수량, 단가를 모두 입력해주세요.\n(예시:\"신한지주 1주 현재가로 매도해줘\")");
                            }


                            break;

                        case BalanceIntent:
                            //await dc.Context.SendActivityAsync(topIntent);

                            // html에 인텐트+엔티티 전달
                            Activity balanceReply = activity.CreateReply();
                            balanceReply.Type  = ActivityTypes.Event;
                            balanceReply.Name  = "balancestock";
                            balanceReply.Value = entityFound.ToString();
                            await dc.Context.SendActivityAsync(balanceReply);

                            break;

                        case SkinBalanceIntent:
                            // html에 인텐트+엔티티 전달
                            Activity balanceSkinReply = activity.CreateReply();
                            balanceSkinReply.Type  = ActivityTypes.Event;
                            balanceSkinReply.Name  = "balanceskin";
                            balanceSkinReply.Value = entityFound.ToString();
                            await dc.Context.SendActivityAsync(balanceSkinReply);

                            // 잔고인텐트 일때는 잔고 카드 전달
                            var balanceCard = CreateWelcomeCardAttachment(@".\Dialogs\BalanceIntent\Resources\balanceCard.json");
                            var response    = CreateResponse(activity, balanceCard);
                            await dc.Context.SendActivityAsync(response);

                            break;
                        }

                        break;

                    case DialogTurnStatus.Waiting:
                        // The active dialog is waiting for a response from the user, so do nothing.
                        break;

                    case DialogTurnStatus.Complete:
                        await dc.EndDialogAsync();

                        break;

                    default:
                        await dc.CancelAllDialogsAsync();

                        break;
                    }
                }
            }
            else if (activity.Type == ActivityTypes.ConversationUpdate)
            {
                if (activity.MembersAdded != null)
                {
                    // Iterate over all new members added to the conversation.
                    foreach (var member in activity.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 == activity.Recipient.Id)
                        {
                            var welcomeCard = CreateWelcomeCardAttachment(@".\Dialogs\Welcome\Resources\welcomeCard.json");
                            var response    = CreateResponse(activity, welcomeCard);
                            await dc.Context.SendActivityAsync(response);
                        }
                    }
                }
            }

            await _conversationState.SaveChangesAsync(turnContext);

            await _userState.SaveChangesAsync(turnContext);
        }
示例#25
0
        /// <summary>
        /// Method that gets fired when a message comes in.
        /// </summary>
        /// <param name="turnContext">The current turn.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Returns a unit of execution.</returns>
        protected override async Task OnMessageActivityAsync(
            ITurnContext <IMessageActivity> turnContext,
            CancellationToken cancellationToken)
        {
            if (turnContext is null)
            {
                throw new ArgumentNullException(nameof(turnContext));
            }

            if (turnContext.Activity.Text == "Take a tour")
            {
                this.telemetryClient.TrackTrace($"Called command: {turnContext.Activity.Text}");
                await this.calcChatBot.SendTourCarouselCard(turnContext, cancellationToken).ConfigureAwait(false);
            }
            else
            {
                var        incomingTextArray  = turnContext.Activity.Text.Split(' ');
                var        command            = incomingTextArray[0];
                var        commandInputList   = incomingTextArray[1];
                Attachment responseAttachment = null;

                switch (command)
                {
                case "sum":
                case "add":
                    var sum = this.arithmetic.CalculateSum(commandInputList, turnContext, cancellationToken);
                    responseAttachment = ResponseCard.GetCardWithIntResult(sum, command);
                    break;

                case "difference":
                case "minus":
                    var diff = this.arithmetic.CalculateDifference(commandInputList, turnContext, cancellationToken);
                    responseAttachment = ResponseCard.GetCardWithIntResult(diff, command);
                    break;

                case "multiplication":
                case "product":
                    var product = this.arithmetic.CalculateProduct(commandInputList, turnContext, cancellationToken);
                    responseAttachment = ResponseCard.GetCardWithIntResult(product, command);
                    break;

                case "division":
                case "quotient":
                    var quotient = this.arithmetic.CalculateQuotient(commandInputList, turnContext, cancellationToken);
                    responseAttachment = ResponseCard.GetCardWithDecimalResult(quotient, command);
                    break;

                case "mean":
                case "average":
                    var mean = this.statistics.CalculateMean(commandInputList, turnContext, cancellationToken);
                    responseAttachment = ResponseCard.GetCardWithDecimalResult(mean, command);
                    break;

                case "median":
                case "middle of the list":
                    var median = this.statistics.CalculateMedian(commandInputList, turnContext, cancellationToken);
                    responseAttachment = ResponseCard.GetCardWithDecimalResult(median, command);
                    break;

                case "range":
                    var range = this.statistics.CalculateRange(commandInputList, turnContext, cancellationToken);
                    responseAttachment = ResponseCard.GetCardWithDecimalResult(range, command);
                    break;

                case "variance":
                    var variance = this.statistics.CalculateVariance(commandInputList, turnContext, cancellationToken);
                    responseAttachment = ResponseCard.GetCardWithDecimalResult(variance, command);
                    break;

                case "mode":
                    var modeList = this.statistics.CalculateMode(commandInputList, turnContext, cancellationToken);
                    responseAttachment = ResponseCard.GetCardWithIntArrayResult(modeList, command);
                    break;

                case "standard deviation":
                    var stdDev = this.statistics.CalculateStandardDeviation(commandInputList, turnContext, cancellationToken);
                    responseAttachment = ResponseCard.GetCardWithDecimalResult(stdDev, command);
                    break;

                case "geometric mean":
                    var geometricMean = this.statistics.CalculateGeometricMean(commandInputList, turnContext, cancellationToken);
                    responseAttachment = ResponseCard.GetCardWithDecimalResult(geometricMean, command);
                    break;

                case "quadratic roots":
                    var quadRoots = this.geometrics.CalculateQuadraticRoots(commandInputList, turnContext, cancellationToken);
                    responseAttachment = ResponseCard.GetCardWithStringResult(quadRoots, command);
                    break;

                case "discriminant":
                    var discriminant = this.geometrics.CalculateDiscriminant(commandInputList, turnContext, cancellationToken);
                    responseAttachment = ResponseCard.GetCardWithIntResult(discriminant, command);
                    break;

                case "midpoint":
                    var midpoint = this.geometrics.CalculateMidpoint(commandInputList, turnContext, cancellationToken);
                    responseAttachment = ResponseCard.GetCardWithStringResult(midpoint, command);
                    break;

                case "distance":
                    var distance = this.geometrics.CalculateDistance(commandInputList, turnContext, cancellationToken);
                    responseAttachment = ResponseCard.GetCardWithDoubleResult(distance, command);
                    break;

                case "pythagorean triple":
                    var pythagoreanTriple = this.geometrics.CalculatePythagoreanTriple(commandInputList, turnContext, cancellationToken);
                    responseAttachment = ResponseCard.GetCardWithStringResult(pythagoreanTriple, command);
                    break;

                default:
                    await turnContext.SendActivityAsync(MessageFactory.Text(Resources.CannotPickUpCommandText), cancellationToken).ConfigureAwait(false);

                    break;
                }

                await turnContext.SendActivityAsync(MessageFactory.Attachment(responseAttachment), cancellationToken).ConfigureAwait(false);
            }
        }
 protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
 {
     await turnContext.SendActivityAsync(MessageFactory.Text($"echo: {turnContext.Activity.Text}"), cancellationToken);
 }
示例#27
0
        /// <summary>
        /// Generates an answer from the knowledge base.
        /// </summary>
        /// <param name="turnContext">The Turn Context that contains the user question to be queried against your knowledge base.</param>
        /// <returns>A list of answers for the user query, sorted in decreasing order of ranking score.</returns>
        public async Task <QueryResult[]> GetAnswersAsync(ITurnContext turnContext)
        {
            if (turnContext == null)
            {
                throw new ArgumentNullException(nameof(turnContext));
            }

            if (turnContext.Activity == null)
            {
                throw new ArgumentNullException(nameof(turnContext.Activity));
            }

            var messageActivity = turnContext.Activity.AsMessageActivity();

            if (messageActivity == null)
            {
                throw new ArgumentException("Activity type is not a message");
            }

            if (string.IsNullOrEmpty(turnContext.Activity.Text))
            {
                throw new ArgumentException("Null or empty text");
            }

            var requestUrl = $"{_endpoint.Host}/knowledgebases/{_endpoint.KnowledgeBaseId}/generateanswer";

            var request = new HttpRequestMessage(HttpMethod.Post, requestUrl);

            var jsonRequest = JsonConvert.SerializeObject(
                new
            {
                question      = messageActivity.Text,
                top           = _options.Top,
                strictFilters = _options.StrictFilters,
                metadataBoost = _options.MetadataBoost,
            }, Formatting.None);

            request.Content = new StringContent(jsonRequest, System.Text.Encoding.UTF8, "application/json");

            var isLegacyProtocol = _endpoint.Host.EndsWith("v2.0") || _endpoint.Host.EndsWith("v3.0");

            if (isLegacyProtocol)
            {
                request.Headers.Add("Ocp-Apim-Subscription-Key", _endpoint.EndpointKey);
            }
            else
            {
                request.Headers.Add("Authorization", $"EndpointKey {_endpoint.EndpointKey}");
            }

            var response = await _httpClient.SendAsync(request).ConfigureAwait(false);

            if (!response.IsSuccessStatusCode)
            {
                return(null);
            }

            var jsonResponse = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            var results = isLegacyProtocol ?
                          ConvertLegacyResults(JsonConvert.DeserializeObject <InternalQueryResults>(jsonResponse))
                    :
                          JsonConvert.DeserializeObject <QueryResults>(jsonResponse);

            foreach (var answer in results.Answers)
            {
                answer.Score = answer.Score / 100;
            }

            var result = results.Answers.Where(answer => answer.Score > _options.ScoreThreshold).ToArray();

            var traceInfo = new QnAMakerTraceInfo
            {
                Message         = (Activity)messageActivity,
                QueryResults    = result,
                KnowledgeBaseId = _endpoint.KnowledgeBaseId,
                ScoreThreshold  = _options.ScoreThreshold,
                Top             = _options.Top,
                StrictFilters   = _options.StrictFilters,
                MetadataBoost   = _options.MetadataBoost,
            };
            var traceActivity = Activity.CreateTraceActivity(QnAMakerMiddlewareName, QnAMakerTraceType, traceInfo, QnAMakerTraceLabel);
            await turnContext.SendActivityAsync(traceActivity).ConfigureAwait(false);

            return(result);
        }
 protected override async Task OnTeamsMessagingExtensionCardButtonClickedAsync(ITurnContext <IInvokeActivity> turnContext, JObject obj, CancellationToken cancellationToken)
 {
     var reply = MessageFactory.Text("OnTeamsMessagingExtensionCardButtonClickedAsync Value: " + JsonConvert.SerializeObject(turnContext.Activity.Value));
     await turnContext.SendActivityAsync(reply, cancellationToken);
 }
示例#29
0
 public static async Task ReplyWithResumeTopic(ITurnContext context)
 {
     await context.SendActivityAsync($"What can I do for you?");
 }
示例#30
0
        /// <summary>
        /// Delete qna pair.
        /// </summary>
        /// <param name="turnContext">Turn context.</param>
        /// <param name="qnaServiceProvider">Qna Service provider.</param>
        /// <param name="activityStorageProvider">Activity Storage Provider.</param>
        /// <param name="logger">Logger.</param>
        /// <param name="cancellationToken">Cancellation Token.</param>
        /// <returns>A task that represents the work queued to execute.</returns>
        public static async Task DeleteQnaPair(
            ITurnContext <IMessageActivity> turnContext,
            IQnaServiceProvider qnaServiceProvider,
            IActivityStorageProvider activityStorageProvider,
            ILogger logger,
            CancellationToken cancellationToken)
        {
            QnASearchResult searchResult;
            Attachment      attachment;

            var activity      = (Activity)turnContext.Activity;
            var activityValue = ((JObject)activity.Value).ToObject <AdaptiveSubmitActionData>();
            QnASearchResultList qnaAnswerResponse = await qnaServiceProvider.GenerateAnswerAsync(activityValue?.OriginalQuestion, isTestKnowledgeBase : false).ConfigureAwait(false);

            bool isSameQuestion = false;

            searchResult = qnaAnswerResponse.Answers.First();

            // Check if question exist in the knowledgebase.
            if (searchResult != null && searchResult.Questions.Count > 0)
            {
                // Check if the deleted question & result returned from the knowledgebase are same.
                isSameQuestion = searchResult.Questions.First().ToUpperInvariant() == activityValue?.OriginalQuestion.ToUpperInvariant().Trim();
            }

            // Delete the QnA pair if question exist in the knowledgebase & exactly the same question user wants to delete.
            if (searchResult.Id != -1 && isSameQuestion)
            {
                await qnaServiceProvider.DeleteQnaAsync(searchResult.Id.Value).ConfigureAwait(false);

                logger.LogInformation($"Question deleted by: {activity.Conversation.AadObjectId}");
                attachment = MessagingExtensionQnaCard.DeletedEntry(activityValue?.OriginalQuestion, searchResult.Answer, activity.From.Name, activityValue?.UpdateHistoryData);
                ActivityEntity activityEntity = new ActivityEntity {
                    ActivityReferenceId = searchResult.Metadata.FirstOrDefault(x => x.Name == Constants.MetadataActivityReferenceId)?.Value
                };

                bool operationStatus = await activityStorageProvider.DeleteActivityEntityAsync(activityEntity).ConfigureAwait(false);

                if (!operationStatus)
                {
                    logger.LogInformation($"Unable to delete the activity data from table storage.");
                }

                var updateCardActivity = new Activity(ActivityTypes.Message)
                {
                    Id           = turnContext.Activity.ReplyToId,
                    Conversation = turnContext.Activity.Conversation,
                    Attachments  = new List <Attachment> {
                        attachment
                    },
                };

                // Send deleted question and answer card as response.
                await turnContext.UpdateActivityAsync(updateCardActivity, cancellationToken).ConfigureAwait(false);
            }
            else
            {
                // check if question and answer is present in unpublished version.
                qnaAnswerResponse = await qnaServiceProvider.GenerateAnswerAsync(activityValue?.OriginalQuestion, isTestKnowledgeBase : true).ConfigureAwait(false);

                if (qnaAnswerResponse?.Answers?.First().Id != -1)
                {
                    await turnContext.SendActivityAsync(MessageFactory.Text(string.Format(CultureInfo.InvariantCulture, Strings.WaitMessage, activityValue?.OriginalQuestion))).ConfigureAwait(false);
                }
            }

            return;
        }