private Activity CreateReceipt(Activity message) {
            Activity replyToConversation = message.CreateReply("Receipt card");
            replyToConversation.Recipient = message.From;
            replyToConversation.Type = "message";
            replyToConversation.Attachments = new List<Attachment>();
            List<CardImage> cardImages = new List<CardImage>();
            cardImages.Add(new CardImage(url: "https://<ImageUrl1>"));
            List<CardAction> cardButtons = new List<CardAction>();
            CardAction plButton = new CardAction() {
                Value = "https://en.wikipedia.org/wiki/Pig_Latin",
                Type = "openUrl",
                Title = "WikiPedia Page"
            };
            cardButtons.Add(plButton);
            ReceiptItem lineItem1 = new ReceiptItem() {
                Title = "Pork Shoulder",
                Subtitle = "8 lbs",
                Text = null,
                Image = new CardImage(url: "https://<ImageUrl1>"),
                Price = "16.25",
                Quantity = "1",
                Tap = null
            };
            ReceiptItem lineItem2 = new ReceiptItem() {
                Title = "Bacon",
                Subtitle = "5 lbs",
                Text = null,
                Image = new CardImage(url: "https://<ImageUrl2>"),
                Price = "34.50",
                Quantity = "2",
                Tap = null
            };
            List<ReceiptItem> receiptList = new List<ReceiptItem>();
            receiptList.Add(lineItem1);
            receiptList.Add(lineItem2);
            ReceiptCard plCard = new ReceiptCard() {
                Title = "I'm a receipt card, isn't this bacon expensive?",
                Buttons = cardButtons,
                Items = receiptList,
                Total = "275.25",
                Tax = "27.52"
            };
            Attachment plAttachment = plCard.ToAttachment();
            replyToConversation.Attachments.Add(plAttachment);
            return replyToConversation;
           

        }
Exemple #2
0
        private async Task <Activity> HandleSystemMessage(Activity message)
        {
            if (message.Type == ActivityTypes.DeleteUserData)
            {
                // Implement user deletion here
                // If we handle user deletion, return a real message
            }
            else if (message.Type == ActivityTypes.ConversationUpdate)
            {
                Trace.TraceInformation("Conversation update");
                ConnectorClient client = new ConnectorClient(new Uri(message.ServiceUrl));

                using (ILifetimeScope scope = DialogModule.BeginLifetimeScope(Conversation.Container, message))
                {
                    IBotData botData = scope.Resolve <IBotData>();

                    await botData.LoadAsync(CancellationToken.None);

                    if (!botData.ConversationData.GetValueOrDefault <bool>("init"))
                    {
                        botData.ConversationData.SetValue("init", true);

                        var reply = message.CreateReply("Hi!I'll post some random question every morning.");
                        await client.Conversations.SendToConversationAsync(reply);

                        var reply2 = message.CreateReply("Commands: " + Environment.NewLine +
                                                         "\t\t  - type `tours` to get a list of tours;" + Environment.NewLine +
                                                         "\t\t  - type `new` to get a new question;" + Environment.NewLine +
                                                         "\t\t  - type `answer` to get an answer to the current question;" + Environment.NewLine +
                                                         "\t\t  - type `level` to select a complexity level");
                        await client.Conversations.SendToConversationAsync(reply2);

                        var reply3 = message.CreateReply("*All questions are taken from* " + "https://db.chgk.info/" +
                                                         Environment.NewLine + "Copyright: " + "https://db.chgk.info/copyright");
                        await client.Conversations.SendToConversationAsync(reply3);

                        var reply4 = message.CreateReply("Good luck! ;-)");
                        await client.Conversations.SendToConversationAsync(reply4);
                    }
                }
                // Handle conversation state changes, like members being added and removed
                // Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info
                // Not available in all channels
            }
            else if (message.Type == ActivityTypes.ContactRelationUpdate)
            {
                // Handle add/remove from contact lists
                // Activity.From + Activity.Action represent what happened
            }
            else if (message.Type == ActivityTypes.Typing)
            {
                // Handle knowing tha the user is typing
            }
            else if (message.Type == ActivityTypes.Ping)
            {
            }

            return(null);
        }
Exemple #3
0
        public virtual async Task <HttpResponseMessage> Post([FromBody] Microsoft.Bot.Connector.Activity activity)
        {
            try
            {
                if (activity != null && activity.GetActivityType() == ActivityTypes.Message)
                {
                    // Get and process
                    IMessageActivity message = activity.AsMessageActivity();

                    ActivityRequest request = new ActivityRequest(
                        recipient: message.Recipient.Name,
                        text: message.Text,
                        from: message.From.Name,
                        fromId: message.From.Id,
                        channelId: message.ChannelId,
                        conversationId: message.Conversation.Id,
                        isGroup: message.Conversation.IsGroup,
                        attachments: message.Attachments?.Select(
                            attachment => new AttachmentRequest(attachment.ContentUrl, attachment.ContentType)
                            ));

                    ActivityResponse response = await this.ActivityProcessor.ProcessActivityAsync(this.Store, request).ConfigureAwait(false);

                    // Reply (on a new network connection) back.
                    Microsoft.Bot.Connector.Activity reply = activity.CreateReply();
                    reply.Text = response.Text;
                    foreach (AttachmentResponse attachment in response.Attachments)
                    {
                        reply.Attachments.Add(new Attachment(attachment.ContentType, attachment.ContentUrl, null, attachment.Name));
                    }

                    // Send it either as a group message or individually, depending on how we received the message,
                    using (ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl)))
                    {
                        if (message.Conversation.IsGroup.HasValue && message.Conversation.IsGroup.Value)
                        {
                            await connector.Conversations.SendToConversationAsync(reply);
                        }
                        else
                        {
                            await connector.Conversations.ReplyToActivityAsync(reply);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                using (ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl)))
                {
                    Microsoft.Bot.Connector.Activity reply = activity.CreateReply();
                    reply.Text = ex.Message + " " + ex.StackTrace;
                    await connector.Conversations.ReplyToActivityAsync(reply);
                }
            }

            // We always accept the message and send the response using the bot framework on another channel.
            return(new HttpResponseMessage(HttpStatusCode.Accepted));
        }
Exemple #4
0
        private async Task HandleTagAdminWorkflow(Microsoft.Bot.Connector.Activity activity, QuestionModel questionModel, string teamId, int courseId)
        {
            var connector = new ConnectorClient(new Uri(activity.ServiceUrl));

            // Tag admin workflow
            IList <ChannelAccount> members = await connector.Conversations.GetConversationMembersAsync(teamId);

            var teamsMembers = members.AsTeamsChannelAccounts().ToList();

            // Get original poster
            var originalPosterAsTeamsChannelAccount = teamsMembers.Where(x => x.ObjectId == activity.From.Properties["aadObjectId"].ToString()).FirstOrDefault();
            var studentUPN = originalPosterAsTeamsChannelAccount.UserPrincipalName;
            var mappedStudentCourseRole = SQLService.GetUser(studentUPN);

            // Set question state
            var questionStatus = Constants.QUESTION_STATUS_UNANSWERED;

            // Save question
            questionModel.QuestionStatus = questionStatus;
            questionModel.OriginalPoster = mappedStudentCourseRole;
            var questionId = SQLService.CreateOrUpdateQuestion(questionModel);

            questionModel.ID = questionId;

            // TagAdmins
            var mentionOnlyReply = activity.CreateReply();
            var adminsOnTeams    = GetAdminChannelAccountsToTag(activity, teamId, courseId, teamsMembers, mappedStudentCourseRole);

            if (adminsOnTeams != null && adminsOnTeams.Count > 0)
            {
                foreach (var admin in adminsOnTeams)
                {
                    mentionOnlyReply.AddMentionToText(admin, MentionTextLocation.AppendText);
                }

                var r1 = await connector.Conversations.ReplyToActivityAsync(mentionOnlyReply);

                var reply      = activity.CreateReply();
                var attachment = CreateUserAnswerCard(questionId);
                reply.Attachments.Add(attachment);
                var r2 = await connector.Conversations.ReplyToActivityAsync(reply);

                questionModel.AnswerCardActivityId = r2?.Id;
                SQLService.CreateOrUpdateQuestion(questionModel);
            }
            else
            {
                var reply = activity.CreateReply();
                reply.Text = "I'm sorry, I could not find anyone to tag. Please ensure the user has been assigned a tutorial group with atleast one demonstrator.";
                var r2 = await connector.Conversations.ReplyToActivityAsync(reply);
            }
        }
        private Activity CreateCard(Activity message) {
            Activity replyToConversation = message.CreateReply("Should go to conversation, with a thumbnail card");
            replyToConversation.Recipient = message.From;
            replyToConversation.Type = "message";
            replyToConversation.Attachments = new List<Attachment>();
            List<CardImage> cardImages = new List<CardImage>();
            cardImages.Add(new CardImage(url: "https://upload.wikimedia.org/wikipedia/commons/f/ff/Aminah_Cendrakasih%2C_c._1959%2C_by_Tati_Photo_Studio.jpg"));
            List<CardAction> cardButtons = new List<CardAction>();
            CardAction plButton = new CardAction() {
                Value = "https://en.wikipedia.org/wiki/Pig_Latin",
                Type = "openUrl",
                Title = "WikiPedia Page"
            };
            cardButtons.Add(plButton);
            ThumbnailCard plCard = new ThumbnailCard() {
                Title = "I'm a thumbnail card",
                Subtitle = "Pig Latin Wikipedia Page",
                Images = cardImages,
                Buttons = cardButtons
            };
            Attachment plAttachment = plCard.ToAttachment();
            //   plAttachment.ContentType = "application/vnd.microsoft.card.heros";

            replyToConversation.Attachments.Add(plAttachment);
            return replyToConversation;
        }
        /// <summary>
        /// Handles O365 connector card action queries.
        /// </summary>
        /// <param name="activity">Incoming request from Bot Framework.</param>
        /// <param name="connectorClient">Connector client instance for posting to Bot Framework.</param>
        /// <returns>Task tracking operation.</returns>

        private static async Task <HttpResponseMessage> HandleO365ConnectorCardActionQuery(Activity activity)
        {
            var connectorClient = new ConnectorClient(new Uri(activity.ServiceUrl));

            // Get O365 connector card query data.
            O365ConnectorCardActionQuery o365CardQuery = activity.GetO365ConnectorCardActionQueryData();

            Activity replyActivity = activity.CreateReply();

            replyActivity.TextFormat = "xml";

            replyActivity.Text = $@"

            <h2>Thanks, {activity.From.Name}</h2><br/>

            <h3>Your input action ID:</h3><br/>

            <pre>{o365CardQuery.ActionId}</pre><br/>

            <h3>Your input body:</h3><br/>

            <pre>{o365CardQuery.Body}</pre>

        ";

            await connectorClient.Conversations.ReplyToActivityWithRetriesAsync(replyActivity);

            return(new HttpResponseMessage(HttpStatusCode.OK));
        }
        private void RequestLogin(Microsoft.Bot.Connector.Activity message)
        {
            var resumptionCookie        = new ResumptionCookie(message);
            var encodedResumptionCookie = UrlToken.Encode <ResumptionCookie>(resumptionCookie);

            Microsoft.Bot.Connector.Activity oriMessage = resumptionCookie.GetMessage();


            var reply = oriMessage.CreateReply(Messages.BOT_PLEASE_LOGIN);

            reply.Recipient   = oriMessage.From;
            reply.Type        = Microsoft.Bot.Connector.ActivityTypes.Message;
            reply.Attachments = new List <Microsoft.Bot.Connector.Attachment>();
            List <Microsoft.Bot.Connector.CardAction> cardButtons = new List <Microsoft.Bot.Connector.CardAction>();
            var encodedCookie = UrlToken.Encode(resumptionCookie);

            Microsoft.Bot.Connector.CardAction button = new Microsoft.Bot.Connector.CardAction()
            {
                Value = $"{ConfigurationHelper.GetString("AgentLogin_URL")}?cookie={encodedCookie}",
                Type  = "signin",
                Title = Messages.BOT_SIGNIN_BUTTON_TEXT,
                Image = "https://michistorageea.blob.core.windows.net/cdn/login.png"
            };
            cardButtons.Add(button);
            Microsoft.Bot.Connector.SigninCard plCard = new Microsoft.Bot.Connector.SigninCard(
                text: $"{Messages.BOT_PLEASE_LOGIN}",
                buttons: cardButtons);
            Microsoft.Bot.Connector.Attachment plAttachment = plCard.ToAttachment();
            reply.Attachments.Add(plAttachment);
            ConnectorClient connector = new ConnectorClient(new Uri(message.ServiceUrl));
            var             response  = connector.Conversations.SendToConversation(reply);
        }
Exemple #8
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)
            {
                await Conversation.SendAsync(activity, () => new Dialogs.RootDialog());
            }
            else if (activity.Type == ActivityTypes.ConversationUpdate)
            {
                // Handle conversation state changes, like members being added and removed
                // Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info
                // Not available in all channels
                var update = (IConversationUpdateActivity)activity;
                using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, activity))
                {
                    var client = scope.Resolve <IConnectorClient>();
                    if (update.MembersAdded.Any(x => x.Id != activity.Recipient.Id))
                    {
                        var newMembers = update.MembersAdded.Where(x => x.Id != activity.Recipient.Id).ToList();
                        foreach (var newMember in newMembers)
                        {
                            var reply = activity.CreateReply($"Welcome to Foo Bar Bot {newMember.Name}! (:");
                            await client.Conversations.ReplyToActivityAsync(reply);
                        }
                    }
                }
            }
            else
            {
                HandleSystemMessage(activity);
            }

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

            return(response);
        }
        private async Task <HttpResponseMessage> RejectMessageFromUnexpectedTenant(Activity activity, ConnectorClient connectorClient)
        {
            //Set the OFFICE_365_TENANT_FILTER key in web.config file with Tenant Information
            //Validate bot for specific teams tenant if any
            string currentTenant = "#ANY#";

            try
            {
                currentTenant = activity.GetTenantId();
            }
            catch (Exception e)
            {
                Trace.TraceError($"Exception from activity.GetTenantId(): {e}");
            }

            if (Middleware.RejectMessageBasedOnTenant(activity, currentTenant))
            {
                Bot.Connector.Activity replyActivity = activity.CreateReply();
                replyActivity.Text = Strings.TenantLevelDeniedAccess;

                await BotConnectorUtility.BuildRetryPolicy().ExecuteAsync(async() =>
                                                                          await connectorClient.Conversations.ReplyToActivityAsync(replyActivity));

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

            return(null);
        }
Exemple #10
0
        private async Task <bool> CheckEnableDisable(Activity activity, CancellationToken cancellationToken)
        {
            bool   success        = false;
            string successMessage = null;

            if (_teamsToggleLogic.Value.IsDisablingBot(activity.Text))
            {
                success = await _teamsToggleLogic.Value.DisableBotInChannel(activity, cancellationToken);

                successMessage = Strings.DisableBotSuccess;
            }
            else if (_teamsToggleLogic.Value.IsEnablingBot(activity.Text))
            {
                success = await _teamsToggleLogic.Value.EnableBotInChannel(activity, cancellationToken);

                successMessage = Strings.EnableBotSuccess;
            }

            if (success)
            {
                var reply = activity.CreateReply(successMessage, activity.Locale);

                using (var connectorClient = new ConnectorClient(new Uri(activity.ServiceUrl)))
                {
                    await connectorClient.Conversations.ReplyToActivityAsync(reply, cancellationToken);
                }
            }

            return(success);
        }
        public static Microsoft.Bot.Connector.Activity CreateReply(Microsoft.Bot.Connector.Activity incoming, string text)
        {
            var reply = incoming.CreateReply(text);

            reply.Speak     = text;
            reply.InputHint = InputHints.ExpectingInput;
            return(reply);
        }
Exemple #12
0
        private async Task HandleOneOnOneConversation(Microsoft.Bot.Connector.Activity activity)
        {
            var connector = new ConnectorClient(new Uri(activity.ServiceUrl));

            // One-on-one chat isn't support yet, encourage to post question in the channel instead
            var defaultReply = activity.CreateReply("Please post your question in the channel instead -- and don't forget to tag me, so I know about it!");
            await connector.Conversations.ReplyToActivityAsync(defaultReply);
        }
 public async Task<Activity> HandleChat(ConnectorClient connector, Activity message) {
     Activity replyToConversation;
     replyToConversation = message.CreateReply(await GetReplyFromLuis(message.Text));
     await connector.Conversations.SendToConversationAsync(replyToConversation);
     Activity proCards = AddRoofHeroCards(replyToConversation);
     await connector.Conversations.SendToConversationAsync(proCards);
     return replyToConversation;
 }
        private static async Task ReturnDialogAsync(Activity activity)
        {
            ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
            // calculate something for us to return
            int length = (activity.Text ?? string.Empty).Length;

            // return our reply to the user
            Activity reply = activity.CreateReply($"RETURN DIALOGUE: You sent {activity.Text} which was {length} characters");
            await connector.Conversations.ReplyToActivityAsync(reply);
        }
Exemple #15
0
        private async Task <HttpResponseMessage> SendMessage(string text, Activity activity, CancellationToken cancellationToken)
        {
            var reply = activity.CreateReply(text, activity.Locale);

            using (var connectorClient = new ConnectorClient(new Uri(activity.ServiceUrl)))
            {
                await connectorClient.Conversations.ReplyToActivityAsync(reply, cancellationToken);
            }

            return(null);
        }
        private Activity HandleSystemMessage(Activity message)
        {
            if (message.Type == ActivityTypes.DeleteUserData)
            {
                // Implement user deletion here
                // If we handle user deletion, return a real message
            }
            else if (message.Type == ActivityTypes.ConversationUpdate)
            {
                // Handle conversation state changes, like members being added and removed
                // Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info
                // Not available in all channels

                // Note: Add introduction here:
                string msg = "Hello there! My name is Arnie Bot and I am here to assist you. You can start by typing things like 'Hello' or 'How are you' or 'Can you give me advice' ... STry one of those : Let's play game, How are you, What's the weather like today, List popular Movies... And if you get stuck or you want to check basic functionality, just type 'help' or 'settings'.";

                IConversationUpdateActivity update = message;
                var client = new ConnectorClient(new Uri(message.ServiceUrl), new MicrosoftAppCredentials());
                if (update.MembersAdded != null && update.MembersAdded.Any())
                {
                    foreach (var newMember in update.MembersAdded)
                    {
                        if (newMember.Id != message.Recipient.Id)
                        {
                            var reply = message.CreateReply();


                            reply.Text = msg;

                            client.Conversations.ReplyToActivityAsync(reply);

                            Session session = new Session();
                            session.Date = DateTime.Now;
                            QureyController qc = new QureyController();
                            qc.PostSession(session);
                        }
                    }
                }
            }
            else if (message.Type == ActivityTypes.ContactRelationUpdate)
            {
                // Handle add/remove from contact lists
                // Activity.From + Activity.Action represent what happened
            }
            else if (message.Type == ActivityTypes.Typing)
            {
                // Handle knowing tha the user is typing
            }
            else if (message.Type == ActivityTypes.Ping)
            {
            }

            return(null);
        }
        /// <summary>
        /// Handle the PopUp SignIn requests
        /// </summary>
        /// <param name="activity"></param>
        /// <returns></returns>
        private static async Task <HttpResponseMessage> PopUpSignInHandler(Activity activity)
        {
            var connectorClient = new ConnectorClient(new Uri(activity.ServiceUrl));

            Activity replyActivity = activity.CreateReply();

            replyActivity.Text = $@"Authentication Successful";

            await connectorClient.Conversations.ReplyToActivityWithRetriesAsync(replyActivity);

            return(new HttpResponseMessage(HttpStatusCode.OK));
        }
 private Activity AddRoofHeroCards(Activity replyToConversation) {
     Activity heroCards = replyToConversation.CreateReply();
     heroCards.Type = "message";
     heroCards.AttachmentLayout = AttachmentLayoutTypes.Carousel;
     heroCards.Attachments = new List<Attachment>();
     List<Professional> pros = Professional.GetProfessionalMockData();
     foreach (var pro in pros) {
         Attachment professionalCard = pro.ToAttachment();
         heroCards.Attachments.Add(professionalCard);
     }
     return heroCards;
 }
Exemple #19
0
        private async Task <HttpResponseMessage> HandleKarmaChange(Activity activity, CancellationToken cancellationToken)
        {
            Trace.TraceInformation($"Message: {activity.Text}");

            // Compose the bot's response
            var reply = activity.CreateReply(string.Empty, activity.Locale);

            // Strip the mention of this bot
            Utilities.RemoveBotMentionsFromActivityText(activity);

            var replies = await _teamsKarmaLogic.Value.GetKarmaResponseTextsAsync(activity, cancellationToken);

            // If a lot of responses need to be given, put them all into one message.
            if (replies.Count > 5)
            {
                var sb = new StringBuilder();
                foreach (var replyMsg in replies)
                {
                    sb.AppendLine($"{replyMsg};\n");
                }
                reply.Text = sb.ToString();

                // Send the response. We need a new ConnectorClient each time so that this action is thread-safe.
                // For example, multiple teams may call the bot simultaneously; it should respond to the right conversation.
                using (var connectorClient = new ConnectorClient(new Uri(activity.ServiceUrl)))
                {
                    await connectorClient.Conversations.ReplyToActivityAsync(reply, cancellationToken);
                }

                Trace.TraceInformation($"Reply: {reply.Text}");
            }
            else
            {
                // Otherwise, 3 separate messages is fine, and preferable for readability and better engagement.
                using (var connectorClient = new ConnectorClient(new Uri(activity.ServiceUrl)))
                {
                    foreach (var replyMsg in replies)
                    {
                        reply.Text = replyMsg;
                        await connectorClient.Conversations.ReplyToActivityAsync(reply, cancellationToken);

                        Trace.TraceInformation($"Reply: {reply.Text}");
                    }
                }
            }


            return(Request.CreateResponse(HttpStatusCode.OK));
        }
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            switch (activity.GetActivityType())
            {
            // all messages pass through one dialog for now
            case ActivityTypes.Message:
                LuisModelAttribute attr    = new LuisModelAttribute(ConfigurationManager.AppSettings[Constants.LuisModelIdKey], ConfigurationManager.AppSettings[Constants.LuisSubscriptionKey]);
                LuisService        luisSvc = new LuisService(attr);
                await Conversation.SendAsync(activity, () => new GitHubLuisDialog(luisSvc));

                break;

            // send a "hello" to someone who just joined the conversation (not all channels support this)
            case ActivityTypes.ConversationUpdate:
                IConversationUpdateActivity update = activity;
                using (ILifetimeScope scope = DialogModule.BeginLifetimeScope(Conversation.Container, activity))
                {
                    IConnectorClient client = scope.Resolve <IConnectorClient>();
                    if (update.MembersAdded.Any())
                    {
                        Activity reply = activity.CreateReply();
                        IEnumerable <ChannelAccount> newMembers = update.MembersAdded?.Where(t => t.Id != activity.Recipient.Id);
                        foreach (var newMember in newMembers)
                        {
                            reply.Text = Constants.DemoText + $"Welcome {newMember.Name}! I can help you with getting information about your GitHub repos.";

                            IBotData data = scope.Resolve <IBotData>();
                            await data.LoadAsync(CancellationToken.None);

                            if (data.UserData.ContainsKey(Constants.AuthTokenKey))
                            {
                                reply.Text += " It looks like you're already logged in, so what can I help you with?";
                            }
                            else
                            {
                                reply.Text += " To get started, type **login** to authorize me to talk to GitHub on your behalf, or type **help** to get more information.";
                            }

                            await client.Conversations.ReplyToActivityAsync(reply);
                        }
                    }
                }
                break;
            }

            return(new HttpResponseMessage(HttpStatusCode.Accepted));
        }
Exemple #21
0
        public async Task <OkResult> Post([FromBody] Microsoft.Bot.Connector.Activity activity)
        {
            if (activity.Type == ActivityTypes.Message)
            {
                //MicrosoftAppCredentials.TrustServiceUrl(activity.ServiceUrl);
                var appCredentials = new MicrosoftAppCredentials(_microsoftAppSettingsResolver.Get(activity.From.Id).Id, _microsoftAppSettingsResolver.Get(activity.From.Id).Password, _logger);
                var connector      = new ConnectorClient(new Uri(activity.ServiceUrl), appCredentials);

                // return our reply to the user
                var reply = activity.CreateReply("HelloWorld");
                await connector.Conversations.ReplyToActivityAsync(reply);
            }
            else
            {
                //HandleSystemMessage(activity);
            }
            return(Ok());
        }
Exemple #22
0
        private async Task <Microsoft.Bot.Connector.Activity> HandleSystemMessage(Microsoft.Bot.Connector.Activity message)
        {
            if (message.Type == ActivityTypes.DeleteUserData)
            {
                // Implement user deletion here
                // If we handle user deletion, return a real message
            }
            else if (message.Type == ActivityTypes.ConversationUpdate)
            {
                // Handle conversation state changes, like members being added and removed
                // Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info
                // Not available in all channels
                if (message.ChannelId == "msteams")
                {
                    var addedBot = false;
                    for (int i = 0; i < message.MembersAdded.Count; i++)
                    {
                        if (message.MembersAdded[i].Id == message.Recipient.Id)
                        {
                            addedBot = true;
                            break;
                        }
                    }

                    if (addedBot)
                    {
                        var             reply     = message.CreateReply("Hi, I'm here to learn and help answer your questions! Just add '@Question' to your queries :)");
                        ConnectorClient connector = new ConnectorClient(new Uri(message.ServiceUrl));
                        await connector.Conversations.ReplyToActivityAsync(reply);
                    }
                }
            }
            else if (message.Type == ActivityTypes.ContactRelationUpdate)
            {
                // Handle add/remove from contact lists
                // Activity.From + Activity.Action represent what happened
            }
            else if (message.Type == ActivityTypes.Typing)
            {
                // Handle knowing tha the user is typing
            }

            return(null);
        }
        /// <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)
            {
                var      connector     = new ConnectorClient(new Uri(activity.ServiceUrl));
                Activity isTypingReply = activity.CreateReply();
                isTypingReply.Type = ActivityTypes.Typing;
                await connector.Conversations.ReplyToActivityAsync(isTypingReply);

                await Conversation.SendAsync(activity, () => new Dialogs.RootDialog());
            }
            else
            {
                HandleSystemMessage(activity);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);

            /*  if (activity.Type == ActivityTypes.Message)
             * {
             *    if (IsSpellCorrectionEnabled)
             *    {
             *        try
             *        {
             *            activity.Text = await this.spellService.GetCorrectedTextAsync(activity.Text);
             *        }
             *        catch (Exception ex)
             *        {
             *            Trace.TraceError(ex.ToString());
             *        }
             *    }
             *
             *    await Conversation.SendAsync(activity, () => new RootDialog());
             * }
             * else
             * {
             *    HandleSystemMessage(activity);
             * }
             *
             * var response = Request.CreateResponse(HttpStatusCode.OK);
             * return response;*/
        }
        public static async Task Resume(ConversationHistory history)
        {
            Activity message = null;

            Trace.TraceInformation($"Resuming  {history.PartitionKey} {history.PartitionKey}");
            try
            {
                message = JsonConvert.DeserializeObject <ConversationReference>(history.Conversation).GetPostToBotMessage();
                ConnectorClient client = new ConnectorClient(new Uri(message.ServiceUrl));

                using (ILifetimeScope scope = DialogModule.BeginLifetimeScope(Conversation.Container, message))
                {
                    IBotData botData = scope.Resolve <IBotData>();

                    await botData.LoadAsync(CancellationToken.None);

                    string todayDate = DateTime.UtcNow.ToShortDateString();
                    if (botData.ConversationData.GetValueOrDefault <string>("today") != todayDate)
                    {
                        botData.ConversationData.SetValue("today", todayDate);
                        await botData.FlushAsync(CancellationToken.None);

                        await botData.LoadAsync(CancellationToken.None);

                        IMessageActivity temp = message.CreateReply().AsMessageActivity();

                        IMessageActivity reply = await RootDialog.PostNewQuestion(botData.ConversationData, temp);

                        if (reply != null)
                        {
                            await client.Conversations.SendToConversationAsync((Activity)reply);
                        }

                        //flush dialog stack
                        await botData.FlushAsync(CancellationToken.None);
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError($"Exception when resuming conversation {message.Conversation?.Id}", ex);
            }
        }
Exemple #25
0
        private async Task HandleBotAnswerWorkflow(IDialogContext context, Microsoft.Bot.Connector.Activity activity, QuestionModel questionModel, QnAAnswer response, string teamId)
        {
            var connector = new ConnectorClient(new Uri(activity.ServiceUrl));

            // above threshold
            // post answer card with helpful/not-helpful

            // Set question state
            questionModel.QuestionStatus = Constants.QUESTION_STATUS_UNANSWERED;

            // Save question
            var questionId = SQLService.CreateOrUpdateQuestion(questionModel);

            var attachment = CreateBotAnswerCard(response.Id, response.Answer, response.Score, questionId, questionModel.OriginalPoster.Email);

            var reply = activity.CreateReply();

            reply.Attachments.Add(attachment);
            await context.PostAsync(reply);
        }
Exemple #26
0
        private async Task  HandleSystemMessage(Microsoft.Bot.Connector.Activity message)
        {
            if (message.Type == ActivityTypes.DeleteUserData)
            {
                // Implement user deletion here
                // If we handle user deletion, return a real message
            }
            else if (message.Type == ActivityTypes.ConversationUpdate)
            {
                // Handle conversation state changes, like members being added and removed
                // Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info
                // Not available in all channels
                if (message.MembersAdded.Any(o => o.Id == message.Recipient.Id))
                {
                    ConnectorClient client = new ConnectorClient(new Uri(message.ServiceUrl));

                    var reply = message.CreateReply();


                    reply.Text = "Welcome to Source API Bot";// Utilities.GetSentence("1");

                    await client.Conversations.ReplyToActivityAsync(reply);
                }
            }
            else if (message.Type == ActivityTypes.ContactRelationUpdate)
            {
                // Handle add/remove from contact lists
                // Activity.From + Activity.Action represent what happened
            }
            else if (message.Type == ActivityTypes.Typing)
            {
                // Handle knowing tha the user is typing
            }
            else if (message.Type == ActivityTypes.Ping)
            {
            }

            //return ;
        }
        private static async Task HandleSystemMessage(Microsoft.Bot.Connector.Activity message)
        {
            if (message.Type == ActivityTypes.DeleteUserData)
            {
                // Implement user deletion here
                // If we handle user deletion, return a real message
            }
            else if (message.Type == ActivityTypes.ConversationUpdate)
            {
                using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, message))
                {
                    var client = scope.Resolve <IConnectorClient>();

                    var rpl = message.CreateReply();
                    foreach (var newMember in message.MembersAdded)
                    {
                        if (CheckIfMemberIsBot(message, newMember))
                        {
                            continue;
                        }

                        rpl.Text = $"Hi there! Welcome to the PentaBOT. How can I help you?";
                        await client.Conversations.ReplyToActivityAsync(rpl);
                    }
                }
            }
            else if (message.Type == ActivityTypes.ContactRelationUpdate)
            {
                // Handle add/remove from contact lists
                // Activity.From + Activity.Action represent what happened
            }
            else if (message.Type == ActivityTypes.Typing)
            {
                // Handle knowing tha the user is typing
            }
            else if (message.Type == ActivityTypes.Ping)
            {
            }
        }
Exemple #28
0
        private async Task <HttpResponseMessage> HandlePersonalMessage(Activity activity, CancellationToken cancellationToken)
        {
            activity.Text = Utilities.TrimWhitespace(activity.Text);

            var scoreboardRegexMatch = _messageLogic.IsGettingScoreboard(activity.Text);

            if (scoreboardRegexMatch.Success)
            {
                return(await HandleScoreboardRequest(activity, scoreboardRegexMatch, cancellationToken));
            }
            else
            {
                var scoreRegexMatch = _messageLogic.IsGettingScore(activity.Text);
                if (scoreRegexMatch.Success)
                {
                    return(await HandleScoreRequest(activity, scoreRegexMatch, cancellationToken));
                }
            }

            // Check for forbidden commands.
            if (KarmaLogic.SomeoneReceivedKarmaInWholeMessage(activity.Text))
            {
                var reply = activity.CreateReply("You cannot change karma in a personal chat.", activity.Locale);
                using (var connectorClient = new ConnectorClient(new Uri(activity.ServiceUrl)))
                {
                    await connectorClient.Conversations.ReplyToActivityAsync(reply, cancellationToken);
                }

                Trace.TraceInformation($"<message>{activity.Text}</message><reply>{reply.Text}</reply>");
            }

            // Add things you *can* do in personal chat (like leaderboard checking) below.
            if (_messageLogic.IsAskingForHelp(activity.Text))
            {
                return(await SendHelpMessage(activity, cancellationToken));
            }

            return(await SendMessage(Strings.DidNotUnderstand, activity, cancellationToken));
        }
        /// <summary>
        /// Creates a response to welcoem new users
        /// </summary>
        /// <param name="message">Incoming text</param>
        /// <returns>A response to the new user, with their name</returns>
        private static async Task WelcomeNewUser(Activity message)
        {
            var client = new ConnectorClient(new Uri(message.ServiceUrl));
            IConversationUpdateActivity update = message;

            if (update.MembersAdded.Any())
            {
                var createReply = message.CreateReply();
                var newMembers  = update.MembersAdded?.Where(t => t.Id != message.Recipient.Id);

                // Welcome each new member
                foreach (var newMember in newMembers)
                {
                    createReply.Text = "Welcome";
                    if (!string.IsNullOrEmpty(newMember.Name))
                    {
                        createReply.Text += $" {newMember.Name}";
                    }
                    createReply.Text += "!";
                    await client.Conversations.ReplyToActivityAsync(createReply);
                }
            }
        }
Exemple #30
0
        private async Task HandleSystemMessage(Microsoft.Bot.Connector.Activity message)
        {
            Trace.TraceInformation($"HandleSystemMessage received message.text {message.Text}");
            if (message.Type == ActivityTypes.DeleteUserData)
            {
                // Implement user deletion here
                // If we handle user deletion, return a real message
            }
            else if (message.Type == ActivityTypes.ConversationUpdate)
            {
                if (message.MembersAdded.Any(o => o.Id == message.Recipient.Id))
                {
                    ConnectorClient client = new ConnectorClient(new Uri(message.ServiceUrl));

                    var reply = message.CreateReply();

                    reply.Text  = $"You have reached the DirectLine bot with Message of type {message.Type}. ";
                    reply.Text += (message.Text.Length == 0) ? "Message is empty." : message.Text;

                    await client.Conversations.ReplyToActivityAsync(reply);

                    return;
                }
            }
            else if (message.Type == ActivityTypes.ContactRelationUpdate)
            {
                // Handle add/remove from contact lists
                // Activity.From + Activity.Action represent what happened
            }
            else if (message.Type == ActivityTypes.Typing)
            {
                // Handle knowing tha the user is typing
            }
            else if (message.Type == ActivityTypes.Ping)
            {
            }
        }
        public async Task DispatchAsync(IDialogContext context, IAwaitable <Microsoft.Bot.Connector.IMessageActivity> item)
        {
            Microsoft.Bot.Connector.Activity activity = (Microsoft.Bot.Connector.Activity) await item;
            Logger.Info($"message received from {activity.From.Name}/{activity.From.Id} : {JsonConvert.SerializeObject(activity)}");
            Logger.Info($"message received to {activity.Recipient.Name}/{activity.Recipient.Id}");

            var storage = new AgentStatusStorage(
                ConfigurationHelper.GetString("BotStatusDBConnectionString"));

            if (activity.From.Name.EndsWith("@ocsuser"))
            {
                //Messages from OCS User, when message from OCS User sent to this method, it has to be coming from DirectLine
                AgentStatus agent = null;
                //retrieve ChannelData which includes channelId for our conversation
                //TODO:figure out a way that simplier
                JObject o  = (JObject)activity.ChannelData;
                var     os = JsonConvert.SerializeObject(o);
                DirectLineChannelData channelData = JsonConvert.DeserializeObject <DirectLineChannelData>(os);

                Logger.Info($"ChannelData = {channelData}");
                //ConversationStatus conversation = null;
                Logger.Info($"RoundTrip = {channelData.RoundTrip}");
                //first message send to agent, find an available agent
                //TODO:the agent has been selected in OCS Bot, need to make it sync
                //      Instead of selecting another one here...
                agent = (await storage.FindAvailableAgentsAsync()).FirstOrDefault();
                var convRecord = (await storage.FindConversationActivityAsync(a => a.UserID == agent.Id)).FirstOrDefault();
                convRecord.RemoteConversationID = channelData.ConversationId;
                convRecord.RemoteBotId          = activity.From.Id;//remote user id actually...
                convRecord.RemoteActivity       = UrlToken.Encode <ResumptionCookie>(
                    new ResumptionCookie((Microsoft.Bot.Connector.Activity)activity));
                convRecord.RemoteUserId   = channelData.UserID;
                convRecord.RemoteUserName = channelData.UserName;
                await storage.UpdateConversationActivityAsync(convRecord);

                Logger.Info($"agent:{agent}");
                if (!agent.IsLoggedIn)
                {
                    //Agent somehow is occupied (logout?)
                    Logger.Info("Agent is occupied");
                    var             reply     = activity.CreateReply($"Agent is occupied");
                    ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
                    await connector.Conversations.ReplyToActivityAsync(reply);
                }
                else
                {
                    //Agnet is available to answer questions, send message to agent
                    Logger.Info("Sending to conversation...");

                    //TODO:Need to check if current agent is this user
                    //agent.IsOccupied = true;
                    //await storage.UpdateAgentStatusAsync(agent);

                    //First retrieve last conversaion if exists
                    //resumptionCookie = UrlToken.Decode<ResumptionCookie>(conversation.AgentResumptionCookie);
                    var localResumptionCookie = UrlToken.Decode <ResumptionCookie>(convRecord.LocalActivity);
                    Logger.Info($"AgentBot::LocalResumptionCookie:{localResumptionCookie}");
                    var localActivity  = localResumptionCookie.GetMessage();
                    var localReply     = localActivity.CreateReply($"[{activity.From.Name}]{activity.Text}");
                    var localConnector = new ConnectorClient(new Uri(localActivity.ServiceUrl),
                                                             new MicrosoftAppCredentials(
                                                                 ConfigurationHelper.GetString("MicrosoftAppId"),
                                                                 ConfigurationHelper.GetString("MicrosoftAppPassword")),
                                                             true);

                    Microsoft.Bot.Connector.Conversations localConversation = new Microsoft.Bot.Connector.Conversations(localConnector);
                    localConversation.ReplyToActivity(localReply);
                    Logger.Info("done");


                    return;
                }
            }
            else
            {
                resumptionCookie = new ResumptionCookie(await item);
                await MessageReceivedAsync(context, item);
            }
        }
Exemple #32
0
        private async Task <Microsoft.Bot.Connector.Activity> dataTypesTest(Microsoft.Bot.Connector.Activity message, ConnectorClient connector, TableBotDataStore botStateStore)
        {
            IBotDataStore <BotData> dataStore      = botStateStore;
            pigLatinBotUserData     deleteUserData = new pigLatinBotUserData();



            StringBuilder sb = new StringBuilder();
            // DM a user
            DateTime timestamp = DateTime.UtcNow;

            pigLatinBotUserData addedUserData = new pigLatinBotUserData();
            BotData             botData       = new BotData();

            try
            {
                botData = (BotData)await dataStore.LoadAsync(new Address(message.Recipient.Id, message.ChannelId, message.From.Id, message.Conversation.Id, message.ServiceUrl), BotStoreType.BotUserData, default(CancellationToken));
            }
            catch (Exception e)
            {
                if (e.Message == "Resource not found")
                {
                }
                else
                {
                    throw e;
                }
            }

            if (botData == null)
            {
                botData = new BotData(eTag: "*");
            }

            addedUserData = botData.GetProperty <pigLatinBotUserData>("v1") ?? new pigLatinBotUserData();

            addedUserData.isNewUser        = false;
            addedUserData.lastReadLegalese = timestamp;

            try
            {
                botData.SetProperty("v1", addedUserData);
                await dataStore.SaveAsync(new Address(message.Recipient.Id, message.ChannelId, message.From.Id, message.Conversation.Id, message.ServiceUrl), BotStoreType.BotUserData, botData, default(CancellationToken));
            }
            catch (Exception e)
            {
                Trace.WriteLine(e.Message);
            }

            try
            {
                botData = (BotData)await dataStore.LoadAsync(new Address(message.Recipient.Id, message.ChannelId, message.From.Id, message.Conversation.Id, message.ServiceUrl), BotStoreType.BotUserData, default(CancellationToken));
            }
            catch (Exception e)
            {
                if (e.Message == "Resource not found")
                {
                }
                else
                {
                    throw e;
                }
            }

            if (botData == null)
            {
                botData = new BotData(eTag: "*");
            }

            addedUserData = botData.GetProperty <pigLatinBotUserData>("v1") ?? new pigLatinBotUserData();

            if (addedUserData.isNewUser != false || addedUserData.lastReadLegalese != timestamp)
            {
                sb.Append(translateToPigLatin("Bot data didn't match doofus."));
            }
            else
            {
                sb.Append(translateToPigLatin("Yo, that get/save/get thing worked."));
            }

            return(message.CreateReply(sb.ToString(), "en-Us"));
        }
Exemple #33
0
        public virtual async Task <HttpResponseMessage> Post([FromBody] Microsoft.Bot.Connector.Activity message)
        {
            ConnectorClient connector = new ConnectorClient(new Uri(message.ServiceUrl));

            IBotDataStore <BotData> dataStore = botStateStore;

            storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("piglatinbotsjameslew_AzureStorageConnectionString"));
            botStateStore  = new TableBotDataStore(storageAccount, "botdata");

            Microsoft.Bot.Connector.Activity replyMessage = message.CreateReply();
            replyMessage.Locale     = "en-Us";
            replyMessage.TextFormat = TextFormatTypes.Plain;

            if (message.GetActivityType() != ActivityTypes.Message)
            {
                replyMessage = await handleSystemMessagesAsync(message, connector, botStateStore);

                if (replyMessage != null)
                {
                    var reply = await connector.Conversations.ReplyToActivityAsync(replyMessage);
                }
            }
            else
            {
                if (message.Text.Contains("MessageTypesTest"))
                {
                    Microsoft.Bot.Connector.Activity mtResult = await messageTypesTest(message, connector);

                    await connector.Conversations.ReplyToActivityAsync(mtResult);
                }
                else if (message.Text.Contains("DataTypesTest"))
                {
                    Microsoft.Bot.Connector.Activity dtResult = await dataTypesTest(message, connector, botStateStore);

                    await connector.Conversations.ReplyToActivityAsync(dtResult);
                }
                else if (message.Text.Contains("CardTypesTest"))
                {
                    Microsoft.Bot.Connector.Activity ctResult = await cardTypesTest(message, connector);

                    await connector.Conversations.ReplyToActivityAsync(ctResult);
                }

                try
                {
                    if (await isNewUser(message.From.Id, message, botStateStore))
                    {
                        Microsoft.Bot.Connector.Activity introMessage = message.CreateReply();
                        introMessage.Locale     = "en-Us";
                        introMessage.TextFormat = TextFormatTypes.Plain;
                        introMessage.InputHint  = InputHints.IgnoringInput;

                        introMessage.Text = string.Format(translateToPigLatin("Hey there, I'm PigLatinBot. I make intelligible text unintelligible.  Ask me how by typing 'Help', and for terms and info, click ") + "[erehay](http://www.piglatinbot.com)", message.From.Name);
                        var reply = await connector.Conversations.ReplyToActivityAsync(introMessage);
                    }
                    replyMessage.InputHint = InputHints.AcceptingInput;
                    replyMessage.Speak     = message.Text;
                    replyMessage.Text      = translateToPigLatin(message.Text);
                    var httpResponse = await connector.Conversations.ReplyToActivityAsync(replyMessage);
                }
                catch (HttpResponseException e)
                {
                    Trace.WriteLine(e.Message);
                    var Response = Request.CreateResponse(HttpStatusCode.InternalServerError);
                    return(Response);
                }
            }
            var responseOtherwise = Request.CreateResponse(HttpStatusCode.OK);

            return(responseOtherwise);
        }
 static async Task Reply(ConnectorClient connector, Activity activity, string message)
 {
     var reply = activity.CreateReply(message);
     await connector.Conversations.ReplyToActivityAsync(reply);
 }
        private Activity GetSecondReply(Activity messageFromUser) {
            Activity toReturn = messageFromUser.CreateReply("Glad to have you back!");

            return toReturn;
        }
        public async Task <object> Post([FromBody] Activity activity)
        {
            try
            {
                // Initialize the azure bot
                using (BotService.Initialize())
                {
                    // BotBuilder insists on getting from the default config - this overrides it
                    Conversation.UpdateContainer(b =>
                    {
                        b.RegisterInstance(new MicrosoftAppCredentials(
                                               Config.GetAppSetting("MicrosoftAppId"),
                                               Config.GetAppSetting("MicrosoftAppPassword")
                                               ));
                    });
                    // use this to check what the registered value is
                    // ((MicrosoftAppCredentials)(Conversation.Container.ComponentRegistry.TryGetRegistration(new Autofac.Core.TypedService(typeof(MicrosoftAppCredentials)), out var xxx) ? Conversation.Container.ResolveComponent(xxx, new Autofac.Core.Parameter[0]) : null)).MicrosoftAppId

                    // Deserialize the incoming activity
                    //string jsonContent = await req.Content.ReadAsStringAsync();
                    //var activity = JsonConvert.DeserializeObject<Activity>(jsonContent);

                    // authenticate incoming request and add activity.ServiceUrl to MicrosoftAppCredentials.TrustedHostNames
                    // if request is authenticated
                    var authHeader    = this.Request.Headers.GetCommaSeparatedValues(HeaderNames.Authorization);
                    var authParts     = authHeader[0].Split(new[] { ' ' }, 2);
                    var identityToken = await BotService.Authenticator.TryAuthenticateAsync(authParts[0], authParts[1], CancellationToken.None);

                    if (null == identityToken || !identityToken.Authenticated)
                    {
                        this.Response.Headers.Add("WWW-Authenticate", $"Bearer realm=\"{Request.Host}\"");
                        return(Unauthorized());
                    }
                    identityToken.ValidateServiceUrlClaim(new[] { activity });
                    MicrosoftAppCredentials.TrustServiceUrl(activity.ServiceUrl);

                    if (activity != null)
                    {
                        // one of these will have an interface and process it
                        switch (activity.GetActivityType())
                        {
                        case ActivityTypes.Message:
                            var text = activity.AsMessageActivity().Text ?? "";
                            Trace.WriteLine($"Recieved message: '{text}' from {activity.From.Id}/{activity.From.Name} on {activity.ChannelId}/{activity.Conversation.IsGroup.GetValueOrDefault()}");
                            Trace.WriteLine($"  ChannelData: {(activity.ChannelData as JObject)}");
                            Trace.WriteLine($"  Conversation: {activity.Conversation.ConversationType}, id: {activity.Conversation.Id}, name: {activity.Conversation.Name}, role: {activity.Conversation.Role}, properties: {activity.Conversation.Properties}");
                            Trace.WriteLine($"  From: {activity.From.Id}/{activity.From.Name}, role: {activity.From.Role}, properties: {activity.From.Properties}");
                            Trace.WriteLine($"  Recipient: {activity.Recipient.Id}/{activity.Recipient.Name}, role: {activity.Recipient.Role}, properties: {activity.Recipient.Properties}");
                            if (text.Contains("</at>") && activity.ChannelId == "msteams")
                            {
                                // ignore the mention of us in the reply
                                text = new Regex("<at>.*</at>").Replace(text, "").Trim();
                            }

                            if (activity.ChannelId == "slack")
                            {
                                var mentions = activity.Entities.Where(i => i.Type == "mention").Select(i =>
                                                                                                        i.Properties.ToAnonymousObject(new
                                {
                                    mentioned = new { id = "", name = "" },
                                    text      = ""
                                }))
                                               .ToList();

                                // ignore any group messages that don't mention us
                                if (activity.Conversation.IsGroup.GetValueOrDefault() &&
                                    !mentions.Any(i => i.mentioned.name == activity.Recipient.Name))
                                {
                                    break;
                                }

                                // filter out any mentions - we don't really care about them...
                                foreach (var mention in mentions)
                                {
                                    if (!string.IsNullOrEmpty(mention.text))
                                    {
                                        text = text.Replace(mention.text, "");
                                    }
                                }

                                // set up the conversation so we'll be in the thread
                                string thread_ts = ((dynamic)activity.ChannelData)?.SlackMessage?.@event?.thread_ts;
                                string ts        = ((dynamic)activity.ChannelData)?.SlackMessage?.@event?.ts;
                                if (string.IsNullOrEmpty(thread_ts) && !string.IsNullOrEmpty(ts) && activity.Conversation.Id.Split(':').Length == 3)
                                {
                                    // this is a main-channel conversation - pretend it came in on a thread
                                    activity.Conversation.Id += $":{ts}";
                                    Trace.WriteLine($"  Modified Conversation: {activity.Conversation.ConversationType}, id: {activity.Conversation.Id}, name: {activity.Conversation.Name}, role: {activity.Conversation.Role}, properties: {activity.Conversation.Properties}");
                                }
                            }

                            activity.AsMessageActivity().Text = text.Trim();

                            Trace.WriteLine($"Processing message: '{text}' from {activity.From.Id}/{activity.From.Name} on {activity.ChannelId}/{activity.Conversation.IsGroup.GetValueOrDefault()}");
                            await Conversation.SendAsync(activity, () => new ExceptionHandlerDialog <object>(new BotDialog(Request.GetRequestUri()), true));

                            break;

                        case ActivityTypes.ConversationUpdate:
                            var client = new ConnectorClient(new Uri(activity.ServiceUrl), new MicrosoftAppCredentials(
                                                                 Config.GetAppSetting("MicrosoftAppId"),
                                                                 Config.GetAppSetting("MicrosoftAppPassword")
                                                                 ));
                            IConversationUpdateActivity update = activity;
                            if (update.MembersAdded?.Any() ?? false)
                            {
                                var reply      = activity.CreateReply();
                                var newMembers = update.MembersAdded?.Where(t => t.Id != activity.Recipient.Id);
                                foreach (var newMember in newMembers)
                                {
                                    reply.Text = "Welcome";
                                    if (!string.IsNullOrEmpty(newMember.Name))
                                    {
                                        reply.Text += $" {newMember.Name}";
                                    }
                                    reply.Text += ", this is a bot from Rightpoint Labs Beta - say 'info' for more.";
                                    await client.Conversations.ReplyToActivityAsync(reply);
                                }
                            }
                            break;

                        case ActivityTypes.ContactRelationUpdate:
                        case ActivityTypes.Typing:
                        case ActivityTypes.DeleteUserData:
                        case ActivityTypes.Ping:
                        default:
                            Trace.WriteLine($"Unknown activity type ignored: {activity.GetActivityType()}");
                            break;
                        }
                    }
                    return(Accepted());
                }
            }
            catch (Exception ex)
            {
                TelemetryClient.TrackException(ex);
                throw;
            }
        }
 private Activity GetGreetingReply(Activity messageFromUser) {
     Activity toReturn = messageFromUser.CreateReply("Hello there!");
     SetGreetingSent(messageFromUser);
     return toReturn;
 }