예제 #1
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)
            {
                HttpClient client = new HttpClient();
                string     x      = await client.GetStringAsync(new Uri("http://api.fixer.io/latest?base=NZD"));

                ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

                // calculate something for us to return
                int length = (activity.Text ?? string.Empty).Length;

                var userMessage = activity.Text;

                // message output is set to this on default
                string endOutput = "Hello, welcome to Contoso, \n\n type 'help' to return a list of our features";


                // help info
                if (userMessage.ToLower().Equals("help"))
                {
                    endOutput  = "";
                    endOutput += "This is our list of features: \n\n 'branches' - shows a list of all our branches \n\n 'staff' - shows a list of all our staff members \n\n 'exchange rates' - shows popular currency exchange rates against our NZD \n\n 'show branch [branch name]' - shows more details of the specific branch \n\n 'show staff [staff name]' - shows more details of the specific staff member";
                }

                //to request more info of specific staff members
                if (userMessage.Length > 11)
                {
                    if (userMessage.ToLower().Substring(0, 10).Equals("show staff"))
                    {
                        string msgstaff = userMessage.ToLower().Substring(11);
                        endOutput = msgstaff;
                        List <Staff> staff = await AzureManager.AzureManagerInstance.GetStaff();

                        endOutput = "";
                        int count = 0;
                        foreach (Staff t in staff)
                        {
                            if (msgstaff == t.Name.ToLower())
                            {
                                endOutput += "Staff Information: \n\n Name: " + t.Name;
                                endOutput += "\n\n Branch: " + t.Branch + "\n\n Position: " + t.Position + "\n\n Contact Number: " + t.Contact_no + "\n\n Contact Email: " + t.Contact_email;
                            }
                        }
                    }
                }
                //to request more info of specific branches
                if (userMessage.Length > 12)
                {
                    if (userMessage.ToLower().Substring(0, 11).Equals("show branch"))
                    {
                        string msgbranch = userMessage.ToLower().Substring(12);
                        endOutput = msgbranch;
                        List <Branch_Tables> branch = await AzureManager.AzureManagerInstance.GetBranch();

                        endOutput = "";
                        int count = 0;
                        foreach (Branch_Tables t in branch)
                        {
                            if (msgbranch == t.Location.ToLower())
                            {
                                endOutput += "Bank Info: \n\n Location: " + t.Location;
                                endOutput += "\n\n Opening Hours: \n\n Monday:" + t.Monday + "\n\n Tuesday: " + t.Tuesday + "\n\n Wednesday: " + t.Wednesday + "\n\n Thursday: " + t.Thursday + "\n\n Friday: " + t.Friday + "\n\n Saturday: " + t.Saturday + "\n\n Sunday: " + t.Sunday;
                                endOutput += "\n\n 24/7 Deposit: " + t._24_7_deposit + "\n\n Coin Deposit: " + t.Coin_deposit;
                            }
                        }
                    }
                }


                // checks the messsage to see if it equals "branches" if so, return the location of all branches in the DB
                if (userMessage.ToLower().Equals("branches"))
                {
                    List <Branch_Tables> branch = await AzureManager.AzureManagerInstance.GetBranch();

                    endOutput = "";
                    foreach (Branch_Tables t in branch)
                    {
                        endOutput += "Location: " + t.Location + "\n\n";
                    }
                }

                //checks if message is "exchange rates" and then returns the exchange rates against the NZD in a card
                if (userMessage.ToLower().Equals("exchange rates"))
                {
                    CurrencyObject.RootObject rootObject;

                    rootObject = JsonConvert.DeserializeObject <CurrencyObject.RootObject>(x);

                    string AUD = rootObject.rates.AUD;
                    string GBP = rootObject.rates.GBP;
                    string EUR = rootObject.rates.EUR;
                    string JPY = rootObject.rates.JPY;
                    string USD = rootObject.rates.USD;

                    Activity replyToConversation = activity.CreateReply("Popular Contoso Exchange Rates");
                    replyToConversation.Recipient   = activity.From;
                    replyToConversation.Type        = "message";
                    replyToConversation.Attachments = new List <Attachment>();

                    List <CardImage> cardImages = new List <CardImage>();
                    cardImages.Add(new CardImage(url: "http://vignette1.wikia.nocookie.net/mobius-paradox/images/6/68/Contoso_logo.jpg/revision/latest?cb=20150621174845"));

                    List <CardAction> cardButtons = new List <CardAction>();

                    ThumbnailCard plCard = new ThumbnailCard()
                    {
                        Title   = "The exchange rate for NZD: ",
                        Text    = ($"AUD: {AUD} \n\n GBP: {GBP} \n\n EUR: {EUR} \n\n  JPY:{JPY} \n\n USD: {USD}"),
                        Images  = cardImages,
                        Buttons = cardButtons
                    };

                    Attachment plAttachment = plCard.ToAttachment();
                    replyToConversation.Attachments.Add(plAttachment);
                    await connector.Conversations.SendToConversationAsync(replyToConversation);

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

                //checks if message is "staff" and then returns the staff in the database

                if (userMessage.ToLower().Equals("staff"))
                {
                    List <Staff> staff = await AzureManager.AzureManagerInstance.GetStaff();

                    endOutput = "";
                    foreach (Staff t in staff)
                    {
                        endOutput += "Staff Names: \n\n " + t.Name + "\n\n";
                    }
                }

                //return reply to user
                Activity reply = activity.CreateReply(endOutput);
                await connector.Conversations.ReplyToActivityAsync(reply);
            }
            else
            {
                HandleSystemMessage(activity);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
예제 #2
0
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            if (activity.Type == ActivityTypes.Message)
            {
                ConnectorClient   connector   = new ConnectorClient(new Uri(activity.ServiceUrl));
                var               userMessage = activity.Text;
                List <CardAction> buttons     = new List <CardAction>();
                Activity          reply       = activity.CreateReply("");
                HeroCard          heroCard;
                Attachment        attachment;

                #region Setting up the state Client
                //1. Setting up the State Client==========================

                StateClient stateClient = activity.GetStateClient();
                BotData     userData    = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id); //Accessing the bot data of a user.

                //========================================================
                #endregion

                #region Clear user state using 'clear' command
                //2. Clear the user state=================================
                if (userMessage.ToLower().Contains("clear"))
                {
                    string message = "Your user data has been cleared!";
                    await stateClient.BotState.DeleteStateForUserAsync(activity.ChannelId, activity.From.Id); //Deleting the user state

                    await connector.Conversations.ReplyToActivityAsync(activity.CreateReply(message));

                    return(Request.CreateResponse(HttpStatusCode.OK));
                }
                //=====================================================
                #endregion


                #region Vision API.
                if (userMessage.ToLower().Contains("describe"))
                {
                    userData.SetProperty("isUrl", true);
                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData); //Update state

                    await connector.Conversations.ReplyToActivityAsync(activity.CreateReply("The photo url you want me to describe"));

                    return(Request.CreateResponse(HttpStatusCode.OK));
                }
                if (userData.GetProperty <bool>("isUrl"))
                {
                    userData.SetProperty("isUrl", false);
                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData); //Update state

                    var visionClient   = new VisionServiceClient("f551e31a0d1c40259727223439b0f33a");
                    var analysisResult = await visionClient.DescribeAsync(activity.Text.Substring(1));

                    message = "I see " + analysisResult.Description.Captions[0].Text;
                    await connector.Conversations.ReplyToActivityAsync(activity.CreateReply(message));

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


                #endregion

                #region Learning the user name
                //3. (First time) Greeting User and Learn the user name.===============
                if (!userData.GetProperty <bool>("SendGreeting")) //First time greeting the user.
                {
                    string welcomeMessage = "Hi! I am the New Frontiers Assistance. You can called me Fronty!";
                    await connector.Conversations.ReplyToActivityAsync(activity.CreateReply(welcomeMessage));

                    welcomeMessage = "What is your name?";
                    await connector.Conversations.ReplyToActivityAsync(activity.CreateReply(welcomeMessage));

                    userData.SetProperty <bool>("SendGreeting", true);                                           //Set the properties of sendGreeting to true as already greet once.
                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData); //Update state

                    return(Request.CreateResponse(HttpStatusCode.OK));
                }
                else
                {
                    //If the name for the user doesn't exist yet.
                    if (userData.GetProperty <string>("UserName") == null || userData.GetProperty <string>("UserName") == "")
                    {
                        //(User input thier prefer name)
                        //If the user name doesn't exist. The nameConfirmCard will be showned.
                        string   userName        = userMessage.Trim();                                               //user type in thier prefer name
                        Activity nameConfirmCard = Controllers.CardBuilding.getNameCard(userName, activity);
                        userData.SetProperty("UserName", userName);                                                  //Set the UserName to selecting mode waiting for yes or no.
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData); //Update state

                        await connector.Conversations.ReplyToActivityAsync(nameConfirmCard);

                        return(Request.CreateResponse(HttpStatusCode.OK));
                    }
                    else if (userData.GetProperty <string>("UserName") != "" && (!userData.GetProperty <bool>("userNameExist"))) //After the name card is showned.
                    {
                        //If the user hit the 'yes' on the nameConfirmCard
                        if (activity.Text.ToLower().Contains("call me") || activity.Text.ToLower().Contains("yes"))
                        {
                            string name = userData.GetProperty <string>("UserName");
                            name.Trim();
                            userData.SetProperty("UserName", name);                                                      //Set the user name
                            userData.SetProperty("userNameExist", true);                                                 //so that the bot knows the user name is already assigned and won't ask again.
                            await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData); //Update state

                            await connector.Conversations.ReplyToActivityAsync(activity.CreateReply("Nice to meet you *" + name + "!*"));

                            await connector.Conversations.ReplyToActivityAsync(activity.CreateReply("You can type *help* to see what I can do for you."));

                            #region Help button
                            Activity reply1 = activity.CreateReply("");
                            reply1.Recipient   = activity.From;
                            reply1.Type        = "message";
                            reply1.Attachments = new List <Attachment>();
                            List <CardAction> buttons1 = new List <CardAction>();

                            CardAction helpButton1 = new CardAction()
                            {
                                Type  = "imBack",
                                Title = "Help",
                                Value = "help"
                            };
                            buttons1.Add(helpButton1);
                            var heroCard1 = new HeroCard()
                            {
                                Title    = "Press 'Help' to Learn More.",
                                Subtitle = "",
                                Buttons  = buttons1
                            };

                            Attachment attachment1 = heroCard1.ToAttachment();
                            reply1.Attachments.Add(attachment1);
                            await connector.Conversations.ReplyToActivityAsync(reply1); //Finally reply to user.

                            #endregion

                            return(Request.CreateResponse(HttpStatusCode.OK));
                        }
                        else
                        //If the user select 'No' on the nameConfirmedCard
                        {
                            userData.SetProperty("UserName", "");                                                        //Set the userName back to null, and ask for the name again.
                            await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData); //Update state

                            await connector.Conversations.ReplyToActivityAsync(activity.CreateReply("What would you like to be called?"));

                            return(Request.CreateResponse(HttpStatusCode.OK));
                        }
                    }
                }
                //=====================================================
                #endregion

                #region User Type 'help'
                if (userMessage.ToLower().Contains("help"))
                {
                    Activity helpCard = activity.CreateReply("");
                    helpCard.Recipient   = activity.From;
                    helpCard.Type        = "message";
                    helpCard.Attachments = new List <Attachment>();
                    Attachment helpCardAttatchment = Controllers.CardBuilding.GetHelpCard();
                    helpCard.Attachments.Add(helpCardAttatchment);
                    await connector.Conversations.ReplyToActivityAsync(helpCard); //Finally reply to user.

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

                #region 'help' Command Panel
                if (userMessage.ToLower().Contains("command panel"))
                {
                    reply             = activity.CreateReply("");
                    reply.Recipient   = activity.From;
                    reply.Type        = "message";
                    reply.Attachments = new List <Attachment>();
                    buttons           = new List <CardAction>();

                    CardAction weatherButton = new CardAction()
                    {
                        Type  = "imBack",
                        Title = "1. Check Today Weather",
                        Value = "weather"
                    };
                    buttons.Add(weatherButton);

                    CardAction shoppingListButton = new CardAction()
                    {
                        Type  = "imBack",
                        Title = "2. Show Shopping List",
                        Value = "shopping list"
                    };
                    buttons.Add(shoppingListButton);

                    CardAction addItemButton = new CardAction()
                    {
                        Type  = "imBack",
                        Title = "3. Add Item to Shopping List",
                        Value = "add item"
                    };
                    buttons.Add(addItemButton);

                    CardAction markItemButton = new CardAction()
                    {
                        Type  = "imBack",
                        Title = "4. Mark Item Paid",
                        Value = "mark item"
                    };
                    buttons.Add(markItemButton);

                    CardAction deleteListButton = new CardAction()
                    {
                        Type  = "imBack",
                        Title = "5. Delete Shopping List",
                        Value = "delete"
                    };
                    buttons.Add(deleteListButton);

                    CardAction clearUserDataButton = new CardAction()
                    {
                        Type  = "imBack",
                        Title = "6. Clear User Data",
                        Value = "clear"
                    };
                    buttons.Add(clearUserDataButton);

                    heroCard = new HeroCard()
                    {
                        Title    = "What would you like to do?",
                        Subtitle = "",
                        Buttons  = buttons
                    };

                    attachment = heroCard.ToAttachment();
                    reply.Attachments.Add(attachment);
                    await connector.Conversations.ReplyToActivityAsync(reply); //Finally reply to user.

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

                #endregion

                #region Weather Report
                if (userMessage.ToLower().Contains("weather") && !userData.GetProperty <bool>("isWeatherRequest"))
                {
                    userData.SetProperty("isWeatherRequest", true);
                    await connector.Conversations.ReplyToActivityAsync(activity.CreateReply("Please enter the city you are currently in."));

                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData); //Update state

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

                if (userData.GetProperty <bool>("isWeatherRequest"))
                {
                    activity.Text.Trim();
                    WeatherObject.RootObject rootObject;
                    HttpClient client = new HttpClient();
                    string     x      = await client.GetStringAsync(new Uri("http://api.openweathermap.org/data/2.5/weather?q=" + activity.Text + "&units=metric&APPID=4f33e9f2a351942d172850c6b9b05595"));

                    rootObject = JsonConvert.DeserializeObject <WeatherObject.RootObject>(x);

                    string cityName = rootObject.name;
                    string temp     = rootObject.main.temp + "°C";
                    string pressure = rootObject.main.pressure + "hPa";
                    string humidity = rootObject.main.humidity + "%";
                    string wind     = rootObject.wind.deg + "°";


                    // return our reply to the user
                    string icon   = rootObject.weather[0].icon;
                    int    cityId = rootObject.id;

                    // return our reply to the user
                    Activity weatherReply = activity.CreateReply($"Current weather for {cityName}");
                    weatherReply.Recipient   = activity.From;
                    weatherReply.Type        = "message";
                    weatherReply.Attachments = new List <Attachment>();

                    List <CardImage> cardImages = new List <CardImage>();
                    cardImages.Add(new CardImage(url: "http://openweathermap.org/img/w/" + icon + ".png"));

                    List <CardAction> cardButtons = new List <CardAction>();
                    CardAction        plButton    = new CardAction()
                    {
                        Value = "https://openweathermap.org/city/" + cityId,
                        Type  = "openUrl",
                        Title = "More Info"
                    };
                    cardButtons.Add(plButton);

                    ThumbnailCard plCard = new ThumbnailCard()
                    {
                        Title    = cityName + " Weather",
                        Subtitle = "Temperature " + temp,
                        Images   = cardImages,
                        Buttons  = cardButtons
                    };

                    Attachment plAttachment = plCard.ToAttachment();
                    weatherReply.Attachments.Add(plAttachment);
                    await connector.Conversations.SendToConversationAsync(weatherReply);

                    //Create warning message.
                    string message = "**Condition: **" + rootObject.weather[0].description;
                    await connector.Conversations.SendToConversationAsync(activity.CreateReply(message));

                    int code = rootObject.weather[0].id;

                    if (rootObject.weather[0].id >= 800 && rootObject.weather[0].id < 900)
                    {
                        message = "**Notes:** It's a fine day, enjoy being outside " + userData.GetProperty <string>("userName") + ".";
                    }
                    else
                    {
                        message = "Weather condition, is not going to be so great today. Staying inside or carrying umbrella is advisable.";
                    }

                    await connector.Conversations.SendToConversationAsync(activity.CreateReply(message));

                    userData.SetProperty("isWeatherRequest", false);
                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData); //Update state

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

                #endregion



                //CRUDE (Grocery Shopping List Features)---------------------------------
                //Connected to the EasyTable
                #region Add row to the shopping list (Create)
                //====================================================
                //Add new row to the shopping list.
                if (userMessage.ToLower().Contains("add item") && (!userData.GetProperty <bool>("isAdding")))
                {
                    string space = "     ";
                    message = "Add item to the shopping list by specifying the following format.";
                    await connector.Conversations.ReplyToActivityAsync(activity.CreateReply(message));

                    message = "**Quantity**" + space + "**Item**" + space + "**Price $**";
                    await connector.Conversations.ReplyToActivityAsync(activity.CreateReply(message));

                    message = "Example: **5 Apple 1.5**";
                    await connector.Conversations.ReplyToActivityAsync(activity.CreateReply(message));

                    userData.SetProperty <bool>("isAdding", true);                                               //Set this is true so that next input will update.
                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData); //Update state

                    return(Request.CreateResponse(HttpStatusCode.OK));
                }
                else if (userData.GetProperty <bool>("isAdding") && userMessage != "")
                {
                    try
                    {
                        string   itemName        = "";
                        int      quantity        = 0;
                        double   individualPrice = 0;
                        double   sumPrice        = 0;
                        string[] userInput       = userMessage.Split();
                        itemName = userInput[1] ?? "";
                        quantity = int.Parse(userInput[0]);
                        string temp = userInput[2] ?? "0";
                        individualPrice = double.Parse(temp);
                        sumPrice        = individualPrice * quantity;
                        message         = "**" + quantity + "** x " + itemName + " (each cost **$" + individualPrice + "**) Total: **$" + sumPrice + "** has been added to your shopping list.";
                        await connector.Conversations.ReplyToActivityAsync(activity.CreateReply(message));

                        ShoppingList shoppingList = new ShoppingList()
                        {
                            ItemName        = itemName,
                            Quantity        = quantity,
                            IndividualPrice = individualPrice,
                            SumPrice        = sumPrice
                        };

                        await AzureManager.AzureManagerInstace.AddShoppingList(shoppingList);
                    } catch (Exception)
                    {
                        await connector.Conversations.ReplyToActivityAsync(activity.CreateReply("Sorry, I didn't understand what you want to add, could you please try again?"));

                        userData.SetProperty <bool>("isAdding", false);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData); //Update state

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

                    userData.SetProperty <bool>("isAdding", false);                                              //Reset this back to false
                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData); //Update state

                    #region ShoppingListCard Display Again
                    Attachment shoppingListCardAttachment;
                    try
                    {
                        List <ShoppingList> shoppingLists1 = await AzureManager.AzureManagerInstace.GetShoppingList(); //Grabbing all the rows from the table.

                        shoppingListCardAttachment = Controllers.CardBuilding.GetShoppingListCard(shoppingLists1);
                    }
                    catch (Exception)
                    {
                        await connector.Conversations.ReplyToActivityAsync(activity.CreateReply("Sorry, " + userData.GetProperty <string>("userName") + " Something went wrong."));

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

                    Activity shoppingListCard = activity.CreateReply("");
                    shoppingListCard.Recipient   = activity.From;
                    shoppingListCard.Type        = "message";
                    shoppingListCard.Attachments = new List <Attachment>();
                    shoppingListCard.Attachments.Add(shoppingListCardAttachment);

                    await connector.Conversations.ReplyToActivityAsync(shoppingListCard); //Finally reply to user.



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


                //====================================================
                #endregion

                #region ShoppingListCard Display (Read)
                if (userMessage.ToLower().Contains("shopping list"))
                {
                    Attachment shoppingListCardAttachment;
                    try
                    {
                        List <ShoppingList> shoppingLists1 = await AzureManager.AzureManagerInstace.GetShoppingList(); //Grabbing all the rows from the table.

                        shoppingListCardAttachment = Controllers.CardBuilding.GetShoppingListCard(shoppingLists1);
                    }
                    catch (Exception)
                    {
                        await connector.Conversations.ReplyToActivityAsync(activity.CreateReply("Sorry, " + userData.GetProperty <string>("userName") + " Something went wrong."));

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

                    Activity shoppingListCard = activity.CreateReply("");
                    shoppingListCard.Recipient   = activity.From;
                    shoppingListCard.Type        = "message";
                    shoppingListCard.Attachments = new List <Attachment>();
                    shoppingListCard.Attachments.Add(shoppingListCardAttachment);

                    await connector.Conversations.ReplyToActivityAsync(shoppingListCard); //Finally reply to user.

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

                #region Mark helper function (Hero Card to Strike out item)
                if (userMessage.ToLower().Equals("mark item"))
                {
                    List <ShoppingList> shoppingLists;
                    try
                    {
                        shoppingLists = await AzureManager.AzureManagerInstace.GetShoppingList(); //Grabbing all the rows from the table.
                    }
                    catch (Exception)
                    {
                        await connector.Conversations.ReplyToActivityAsync(activity.CreateReply("Sorry, " + userData.GetProperty <string>("userName") + " Something went wrong."));

                        return(Request.CreateResponse(HttpStatusCode.OK));
                    }
                    if (shoppingLists.Count() == 0) //If the list is not empty or already been all striked out.
                    {
                        await connector.Conversations.ReplyToActivityAsync(activity.CreateReply("Your Shopping List is Currently Empty."));

                        #region 'help' Command Panel

                        reply             = activity.CreateReply("");
                        reply.Recipient   = activity.From;
                        reply.Type        = "message";
                        reply.Attachments = new List <Attachment>();
                        buttons           = new List <CardAction>();

                        CardAction weatherButton = new CardAction()
                        {
                            Type  = "imBack",
                            Title = "1. Check Today Weather",
                            Value = "weather"
                        };
                        buttons.Add(weatherButton);

                        CardAction shoppingListButton = new CardAction()
                        {
                            Type  = "imBack",
                            Title = "2. Show Shopping List",
                            Value = "shopping list"
                        };
                        buttons.Add(shoppingListButton);

                        CardAction addItemButton = new CardAction()
                        {
                            Type  = "imBack",
                            Title = "3. Add Item to Shopping List",
                            Value = "add item"
                        };
                        buttons.Add(addItemButton);

                        CardAction markItemButton = new CardAction()
                        {
                            Type  = "imBack",
                            Title = "4. Mark Item Paid",
                            Value = "mark item"
                        };
                        buttons.Add(markItemButton);

                        CardAction deleteListButton = new CardAction()
                        {
                            Type  = "imBack",
                            Title = "5. Delete Shopping List",
                            Value = "delete"
                        };
                        buttons.Add(deleteListButton);

                        CardAction clearUserDataButton = new CardAction()
                        {
                            Type  = "imBack",
                            Title = "6. Clear User Data",
                            Value = "clear"
                        };
                        buttons.Add(clearUserDataButton);

                        heroCard = new HeroCard()
                        {
                            Title    = "What would you like to do?",
                            Subtitle = "",
                            Buttons  = buttons
                        };

                        attachment = heroCard.ToAttachment();
                        reply.Attachments.Add(attachment);
                        await connector.Conversations.ReplyToActivityAsync(reply); //Finally reply to user.



                        #endregion
                        return(Request.CreateResponse(HttpStatusCode.OK));
                    }
                    bool allStrikedOut = true; //Set to check if all the items are striked out already, if so it will not enter mark screen
                    foreach (ShoppingList l in shoppingLists)
                    {
                        if (l.StrikeOut == false && l.Deleted == false)
                        {
                            allStrikedOut = false;
                        }
                    }
                    if (allStrikedOut)
                    {
                        await connector.Conversations.ReplyToActivityAsync(activity.CreateReply("You have already bought all the items on the list."));

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


                    //Creating the item selection card (user can select which one to strink out)
                    reply             = activity.CreateReply("");
                    reply.Recipient   = activity.From;
                    reply.Type        = "message";
                    reply.Attachments = new List <Attachment>();
                    buttons           = new List <CardAction>();
                    int count = 1;
                    foreach (ShoppingList l in shoppingLists)
                    {
                        if (!l.StrikeOut)
                        {
                            message = count + "." + l.ItemName + " (x" + l.Quantity + ") $" + l.SumPrice;
                            CardAction button = new CardAction()
                            {
                                Type  = "imBack",
                                Title = message,
                                Value = "buy " + count
                            };
                            buttons.Add(button);
                        }
                        count++;
                    }
                    heroCard = new HeroCard()
                    {
                        Title    = "Select the following.",
                        Subtitle = "",
                        Buttons  = buttons
                    };

                    attachment = heroCard.ToAttachment();
                    reply.Attachments.Add(attachment);
                    await connector.Conversations.ReplyToActivityAsync(reply); //Finally reply to user.

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

                #region Strike out item in the shopping list (Update)
                //Strike out item in the shopping list (update)=======================
                if (userMessage.ToLower().Contains("buy"))
                {
                    string       itemName;
                    int          listIndexSelect;
                    ShoppingList updatedList;
                    try
                    {
                        List <ShoppingList> shoppingLists1 = await AzureManager.AzureManagerInstace.GetShoppingList(); //Grabbing all the rows from the table.

                        string userSelection = userMessage.Substring(3);
                        listIndexSelect       = int.Parse(userSelection.Trim());
                        itemName              = shoppingLists1[listIndexSelect - 1].ItemName;
                        updatedList           = shoppingLists1[listIndexSelect - 1];
                        updatedList.StrikeOut = true;
                    }
                    catch (Exception)
                    {
                        await connector.Conversations.ReplyToActivityAsync(activity.CreateReply("Sorry, " + userData.GetProperty <string>("userName") + " I did not understand what you mean."));

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

                    await connector.Conversations.ReplyToActivityAsync(activity.CreateReply(listIndexSelect + ". ~~" + itemName + "~~ has been bought."));

                    await AzureManager.AzureManagerInstace.UpdateShoppingList(updatedList); //Updated the row to the table

                    #region ShoppingListCard Display Again
                    Attachment shoppingListCardAttachment;
                    try
                    {
                        List <ShoppingList> shoppingLists1 = await AzureManager.AzureManagerInstace.GetShoppingList(); //Grabbing all the rows from the table.

                        shoppingListCardAttachment = Controllers.CardBuilding.GetShoppingListCard(shoppingLists1);
                    }
                    catch (Exception)
                    {
                        await connector.Conversations.ReplyToActivityAsync(activity.CreateReply("Sorry, " + userData.GetProperty <string>("userName") + " Something went wrong."));

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

                    Activity shoppingListCard = activity.CreateReply("");
                    shoppingListCard.Recipient   = activity.From;
                    shoppingListCard.Type        = "message";
                    shoppingListCard.Attachments = new List <Attachment>();
                    shoppingListCard.Attachments.Add(shoppingListCardAttachment);

                    await connector.Conversations.ReplyToActivityAsync(shoppingListCard); //Finally reply to user.



                    #endregion
                    return(Request.CreateResponse(HttpStatusCode.OK));
                }
                //====================================================================
                #endregion


                #region Delete the shopping list (Delete)
                if (userMessage.ToLower().Contains("delete"))
                {
                    try
                    {
                        List <ShoppingList> shoppingLists1 = await AzureManager.AzureManagerInstace.GetShoppingList(); //Grabbing all the rows from the table.

                        foreach (ShoppingList list in shoppingLists1)
                        {
                            await AzureManager.AzureManagerInstace.DeleteShoppingList(list);
                        }
                        await connector.Conversations.ReplyToActivityAsync(activity.CreateReply("Your grocery shopping list has been deleted."));

                        return(Request.CreateResponse(HttpStatusCode.OK));
                    } catch (Exception)
                    {
                        await connector.Conversations.ReplyToActivityAsync(activity.CreateReply("Sorry, " + userData.GetProperty <string>("userName") + " something went wrong."));

                        return(Request.CreateResponse(HttpStatusCode.OK));
                    }
                }
                #endregion
                //-----------------------------------------------------------------------
                //General

                #region Reply to Users saying "hi, hey, hello" and unrecognised command
                //=====================================================
                //if user says "hi"
                if (userMessage.ToLower().Contains("hi") || userMessage.ToLower().Contains("hello") || userMessage.ToLower().Contains("hey"))
                {
                    name = userData.GetProperty <string>("UserName");
                    await connector.Conversations.ReplyToActivityAsync(activity.CreateReply("Hello, " + name + "."));

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


                //Reply back to user if no command match===============
                name = userData.GetProperty <string>("UserName");
                await connector.Conversations.ReplyToActivityAsync(activity.CreateReply("Sorry I did not understand what you said " + name + "."));

                await connector.Conversations.ReplyToActivityAsync(activity.CreateReply("You can type *help* to see what I can do for you."));

                #region Help button
                reply             = activity.CreateReply("");
                reply.Recipient   = activity.From;
                reply.Type        = "message";
                reply.Attachments = new List <Attachment>();
                buttons           = new List <CardAction>();

                CardAction helpButton = new CardAction()
                {
                    Type  = "imBack",
                    Title = "Help",
                    Value = "help"
                };
                buttons.Add(helpButton);
                heroCard = new HeroCard()
                {
                    Title    = "Press 'Help' to Learn More.",
                    Subtitle = "",
                    Buttons  = buttons
                };

                attachment = heroCard.ToAttachment();
                reply.Attachments.Add(attachment);
                await connector.Conversations.ReplyToActivityAsync(reply); //Finally reply to user.

                #endregion

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

                //=====================================================
                #endregion
            }
            else
            {
                HandleSystemMessage(activity);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);
            return(response);
        }
예제 #3
0
        public virtual async Task ShowCharacters(IDialogContext context, IAwaitable <IMessageActivity> result)
        {
            var heroCard = new HeroCard
            {
                Title    = "Hi There!",
                Subtitle = "Im MC - the MadCalm demo bot.",
                Text     = "I'm here **ONLY** to show you how great a chat bot can be for helping customers to change their plan or get a new phone.",
                Images   = new List <CardImage> {
                    new CardImage("http://madcalm.com/wp-content/uploads/2018/06/MADCALM-HELLO.png")
                },
                Buttons = new List <CardAction> {
                }
            };

            var message = context.MakeMessage();

            message.Attachments.Add(heroCard.ToAttachment());

            await context.PostAsync(message);

            await Task.Delay(4000);

            await context.PostAsync("Because this is a demo we need you to pretend you are a customer.  Soon you will see 6 different customers that you can choose from.  You will become this person for the demo.");

            await Task.Delay(4000);

            var reply = ((Activity)context.Activity).CreateReply();

            var Card_1 = new ThumbnailCard
            {
                Title    = "Ryan",
                Subtitle = "The tech lover.",
                Text     = "Ryan loves to have the latest tech.  He loves to have the internet everywhere he goes and his phone is great for this as he travels a lot for his work.",
                Images   = new List <CardImage> {
                    new CardImage("http://www.madcalm.com/wp-content/uploads/2018/06/boy_c.png")
                },
                Buttons = new List <CardAction> {
                    new CardAction(ActionTypes.PostBack, "Pick Me!", value: "876524834")
                }
            };

            var Card_2 = new ThumbnailCard
            {
                Title    = "Pete",
                Subtitle = "The travelling business man.",
                Text     = "Pete's business takes him all over the world and he always takes his phone with him.  He has been with the same carrier for a long time and needs lots of international calls, roaming and data included.",
                Images   = new List <CardImage> {
                    new CardImage("http://www.madcalm.com/wp-content/uploads/2018/06/boy_d.png")
                },
                Buttons = new List <CardAction> {
                    new CardAction(ActionTypes.PostBack, "Pick Me!", value: "872033118")
                }
            };

            var Card_3 = new ThumbnailCard
            {
                Title    = "Jennifer",
                Subtitle = "Family all over the world.",
                Text     = "Jennifer has recently moved overseas.  She loves to keep in touch with her family back home and all over the world, so needs lots of international calls included.",
                Images   = new List <CardImage> {
                    new CardImage("http://www.madcalm.com/wp-content/uploads/2018/06/girl_a.png")
                },
                Buttons = new List <CardAction> {
                    new CardAction(ActionTypes.PostBack, "Pick Me!", value: "857701192")
                }
            };

            var Card_4 = new ThumbnailCard
            {
                Title    = "Mervyn",
                Subtitle = "The data user.",
                Text     = "Mervyn is a millennial who is just starting out in the workplace - so his budget is tight.  He doesn't really use his phone for calls or texts but is always on the latest apps or browsing the internet.",
                Images   = new List <CardImage> {
                    new CardImage("http://www.madcalm.com/wp-content/uploads/2018/06/boy_a.png")
                },
                Buttons = new List <CardAction> {
                    new CardAction(ActionTypes.PostBack, "Pick Me!", value: "876403453")
                }
            };

            var Card_5 = new ThumbnailCard
            {
                Title    = "Tania",
                Subtitle = "The techo-phobe.",
                Text     = "Tania has just gotten used to using her phone to call and text, so she doesn't really use it for data.  She just wants something easy to use and simple.",
                Images   = new List <CardImage> {
                    new CardImage("http://www.madcalm.com/wp-content/uploads/2018/06/girl_d.png")
                },
                Buttons = new List <CardAction> {
                    new CardAction(ActionTypes.PostBack, "Pick Me!", value: "830123752")
                }
            };

            var Card_6 = new ThumbnailCard
            {
                Title    = "Oliver",
                Subtitle = "The heavy user.",
                Text     = "Oliver uses his phone for absolutely everything.  He is always calling, text or browsing the internet.",
                Images   = new List <CardImage> {
                    new CardImage("http://www.madcalm.com/wp-content/uploads/2018/06/boy_b.png")
                },
                Buttons = new List <CardAction> {
                    new CardAction(ActionTypes.PostBack, "Pick Me!", value: "834795990")
                }
            };

            var Card_7 = new ThumbnailCard
            {
                Title    = "Amanda",
                Subtitle = "The chatter-box",
                Text     = "Amanda is always on the phone to friends and family but is also conscious of how much she uses so that she doesnt get charged extra.",
                Images   = new List <CardImage> {
                    new CardImage("http://www.madcalm.com/wp-content/uploads/2018/06/girl_b.png")
                },
                Buttons = new List <CardAction> {
                    new CardAction(ActionTypes.PostBack, "Pick Me!", value: "830313284")
                }
            };

            reply.AttachmentLayout = "carousel";
            reply.Attachments.Add(Card_1.ToAttachment());
            reply.Attachments.Add(Card_2.ToAttachment());
            reply.Attachments.Add(Card_3.ToAttachment());
            reply.Attachments.Add(Card_6.ToAttachment());
            reply.Attachments.Add(Card_4.ToAttachment());
            reply.Attachments.Add(Card_5.ToAttachment());
            reply.Attachments.Add(Card_7.ToAttachment());


            await context.PostAsync(reply);

            context.Wait(CharacterSelectedAsync);
        }
예제 #4
0
        public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> argument)
        {
            var message = await argument;

            if (_pizzaFlow)
            {
                if (message.Text == "abort")
                {
                    PromptDialog.Confirm(context, AfterResetAsync, "Are you sure you want to abort ordering?", "Didn't get that!", promptStyle: PromptStyle.None);
                }
                else
                {
                    context.Wait(MessageReceivedAsync);
                }
            }
            else
            {
                string resultString = "Sorry, I am not getting you...";

                QueryResult luisResult = await GetEntityFromLuis(message.Text);

                switch (luisResult.topScoringIntent.intent)
                {
                case "Coding":
                {
                    if (luisResult.entities.Any())
                    {
                        var query = luisResult.entities.FirstOrDefault(x => x.type.ToLower().Contains("topic"))?.entity ?? "";
                        var tag   = luisResult.entities.FirstOrDefault(x => x.type.ToLower().Contains("language"))?.entity ?? "";

                        //var query = luisResult.entities.OrderBy(x => x.startIndex).Select(x => x.entity).Aggregate((current, next) => current + " " + next);


                        //msg.Text = soResult.Body;
                        //msg.Attachments = new List<Attachment>()
                        //{
                        //    new Attachment()
                        //    {
                        //        ContentType = "application/vnd.microsoft.card.thumbnail",
                        //        Name = soResult.Title,
                        //        Content = "Please visit my site.",
                        //        ContentUrl = soResult.Link,

                        //    }
                        //};

                        var soResult = await StackOverflow.Query(query, tag);

                        var msg2 = context.MakeMessage();
                        msg2.Type       = "message";
                        msg2.TextFormat = "markdown";
                        //var converter = new Converter();
                        //var markdown = converter.Convert(soResult.Body);
                        //var converter = new ReverseMarkdown.Converter();
                        //string markdown = converter.Convert(soResult.Body);
                        msg2.Text = soResult.Body;

                        await context.PostAsync(msg2);

                        var msg = context.MakeMessage();
                        msg.Type        = "message";
                        msg.Attachments = new List <Attachment>();
                        List <CardImage> cardImages = new List <CardImage>();
                        cardImages.Add(new CardImage(url: "https://cdn.sstatic.net/Sites/stackoverflow/img/[email protected]?v=73d79a89bded&a"));
                        List <CardAction> cardButtons = new List <CardAction>();
                        CardAction        plButton    = new CardAction()
                        {
                            Value = soResult.Link,
                            Type  = "openUrl",
                            Title = soResult.Title
                        };
                        cardButtons.Add(plButton);
                        ThumbnailCard plCard = new ThumbnailCard()
                        {
                            Title    = soResult.Title,
                            Subtitle = "Please click me for more information!",
                            Images   = cardImages,
                            Buttons  = cardButtons
                        };
                        Attachment plAttachment = plCard.ToAttachment();
                        msg.Attachments.Add(plAttachment);

                        //  "attachments": [
                        //  {
                        //    "contentType": "application/vnd.microsoft.card.thumbnail",
                        //    "content": {
                        //      "title": "I'm a thumbnail card",
                        //      "subtitle": "Please visit my site.",
                        //      "images": [
                        //        {
                        //          "url": "https://mydeploy.azurewebsites.net/matsu.jpg"
                        //        }
                        //      ],
                        //      "buttons": [
                        //        {
                        //          "type": "openUrl",
                        //          "title": "Go to my site",
                        //          "value": "https://blogs.msdn.microsoft.com/tsmatsuz"
                        //        }
                        //      ]
                        //    }
                        //  }
                        //]

                        await context.PostAsync(msg);
                    }
                    context.Wait(MessageReceivedAsync);
                    break;
                }

                case "Greeting":
                {
                    var rand = new Random();
                    resultString = Greetings[rand.Next(0, Greetings.Length)];
                    await context.PostAsync(resultString);

                    context.Wait(MessageReceivedAsync);
                    break;
                }

                case "xkcd":
                {
                    var reply     = context.MakeMessage();
                    var imgString = string.Empty;
                    if (luisResult.entities.Any())
                    {
                        imgString = await XkcdLib.GetComic(luisResult.entities[0].entity);
                    }
                    else
                    {
                        imgString = await XkcdLib.GetRandomComic();
                    }

                    reply.Attachments = new List <Attachment>
                    {
                        new Attachment()
                        {
                            ContentUrl  = imgString,
                            ContentType = "image/jpg",
                            Name        = $"{Guid.NewGuid()}.jpg"
                        }
                    };

                    await context.PostAsync(reply);

                    context.Wait(MessageReceivedAsync);
                    break;
                }

                case "OrderPizza":
                {
                    //await context.PostAsync($"Hmm would you like to order pizza?");
                    _pizzaFlow = true;
                    PromptDialog.Text(context, Resume, "Hmm would you like to order pizza?", "Didn't get that!");

                    break;
                }

                default:
                {
                    await context.PostAsync(resultString);

                    context.Wait(MessageReceivedAsync);
                    break;
                }
                }
            }
        }
        /// <summary>
        /// Get result for messaging extension tab.
        /// </summary>
        /// <param name="searchServiceResults">List of tickets from Azure search service.</param>
        /// <param name="localizer">The current cultures' string localizer.</param>
        /// <param name="commandId">Command id to determine which tab in message extension has been invoked.</param>
        /// <param name="onCallSMEUsers">OncallSMEUsers to give support from group-chat or on-call.</param>
        /// <returns><see cref="Task"/> Returns MessagingExtensionResult which will be shown in messaging extension tab.</returns>
        public static MessagingExtensionResult GetMessagingExtensionResult(
            IList <TicketDetail> searchServiceResults,
            IStringLocalizer <Strings> localizer,
            string commandId      = "",
            string onCallSMEUsers = "")
        {
            MessagingExtensionResult composeExtensionResult = new MessagingExtensionResult
            {
                Type             = "result",
                AttachmentLayout = AttachmentLayoutTypes.List,
                Attachments      = new List <MessagingExtensionAttachment>(),
            };

            if (searchServiceResults != null)
            {
                foreach (var ticket in searchServiceResults)
                {
                    var dynamicElements = new List <AdaptiveElement>
                    {
                        CardHelper.GetAdaptiveCardColumnSet(localizer.GetString("RequestNumberText"), $"#{ticket.TicketId}", localizer),
                        CardHelper.GetAdaptiveCardColumnSet(localizer.GetString("TitleDisplayText"), ticket.Title, localizer),
                        CardHelper.GetAdaptiveCardColumnSet(localizer.GetString("DescriptionText"), ticket.Description, localizer),
                        CardHelper.GetAdaptiveCardColumnSet(localizer.GetString("CreatedOnText"), ticket.CreatedOn.ToString(CultureInfo.InvariantCulture), localizer),
                    };

                    AdaptiveCard commandIdCard = new AdaptiveCard(Constants.AdaptiveCardVersion)
                    {
                        Body    = dynamicElements,
                        Actions = new List <AdaptiveAction>(),
                    };

                    if (commandId == Constants.ActiveCommandId && !string.IsNullOrEmpty(onCallSMEUsers))
                    {
                        commandIdCard.Actions.Add(
                            new AdaptiveOpenUrlAction
                        {
                            Title = localizer.GetString("EscalateButtonText"),
                            Url   = new Uri(CreateGroupChat(onCallSMEUsers, ticket.TicketId, ticket.RequesterName, localizer)),
                        });
                    }
                    else if ((commandId == Constants.UrgentCommandId || commandId == Constants.AssignedCommandId || commandId == Constants.UnassignedCommandId) && ticket.SmeConversationId != null)
                    {
                        commandIdCard.Actions.Add(
                            new AdaptiveOpenUrlAction
                        {
                            Title = localizer.GetString("GoToOriginalThreadButtonText"),
                            Url   = new Uri(CreateDeepLinkToThread(ticket.SmeConversationId)),
                        });
                    }

                    ThumbnailCard previewCard = new ThumbnailCard
                    {
                        Title                          = $"<b>{HttpUtility.HtmlEncode(ticket.Title)} | {HttpUtility.HtmlEncode(ticket.Severity == (int)TicketSeverity.Urgent ? localizer.GetString("UrgentText") : localizer.GetString("NormalText"))}</b>",
                        Subtitle                       = ticket.Description.Length <= TruncateDescriptionLength?HttpUtility.HtmlEncode(ticket.Description) : HttpUtility.HtmlEncode(ticket.Description.Substring(0, 45)) + Ellipsis,
                                                  Text = ticket.RequesterName,
                    };
                    composeExtensionResult.Attachments.Add(new Attachment
                    {
                        ContentType = AdaptiveCard.ContentType,
                        Content     = commandIdCard,
                    }.ToMessagingExtensionAttachment(previewCard.ToAttachment()));
                }
            }

            return(composeExtensionResult);
        }
        // Handle incoming invoke activities
        private HttpResponseMessage HandleInvokeActivity(Activity activity)
        {
            if (activity.Name == "composeExtension/fetchTask")
            {
                string user      = activity.From.Id;
                string tenant    = activity.GetTenantId();
                string jwt       = this.jwtHelper.GenerateToken(activity.From.Id, activity.From.Properties["aadObjectId"].ToString(), activity.GetTenantId(), this.jwtLifetimeInMinutes);
                string sessionId = Guid.NewGuid().ToString();

                TaskInfo taskInfo = new TaskInfo()
                {
                    Url    = $"https://{this.appBaseDomain}/search?token={jwt}&sessionId={sessionId}&theme={{theme}}",
                    Title  = Strings.MessagingExtensionTitle,
                    Width  = WidthInPixels,
                    Height = HeightInPixels,
                };
                TaskSubmitResponse taskEnvelope = new TaskSubmitResponse()
                {
                    Task = new TaskContinueResult(taskInfo),
                };

                // Log invocation of messaging extension
                this.logProvider.LogEvent("SearchSessionStarted", new Dictionary <string, string>
                {
                    { "SessionId", sessionId },
                });

                return(this.Request.CreateResponse(HttpStatusCode.OK, taskEnvelope));
            }
            else if (activity.Name == "composeExtension/submitAction")
            {
                var jsonSerializerSettings = new JsonSerializerSettings()
                {
                    ContractResolver = new CamelCaseExceptDictionaryKeysResolver(),
                    Formatting       = Formatting.None,
                };
                var reply = ((JObject)activity.Value)["data"].ToString();
                SelectedSearchResult selectedSearchResult = JsonConvert.DeserializeObject <SelectedSearchResult>(reply, jsonSerializerSettings);

                List <AdaptiveFact> facts = new List <AdaptiveFact>();
                foreach (DeserializedAnswer child in selectedSearchResult.Answers)
                {
                    facts.Add(new AdaptiveFact()
                    {
                        Title = Convert.ToString(child.Question + ":"),
                        Value = Convert.ToString(child.Answer),
                    });
                }

                AdaptiveCard card = new AdaptiveCard(AdaptiveCardVersion)
                {
                    Body = new List <AdaptiveElement>()
                    {
                        new AdaptiveContainer()
                        {
                            Items = new List <AdaptiveElement>()
                            {
                                new AdaptiveTextBlock()
                                {
                                    Text   = selectedSearchResult.Question,
                                    Weight = AdaptiveTextWeight.Bolder,
                                    Wrap   = true,
                                    Size   = AdaptiveTextSize.Large,
                                },
                            },
                        },
                        new AdaptiveContainer()
                        {
                            Items = new List <AdaptiveElement>()
                            {
                                new AdaptiveFactSet()
                                {
                                    Facts = facts ?? new List <AdaptiveFact>(),
                                },
                            },
                        },
                    },
                    Actions = new List <AdaptiveAction>()
                    {
                        new AdaptiveOpenUrlAction()
                        {
                            Url   = new Uri(this.CreateListItemUrl(selectedSearchResult.SharePointListUrl, selectedSearchResult.ListItemId)),
                            Title = Strings.ResultCardButtonTitle,
                        },
                    },
                };

                var result = new Attachment()
                {
                    Content     = card,
                    ContentType = AdaptiveCard.ContentType,
                };
                var preview = new ThumbnailCard
                {
                    Title = selectedSearchResult.Question,
                };

                ComposeExtensionResponse composeExtensionResponse = new ComposeExtensionResponse()
                {
                    ComposeExtension = new ComposeExtensionResult()
                    {
                        Attachments = new List <ComposeExtensionAttachment>()
                        {
                            result.ToComposeExtensionAttachment(preview.ToAttachment())
                        },
                        Type             = ComposeExtensionResultType.Result,
                        AttachmentLayout = AttachmentLayoutTypes.List,
                    },
                };

                // Log that the search result was selected and turned into a card
                this.logProvider.LogEvent("SearchResultShared", new Dictionary <string, string>
                {
                    { "KnowledgeBaseId", selectedSearchResult.KBId },
                    { "ListItemId", selectedSearchResult.ListItemId },
                    { "SessionId", selectedSearchResult.SessionId },
                });

                return(this.Request.CreateResponse(HttpStatusCode.OK, composeExtensionResponse));
            }

            return(new HttpResponseMessage(HttpStatusCode.Accepted));
        }
예제 #7
0
        private static async Task GetSwgohReponse(ITurnContext turnContext, CancellationToken cancellationToken, string command)
        {
            Log.Verbose(string.Format("Inside GetSwgohResponse(), command text = {0}", command));

            List <SwgohChar> charlist;

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri("https://swgoh.gg");
                    client.DefaultRequestHeaders.Add("User-Agent", "Anything");
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    HttpResponseMessage response = await client.GetAsync("/api/characters/");

                    response.EnsureSuccessStatusCode();
                    charlist = response.Content.ReadAsAsync <List <SwgohChar> >().Result;
                    string responseBody = await response.Content.ReadAsStringAsync();
                }
            } catch (Exception ex)
            {
                await turnContext.SendActivityAsync(MessageFactory.Text($"Error: " + ex.Message), cancellationToken);

                return;
            }

            List <SwgohChar> requestedchars = new List <SwgohChar>();

            if (command.StartsWith("list") && command.Contains("light"))
            {
                requestedchars.AddRange(charlist.Where(c => c.Alignment == "Light Side"));
                await SendSimpleList(turnContext, cancellationToken, requestedchars);
            }
            else if (command.StartsWith("list") && command.Contains("dark"))
            {
                requestedchars.AddRange(charlist.Where(c => c.Alignment == "Dark Side"));
                await SendSimpleList(turnContext, cancellationToken, requestedchars);
            }
            else if (command == "list" || (command.StartsWith("list") && command.Contains("all")))
            {
                requestedchars = charlist;
            }
            else if (command.StartsWith("show"))
            {
                Log.Verbose(string.Format("show = true, command text = {0}", command));

                string charname = command.Substring(5);
                charname.Trim();
                Log.Verbose(string.Format("show = true, stripped charname = {0}", charname));
                bool result = charname.Equals("embo");
                Log.Verbose(string.Format("String comparison = {0}", result));
                result = charname.Equals("embo", StringComparison.Ordinal);
                Log.Verbose(string.Format("String ordinal comparison = {0}", result));
                SwgohChar t1 = charlist.FirstOrDefault(c => c.Name.ToLowerInvariant() == charname);
                if (t1 == null)
                {
                    Log.Verbose(string.Format("show = true, charname returned nothing", charname));
                    requestedchars = charlist.Where(c => c.Name.ToLowerInvariant().Contains(charname)).ToList();

                    if (requestedchars.Count == 0)
                    {
                        t1 = new SwgohChar
                        {
                            Name        = "Character not found!",
                            Image       = "//swgohbot.azurewebsites.net/Images/not_found_128x128.png",
                            Alignment   = "Please try again",
                            Description = "type 'help' for Help",
                            Base_Id     = "NOTFOUND",
                            PK          = "999",
                            Categories  = new string[] { "Not Found" }
                        };
                    }
                }

                if (requestedchars.Count > 1)
                {
                    Log.Verbose(string.Format("Query for {0} returned more than one result", charname));
                    var reply = turnContext.Activity.CreateReply();
                    reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                    for (int i = 0; i < requestedchars.Count; i++)
                    {
                        ThumbnailCard tCard = GetThumbnailCard(requestedchars[i]);
                        reply.Attachments.Add(tCard.ToAttachment());
                    }
                    await turnContext.SendActivityAsync(reply, cancellationToken);
                }
                else
                {
                    ThumbnailCard cardT = GetThumbnailCard(t1);
                    //BasicCard cardB = GetBasicCard(t1);
                    //HeroCard cardH = GetHeroCard(t1);
                    //ReceiptCard card = GetReceiptCard(t1);
                    var reply = turnContext.Activity.CreateReply();

                    reply.Attachments = new List <Attachment>
                    {
                        cardT.ToAttachment()
                    };
                    await turnContext.SendActivityAsync(reply, cancellationToken);

                    requestedchars.Add(t1);
                }
            }
            else
            {
                await turnContext.SendActivityAsync(MessageFactory.Text($"Unknown Command, try again"), cancellationToken);
            }
        }
예제 #8
0
        private async Task ResumeAfterLostFormDialog(IDialogContext context, IAwaitable <LostQuery> result)
        {
            try
            {
                var searchQuery = await result;

                var dogs = await GetDogsAsync(searchQuery);

                await context.PostAsync($"I found in total {dogs.Count()} dogs for you:");

                var resultMessage = context.MakeMessage();
                resultMessage.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                resultMessage.Attachments      = new List <Attachment>();

                foreach (var dog in dogs)
                {
                    ThumbnailCard dogCard = new ThumbnailCard()
                    {
                        Title    = $"Animal:  {dog.AnimalType}",
                        Subtitle = $"Date Found - {String.Format("{0:g}", dog.DateFound)} {Environment.NewLine} Color - {dog.Color} {Environment.NewLine} Gender - {dog.Sex}",
                        Images   = new List <CardImage>()
                        {
                            new CardImage()
                            {
                                Url = "https://i.ebayimg.com/thumbs/images/g/ResAAOSwyjBW5pty/s-l200.jpg"
                            }
                        },
                        Buttons = new List <CardAction>()
                        {
                            new CardAction()
                            {
                                Title = "Claim Dog",
                                Type  = ActionTypes.OpenUrl,
                                Value = $"http://petapihackforhumanity2018.azurewebsites.net/"
                            },
                            new CardAction()
                            {
                                Title = "More details",
                                Type  = ActionTypes.OpenUrl,
                                Value = $"http://petapihackforhumanity2018.azurewebsites.net/"
                            }
                        }
                    };

                    resultMessage.Attachments.Add(dogCard.ToAttachment());
                }

                await context.PostAsync(resultMessage);
            }
            catch (FormCanceledException ex)
            {
                string reply;

                if (ex.InnerException == null)
                {
                    reply = "You have canceled the operation";
                }
                else
                {
                    reply = $"Oops! Something went wrong :( Technical Details: {ex.InnerException.Message}";
                }

                await context.PostAsync(reply);
            }
            finally
            {
                context.Done <object>(null);
            }
        }
        protected override async Task <MessagingExtensionResponse> OnTeamsMessagingExtensionQueryAsync(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionQuery action, CancellationToken cancellationToken)
        {
            var text = action?.Parameters?[0]?.Value as string ?? string.Empty;

            var attachments        = new List <MessagingExtensionAttachment>();
            var userConfigSettings = await _userConfigProperty.GetAsync(turnContext, () => string.Empty);

            if (userConfigSettings.ToUpper().Contains("EMAIL"))
            {
                // When the Bot Service Auth flow completes, the action.State will contain a magic code used for verification.
                var magicCode = string.Empty;
                var state     = action.State;
                if (!string.IsNullOrEmpty(state))
                {
                    int parsed = 0;
                    if (int.TryParse(state, out parsed))
                    {
                        magicCode = parsed.ToString();
                    }
                }

                var tokenResponse = await(turnContext.Adapter as IUserTokenProvider).GetUserTokenAsync(turnContext, _connectionName, magicCode, cancellationToken: cancellationToken);
                if (tokenResponse == null || string.IsNullOrEmpty(tokenResponse.Token))
                {
                    // There is no token, so the user has not signed in yet.

                    // Retrieve the OAuth Sign in Link to use in the MessagingExtensionResult Suggested Actions
                    var signInLink = await(turnContext.Adapter as IUserTokenProvider).GetOauthSignInLinkAsync(turnContext, _connectionName, cancellationToken);

                    return(new MessagingExtensionResponse
                    {
                        ComposeExtension = new MessagingExtensionResult
                        {
                            Type = "auth",
                            SuggestedActions = new MessagingExtensionSuggestedAction
                            {
                                Actions = new List <CardAction>
                                {
                                    new CardAction
                                    {
                                        Type = ActionTypes.OpenUrl,
                                        Value = signInLink,
                                        Title = "Bot Service OAuth",
                                    },
                                },
                            },
                        },
                    });
                }

                var client = new SimpleGraphClient(tokenResponse.Token);

                var messages = await client.SearchMailInboxAsync(text);

                // Here we construct a ThumbnailCard for every attachment, and provide a HeroCard which will be
                // displayed if the selects that item.
                attachments = messages.Select(msg => new MessagingExtensionAttachment
                {
                    ContentType = HeroCard.ContentType,
                    Content     = new HeroCard
                    {
                        Title    = msg.From.EmailAddress.Address,
                        Subtitle = msg.Subject,
                        Text     = msg.Body.Content,
                    },
                    Preview = new ThumbnailCard
                    {
                        Title  = msg.From.EmailAddress.Address,
                        Text   = $"{msg.Subject}<br />{msg.BodyPreview}",
                        Images = new List <CardImage>()
                        {
                            new CardImage("https://raw.githubusercontent.com/microsoft/botbuilder-samples/master/docs/media/OutlookLogo.jpg", "Outlook Logo"),
                        },
                    }.ToAttachment()
                }
                                              ).ToList();
            }
            else
            {
                var packages = await FindPackages(text);

                // We take every row of the results and wrap them in cards wrapped in in MessagingExtensionAttachment objects.
                // The Preview is optional, if it includes a Tap, that will trigger the OnTeamsMessagingExtensionSelectItemAsync event back on this bot.
                attachments = packages.Select(package => {
                    var previewCard = new ThumbnailCard {
                        Title = package.Item1, Tap = new CardAction {
                            Type = "invoke", Value = package
                        }
                    };
                    if (!string.IsNullOrEmpty(package.Item5))
                    {
                        previewCard.Images = new List <CardImage>()
                        {
                            new CardImage(package.Item5, "Icon")
                        };
                    }

                    var attachment = new MessagingExtensionAttachment
                    {
                        ContentType = HeroCard.ContentType,
                        Content     = new HeroCard {
                            Title = package.Item1
                        },
                        Preview = previewCard.ToAttachment()
                    };

                    return(attachment);
                }).ToList();
            }

            // The list of MessagingExtensionAttachments must we wrapped in a MessagingExtensionResult wrapped in a MessagingExtensionResponse.
            return(new MessagingExtensionResponse
            {
                ComposeExtension = new MessagingExtensionResult
                {
                    Type = "result",
                    AttachmentLayout = "list",
                    Attachments = attachments
                }
            });
        }
예제 #10
0
        public async Task CreateOrder(IDialogContext context, IAwaitable <IMessageActivity> message, LuisResult result)
        {
            if (!await CheckForWelcome(context, message))
            {
                EntityRecommendation productRecommendation = null;
                if (result != null)
                {
                    result.TryFindEntity(EntityProductName, out productRecommendation);
                }
                var msg = await message;

                var product = result != null ? productRecommendation?.Entity : msg.Text;
                if (!string.IsNullOrWhiteSpace(product))
                {
                    if (!MemoryStorage.Products.Any(p => p.Name.ToLower().Contains(product.ToLower())))
                    {
                        await context.PostAsync($"Lo sentimos, el producto *{product}* no se encuentra en stock.");

                        context.Done <object>(null);
                    }
                    else
                    {
                        var selectedProduct =
                            MemoryStorage.Products.First(p => p.Name.ToLower().Contains(product.ToLower()));

                        PromptDialog.Confirm(
                            context,
                            AfterConfirmation,
                            $"**Confirmación pedido** \n\n" +
                            $"¿Desea comprar el producto *{selectedProduct.Name}* por un precio de **{selectedProduct.Price}€**?",
                            options: new[] { "Sí", "No" }, patterns: new string[][] { new[] { "Sí", "Confirmar", "Aceptar", "sí", "confirmar", "aceptar" }, new[] { "No", "Cancelar", "Atrás", "no", "cancelar", "atrás" } });

                        _currentOrder = new Order()
                        {
                            Product = selectedProduct.Name,
                            Date    = DateTime.Now,
                            Price   = selectedProduct.Price
                        };
                    }
                }
                else
                {
                    var reply = context.MakeMessage();
                    reply.Text             = "¿Qué te gustaría comprar? \n\n Tenemos los siguientes productos en stock:";
                    reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                    reply.Attachments      = new List <Attachment>();

                    foreach (var stockProduct in MemoryStorage.Products)
                    {
                        List <CardAction> cardButtons = new List <CardAction>();

                        CardAction plButton = new CardAction()
                        {
                            Value = $"comprar {stockProduct.Name}",
                            Type  = "postBack",
                            Title = "Comprar"
                        };

                        cardButtons.Add(plButton);

                        byte[] imageBytes = File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Content/" + stockProduct.Image));

                        ThumbnailCard plCard = new ThumbnailCard()
                        {
                            Title    = stockProduct.Name,
                            Subtitle = stockProduct.Price + "€",
                            Text     = stockProduct.Description,
                            Images   = new List <CardImage>()
                            {
                                new CardImage()
                                {
                                    Url = "data:image/png;base64," + Convert.ToBase64String(imageBytes)
                                }
                            },
                            Buttons = cardButtons
                        };

                        Attachment plAttachment = plCard.ToAttachment();
                        reply.Attachments.Add(plAttachment);
                    }

                    await context.PostAsync(reply, CancellationToken.None);

                    context.Done <object>(null);
                }
            }
        }
        protected override async Task <MessagingExtensionResponse> OnTeamsMessagingExtensionQueryAsync(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionQuery query, CancellationToken cancellationToken)
        {
            var title      = string.Empty;
            var data       = turnContext.Activity.Value;
            var titleParam = query.Parameters?.FirstOrDefault(p => (p.Name == "Documents" || p.Name == "assetTitle"));

            if (titleParam != null)
            {
                title = titleParam.Value.ToString();
            }

            var assets = await MESearchHandler.Search(query.CommandId, title, this.configuration);

            if (assets.Count == 0)
            {
                return(new MessagingExtensionResponse
                {
                    ComposeExtension = new MessagingExtensionResult
                    {
                        Type = "message",
                        Text = "No match found.",
                    },
                });
            }

            // We take every row of the results and wrap them in cards wrapped in in MessagingExtensionAttachment objects.
            // The Preview is optional, if it includes a Tap, that will trigger the OnTeamsMessagingExtensionSelectItemAsync event back on this bot.
            var attachments = assets.Select(asset =>
            {
                var previewCard = new ThumbnailCard
                {
                    Title = asset.Title
                };
                previewCard.Images = new List <CardImage>()
                {
                    new CardImage(configuration["BaseUri"] + "/Images/MSC17_cloud_006.png")
                };
                CardHelper cardhelper = new CardHelper();
                var assetCard         = cardhelper.GetAssetCard(asset);
                var attachment        = new MessagingExtensionAttachment
                {
                    ContentType = AdaptiveCards.AdaptiveCard.ContentType,
                    Content     = assetCard.Content,
                    Preview     = previewCard.ToAttachment(),
                };

                return(attachment);
            }).ToList();

            return(new MessagingExtensionResponse
            {
                ComposeExtension = new MessagingExtensionResult
                {
                    Type = "result",
                    AttachmentLayout = "list",
                    Attachments = attachments,
                },
            });

            // The list of MessagingExtensionAttachments must we wrapped in a MessagingExtensionResult wrapped in a MessagingExtensionResponse.
        }
예제 #12
0
        /// <summary>
        /// Processes an <see cref="Activity"/> of <see cref="ActivityTypes.Invoke"/> type.
        /// </summary>
        /// <param name="activity">The incoming activity from Bot Framework.</param>
        /// <returns>A <see cref="Task"/> that resolves to a <see cref="IHttpActionResult"/> with the response from the API.</returns>
        private async Task <IHttpActionResult> HandleInvokeMessageAsync(Activity activity)
        {
            if (activity.IsComposeExtensionQuery())
            {
                // Parse out the search parameters to fetch the name of the user.
                var queryData   = activity.GetComposeExtensionQueryData();
                var searchParam = "";
                if (queryData != null && queryData.Parameters != null && queryData.Parameters.Any(p => p.Name != "initialRun"))
                {
                    searchParam = queryData.Parameters.First().Value as string;
                }

                // Attempt to get all the members of the current conversation.
                var connectorClient = new ConnectorClient(new Uri(activity.ServiceUrl));
                var members         = new ChannelAccount[] { activity.From };
                try
                {
                    members = await connectorClient.Conversations.GetConversationMembersAsync(activity.Conversation.Id);
                }
                catch (UnauthorizedAccessException)
                {
                    // Swallow this exception. It happens when the messaging extension is queried in a conversation that it has no access to.
                    // We can just pretend that there are no members and return an empty result set.
                }

                // Find the service record in the global service record storage or return an empty service record.
                var records = members.Select(member =>
                {
                    var record = ServiceRecordStorage.GetServiceRecordForUserId(member.Id);
                    return(record ?? new ServiceRecord {
                        User = member.AsTeamsChannelAccount(), Losses = 0, Wins = 0, Ties = 0
                    });
                });


                // Filter records to the search parameters
                if (!string.IsNullOrWhiteSpace(searchParam))
                {
                    records = records.Where(record => record.User.Name.ToLowerInvariant().Contains(searchParam.ToLowerInvariant()));
                }

                // Create cards out of the service records.
                var cards = records.Select(record =>
                {
                    // This is the preview that shows up in the list.
                    var preview = new ThumbnailCard
                    {
                        Text = record.User.Name + " wins: " + record.Wins + " losses: " + record.Losses + " ties: " + record.Ties
                    };

                    // This is the actual card that is pasted into the chat window.
                    var attachment = new HeroCard
                    {
                        Text = record.User.Name + " wins: " + record.Wins + " losses: " + record.Losses + " ties: " + record.Ties
                    }.ToAttachment()
                    .ToComposeExtensionAttachment(preview.ToAttachment());

                    return(attachment);
                }).ToList();

                // This is the response format we must return.
                var response = new ComposeExtensionResponse
                {
                    ComposeExtension = new ComposeExtensionResult
                    {
                        AttachmentLayout = AttachmentLayoutTypes.List,
                        Type             = "result",
                        Attachments      = cards
                    }
                };
                return(Ok(response));
            }
            return(Ok());
        }
        protected override async Task <MessagingExtensionResponse> OnTeamsMessagingExtensionQueryAsync(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionQuery query, CancellationToken cancellationToken)
        {
            var queryText = string.Empty;
            var taskParam = query.Parameters?.FirstOrDefault(p => p.Name == "taskTitle");

            if (taskParam != null)
            {
                queryText = taskParam.Value.ToString();
            }
            string useremail = "Gousia Begum";
            List <TaskDataEntity> userTasksData = new List <TaskDataEntity>();

            switch (query.CommandId)
            {
            case "MyTasks":
                userTasksData = await _taskDataRepository.GetUserTasksAsync(useremail);

                break;

            case "SubscribedTasks":
                userTasksData = await _taskDataRepository.GetUserSubscribedTasksAsync(useremail);

                break;

            default:
                break;
            }

            var filteredTask = userTasksData;

            if (!string.IsNullOrEmpty(queryText))
            {
                filteredTask = userTasksData.Where(task => task.TaskName.ToLower() == queryText.ToLower() || task.TaskTitle.ToLower() == queryText.ToLower()).ToList();
            }

            if (filteredTask.Count == 0)
            {
                return(new MessagingExtensionResponse
                {
                    ComposeExtension = new MessagingExtensionResult
                    {
                        Type = "message",
                        Text = "No match found.",
                    },
                });
            }

            var taskattachments = new List <MessagingExtensionAttachment>();

            foreach (var task in filteredTask)
            {
                var previewCard = new ThumbnailCard
                {
                    Title = task.TaskName + " - " + task.TaskTitle,
                    Text  = $"Owner - {task.TaskAssignedTo}" +
                            $" ({ task.TaskStatus})",
                    Images = new List <CardImage>()
                    {
                        new CardImage {
                            Url = _configuration["BaseUri"] + "/Images/" + task.TaskPriority + ".png"
                        }
                    }
                };
                var adaptiveCard = _cardHelper.TaskInformationCard(await CreateTaskInfoFromTaskEntity(task));
                taskattachments.Add(new MessagingExtensionAttachment
                {
                    ContentType = AdaptiveCard.ContentType,
                    Content     = adaptiveCard,
                    Preview     = previewCard.ToAttachment(),
                });
            }


            // The list of MessagingExtensionAttachments must we wrapped in a MessagingExtensionResult wrapped in a MessagingExtensionResponse.
            return(new MessagingExtensionResponse
            {
                ComposeExtension = new MessagingExtensionResult
                {
                    Type = "result",
                    AttachmentLayout = "list",
                    Attachments = taskattachments
                }
            });
        }
예제 #14
0
        /// <summary>
        /// Contoso Bank Bot
        /// Greets on receiving "Hello"
        /// Returns an exchange rate card on receiving {currency code} {currency code} {amount}
        /// interacts with a database on "create/get/update/delete bank account(s) [name] [amount]
        /// </summary>

        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            if (activity.Type == ActivityTypes.Message)
            {
                MobileServiceClient mobileClient = AzureDatabaseService.AzureDatabaseServiceInstance.AzureClient;
                ConnectorClient     connector    = new ConnectorClient(new Uri(activity.ServiceUrl));
                StateClient         stateClient  = activity.GetStateClient();
                HttpClient          luisClient   = new HttpClient();
                BotData             userData     = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                string userMessage = activity.Text; //User's incoming message
                string endOutput   = "";            //Used for final reply

                //LUIS is used to determine the type of query and, for greetings/GETs, execute the method
                string luisQuery = await luisClient.GetStringAsync(new Uri("https://api.projectoxford.ai/luis/v2.0/apps/90953ceb-19de-4415-9d85-0e11a325f27f?subscription-key=46c1c462651649af974ac4ec39dfa474&q=" + userMessage)); //sends GET request to luis

                string intent = JObject.Parse(luisQuery)["topScoringIntent"]["intent"].ToString();                                                                                                                                  //deserializes json object, stores top intent as string

                if (intent.Equals("greeting"))
                {
                    //Greets user, lists commands
                    endOutput = $"Hi there, {activity.From.Name}! I'm ContosoBot, welcome to Contoso Bank! How can I help you today?";
                }

                if (intent.Equals("exchange"))
                {
                    //Calculates exchange rates between two currencies
                    double currencyDouble;
                    string fromCurrency, toCurrency, currencyString;

                    //checks if message is either a number, or two currency codes followed by a number
                    if (double.TryParse(userMessage, out currencyDouble) || double.TryParse(userMessage.Substring(8), out currencyDouble))
                    {
                        //if input is just a number, uses the previous values of currency codes and input as amount
                        if (double.TryParse(userMessage, out currencyDouble))
                        {
                            toCurrency   = userData.GetProperty <string>("toCurrencyLast");
                            fromCurrency = userData.GetProperty <string>("fromCurrencyLast");
                        }
                        else
                        {
                            //else gets currency codes and amount from substrings
                            fromCurrency   = userMessage.ToUpper().Substring(0, 3);
                            toCurrency     = userMessage.ToUpper().Substring(4, 3);
                            currencyString = userMessage.Substring(8);
                            currencyDouble = double.Parse(currencyString);

                            userData.SetProperty <string>("toCurrencyLast", toCurrency);
                            userData.SetProperty <string>("fromCurrencyLast", fromCurrency);
                            await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                        }

                        //queries the fixer.io API
                        HttpClient HttpClient  = new HttpClient();
                        string     getCurrency = await HttpClient.GetStringAsync(new Uri("http://api.fixer.io/latest?base=" + fromCurrency + "&symbols=" + toCurrency));

                        //deserializes JSON object and takes toCurrency rate
                        var rate = double.Parse(JObject.Parse(getCurrency)["rates"][toCurrency].ToString());

                        //creates thumbnail card
                        Activity thumbnailReply = activity.CreateReply();
                        thumbnailReply.Recipient   = activity.From;
                        thumbnailReply.Type        = "message";
                        thumbnailReply.Attachments = new List <Attachment>();

                        //adds contoso logo to card
                        List <CardImage> cardImage = new List <CardImage>();
                        cardImage.Add(new CardImage(url: "http://i.imgur.com/je1BEZr.png"));

                        ThumbnailCard exchangeCard = new ThumbnailCard()
                        {
                            Title    = $"{currencyDouble} {fromCurrency} = {rate * currencyDouble} {toCurrency}",
                            Subtitle = "Type another amount to use the same currencies",
                            Images   = cardImage
                        };

                        //finalises card and replies
                        Attachment cardAttachment = exchangeCard.ToAttachment();
                        thumbnailReply.Attachments.Add(cardAttachment);
                        await connector.Conversations.SendToConversationAsync(thumbnailReply);
                    }
                    else
                    {
                        //reset the exchange intent so it's processed as a normal reply, not a card reply
                        intent    = "";
                        endOutput = "The command to calculate an exchange is:\n\n\"[Original Currency Code (3)] [New Currency Code (3)] [amount]\"\n\n You may also simply enter a number to use the previous currencies";
                    }
                }

                if (intent.Equals("getAccounts"))
                {
                    //GET
                    //queries database using AzureDatabaseServices GET method, creates list of bank accounts in database
                    List <ContosoBankAccounts> bankAccountList = await AzureDatabaseService.AzureDatabaseServiceInstance.getAccounts();

                    foreach (ContosoBankAccounts bankAccount in bankAccountList)
                    {
                        endOutput += $"Bank Account = {bankAccount.id}\n\n Account Balance = ${bankAccount.balance}\n\n";
                    }
                }

                if (intent.Equals("createAccount"))
                {
                    //POST
                    //takes input of form "create bank account [name(5)] [amount]"
                    if (userMessage.ToLower().Substring(0, 19).Equals("create bank account"))
                    {
                        ContosoBankAccounts bankAccount = new ContosoBankAccounts()
                        {
                            id        = userMessage.Substring(20, 5),
                            balance   = double.Parse(userMessage.Substring(26)),
                            createdAt = DateTime.Now
                        };

                        await AzureDatabaseService.AzureDatabaseServiceInstance.addAccount(bankAccount);

                        endOutput = $"Account \"{bankAccount.id}\" created";
                    }
                    else
                    {
                        endOutput = "The command to create a bank account is:\n\n\"create bank account [id(5)] [amount]\"";
                    }
                }

                if (intent.Equals("updateAccount"))
                {
                    //PUT
                    //takes input of form "update bank account [name(5)] [amount]"
                    if (userMessage.ToLower().Substring(0, 19).Equals("update bank account"))
                    {
                        ContosoBankAccounts bankAccount = new ContosoBankAccounts()
                        {
                            id        = userMessage.Substring(20, 5),
                            balance   = double.Parse(userMessage.Substring(26)),
                            createdAt = DateTime.Now
                        };

                        await AzureDatabaseService.AzureDatabaseServiceInstance.updateAccount(bankAccount);

                        endOutput = $"Account \"{bankAccount.id}\" updated to {bankAccount.balance}";
                    }
                    else
                    {
                        endOutput = "The command to update a bank account is:\n\n\"update bank account [id(5)] [amount]\"";
                    }
                }

                if (intent.Equals("deleteAccount"))
                {
                    //DELETE
                    //takes input of form "delete bank account [name(5)]"
                    if (userMessage.ToLower().Substring(0, 19).Equals("delete bank account"))
                    {
                        ContosoBankAccounts bankAccount = new ContosoBankAccounts()
                        {
                            id = userMessage.Substring(20)
                        };

                        endOutput = $"Account \"{bankAccount.id}\" deleted";
                        await AzureDatabaseService.AzureDatabaseServiceInstance.deleteAccount(bankAccount);
                    }
                    else
                    {
                        endOutput = "The command to delete a bank account is:\n\n\"delete bank account [id(5)]\"";
                    }
                }

                if (intent.Equals("None"))
                {
                    //Catch-all for when LUIS gets confused. AGAIN.
                    endOutput = "I didn't understand that command, sorry :(";
                }

                //reply
                if (!intent.Equals("exchange"))
                {
                    Activity reply = activity.CreateReply(endOutput);
                    await connector.Conversations.ReplyToActivityAsync(reply);
                }

                //end
            }
            else
            {
                HandleSystemMessage(activity);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }