/// <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 = new ConnectorClient(new Uri(activity.ServiceUrl));

            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);

                //Set the OFFICE_365_TENANT_FILTER key in web.config file with Tenant Information
                //Validate bot for specific teams tenant if any
                if (Middleware.RejectMessageBasedOnTenant(activity, activity.GetTenantId()))
                {
                    Activity replyActivity = activity.CreateReply();
                    replyActivity.Text = Strings.TenantLevelDeniedAccess;

                    await connectorClient.Conversations.ReplyToActivityAsync(replyActivity);

                    return(Request.CreateResponse(HttpStatusCode.OK));
                }

                // Set activity text if request is from an adaptive card submit action
                activity = Middleware.AdaptiveCardSubmitActionHandler(activity);

                await Conversation.SendAsync(activity, () => new RootDialog());
            }
            else if (activity.Type == ActivityTypes.MessageReaction)
            {
                var      reactionsAdded   = activity.ReactionsAdded;
                var      reactionsRemoved = activity.ReactionsRemoved;
                var      replytoId        = activity.ReplyToId;
                Activity reply;

                if (reactionsAdded != null && reactionsAdded.Count > 0)
                {
                    reply = activity.CreateReply(Strings.LikeMessage);
                    await connectorClient.Conversations.ReplyToActivityAsync(reply);
                }
                else if (reactionsRemoved != null && reactionsRemoved.Count > 0)
                {
                    reply = activity.CreateReply(Strings.RemoveLike);
                    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(messageActivity, () => new Dialogs.RootDialog());

                    return(Request.CreateResponse(HttpStatusCode.OK));
                }
            }
            else
            {
                await HandleSystemMessageAsync(activity, connectorClient, cancellationToken);
            }

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

            return(response);
        }
        /// <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);
        }
Exemple #3
0
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            if (activity.Type == ActivityTypes.Message)
            {
                //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);

                //Set the OFFICE_365_TENANT_FILTER key in web.config file with Tenant Information
                //Validate bot for specific teams tenant if any
                if (Middleware.RejectMessageBasedOnTenant(activity, activity.GetTenantId()))
                {
                    var connectorClient = new ConnectorClient(new Uri(activity.ServiceUrl));

                    Activity replyActivity = activity.CreateReply();
                    replyActivity.Text = Strings.TenantLevelDeniedAccess;

                    await connectorClient.Conversations.ReplyToActivityAsync(replyActivity);

                    return(Request.CreateResponse(HttpStatusCode.OK));
                }

                try
                {
                    await Conversation.SendAsync(activity, () => new Dialogs.RootDialog());
                }
                catch (Exception ex)
                {
                }
            }
            else if (activity.Type == ActivityTypes.Invoke) // Received an invoke
            {
                // Handle ComposeExtension query
                if (activity.IsComposeExtensionQuery())
                {
                    // this will handle the compose extension request
                    var invokeResponse = WikipediaComposeExtension.GetComposeExtensionResponse(activity);
                    return(Request.CreateResponse <ComposeExtensionResponse>(HttpStatusCode.OK, invokeResponse));
                }
                //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(messageActivity, () => new Dialogs.RootDialog());

                    return(Request.CreateResponse(HttpStatusCode.OK));
                }
            }
            else
            {
                HandleSystemMessage(activity);
            }

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

            return(response);
        }