Example #1
0
        private static async Task SaveAgentChannelIdInAzureStore(IDialogContext context)
        {
            try
            {
                using (var connectorClient = await BotConnectorUtility.BuildConnectorClientAsync(context.Activity.ServiceUrl))
                {
                    var ci = GetChannelId(connectorClient, context, ConfigurationManager.AppSettings["AgentChannelName"]);
                    await IdTable.SetAgentChannel(ci.Name, ci.Id);

                    WebApiConfig.TelemetryClient.TrackEvent("SaveAgentChannelIdInAzureStore",
                                                            new Dictionary <string, string> {
                        { ci.Name, ci.Id }
                    });
                    Trace.TraceInformation($"Id of {ci.Name}' is {ci.Id}.");
                }
            }
            catch (System.Exception e)
            {
                Trace.TraceError($"Error getting channel id. {e}");
            }
        }
Example #2
0
        private async Task OnDeadlineSelected(IDialogContext context, IAwaitable<IEnumerable<DateTime>> result)
        {
            try
            {
                // "result" contains the date (or array of dates) returned from the prompt
                IEnumerable<DateTime> momentOrRange = await result;
                var deadline = momentOrRange.First(); // DeadlinePrompt.MomentOrRangeToString(momentOrRange);

                // Store date
                context.ConversationData.SetValue("deadline", deadline);

                var description = context.ConversationData.GetValue<string>("description");

                string mobilePhone = string.Empty;
                string alias = string.Empty;

                if (!context.UserData.TryGetValue(UserProfileHelper.UserProfileKey, out UserProfile userProfile))
                {
                    mobilePhone = userProfile.MobilePhone;
                    alias = userProfile.Alias;
                }

                var vsoTicketNumber = await VsoHelper.CreateTaskInVso(VsoHelper.VirtualAssistanceTaskType,
                    context.Activity.From.Name,
                    description,
                    ConfigurationManager.AppSettings["AgentToAssignVsoTasksTo"],
                    deadline,
                    "",
                    null,
                    context.Activity.ChannelId);

                MicrosoftAppCredentials.TrustServiceUrl(ActivityHelper.TeamsServiceEndpoint);

                AdaptiveCard card = new AdaptiveCard();
                card.Body.Add(new AdaptiveTextBlock()
                {
                    Text = $"New Virtual Assistance request from {context.Activity.From.Name}. VSO:{vsoTicketNumber}",
                    Size = AdaptiveTextSize.Large,
                    Wrap = true,
                    Separator = true
                });
                var summary = new AdaptiveFactSet
                {
                    Facts = new List<AdaptiveFact>
                    {
                        new AdaptiveFact("Who", context.Activity.From.Name),
                        new AdaptiveFact("What", description),
                        new AdaptiveFact("When", deadline.ToString()),
                        new AdaptiveFact("Vso", vsoTicketNumber.ToString()),
                    }
                };
                card.Body.Add(summary);

                using (var connectorClient = await BotConnectorUtility.BuildConnectorClientAsync(ActivityHelper.TeamsServiceEndpoint))
                {
                    var channelInfo = GetHardcodedChannelId();
                    context.ConversationData.SetValue("VsoId", vsoTicketNumber);
                    context.ConversationData.SetValue("EndUserConversationId", context.Activity.Conversation.Id);

                    var conversationResourceResponse = await ConversationHelpers.CreateAgentConversation(channelInfo,
                        card,
                        $"New research request from {context.Activity.Recipient.Name}",
                        connectorClient,
                        vsoTicketNumber,
                        context.Activity as IMessageActivity);

                    EndUserAndAgentConversationMappingState state =
                        new EndUserAndAgentConversationMappingState(vsoTicketNumber.ToString(),
                            context.Activity.From.Name,
                            context.Activity.From.Id,
                            context.Activity.Conversation.Id,
                            conversationResourceResponse.Id);

                    await state.SaveInVso(vsoTicketNumber.ToString());
                }

                await context.PostWithRetryAsync("Thank you! I have posted following to internal agents. " +
                                                 "I will be in touch with you shortly. " +
                                                 $"Please use reference #{vsoTicketNumber} for this request in future. " +
                                                 $"What: {description}. When: {deadline}.");

                context.Done<object>(null);
            }
            catch (TooManyAttemptsException)
            {
                await context.PostWithRetryAsync("TooManyAttemptsException. Restarting now...");
            }
            catch (System.Exception e)
            {
                WebApiConfig.TelemetryClient.TrackException(e, new Dictionary<string, string>
                {
                    {"dialog", "InternetResearchDialog" },
                    {"function", "OnDeadlineSelected" }
                });
                throw;
            }
        }
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity, CancellationToken cancellationToken)
        {
            var connectorClient = await BotConnectorUtility.BuildConnectorClientAsync(activity.ServiceUrl);

            try
            {
                if (activity.Type == ActivityTypes.Message)
                {
                    // Special handling for a command to simulate a reset of the bot chat
                    if (!(activity.Conversation.IsGroup ?? false) && (activity.Text == "/resetbotchat"))
                    {
                        return(await HandleResetBotChatAsync(activity, cancellationToken));
                    }

                    //Set the Locale for Bot
                    activity.Locale = TemplateUtility.GetLocale(activity);

                    //Strip At mention from incoming request text
                    activity = Middleware.StripAtMentionText(activity);

                    //Convert incoming activity text to lower case, to match the intent irrespective of incoming text case
                    activity = Middleware.ConvertActivityTextToLower(activity);

                    // todo: enable tenant check
                    //var unexpectedTenantResponse = await RejectMessageFromUnexpectedTenant(activity, connectorClient);
                    //if (unexpectedTenantResponse != null) return unexpectedTenantResponse;

                    //await Conversation.SendAsync(activity, () => ActivityHelper.IsConversationPersonal(activity)
                    //    ? (IDialog<object>)new UserRootDialog()
                    //    : new AgentRootDialog());

                    await Conversation.SendAsync(activity, () => ActivityHelper.GetRootDialog(activity));

                    //await Conversation.SendAsync(activity, () => ActivityHelper.IsConversationPersonal(activity)
                    //    ? new ExceptionHandlerDialog<object>(new UserRootDialog(),
                    //        displayException: true)
                    //    : new ExceptionHandlerDialog<object>(new AgentRootDialog(),
                    //        displayException: true));
                }
                else if (activity.Type == ActivityTypes.MessageReaction)
                {
                    var reactionsAdded   = activity.ReactionsAdded;
                    var reactionsRemoved = activity.ReactionsRemoved;
                    var replytoId        = activity.ReplyToId;
                    Bot.Connector.Activity reply;

                    if (reactionsAdded != null && reactionsAdded.Count > 0)
                    {
                        reply = activity.CreateReply(Strings.LikeMessage);
                        await BotConnectorUtility.BuildRetryPolicy().ExecuteAsync(async() =>
                                                                                  await connectorClient.Conversations.ReplyToActivityAsync(reply));
                    }
                    else if (reactionsRemoved != null && reactionsRemoved.Count > 0)
                    {
                        reply = activity.CreateReply(Strings.RemoveLike);
                        await BotConnectorUtility.BuildRetryPolicy().ExecuteAsync(async() =>
                                                                                  await connectorClient.Conversations.ReplyToActivityAsync(reply));
                    }

                    return(Request.CreateResponse(HttpStatusCode.OK));
                }
                else if (activity.Type == ActivityTypes.Invoke) // Received an invoke
                {
                    // Handle ComposeExtension query
                    if (activity.IsComposeExtensionQuery())
                    {
                        WikipediaComposeExtension wikipediaComposeExtension = new WikipediaComposeExtension();
                        HttpResponseMessage       httpResponse = null;

                        using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, activity))
                        {
                            var botDataStore = scope.Resolve <IBotDataStore <BotData> >();
                            // Handle compose extension selected item
                            if (activity.Name == "composeExtension/selectItem")
                            {
                                // This handler is used to process the event when a user in Teams selects wiki item from wiki result
                                ComposeExtensionResponse selectedItemResponse = await wikipediaComposeExtension.HandleComposeExtensionSelectedItem(activity, botDataStore);

                                httpResponse = Request.CreateResponse <ComposeExtensionResponse>(HttpStatusCode.OK, selectedItemResponse);
                            }
                            else
                            {
                                // Handle the wiki compose extension request and returned the wiki result response
                                ComposeExtensionResponse composeExtensionResponse = await wikipediaComposeExtension.GetComposeExtensionResponse(activity, botDataStore);

                                httpResponse = Request.CreateResponse <ComposeExtensionResponse>(HttpStatusCode.OK, composeExtensionResponse);
                            }

                            var address = Address.FromActivity(activity);
                            await botDataStore.FlushAsync(address, CancellationToken.None);
                        }
                        return(httpResponse);
                    }
                    //Actionable Message
                    else if (activity.IsO365ConnectorCardActionQuery())
                    {
                        // this will handle the request coming any action on Actionable messages
                        return(await HandleO365ConnectorCardActionQuery(activity));
                    }
                    //PopUp SignIn
                    else if (activity.Name == "signin/verifyState")
                    {
                        // this will handle the request coming from PopUp SignIn
                        return(await PopUpSignInHandler(activity));
                    }
                    // Handle rest of the invoke request
                    else
                    {
                        var messageActivity = (IMessageActivity)null;

                        //this will parse the invoke value and change the message activity as well
                        messageActivity = InvokeHandler.HandleInvokeRequest(activity);

                        await Conversation.SendAsync(activity, () => ActivityHelper.GetRootDialog(activity));

                        //await Conversation.SendAsync(activity, () => ActivityHelper.IsConversationPersonal(activity)
                        //    ? (IDialog<object>) new UserRootDialog()
                        //    : new AgentRootDialog());

                        //await Conversation.SendAsync(messageActivity, () => ActivityHelper.IsConversationPersonal(messageActivity)
                        //    ? new ExceptionHandlerDialog<object>(new UserRootDialog(),
                        //        displayException: true)
                        //    : new ExceptionHandlerDialog<object>(new AgentRootDialog(),
                        //        displayException: true));

                        return(Request.CreateResponse(HttpStatusCode.OK));
                    }
                }
                else
                {
                    await HandleSystemMessageAsync(activity, connectorClient, cancellationToken);
                }
            }
            catch (Exception e)
            {
                WebApiConfig.TelemetryClient.TrackException(e, new Dictionary <string, string>
                {
                    { "class", "MessagesController" }
                });
                throw;
            }

            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
        public static async Task <string> CreateAgentConversationEx(IDialogContext context,
                                                                    string topicName,
                                                                    AdaptiveCard cardToSend,
                                                                    UserProfile endUserProfile)
        {
            string serviceUrl = GetServiceUrl(context);

            var agentChannelInfo = await IdTable.GetAgentChannelInfo();

            ChannelAccount botMsTeamsChannelAccount = context.Activity.ChannelId == ActivityHelper.SmsChannelId
                ? await IdTable.GetBotId()
                : context.Activity.From;

            using (var connectorClient = await BotConnectorUtility.BuildConnectorClientAsync(serviceUrl))
            {
                try
                {
                    var channelData = new TeamsChannelData {
                        Channel = agentChannelInfo
                    };

                    IMessageActivity agentMessage = Activity.CreateMessageActivity();
                    agentMessage.From      = botMsTeamsChannelAccount;
                    agentMessage.Recipient =
                        new ChannelAccount(ConfigurationManager.AppSettings["AgentToAssignVsoTasksTo"]);
                    agentMessage.Type       = ActivityTypes.Message;
                    agentMessage.ChannelId  = ActivityHelper.MsTeamChannelId;
                    agentMessage.ServiceUrl = serviceUrl;

                    agentMessage.Attachments = new List <Attachment>
                    {
                        new Attachment {
                            ContentType = AdaptiveCard.ContentType, Content = cardToSend
                        }
                    };

                    var agentMessageActivity = (Activity)agentMessage;

                    ConversationParameters conversationParams = new ConversationParameters(
                        isGroup: true,
                        bot: null,
                        members: null,
                        topicName: topicName,
                        activity: agentMessageActivity,
                        channelData: channelData);

                    var conversationResourceResponse = await BotConnectorUtility.BuildRetryPolicy().ExecuteAsync(
                        async()
                        => await connectorClient.Conversations.CreateConversationAsync(conversationParams));

                    Trace.TraceInformation(
                        $"[SUCCESS]: CreateAgentConversation. response id ={conversationResourceResponse.Id}");

                    WebApiConfig.TelemetryClient.TrackEvent("CreateAgentConversation", new Dictionary <string, string>
                    {
                        { "endUser", agentMessage.From.Name },
                        { "agentConversationId", conversationResourceResponse.Id },
                    });

                    return(conversationResourceResponse.Id);
                }
                catch (System.Exception e)
                {
                    WebApiConfig.TelemetryClient.TrackException(e, new Dictionary <string, string>
                    {
                        { "function", "CreateAgentConversation" }
                    });

                    throw;
                }
            }
        }