Ejemplo n.º 1
0
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <object> result)
        {
            var activity = await result as Activity;

            if (activity.Attachments.Any())
            {
                Trace.WriteLine(activity.Attachments.FirstOrDefault().ContentType);
            }

            var audioAttachment = activity.Attachments?.FirstOrDefault(a => a.ContentType.StartsWith("video"));

            if (audioAttachment != null)
            {
                await context.PostAsync($"Processing your video upload...");

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

                Debug.WriteLine(audioAttachment.ContentType);
                string fileExtension = "";
                if (audioAttachment.ContentType.EndsWith("/quicktime"))
                {
                    fileExtension = ".mov";
                }
                else if (audioAttachment.ContentType.EndsWith("mp4"))
                {
                    fileExtension = ".mp4";
                }
                else
                {
                    fileExtension = ".mp4";
                }

                var bytes = await GetAudioBytesAsync(connector, audioAttachment);

                Trace.WriteLine("Downloaded " + bytes.Length + " bytes.");
                var tempPath      = Path.GetTempPath();
                var tempVideoPath = Path.Combine(tempPath, "temp" + fileExtension);
                var tempWavPath   = Path.Combine(tempPath, "temp.wav");
                Trace.WriteLine(tempVideoPath);
                Trace.WriteLine(tempWavPath);
                File.WriteAllBytes(tempVideoPath, bytes);
                Trace.WriteLine("File saved to temp folder");
                try
                {
                    using (var process = new Process())
                    {
                        process.StartInfo.FileName        = Path.Combine(HttpContext.Current.Server.MapPath("~"), @"ffmpeg\ffmpeg.exe");
                        process.StartInfo.Arguments       = @"-i " + tempVideoPath + " " + tempWavPath;
                        process.StartInfo.UseShellExecute = false;
                        process.Start();
                        process.WaitForExit();
                        Trace.WriteLine("WAV file created.");
                    }
                }
                catch (Exception ex)
                {
                    Trace.WriteLine(ex.Message);
                    throw;
                }
                string text = string.Empty;
                using (var fileStream = File.OpenRead(tempWavPath))
                {
                    text = await this.speechService.GetTextFromAudioAsync(fileStream);

                    fileStream.Close();
                }
                File.Delete(tempVideoPath);
                File.Delete(tempWavPath);
                int speechLength = (text ?? string.Empty).Length;
                await context.PostAsync($"You said {text} which was {speechLength} characters");
            }
            else
            {
                // calculate something for us to return
                int length = (activity.Text ?? string.Empty).Length;

                Debug.WriteLine(activity.Text);
                System.Diagnostics.Trace.WriteLine(activity.Text);
                // return our reply to the user
                await context.PostAsync($"You sent {activity.Text} which was {length} characters");
            }

            context.Wait(MessageReceivedAsync);
        }
        /// <summary>
        /// Handle the incoming message
        /// </summary>
        /// <param name="msgId">message id</param>
        /// <param name="connectorClient">connector client</param>
        /// <param name="activity">activity that had the message</param>
        /// <param name="senderAadId">sender AAD id</param>
        /// <returns>Task</returns>
        public Task HandleMessage(string msgId, ConnectorClient connectorClient, Activity activity, string senderAadId)
        {
            var handler = this.messageHandlers[msgId];

            return(handler(msgId, connectorClient, activity, senderAadId));
        }
        private static async Task ApplyForLeave(IDialogContext context, Activity activity, Employee employee, string leaveCategory)
        {
            if (string.IsNullOrEmpty(employee.ManagerEmailId) && string.IsNullOrEmpty(employee.DemoManagerEmailId))
            {
                var reply = activity.CreateReply();
                reply.Text = "Please set your manager and try again.";
                reply.Attachments.Add(EchoBot.SetManagerCard());
                await context.PostAsync(reply);

                return;
            }
            var managerId = await GetManagerId(employee);

            if (managerId == null)
            {
                var reply = activity.CreateReply();
                reply.Text = "Unable to fetch your manager details. Please make sure that your manager has installed the Leave App.";
                await context.PostAsync(reply);
            }
            else
            {
                VacationDetails vacationDetails = null;
                if (activity.Name == Constants.EditLeave) // Edit request
                {
                    var editRequest = JsonConvert.DeserializeObject <EditRequest>(activity.Value.ToString());
                    vacationDetails = editRequest.data;
                }
                else
                {
                    vacationDetails = JsonConvert.DeserializeObject <VacationDetails>(activity.Value.ToString());
                }

                LeaveDetails leaveDetails;
                if (!string.IsNullOrEmpty(vacationDetails.LeaveId))
                {
                    // Edit request
                    leaveDetails = await DocumentDBRepository.GetItemAsync <LeaveDetails>(vacationDetails.LeaveId);
                }
                else
                {
                    leaveDetails         = new LeaveDetails();
                    leaveDetails.LeaveId = Guid.NewGuid().ToString();
                }
                leaveDetails.AppliedByEmailId = employee.EmailId;
                leaveDetails.EmployeeComment  = vacationDetails.LeaveReason;

                var channelData = context.Activity.GetChannelData <TeamsChannelData>();

                leaveDetails.ChannelId = channelData.Channel?.Id; // Set channel Data if request is coming from a channel.
                if (!string.IsNullOrEmpty(leaveDetails.ChannelId))
                {
                    leaveDetails.ConversationId = activity.Conversation.Id;
                }

                leaveDetails.StartDate = new LeaveDate()
                {
                    Date = DateTime.Parse(vacationDetails.FromDate),
                    Type = (DayType)Enum.Parse(typeof(DayType), vacationDetails.FromDuration)
                };
                leaveDetails.EndDate = new LeaveDate()
                {
                    Date = DateTime.Parse(vacationDetails.ToDate),
                    Type = (DayType)Enum.Parse(typeof(DayType), vacationDetails.ToDuration)
                };

                leaveDetails.LeaveType      = (LeaveType)Enum.Parse(typeof(LeaveType), vacationDetails.LeaveType);
                leaveDetails.Status         = LeaveStatus.Pending;
                leaveDetails.ManagerEmailId = employee.ManagerEmailId;// Added for easy reporting.

                switch (leaveCategory)
                {
                case Constants.ApplyForPersonalLeave:
                    leaveDetails.LeaveCategory = LeaveCategory.Personal;
                    break;

                case Constants.ApplyForSickLeave:
                    leaveDetails.LeaveCategory = LeaveCategory.Sickness;
                    break;

                case Constants.ApplyForVacation:
                    leaveDetails.LeaveCategory = LeaveCategory.Vacation;
                    break;

                case Constants.ApplyForOtherLeave:
                default:
                    leaveDetails.LeaveCategory = LeaveCategory.Other;
                    break;
                }

                if (!string.IsNullOrEmpty(vacationDetails.LeaveId))
                {
                    // Edit request
                    await DocumentDBRepository.UpdateItemAsync(leaveDetails.LeaveId, leaveDetails);
                }
                else
                {
                    await DocumentDBRepository.CreateItemAsync(leaveDetails);
                }

                var attachment = EchoBot.ManagerViewCard(employee, leaveDetails);

                UpdateMessageInfo managerMessageIds = leaveDetails.UpdateMessageInfo;

                // Manger Updates.
                var conversationId = await SendNotification(context, managerId, null, attachment, managerMessageIds.Manager, false);

                if (!string.IsNullOrEmpty(conversationId))
                {
                    managerMessageIds.Manager = conversationId;
                }

                if (!string.IsNullOrEmpty(conversationId))
                {
                    ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

                    var employeeCardReply = activity.CreateReply();
                    var employeeView      = EchoBot.EmployeeViewCard(employee, leaveDetails);
                    employeeCardReply.Attachments.Add(employeeView);

                    if (!string.IsNullOrEmpty(managerMessageIds.Employee))
                    {
                        // Update existing item.
                        await connector.Conversations.UpdateActivityAsync(employeeCardReply.Conversation.Id, managerMessageIds.Employee, employeeCardReply);
                    }
                    else
                    {
                        var reply = activity.CreateReply();
                        reply.Text = "Your leave request has been successfully submitted to your manager! Please review your details below:";
                        await context.PostAsync(reply);

                        var msgToUpdate = await connector.Conversations.ReplyToActivityAsync(employeeCardReply);

                        managerMessageIds.Employee = msgToUpdate.Id;
                    }
                }
                else
                {
                    var reply = activity.CreateReply();
                    reply.Text = "Failed to send notification to your manger. Please try again later.";
                    await context.PostAsync(reply);
                }

                await DocumentDBRepository.UpdateItemAsync(leaveDetails.LeaveId, leaveDetails);
            }
        }
Ejemplo n.º 4
0
        public async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> argument)
        {
            var message = await argument;
            //  var legal_case = "Ten years ago, my husband and I started a company and its business developed pretty well. However, since 2013, we grew conflict and seperated since then. Beforehead, the expense for me or the children are paied by my hubsband and genrally not affordable for my own. Howerer, after our seperation, this case was cut. For now I can still handle the scenario with my deposit, yet not for the future. So I want him to still hold the expense responsibility";

            var activity = (Activity)await argument;

            if (message.Text == "reset")
            {
                PromptDialog.Confirm(
                    context,
                    AfterResetAsync,
                    "Are you sure you want to reset the count?",
                    "Didn't get that!",
                    promptStyle: PromptStyle.Auto);
            }
            else if (message.Text == "Yes")
            {
                await context.PostAsync($"We can do the registration now.");

                await context.PostAsync($"What is your name?");

                context.Wait(MessageReceivedAsync);
            }
            else if (message.Text == "Charles")
            {
                await context.PostAsync($"Charles! What is your phone number?");

                context.Wait(MessageReceivedAsync);
            }
            else if (message.Text == "61234567")
            {
                await context.PostAsync($"What is your email?");

                context.Wait(MessageReceivedAsync);
            }

            /*
             * else if(message.Text == "Address Proof uploaded"){
             *  await context.PostAsync($"Received. Now maybe you would like to upload the legal case document :)  (you can upload multiple images and I will choose the last one, please type 'Document uploaded' when you finish)");
             *  context.Wait(MessageReceivedAsync);
             * }
             */
            else if (message.Text == "*****@*****.**" || message.Text == "No")
            {
                /*
                 * await context.PostAsync($"OK, we perceived it is a Civil Cases. Let me find you the best lawyer.");
                 * await context.PostAsync($"Here he is: Mr. Lam. His available time is 4pm-5pm in 25/F Queensway Government Offices. Are you available in this timeslot? If yes, I can help you to make an appointment now.  ");
                 *
                 * var replyMessage = context.MakeMessage();
                 *
                 * Attachment attachment = new Attachment
                 * {
                 *  Name = "lam.jpg",
                 *  ContentType = "image/jpg",
                 *  ContentUrl = "https://www.pakutaso.com/shared/img/thumb/N112_sorededou_TP_V.jpg"
                 * };
                 *
                 * replyMessage.Attachments = new List<Attachment> { attachment };
                 *
                 * await context.PostAsync(replyMessage);
                 */

                Activity replyToConversation = activity.CreateReply("What financial intrustment interests you the most");
                replyToConversation.Attachments = new List <Attachment>();

                AdaptiveCard card = new AdaptiveCard();

                card.Body.Add(new ChoiceSet()
                {
                    Id      = "snooze",
                    Style   = ChoiceInputStyle.Compact,
                    Choices = new List <Choice>()
                    {
                        new Choice()
                        {
                            Title = "travel", Value = "5", IsSelected = true
                        },
                        new Choice()
                        {
                            Title = "golf", Value = "15"
                        },
                        new Choice()
                        {
                            Title = "food", Value = "30"
                        },
                        new Choice()
                        {
                            Title = "wine", Value = "40"
                        },
                        new Choice()
                        {
                            Title = "hotel", Value = "50"
                        }
                    }
                });

                Attachment attachment = new Attachment()
                {
                    ContentType = AdaptiveCard.ContentType,
                    Content     = card
                };

                replyToConversation.Attachments.Add(attachment);

                var connector = new ConnectorClient(new System.Uri(message.ServiceUrl), new MicrosoftAppCredentials());

                var reply = await connector.Conversations.SendToConversationAsync(replyToConversation);

                //await context.PostAsync(reply.Id);

                context.Wait(MessageReceivedAsync);
            }
            else if (message.Text == "travel" || message.Text == "golf" || message.Text == "food" || message.Text == "wine" || message.Text == "hotel")
            {
                await context.PostAsync($"{message.Text}");
            }
        }
Ejemplo n.º 5
0
        private async Task HandleConnectorAction(IDialogContext context, Activity message)
        {
            O365ConnectorCardActionQuery o365CardQuery = message.GetO365ConnectorCardActionQueryData();
            O365ConnectorActionRequest   actionInfo    = Newtonsoft.Json.JsonConvert.DeserializeObject <O365ConnectorActionRequest>(o365CardQuery.Body);

            Activity reply = message.CreateReply();

            switch (actionInfo.Value)
            {
            case "Weather":
                reply.Attachments.Add(GetWeatherCard());
                break;

            case "OperationsDelay":
                reply.Attachments.Add(GetOperationsDelayCard());
                break;

            case "SocialEvents":
                List <Attachment> events = GetSocialEvents();
                foreach (var evnt in events)
                {
                    reply.Attachments.Add(evnt);
                }
                reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                break;

            default:
                break;
            }

            MicrosoftAppCredentials.TrustServiceUrl(message.ServiceUrl, DateTime.MaxValue);
            ConnectorClient connector = new ConnectorClient(new Uri(message.ServiceUrl));

            reply.ChannelData = new TeamsChannelData()
            {
                Notification = new NotificationInfo(true)
            };

            var lastMessageId = context.ConversationData.GetValueOrDefault <string>(actionInfo.ActionId);

            if (lastMessageId == null && privateStorage.ContainsKey(actionInfo.ActionId))
            {
                lastMessageId = privateStorage[actionInfo.ActionId];
            }
            if (!string.IsNullOrEmpty(lastMessageId))
            {
                // Update existing item.
                await connector.Conversations.UpdateActivityAsync(reply.Conversation.Id, lastMessageId, reply);

                context.ConversationData.RemoveValue(actionInfo.ActionId);
                if (privateStorage.ContainsKey(actionInfo.ActionId))
                {
                    privateStorage.Remove(actionInfo.ActionId);
                }

                // Send private messages.
                if (!string.IsNullOrEmpty(actionInfo.Members))
                {
                    // Send private message to these users.
                    var members = actionInfo.Members.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                    if (members.Any(x => x.Contains("ALL TEAM")))
                    {
                        // Provide option to send message to all members.
                        var channelData = message.GetChannelData <TeamsChannelData>();
                        if (context.ConversationData.ContainsKey(channelData.Channel.Id))
                        {
                            members = context.ConversationData.GetValue <List <string> >(channelData.Channel.Id).ToArray();
                            context.ConversationData.RemoveValue(channelData.Channel.Id);
                        }
                        else
                        {
                            IList <ChannelAccount> allMembers = await GetAllMembers(connector, channelData);

                            members = allMembers.Select(m => m.Id).ToArray();
                        }
                    }
                    foreach (var memberId in members)
                    {
                        // Create or get existing chat conversation with user
                        try
                        {
                            await SendNotification(context, reply, memberId, actionInfo.Value);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex);
                        }
                    }
                }
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Checks the given activity for a possible command.
        ///
        /// All messages that start with a specific command keyword or contain a mention of the bot
        /// ("@<bot name>") are checked for possible commands.
        /// </summary>
        /// <param name="activity">An Activity instance containing a possible command.</param>
        /// <returns>True, if a command was detected and handled. False otherwise.</returns>
        public async virtual Task <bool> HandleCommandAsync(Activity activity)
        {
            bool     wasHandled    = false;
            Activity replyActivity = null;
            Command  command       = ExtractCommand(activity);

            if (command != null)
            {
                Party senderParty = MessagingUtils.CreateSenderParty(activity);

                switch (command.BaseCommand.ToLower())
                {
                case string baseCommand when(baseCommand.Equals(Commands.CommandListOptions)):
                    // Present all command options in a card
                    replyActivity = CommandCardFactory.AddCardToActivity(
                        activity.CreateReply(), CommandCardFactory.CreateCommandOptionsCard(activity.Recipient?.Name));

                    wasHandled = true;
                    break;

                case string baseCommand when(baseCommand.Equals(Commands.CommandAddAggregationChannel)):
                    // Establish the sender's channel/conversation as an aggreated one if not already exists
                    Party aggregationPartyToAdd =
                        new Party(activity.ServiceUrl, activity.ChannelId, null, activity.Conversation);

                    if (_messageRouterManager.RoutingDataManager.AddAggregationParty(aggregationPartyToAdd))
                    {
                        replyActivity = activity.CreateReply(ConversationText.AggregationChannelSet);
                    }
                    else
                    {
                        replyActivity = activity.CreateReply(ConversationText.AggregationChannelAlreadySet);
                    }

                    wasHandled = true;
                    break;

                case string baseCommand when(baseCommand.Equals(Commands.CommandRemoveAggregationChannel)):
                    // Remove the sender's channel/conversation from the list of aggregation channels
                    if (_messageRouterManager.RoutingDataManager.IsAssociatedWithAggregation(senderParty))
                    {
                        Party aggregationPartyToRemove =
                            new Party(activity.ServiceUrl, activity.ChannelId, null, activity.Conversation);

                        if (_messageRouterManager.RoutingDataManager.RemoveAggregationParty(aggregationPartyToRemove))
                        {
                            replyActivity = activity.CreateReply(ConversationText.AggregationChannelRemoved);
                        }
                        else
                        {
                            replyActivity = activity.CreateReply(ConversationText.FailedToRemoveAggregationChannel);
                        }

                        wasHandled = true;
                    }

                    break;

                case string baseCommand when(baseCommand.Equals(Commands.CommandAcceptRequest) ||
                                             baseCommand.Equals(Commands.CommandRejectRequest)):
                    // Accept/reject conversation request
                    bool doAccept = baseCommand.Equals(Commands.CommandAcceptRequest);

                    if (_messageRouterManager.RoutingDataManager.IsAssociatedWithAggregation(senderParty))
                    {
                        // The party is associated with the aggregation and has the right to accept/reject
                        if (command.Parameters.Count == 0)
                        {
                            replyActivity = activity.CreateReply();

                            IList <Party> pendingRequests =
                                _messageRouterManager.RoutingDataManager.GetPendingRequests();

                            if (pendingRequests.Count == 0)
                            {
                                replyActivity.Text = ConversationText.NoPendingRequests;
                            }
                            else
                            {
                                replyActivity = CommandCardFactory.AddCardToActivity(
                                    replyActivity, CommandCardFactory.CreateAcceptOrRejectCardForMultipleRequests(
                                        pendingRequests, doAccept, activity.Recipient?.Name));
                            }
                        }
                        else if (!doAccept &&
                                 command.Parameters[0].Equals(Commands.CommandParameterAll))
                        {
                            if (!await new MessageRoutingUtils().RejectAllPendingRequestsAsync(
                                    _messageRouterManager, _messageRouterResultHandler))
                            {
                                replyActivity      = activity.CreateReply();
                                replyActivity.Text = ConversationText.FailedToRejectPendingRequests;
                            }
                        }
                        else
                        {
                            string errorMessage = await new MessageRoutingUtils().AcceptOrRejectRequestAsync(
                                _messageRouterManager, _messageRouterResultHandler, senderParty, doAccept, command.Parameters[0]);

                            if (!string.IsNullOrEmpty(errorMessage))
                            {
                                replyActivity      = activity.CreateReply();
                                replyActivity.Text = errorMessage;
                            }
                        }
                    }
#if DEBUG
                    // We shouldn't respond to command attempts by regular users, but I guess
                    // it's okay when debugging
                    else
                    {
                        replyActivity = activity.CreateReply(ConversationText.ConnectionRequestResponseNotAllowed);
                    }
#endif

                    wasHandled = true;
                    break;

                case string baseCommand when(baseCommand.Equals(Commands.CommandDisconnect)):
                    // End the 1:1 conversation
                    IList <MessageRouterResult> messageRouterResults = _messageRouterManager.Disconnect(senderParty);

                    foreach (MessageRouterResult messageRouterResult in messageRouterResults)
                    {
                        await _messageRouterResultHandler.HandleResultAsync(messageRouterResult);
                    }

                    wasHandled = true;
                    break;


                    #region Implementation of debugging commands
#if DEBUG
                case string baseCommand when(baseCommand.Equals(Commands.CommandDeleteAllRoutingData)):
                    // DELETE ALL ROUTING DATA
                    replyActivity = activity.CreateReply(ConversationText.DeletingAllData);

                    _messageRouterManager.RoutingDataManager.DeleteAll();
                    wasHandled = true;
                    break;

                case string baseCommand when(baseCommand.Equals(Commands.CommandList)):
                    bool listAll = command.Parameters.Contains(Commands.CommandParameterAll);

                    replyActivity = activity.CreateReply();
                    string replyMessageText = string.Empty;

                    if (listAll || command.Parameters.Contains(Commands.CommandParameterParties))
                    {
                        // List user and bot parties
                        IRoutingDataManager routingDataManager = _messageRouterManager.RoutingDataManager;
                        string partiesAsString = PartyListToString(routingDataManager.GetUserParties());

                        replyMessageText += string.IsNullOrEmpty(partiesAsString)
                                ? $"{ConversationText.NoUsersStored}{StringAndCharConstants.LineBreak}"
                                : $"{ConversationText.Users}:{StringAndCharConstants.LineBreak}{partiesAsString}{StringAndCharConstants.LineBreak}";

                        partiesAsString = PartyListToString(routingDataManager.GetBotParties());

                        replyMessageText += string.IsNullOrEmpty(partiesAsString)
                                ? $"{ConversationText.NoBotsStored}{StringAndCharConstants.LineBreak}"
                                : $"{ConversationText.Bots}:{StringAndCharConstants.LineBreak}{partiesAsString}{StringAndCharConstants.LineBreak}";

                        wasHandled = true;
                    }

                    if (listAll || command.Parameters.Contains(Commands.CommandParameterRequests))
                    {
                        // List all pending requests
                        IList <Attachment> attachments =
                            CommandCardFactory.CreateMultipleRequestCards(
                                _messageRouterManager.RoutingDataManager.GetPendingRequests(), activity.Recipient?.Name);

                        if (attachments.Count > 0)
                        {
                            replyMessageText += string.Format(ConversationText.PendingRequestsFoundWithCount, attachments.Count);
                            replyMessageText += StringAndCharConstants.LineBreak;
                            replyActivity.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                            replyActivity.Attachments      = attachments;
                        }
                        else
                        {
                            replyMessageText += $"{ConversationText.NoPendingRequests}{StringAndCharConstants.LineBreak}";
                        }

                        wasHandled = true;
                    }

                    if (listAll || command.Parameters.Contains(Commands.CommandParameterConnections))
                    {
                        // List all connections (conversations)
                        string connectionsAsString = _messageRouterManager.RoutingDataManager.ConnectionsToString();

                        replyMessageText += string.IsNullOrEmpty(connectionsAsString)
                                ? $"{ConversationText.NoConversations}{StringAndCharConstants.LineBreak}"
                                : $"{connectionsAsString}{StringAndCharConstants.LineBreak}";

                        wasHandled = true;
                    }

                    if (listAll || command.Parameters.Contains(Commands.CommandParameterResults))
                    {
                        // List all logged message router results
                        string resultsAsString = _messageRouterManager.RoutingDataManager.GetLastMessageRouterResults();

                        replyMessageText += string.IsNullOrEmpty(resultsAsString)
                                ? $"{ConversationText.NoResults}{StringAndCharConstants.LineBreak}"
                                : $"{resultsAsString}{StringAndCharConstants.LineBreak}";

                        wasHandled = true;
                    }

                    if (!wasHandled)
                    {
                        replyMessageText = ConversationText.InvalidOrMissingCommandParameter;
                    }

                    replyActivity.Text = replyMessageText;
                    break;
#endif
                    #endregion

                default:
                    replyActivity = activity.CreateReply(string.Format(ConversationText.CommandNotRecognized, command.BaseCommand));
                    break;
                }

                if (replyActivity != null)
                {
                    ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
                    await connector.Conversations.ReplyToActivityAsync(replyActivity);
                }
            }

            return(wasHandled);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            CheckNews    news    = new CheckNews();
            CheckWeather weather = new CheckWeather();
            Prompting    prompts = new Prompting();
            Enquiry      Enquiry = new Enquiry();

            if (activity.Type == ActivityTypes.Message)
            {
                Luis.StockLUIS stLuis = await Luis.LUISStockClient.ParseUserInput(activity.Text);

                string strRet = " ";
                int    len    = 0;


                // Get the stateClient to get/set Bot Data
                //StateClient _stateClient = activity.GetStateClient();
                //BotData _botData = _stateClient.BotState.GetUserData(activity.Type, activity.Text); ;

                //data base connection
                string connectionString = "";
                connectionString = "Data Source=VISHWANATH\\SQLSERVER2014;Initial Catalog=Bot_db;Integrated Security=true;User ID=Vishwanath; Password = "******"Dialogs":
                    string[] dialog = { "wassuup..!!", "Hello there... how can i help you??", "hello... i'm here to help you" };
                    strRet = dialog[new Random().Next(0, dialog.Length)];
                    break;

                case "Intro":
                    string[] Intro = { "I'm xxx.You ask anything related to career guidance and apart from that you can get trending news and weather forecast. What's your name?", "Hey..!!!!.I'm xxx.Nice to meet you. You can get career-related information.By the way what's your name.", "I'm the best bot you can ever have" };
                    strRet = Intro[new Random().Next(0, Intro.Length)];
                    break;

                case "NormalConvo":
                    string[] Convo = { "Don't worry..we will solve it together.", "Tell me what's worrying you", "I guess I can solve it" };
                    strRet = Convo[new Random().Next(0, Convo.Length)];
                    break;

                case "User":
                    string   name = stLuis.entities[0].entity;
                    string[] user = { "Heyy " + name + " what can I do ", "wasupp? " + name + " how are you doin?" };
                    strRet = user[new Random().Next(0, user.Length)];
                    break;

                case "End_Convo":
                    string[] endConvo = { "It was nice talking to you. I hope this would be helpful.", "I would be glad if this helps you in choosing the right path", "I am happy, if this conversation would be of any help in choosing correct path for your career.All the best, hope you achieve great things ahead." };
                    strRet = endConvo[new Random().Next(0, endConvo.Length)];
                    break;

                case "News":
                    await news.getNews();

                    Activity reply2 = activity.CreateReply("News:");
                    reply2.Attachments      = new List <Attachment>();
                    reply2.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                    for (int i = 0; i < 10; i++)
                    {
                        reply2.Attachments.Add(
                            new HeroCard
                        {
                            Title    = news.title[i],
                            Subtitle = news.desc[i],
                            Images   = new List <CardImage> {
                                new CardImage(url: news.urlToImage[i])
                            },
                            Buttons = new List <CardAction> {
                                new CardAction()
                                {
                                    Value = news.url[i],
                                    Type  = "openUrl",
                                    Title = "More"
                                }
                            }
                        }.ToAttachment()
                            );
                    }

                    await connector.Conversations.ReplyToActivityAsync(reply2);

                    break;

                case "Weather":
                    string result = stLuis.entities[0].entity;
                    string strWea = await weather.getWeather(result);

                    string[] words    = strWea.Split(',');
                    Activity reply1   = activity.CreateReply("weather:");
                    string   subTitle = "Temperature (celcius): " + words[0] + "  \n" + "Condition: " + words[1] + "  \n" + "Humidity: " + words[3];
                    reply1.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                    HeroCard card = new HeroCard()
                    {
                        Title    = "Current Weather",
                        Subtitle = subTitle,
                        Images   = new List <CardImage> {
                            new CardImage(url: "https:" + words[2])
                        }
                    };
                    reply1.Attachments = new List <Attachment> {
                        card.ToAttachment( )
                    };
                    await connector.Conversations.ReplyToActivityAsync(reply1);

                    break;

                case "Course":
                    string fields = stLuis.entities[0].entity.ToLower();
                    //for (int i = 0; i < 2; i++)
                    if (stLuis.entities[1].type.ToLower() == "field")
                    {
                        fields = stLuis.entities[1].entity.ToLower();
                    }
                    con.Open();
                    cmd = new SqlCommand("select Course,Course_Desc,Years,Url from Courses where Field = '" + fields + "'", con);
                    dr  = cmd.ExecuteReader();
                    string[] Course      = new string[30];
                    string[] Course_Desc = new string[30];
                    string[] Years       = new string[30];
                    string[] Url1        = new string[30];
                    while (dr.Read())
                    {
                        Course[len]      = "" + dr["Course"];
                        Course_Desc[len] = "" + dr["Course_Desc"];
                        Years[len]       = "" + dr["Years"];
                        Url1[len]        = "" + dr["Url"];
                        len++;
                    }
                    dr.Close();
                    cmd.Dispose();
                    con.Close();
                    Activity reply5 = activity.CreateReply();
                    reply5.Attachments      = new List <Attachment>();
                    reply5.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                    for (int i = 0; i < len; i++)
                    {
                        reply5.Attachments.Add(
                            new ThumbnailCard
                        {
                            Title    = Course[i],
                            Subtitle = Course_Desc[i] + "-" + Years[i],
                            Images   = new List <CardImage>
                            {
                                new CardImage
                                {
                                    Url = Url1[i],
                                }
                            },
                        }.ToAttachment()
                            );
                    }
                    await connector.Conversations.ReplyToActivityAsync(reply5);

                    //}

                    /*catch (IndexOutOfRangeException e)
                     * {
                     *  strRet = "Ummm...can you specify in the following format 'Courses in field name' without any typos.";
                     * }*/

                    break;

                case "Specialization":
                    string fieldss = "";
                    try
                    {
                        for (int i = 0; i < 2; i++)
                        {
                            if (stLuis.entities[i].type.ToLower() == "field")
                            {
                                fieldss = stLuis.entities[i].entity.ToLower();
                            }
                        }
                        con.Open();
                        cmd = new SqlCommand("select Specialization,S_Desc, Url from Specializations where Field = '" + fieldss + "'", con);
                        dr  = cmd.ExecuteReader();
                        string[] Specialization = new string[34];
                        string[] S_Desc         = new string[34];
                        string[] Url            = new string[34];
                        Activity reply4         = activity.CreateReply(" ");
                        reply4.Attachments      = new List <Attachment>();
                        reply4.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                        while (dr.Read())
                        {
                            Specialization[len] = "" + dr["Specialization"];
                            S_Desc[len]         = "" + dr["S_Desc"];
                            Url[len]            = "" + dr["Url"];
                            len++;
                        }
                        dr.Close();
                        cmd.Dispose();
                        con.Close();
                        for (int i = 0; i < len; i++)
                        {
                            reply4.Attachments.Add(
                                new ThumbnailCard
                            {
                                Title    = Specialization[i],
                                Subtitle = S_Desc[i],
                                Images   = new List <CardImage>
                                {
                                    new CardImage
                                    {
                                        Url = Url[i],
                                    }
                                },
                            }.ToAttachment()
                                );
                        }
                        await connector.Conversations.ReplyToActivityAsync(reply4);
                    }
                    catch (IndexOutOfRangeException e)
                    {
                        strRet = "Ummm...can you specify in the following format 'Specialization in field name' without any typos.";
                    }
                    break;

                case "Exams":
                    string field = stLuis.entities[0].entity.ToLower();
                    //for (int i = 0; i < 2; i++)
                    if (stLuis.entities[1].type.ToLower() == "field")
                    {
                        field = stLuis.entities[1].entity.ToLower();
                    }
                    con.Open();
                    cmd = new SqlCommand("select Exam_Name,Exam_Desc from Exams where Exam_ID IN (select Exam_ID from UG_Fields where Field = '" + field + "') ", con);
                    dr  = cmd.ExecuteReader();
                    string[] Exam_Name = new string[7];
                    string[] Exam_Desc = new string[7];
                    Activity reply3    = activity.CreateReply(" ");
                    reply3.Attachments      = new List <Attachment>();
                    reply3.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                    while (dr.Read())
                    {
                        Exam_Name[len] = "" + dr["Exam_Name"];
                        Exam_Desc[len] = "" + dr["Exam_Desc"];
                        len++;
                    }
                    dr.Close();
                    cmd.Dispose();
                    con.Close();
                    for (int i = 0; i < len; i++)
                    {
                        reply3.Attachments.Add(
                            new ThumbnailCard
                        {
                            Title    = Exam_Name[i],
                            Subtitle = Exam_Desc[i],
                            Images   = new List <CardImage>
                            {
                                new CardImage
                                {
                                    Url = $"http://d2cyt36b7wnvt9.cloudfront.net/100marks/wp-content/uploads/2015/12/15151818/Entrance-exams.jpg"
                                }
                            },
                        }.ToAttachment()
                            );
                    }
                    await connector.Conversations.ReplyToActivityAsync(reply3);

                    break;

                case "Career":
                    await Conversation.SendAsync(activity, () => new RootDialog());

                    break;

                case "None":
                    strRet = "I think you are going off topic. I can help you with career, news and weather. Please ask any queries related to this. ";
                    break;

                default:
                    string worriedFace = "\U0001F61F";
                    strRet = "Sorry, I am not getting you..." + worriedFace;
                    break;
                }
                if (strRet != " ")
                {
                    // return our reply to the user
                    Activity reply = activity.CreateReply(strRet);
                    await connector.Conversations.ReplyToActivityAsync(reply);
                }
            }
            else
            {
                HandleSystemMessage(activity);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
Ejemplo n.º 8
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UserIntractionHandler"/> class.
 /// </summary>
 /// <param name="connector">Connector to User</param>
 /// <param name="activity">User Activity</param>
 public UserIntractionHandler(ConnectorClient connector, Activity activity)
 {
     this.connector = connector;
     this.activity  = activity;
 }
        private async Task HandleSystemMessageAsync(Activity message, ConnectorClient connectorClient, CancellationToken cancellationToken)
        {
            if (message.Type == ActivityTypes.DeleteUserData)
            {
                // Implement user deletion here
                // If we handle user deletion, return a real message
            }
            else if (message.Type == ActivityTypes.ConversationUpdate)
            {
                // This shows how to send a welcome message in response to a conversationUpdate event

                // We're only interested in member added events
                if (message.MembersAdded?.Count > 0)
                {
                    // Determine if the bot was added to the team/conversation
                    var botId       = message.Recipient.Id;
                    var botWasAdded = message.MembersAdded.Any(member => member.Id == botId);

                    // Create the welcome message to send
                    Activity welcomeMessage = message.CreateReply();
                    welcomeMessage.Text = Strings.BotWelcomeMessage;

                    if (!(message.Conversation.IsGroup ?? false))
                    {
                        // 1:1 conversation event

                        // If the user hasn't received a first-run message yet, then send a message to the user
                        // introducing your bot and what it can do. Do NOT send this blindly, as your bot can receive
                        // spurious conversationUpdate events, especially if you use proactive messaging.
                        using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, message))
                        {
                            var address      = Address.FromActivity(message);
                            var botDataStore = scope.Resolve <IBotDataStore <BotData> >();
                            var botData      = await botDataStore.LoadAsync(address, BotStoreType.BotUserData, cancellationToken);

                            if (!botData.GetProperty <bool>("IsFreSent"))
                            {
                                await connectorClient.Conversations.ReplyToActivityWithRetriesAsync(welcomeMessage, cancellationToken);

                                // Remember that we sent the welcome message already
                                botData.SetProperty("IsFreSent", true);
                                await botDataStore.SaveAsync(address, BotStoreType.BotUserData, botData, cancellationToken);
                            }
                            else
                            {
                                // First-run message has already been sent, so skip sending it again.
                                // Do not remove the check for IsFreSent above. Your bot can receive spurious conversationUpdate
                                // activities from chat service, so if you always respond to all of them, you will send random
                                // welcome messages to users who have already received the welcome.
                            }
                        }
                    }
                    else
                    {
                        // Not 1:1 chat event (bot or user was added to a team or group chat)
                        if (botWasAdded)
                        {
                            // Bot was added to the team
                            // Send a message to the team's channel, introducing your bot and what you can do
                            await connectorClient.Conversations.ReplyToActivityWithRetriesAsync(welcomeMessage, cancellationToken);
                        }
                        else
                        {
                            // Other users were added to the team/conversation
                        }
                    }
                }
            }
            else if (message.Type == ActivityTypes.ContactRelationUpdate)
            {
                // Handle add/remove from contact lists
                // Activity.From + Activity.Action represent what happened
            }
            else if (message.Type == ActivityTypes.Typing)
            {
                // Handle knowing that the user is typing
            }
            else if (message.Type == ActivityTypes.Ping)
            {
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

            if (activity == null || activity.GetActivityType() != ActivityTypes.Message)
            {
                //add code to handle errors, or non-messaging activities
            }

            const string apiKey   = "674880b753de4d16b4ce1af12790392b";
            string       queryUri = "https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/keyPhrases";

            HttpClient client = new HttpClient();

            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", apiKey);
            client.DefaultRequestHeaders.Add("Accept", "application/json");
            BatchInput phraseInput = new BatchInput();

            phraseInput.documents = new List <DocumentInput>();
            phraseInput.documents.Add(new DocumentInput()
            {
                id   = 1,
                text = activity.Text
            });

            var phraseJsonInput = JsonConvert.SerializeObject(phraseInput);

            byte[] byteData = Encoding.UTF8.GetBytes(phraseJsonInput);
            var    content  = new ByteArrayContent(byteData);

            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            var phrasePost = await client.PostAsync(queryUri, content);

            var phraseRawResponse = await phrasePost.Content.ReadAsStringAsync();

            var phraseJsonResponse = JsonConvert.DeserializeObject <BatchResult>(phraseRawResponse);

            string[] keyPhrases = phraseJsonResponse.documents[0].keyPhrases;

            var diseases = GetDiseases(keyPhrases);


            var replyMessage = activity.CreateReply();

            replyMessage.Recipient = activity.From;
            replyMessage.Type      = ActivityTypes.Message;

            if (diseases.Count > 0)
            {
                replyMessage.Text = "I think you might have ";
                foreach (var disease in diseases)
                {
                    if (replyMessage.Text != "I think you might have ")
                    {
                        replyMessage.Text += " or ";
                    }
                    replyMessage.Text += disease.Issue.Name;
                }
            }
            else
            {
                replyMessage.Text = "Your symptoms don't match any known diseases.";
            }

            //if (sentimentScore > 0.9)
            //{
            //    replyMessage.Text = $"This appears quite positive to me.";
            //}
            //else if (sentimentScore < 0.1)
            //{
            //    replyMessage.Text = $"This appears quite negative to me.";
            //}
            //else
            //{
            //    replyMessage.Text = $"I can not decipher the sentiment here.  Please try again or add more information.";
            //}

            await connector.Conversations.ReplyToActivityAsync(replyMessage);

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

            return(response);
        }
Ejemplo n.º 11
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();
                ConnectorClient connector   = new ConnectorClient(new Uri(activity.ServiceUrl));
                StateClient     stateClient = activity.GetStateClient();
                BotData         userData    = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                //Activity thereply = activity.CreateReply(activity.From.Name);
                //await connector.Conversations.ReplyToActivityAsync(thereply);
                try
                {
                    var account = new AccountEntity {
                        Name = activity.Text
                    };
                    var replyString    = "";
                    var userMessage    = activity.Text;
                    var accountManager = new AccountManager();
                    var authUser       = await accountManager.CheckValidation(activity.From.Id);

                    //var authUser = await accountManager.CheckValidation("109906983001699");
                    //created data

                    //var transaction = new TransactionState();
                    //userData.SetProperty<TransactionState>("TransactionAsk", transaction);
                    var transaction = userData.GetProperty <TransactionState>("TransactionAsk");
                    if (transaction == null)
                    {
                        transaction = new TransactionState();
                    }
                    if (userMessage.ToLower().Contains("cancel"))
                    {
                        transaction = new TransactionState();
                        replyString = "I have cancelled your transaction, did you need anything else?";
                        userData.SetProperty <TransactionState>("TransactionAsk", transaction);
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                    }



                    if (authUser != null)
                    {
                        if (userMessage.ToLower().Contains("view"))
                        {
                            //Activity replyToConversation = activity.CreateReply("");
                            //replyToConversation.Recipient = activity.From;
                            //replyToConversation.Type = "message";
                            //replyToConversation.Attachments = new List<Attachment>();
                            //////////////////////

                            //List<CardAction> receiptList = new List<CardAction>();
                            //// List<ReceiptItem> receiptList = new List<ReceiptItem>();


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

                            if (userMessage.ToLower().Contains("transactions"))
                            {
                                replyString = "Here are your transactions.";
                                var collection = await accountManager.ViewTransactions(authUser, 5);

                                foreach (TransactionEntity userTransaction in collection)
                                {
                                    string deposit = "";
                                    if (userTransaction.Deposit)
                                    {
                                        deposit = "deposited";
                                    }
                                    else
                                    {
                                        deposit = "withdrawn";
                                    }

                                    replyString += $"\n\n {userTransaction.Date}: ${userTransaction.Amount} was {deposit} \n\n {userTransaction.Description} \n - - - \n";
                                    //CardAction lineItem = new CardAction()
                                    //{
                                    //    Title = $"{userTransaction.Date}: ${userTransaction.Amount} was {deposit} \n\n {userTransaction.Description} ",
                                    //};
                                    //receiptList.Add(lineItem);
                                }
                            }
                            if (userMessage.ToLower().Contains("accounts"))
                            {
                                replyString = "Here are your accounts.";
                                var collection = await accountManager.ViewAccounts(authUser);

                                foreach (AccountEntity userAccount in collection)
                                {
                                    replyString += $"\n\n {userAccount.Name} - Balance: {userAccount.Balance.ToString("c")}\n - - - \n";
                                    //ReceiptItem lineItem = new ReceiptItem()
                                    //{
                                    //    Title = $"{userAccount.Name} "
                                    //};
                                    ////receiptList.Add(lineItem);
                                }
                            }
                            if (userMessage.ToLower().Contains("payees"))
                            {
                                replyString = "Here are your payees.";
                                var collection = await accountManager.ViewPayee(authUser);

                                foreach (PayeeEntity userAccount in collection)
                                {
                                    replyString += $"\n\n {userAccount.Name}\n - - - \n";
                                    //ReceiptItem lineItem = new ReceiptItem()
                                    //{
                                    //    Title = $"{userAccount.Name} "
                                    //};
                                    ////receiptList.Add(lineItem);
                                }
                            }

                            //HeroCard plCard = new HeroCard()
                            //{
                            //    Title = "Transactions",
                            //    Buttons = receiptList
                            //};
                            //replyString = "";
                            //Attachment plAttatchment = plCard.ToAttachment();
                            //replyToConversation.Attachments.Add(plAttatchment);

                            //await connector.Conversations.SendToConversationAsync(replyToConversation);
                        }
                        else if (userData.GetProperty <bool>("currencyAsk"))
                        {
                            var inputs = userMessage.Split();
                            if (inputs.Length == 4)
                            {
                                var    currencyToConvert = Convert.ToDouble(inputs[0]);
                                string x = await client.GetStringAsync(new Uri("http://api.fixer.io/latest?base=" + inputs[1]));


                                RootObject rootObject = JsonConvert.DeserializeObject <RootObject>(x);
                                string     secondCurr = inputs[3];
                                double     finalrate  = 1;
                                if (secondCurr.ToLower() == "aud")
                                {
                                    finalrate = rootObject.rates.AUD;
                                }
                                else if (secondCurr.ToLower() == "bgn")
                                {
                                    finalrate = rootObject.rates.BGN;
                                }
                                else if (secondCurr.ToLower() == "brl")
                                {
                                    finalrate = rootObject.rates.BRL;
                                }
                                else if (secondCurr.ToLower() == "cad")
                                {
                                    finalrate = rootObject.rates.CAD;
                                }
                                else if (secondCurr.ToLower() == "chf")
                                {
                                    finalrate = rootObject.rates.CHF;
                                }
                                else if (secondCurr.ToLower() == "cny")
                                {
                                    finalrate = rootObject.rates.CNY;
                                }
                                else if (secondCurr.ToLower() == "czk")
                                {
                                    finalrate = rootObject.rates.CZK;
                                }
                                else if (secondCurr.ToLower() == "dkk")
                                {
                                    finalrate = rootObject.rates.DKK;
                                }
                                else if (secondCurr.ToLower() == "gbp")
                                {
                                    finalrate = rootObject.rates.GBP;
                                }
                                else if (secondCurr.ToLower() == "hkd")
                                {
                                    finalrate = rootObject.rates.HKD;
                                }
                                else if (secondCurr.ToLower() == "hrk")
                                {
                                    finalrate = rootObject.rates.HRK;
                                }
                                else if (secondCurr.ToLower() == "huf")
                                {
                                    finalrate = rootObject.rates.HUF;
                                }
                                else if (secondCurr.ToLower() == "idr")
                                {
                                    finalrate = rootObject.rates.IDR;
                                }
                                else if (secondCurr.ToLower() == "ils")
                                {
                                    finalrate = rootObject.rates.ILS;
                                }
                                else if (secondCurr.ToLower() == "inr")
                                {
                                    finalrate = rootObject.rates.INR;
                                }
                                else if (secondCurr.ToLower() == "jpy")
                                {
                                    finalrate = rootObject.rates.JPY;
                                }
                                else if (secondCurr.ToLower() == "krw")
                                {
                                    finalrate = rootObject.rates.KRW;
                                }
                                else if (secondCurr.ToLower() == "mxn")
                                {
                                    finalrate = rootObject.rates.MXN;
                                }
                                else if (secondCurr.ToLower() == "myr")
                                {
                                    finalrate = rootObject.rates.MYR;
                                }
                                else if (secondCurr.ToLower() == "nok")
                                {
                                    finalrate = rootObject.rates.NOK;
                                }
                                else if (secondCurr.ToLower() == "nzd")
                                {
                                    finalrate = rootObject.rates.NZD;
                                }
                                else if (secondCurr.ToLower() == "php")
                                {
                                    finalrate = rootObject.rates.PHP;
                                }
                                else if (secondCurr.ToLower() == "pln")
                                {
                                    finalrate = rootObject.rates.PLN;
                                }
                                else if (secondCurr.ToLower() == "ron")
                                {
                                    finalrate = rootObject.rates.RON;
                                }
                                else if (secondCurr.ToLower() == "rub")
                                {
                                    finalrate = rootObject.rates.RUB;
                                }
                                else if (secondCurr.ToLower() == "sek")
                                {
                                    finalrate = rootObject.rates.SEK;
                                }
                                else if (secondCurr.ToLower() == "sgd")
                                {
                                    finalrate = rootObject.rates.SGD;
                                }
                                else if (secondCurr.ToLower() == "thb")
                                {
                                    finalrate = rootObject.rates.THB;
                                }
                                else if (secondCurr.ToLower() == "try")
                                {
                                    finalrate = rootObject.rates.TRY;
                                }
                                else if (secondCurr.ToLower() == "usd")
                                {
                                    finalrate = rootObject.rates.USD;
                                }
                                else if (secondCurr.ToLower() == "zar")
                                {
                                    finalrate = rootObject.rates.ZAR;
                                }
                                double finalAmount = currencyToConvert * finalrate;
                                replyString = $"${currencyToConvert} {inputs[1]} will give you ${Math.Round(finalAmount,2)} in {secondCurr}. ";
                            }
                            else
                            {
                                replyString = "I could not convert those currencies";
                            }


                            userData.SetProperty <bool>("currencyAsk", false);
                            await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                        }
                        else if (userMessage.ToLower().Contains("currency") | userMessage.ToLower().Contains("exchange"))
                        {
                            userData.SetProperty <bool>("currencyAsk", true);
                            await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                            replyString = "How much and what type of currency do you want to exchange?";
                        }
                        else if (transaction.finalisedBool)
                        {
                            if (userMessage.ToLower().Contains("confirm"))
                            {
                                await accountManager.ProcessTransaction(transaction);

                                replyString = "Transaction has been processed";

                                transaction = new TransactionState();
                                userData.SetProperty <TransactionState>("TransactionAsk", transaction);
                                await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                            }
                        }
                        else if (transaction.descriptionBool)
                        {
                            if (userMessage.ToLower() == "no" | userMessage.ToLower() == "no thanks" | userMessage.ToLower() == "nah" | userMessage.ToLower() == "no thank you")
                            {
                                userMessage = "Sent from Contoso BankBot";
                            }

                            transaction.finalisedBool   = true;
                            transaction.descriptionBool = false;
                            transaction.DescriptionInfo = userMessage;
                            userData.SetProperty <TransactionState>("TransactionAsk", transaction);
                            await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);



                            Activity replyToConversation = activity.CreateReply("Does this look correct?");
                            replyToConversation.Recipient   = activity.From;
                            replyToConversation.Type        = "message";
                            replyToConversation.Attachments = new List <Attachment>();

                            //List<CardImage> cardImages = new List<CardImage>();
                            //cardImages.Add(new CardImage(url: "Contoso.png"));

                            List <CardAction> cardButtons   = new List <CardAction>();
                            CardAction        confirmButton = new CardAction()
                            {
                                Value = "Confirm",
                                Type  = "postBack",
                                Title = "Confirm"
                            };
                            cardButtons.Add(confirmButton);
                            CardAction cancelButton = new CardAction()
                            {
                                Value = "cancel",
                                Type  = "postBack",
                                Title = "Cancel"
                            };
                            cardButtons.Add(cancelButton);
                            var recieverAccount = await accountManager.CheckValidAccount(transaction.RecieverAccountId);

                            var senderAccount = await accountManager.CheckValidAccount(transaction.SenderAccountId);

                            string toReply = "";

                            toReply += $"\n\n From: {senderAccount.Name}";
                            toReply += $"\n\n To: {recieverAccount.Name}";
                            toReply += $"\n\n Amount: ${transaction.Amount.ToString()}";
                            toReply += $"\n\n Description: {transaction.DescriptionInfo}";
                            Activity reply = activity.CreateReply(toReply);
                            await connector.Conversations.ReplyToActivityAsync(reply);

                            //ReceiptItem lineItem1 = new ReceiptItem()
                            //{
                            //    Title = "From: ",
                            //    Subtitle = senderAccount.Name
                            //};
                            //ReceiptItem lineItem2 = new ReceiptItem()
                            //{
                            //    Title = "To: ",
                            //    Subtitle = recieverAccount.Name
                            //};
                            //ReceiptItem lineItem3 = new ReceiptItem()
                            //{
                            //    Title = "Amount: ",
                            //    Subtitle = $"${transaction.Amount.ToString()}"
                            //};
                            //ReceiptItem lineItem4 = new ReceiptItem()
                            //{
                            //    Title = "Transaction Description: ",
                            //    Subtitle = transaction.DescriptionInfo
                            //};
                            //List<ReceiptItem> receiptList = new List<ReceiptItem>();

                            //receiptList.Add(lineItem1);
                            //receiptList.Add(lineItem2);
                            //receiptList.Add(lineItem3);
                            //receiptList.Add(lineItem4);

                            HeroCard plCard = new HeroCard()
                            {
                                Buttons = cardButtons
                            };


                            replyString = "";
                            Attachment plAttatchment = plCard.ToAttachment();
                            replyToConversation.Attachments.Add(plAttatchment);


                            await connector.Conversations.SendToConversationAsync(replyToConversation);

                            //    //Means we have asked if they want a description
                            //    //if they say no create a default transaction
                            //    //if they have implimented a description then throw that in there
                            //    //the calculation is then done subtracting from reciever and sending to sender, creating a transaction and whatnot
                        }

                        else if (transaction.amountBool)
                        {
                            account = await accountManager.CheckValidAccount(transaction.SenderAccountId);

                            bool   fail       = false;
                            double userAmount = 0;
                            try
                            {
                                userAmount = Convert.ToDouble(userMessage);
                            }
                            catch
                            {
                                fail        = true;
                                replyString = "I can only deal with numbers at the moment. Could you try again with a valid number";
                            }
                            if (fail == false)
                            {
                                if (userAmount > account.Balance)
                                {
                                    replyString = $"Sorry, you don't have enough money to make that transaction. you only have ${account.Balance}. Please try again.";
                                }
                                else
                                {
                                    replyString = "Okay awesome, what kind of description do you want? If you don't want one just say no and I can make one for you";

                                    transaction.amountBool      = false;
                                    transaction.descriptionBool = true;
                                    transaction.Amount          = userAmount;
                                    userData.SetProperty <TransactionState>("TransactionAsk", transaction);
                                    await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                                }
                            }
                            //    //Means we have asked how much they want to transfer
                            //    //If user selects a valid amount then ask if the user wants to add a description
                            //    //
                        }
                        else if (transaction.senderBool)
                        {
                            var validAccount = await accountManager.CheckAccount(authUser, userMessage);

                            if (validAccount != null)
                            {
                                replyString = "Awesome, how much would you like to transfer?";

                                transaction.senderBool      = false;
                                transaction.amountBool      = true;
                                transaction.SenderAccountId = validAccount.Id;
                                userData.SetProperty <TransactionState>("TransactionAsk", transaction);
                                await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                            }
                            else
                            {
                                replyString = "Sorry something went wrong, please cancel and try again";
                            }
                            //if(sender == true)
                            //{
                            //    //means we have asked what account they want to use
                            //    //If user selects valid account then ask the amount to transfer  (Maybe put in how much they currently have)
                            //    //If not valid then same as above
                        }

                        else if (transaction.recieverBool)
                        {
                            //Means we have asked for account.
                            //If user gives us valid account then we should ask for what account they want to use
                            //if user does not give us a valid account then either ask again or terminate??
                            var possiblePayee = await accountManager.CheckValidPayee(authUser, userMessage);

                            if (possiblePayee != null)
                            {
                                userMessage = possiblePayee.AccountNumber;
                            }

                            var validAccount = await accountManager.CheckValidAccount(userMessage);

                            if (validAccount != null)
                            {
                                Activity cardReply = activity.CreateReply("What account would you like to use?");
                                cardReply.Recipient   = activity.From;
                                cardReply.Type        = "message";
                                cardReply.Attachments = new List <Attachment>();

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

                                replyString = "";
                                var list = _context.Accounts.Where(x => x.UserId == authUser.Id);

                                foreach (AccountEntity blah in list)
                                {
                                    CardAction plButton = new CardAction()
                                    {
                                        Type  = "postBack",
                                        Title = $"${blah.Balance} | {blah.Name}   ",
                                        Value = blah.Name
                                    };
                                    actions.Add(plButton);
                                }

                                HeroCard plcard = new HeroCard()
                                {
                                    Buttons = actions
                                };

                                Attachment plAttatchment = plcard.ToAttachment();
                                cardReply.Attachments.Add(plAttatchment);
                                await connector.Conversations.SendToConversationAsync(cardReply);

                                transaction.senderBool        = true;
                                transaction.recieverBool      = false;
                                transaction.RecieverAccountId = validAccount.Id;
                                userData.SetProperty <TransactionState>("TransactionAsk", transaction);
                                await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                            }
                            else
                            {
                                replyString = "Sorry, that is not a valid account";
                            }
                        }


                        else if (userMessage.Contains("create account"))
                        {
                            var newAccount = accountManager.CreateAccount(authUser, "savings");
                            if (newAccount != null)
                            {
                                Activity creationReply = activity.CreateReply($"Account with number { newAccount.Name} has been created to the user {authUser.Name}");
                                await connector.Conversations.ReplyToActivityAsync(creationReply);
                            }
                            else
                            {
                                Activity creationReply = activity.CreateReply("Something went wrong when creating the account");
                                await connector.Conversations.ReplyToActivityAsync(creationReply);
                            }
                        }

                        else if (userMessage.ToLower().Contains("hello") | userMessage.ToLower().Contains("hey"))
                        {
                            if (userData.GetProperty <bool>("greeted"))
                            {
                                replyString = "Hello there again, What can I do for you this time?";
                            }
                            else
                            {
                                replyString = "Hello, Welcome to the Contoso Bank. How can I help you?";
                                userData.SetProperty <bool>("greeted", true);
                                await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                            }
                        }
                        else if (userMessage.Contains("make a transaction"))
                        {
                            transaction = new TransactionState {
                                recieverBool = true
                            };
                            replyString = "Please enter an account or payee to make a transaction to";
                            if (userMessage.Length >= 22)
                            {
                                if (userMessage.Contains("make a transaction to "))
                                {
                                    var array = userMessage.Substring(22).Split();
                                    if (array.Length >= 1)
                                    {
                                        var possiblePayee = await accountManager.CheckValidPayee(authUser, array[0]);

                                        if (possiblePayee != null)
                                        {
                                            var possibleAccount = await accountManager.CheckValidAccount(possiblePayee.AccountNumber);

                                            if (possibleAccount != null)
                                            {
                                                transaction.recieverBool      = true;
                                                transaction.RecieverAccountId = possibleAccount.Id;
                                                replyString = "Please press enter ";
                                            }
                                            else
                                            {
                                                replyString = "Sorry, I couldn't find that payees account. Please enter a valid account number";
                                            }
                                            //do it with the users input
                                        }
                                        else
                                        {
                                            var possibleAccount = await accountManager.CheckValidAccount(possiblePayee.AccountNumber);

                                            if (possibleAccount != null)
                                            {
                                                transaction.recieverBool      = false;
                                                transaction.senderBool        = true;
                                                transaction.RecieverAccountId = possibleAccount.Id;
                                            }
                                            else
                                            {
                                                replyString = "Sorry, I couldn't find that account. Please enter a valid account number";
                                            }
                                            //do it with possiblepayee.accountname t
                                            //possiblePayee.ac
                                        }
                                    }
                                }
                            }

                            userData.SetProperty <TransactionState>("TransactionAsk", transaction);
                            await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                        }


                        if (userMessage.Length >= 12)
                        {
                            if (userMessage.Substring(0, 12).ToLower().Equals("set a payee "))
                            {
                                var array = userMessage.Substring(12).Split();
                                if (array.Length == 0)
                                {
                                    replyString = "Please enter a name and account number";
                                }
                                else if (array.Length == 1)
                                {
                                    if (array[0].Substring(0, 3).Equals("43-"))
                                    {
                                        //Throw in states
                                        replyString = "Please enter a name and account number";
                                    }
                                    else
                                    {
                                        replyString = "Please enter a name and account number";
                                    };
                                }
                                else if (array.Length >= 2)
                                {
                                    var payee = await accountManager.CreatePayee(authUser, array[0], array[1]);

                                    replyString = $"Payee {payee.Name} was succesfully saved";
                                }
                            }
                        }
                        if (userMessage.Length >= 13)
                        {
                            if (userMessage.Substring(0, 13).ToLower().Equals("remove payee "))
                            {
                                var array = userMessage.Substring(13).Split();
                                if (array.Length == 0)
                                {
                                    replyString = "Please specify also specify a payee to remove";
                                }
                                else if (array.Length >= 1)
                                {
                                    var removedPayee = await accountManager.RemovePayee(authUser, array[0]);

                                    if (removedPayee != null)
                                    {
                                        replyString = $"Payee {removedPayee.Name} has been removed.";
                                    }
                                    else
                                    {
                                        replyString = $"Payee with the name {array[0]} could not be found.";
                                    }
                                }
                            }
                        }
                    }
                    //--------------------
                    else
                    {
                        if (userData.GetProperty <bool>("AskedAccount"))
                        {
                            if (userMessage.ToLower().Contains("ye"))
                            {
                                await accountManager.CreateUser(activity.From.Name, activity.From.Id);

                                //await accountManager.CreateUser("Robert Bryson Hall", "109906983001699");
                                userData.SetProperty <bool>("AskedAccount", false);
                                await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

                                replyString = "Okay cool, we've got you in the system now. What do you want to do?";
                            }
                            else if (userMessage.ToLower().Contains("no"))
                            {
                                replyString = "Sorry, but you are unable to access our services without an account";
                                userData.SetProperty <bool>("AskedAccount", false);
                                await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                            }
                            else
                            {
                                replyString = "Sorry, I didn't catch that";
                            }
                        }
                        else
                        {
                            replyString = "You are not authorized to the bank, would you like to create an account?";
                            userData.SetProperty <bool>("AskedAccount", true);
                            await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                        }
                    }

                    if (replyString != "")
                    {
                        Activity reply = activity.CreateReply(replyString);
                        await connector.Conversations.ReplyToActivityAsync(reply);
                    }
                    else
                    {
                    }
                    // calculate something for us to return



                    //await _context.SaveChangesAsync();
                    // return our reply to the user
                }
                catch (Exception e)
                {
                    Activity reply = activity.CreateReply(e.Message);
                    await connector.Conversations.ReplyToActivityAsync(reply);
                }
            }
            else
            {
                HandleSystemMessage(activity);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
Ejemplo n.º 12
0
        private async Task HandleInvoke(IDialogContext context, IMessageActivity message)
        {
            var activity        = (Activity)message;
            var connectorClient = new ConnectorClient(new Uri(activity.ServiceUrl));
            //string savedMessageId;
            // Get O365 connector card query data.
            O365ConnectorCardActionQuery o365CardQuery = activity.GetO365ConnectorCardActionQueryData();
            AirCraftDetails actionInfo    = Newtonsoft.Json.JsonConvert.DeserializeObject <AirCraftDetails>(o365CardQuery.Body);
            Activity        replyActivity = activity.CreateReply();


            switch (o365CardQuery.ActionId)
            {
            case Constants.Assignaircraft:
                AirCraftDetails assignairCraftInfo = Newtonsoft.Json.JsonConvert.DeserializeObject <AirCraftDetails>(o365CardQuery.Body);


                await AttachAssignairCraft(assignairCraftInfo, replyActivity);

                break;

            case Constants.MarkGrounded:
                AirCraftDetails groundedAirCraftInfo = Newtonsoft.Json.JsonConvert.DeserializeObject <AirCraftDetails>(o365CardQuery.Body);

                await MarkGroundedAirCraft(groundedAirCraftInfo, replyActivity);

                break;

            case Constants.Available:
                AirCraftDetails freeAirCraftInfo = Newtonsoft.Json.JsonConvert.DeserializeObject <AirCraftDetails>(o365CardQuery.Body);

                await MarkFreeAirCraft(freeAirCraftInfo, replyActivity);

                break;

            default:
                break;
            }



            var lastMessageId = context.ConversationData.GetValueOrDefault <string>(actionInfo.ActionId);

            if (lastMessageId == null && privateStorage.ContainsKey(actionInfo.ActionId))
            {
                lastMessageId = privateStorage[actionInfo.ActionId];
            }
            if (!string.IsNullOrEmpty(lastMessageId))
            {
                // Update existing item.
                await connectorClient.Conversations.UpdateActivityAsync(replyActivity.Conversation.Id, lastMessageId, replyActivity);

                context.ConversationData.RemoveValue(actionInfo.ActionId);
                //if (privateStorage.ContainsKey(Actionid))
                //    privateStorage.Remove(Actionid);
            }
            else
            {
                await connectorClient.Conversations.SendToConversationAsync(replyActivity);
            }
        }
Ejemplo n.º 13
0
        public virtual async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            if (activity != null)
            {
                try
                {
                    IConversationUpdateActivity update = activity;
                    var client = new ConnectorClient(new Uri(activity.ServiceUrl), new MicrosoftAppCredentials());
                    activity.Recipient.Name = Resources.ChatBot.BotName;

                    // one of these will have an interface and process it
                    switch (activity.GetActivityType())
                    {
                    case ActivityTypes.Message:

                        //var messageHandler = Task.Run(() => Conversation.SendAsync(activity, () => new ExceptionHandlerDialog<object>(new RootDialog(), displayException: true)));
                        //messageHandler.Wait();
                        //var replyRunning = activity.CreateReply();
                        //if (messageHandler.Status == TaskStatus.Running) {
                        //}
                        //if (messageHandler.IsCompleted) {
                        //    await client.Conversations.ReplyToActivityAsync(replyRunning);
                        //    //var reply = activity.CreateReply();
                        //    //reply.Text = "Task Completed";
                        //    //await client.Conversations.ReplyToActivityAsync(reply);
                        //}

                        await Conversation.SendAsync(activity, () => new ExceptionHandlerDialog <object>(new RootDialog(), displayException : false));

                        break;

                    case ActivityTypes.ConversationUpdate:
                        if (activity.MembersAdded.Any(x => x.Id == activity.Recipient.Id))
                        {
                            ThumbnailCard     plCard      = new ThumbnailCard();
                            List <CardAction> cardButtons = new List <CardAction>();

                            cardButtons.Add(new CardAction {
                                Title = "FAQ", Type = ActionTypes.ImBack, Value = "FAQ"
                            });
                            cardButtons.Add(new CardAction {
                                Title = "Retailer Finder", Type = ActionTypes.ImBack, Value = "Retailer Finder"
                            });

                            plCard.Images = new List <CardImage> {
                                new CardImage {
                                    Url = string.Format(@"{0}/{1}", this.Url.Request.RequestUri.AbsoluteUri.Replace(@"api/messages", ""), "Images/PurinaChatBot.png")
                                }
                            };
                            plCard.Text    = Resources.ChatBot.WelcomeMessage;
                            plCard.Buttons = cardButtons;

                            var reply = activity.CreateReply();
                            reply.Attachments.Add(plCard.ToAttachment());

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

                    case ActivityTypes.ContactRelationUpdate:
                    case ActivityTypes.Typing:
                    //var typingReply = activity.CreateReply();
                    //typingReply.Text = "Typing...";
                    //await client.Conversations.ReplyToActivityAsync(typingReply);
                    //break;
                    case ActivityTypes.DeleteUserData:
                    default:
                        Trace.TraceError($"Unknown activity type ignored: {activity.GetActivityType()}");
                        break;
                    }
                }
                catch (Exception ex)
                {
                    //var exReply = activity.CreateReply(ex.Message);
                    //await client.Conversations.ReplyToActivityAsync(exReply);
                }
            }

            return(new HttpResponseMessage(System.Net.HttpStatusCode.Accepted));
        }
Ejemplo n.º 14
0
        /// <summary>
        /// On Teams Messaging Extension Submit Action Async.
        /// </summary>
        /// <param name="turnContext">turnContext.</param>
        /// <param name="action">action.</param>
        /// <param name="cancellationToken">cancellationToken.</param>
        /// <returns>.</returns>
        protected override async Task <MessagingExtensionActionResponse> OnTeamsMessagingExtensionSubmitActionAsync(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken)
        {
            _telemetry.TrackEvent("OnTeamsMessagingExtensionSubmitActionAsync");
            ReflectionDataRepository reflectionDataRepository = new ReflectionDataRepository(_configuration, _telemetry);

            try
            {
                TaskInfo taskInfo = JsonConvert.DeserializeObject <TaskInfo>(action.Data.ToString());
                switch (taskInfo.action)
                {
                case "reflection":
                    return(await OnTeamsMessagingExtensionFetchTaskAsync(turnContext, action, cancellationToken));

                case "sendAdaptiveCard":
                    try
                    {
                        var name = (turnContext.Activity.From.Name).Split();
                        taskInfo.postCreateBy       = name[0] + ' ' + name[1];
                        taskInfo.postCreatedByEmail = await _dbHelper.GetUserEmailId(turnContext);

                        taskInfo.channelID        = turnContext.Activity.TeamsGetChannelId();
                        taskInfo.postSendNowFlag  = (taskInfo.executionTime == "Send now") ? true : false;
                        taskInfo.IsActive         = true;
                        taskInfo.questionRowKey   = Guid.NewGuid().ToString();
                        taskInfo.recurrsionRowKey = Guid.NewGuid().ToString();
                        taskInfo.reflectionRowKey = Guid.NewGuid().ToString();
                        taskInfo.serviceUrl       = turnContext.Activity.ServiceUrl;
                        taskInfo.teantId          = turnContext.Activity.Conversation.TenantId;
                        taskInfo.scheduleId       = Guid.NewGuid().ToString();
                        await _dbHelper.SaveReflectionDataAsync(taskInfo);

                        if (taskInfo.postSendNowFlag == true)
                        {
                            var typingActivity = MessageFactory.Text(string.Empty);
                            typingActivity.Type = ActivityTypes.Typing;
                            await turnContext.SendActivityAsync(typingActivity);

                            var adaptiveCard = _cardHelper.CreateNewReflect(taskInfo);
                            var message      = MessageFactory.Attachment(new Attachment {
                                ContentType = AdaptiveCard.ContentType, Content = adaptiveCard
                            });
                            var resultid = await turnContext.SendActivityAsync(message, cancellationToken);

                            ReflectionDataEntity reflectData = await reflectionDataRepository.GetReflectionData(taskInfo.reflectionID);

                            reflectData.ReflectMessageId = resultid.Id;
                            await reflectionDataRepository.InsertOrMergeAsync(reflectData);

                            try
                            {
                                var feedbackCard = _cardHelper.FeedBackCard(new Dictionary <int, List <FeedbackDataEntity> >(), taskInfo.reflectionID, taskInfo.question);

                                Attachment attachmentfeedback = new Attachment()
                                {
                                    ContentType = AdaptiveCard.ContentType,
                                    Content     = feedbackCard,
                                };
                                using var connector = new ConnectorClient(new Uri(reflectData.ServiceUrl), _configuration["MicrosoftAppId"], _configuration["MicrosoftAppPassword"]);

                                var conversationId = $"{reflectData.ChannelID};messageid={reflectData.ReflectMessageId}";
                                var replyActivity  = MessageFactory.Attachment(new Attachment {
                                    ContentType = AdaptiveCard.ContentType, Content = feedbackCard
                                });
                                replyActivity.Conversation = new ConversationAccount(id: conversationId);
                                var resultfeedback = await connector.Conversations.SendToConversationAsync((Activity)replyActivity, cancellationToken);

                                reflectData.MessageID = resultfeedback.Id;
                                // update messageid in reflection table
                                await reflectionDataRepository.InsertOrMergeAsync(reflectData);
                            }
                            catch (System.Exception e)
                            {
                                _telemetry.TrackException(e);
                                Console.WriteLine(e.Message.ToString());
                            }
                        }
                        return(null);
                    }
                    catch (Exception ex)
                    {
                        _telemetry.TrackException(ex);
                        return(null);
                    }

                case "ManageRecurringPosts":
                    var postCreatedByEmail = await _dbHelper.GetUserEmailId(turnContext);

                    var response = new MessagingExtensionActionResponse()
                    {
                        Task = new TaskModuleContinueResponse()
                        {
                            Value = new TaskModuleTaskInfo()
                            {
                                Height = 600,
                                Width  = 780,
                                Title  = "Make space for people to share how they feel",
                                Url    = this._configuration["BaseUri"] + "/ManageRecurringPosts/" + postCreatedByEmail + "?pathfromindex=true"
                            },
                        },
                    };
                    return(response);

                case "OpenDetailfeedback":
                    var responsefeedback = new MessagingExtensionActionResponse()
                    {
                        Task = new TaskModuleContinueResponse()
                        {
                            Value = new TaskModuleTaskInfo()
                            {
                                Height = 600,
                                Width  = 780,
                                Title  = "Make space for people to share how they feel",
                                Url    = this._configuration["BaseUri"] + "/openReflectionFeedback/" + taskInfo.reflectionID + "/" + taskInfo.feedback,
                            },
                        },
                    };
                    return(responsefeedback);

                case "removeposts":
                    try
                    {
                        var activity = Activity.CreateMessageActivity();
                        if (taskInfo.isDelete)
                        {
                            var messageId = await _dbHelper.RemoveReflectionId(taskInfo.messageID);

                            if (messageId != null)
                            {
                                await turnContext.DeleteActivityAsync(messageId);
                            }
                            await turnContext.DeleteActivityAsync(taskInfo.messageID);

                            activity.Text = "This Reflect poll has been removed";
                            await turnContext.SendActivityAsync(activity);

                            return(null);
                        }
                        else
                        {
                            return(null);
                        }
                    }
                    catch (Exception ex)
                    {
                        _telemetry.TrackException(ex);
                        return(null);
                    }

                default:
                    return(null);
                }
                ;
            }
            catch (Exception ex)
            {
                _telemetry.TrackException(ex);
                return(null);
            }
        }
Ejemplo n.º 15
0
        public Attachment getAttachmentFromDialog(DialogList dlg, Activity activity)
        {
            Attachment      returnAttachment = new Attachment();
            ConnectorClient connector        = new ConnectorClient(new Uri(activity.ServiceUrl));

            if (dlg.dlgType.Equals(MessagesController.TEXTDLG))
            {
                if (!activity.ChannelId.Equals("facebook"))
                {
                    UserHeroCard plCard = new UserHeroCard()
                    {
                        Title   = dlg.cardTitle,
                        Text    = dlg.cardText,
                        Gesture = dlg.gesture
                    };
                    returnAttachment = plCard.ToAttachment();
                }
            }
            else if (dlg.dlgType.Equals(MessagesController.MEDIADLG))
            {
                string cardDiv = "";
                string cardVal = "";

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

                HistoryLog("CARD IMG START");
                if (dlg.mediaUrl != null)
                {
                    HistoryLog("FB CARD IMG " + dlg.mediaUrl);
                    cardImages.Add(new CardImage(url: dlg.mediaUrl));
                }


                HistoryLog("CARD BTN1 START");
                if (activity.ChannelId.Equals("facebook") && dlg.btn1Type == null && !string.IsNullOrEmpty(dlg.cardDivision) && dlg.cardDivision.Equals("play") && !string.IsNullOrEmpty(dlg.cardValue))
                {
                    CardAction plButton = new CardAction();
                    plButton = new CardAction()
                    {
                        Value = dlg.cardValue,
                        Type  = "openUrl",
                        Title = "영상보기"
                    };
                    cardButtons.Add(plButton);
                }
                else if (dlg.btn1Type != null)
                {
                    CardAction plButton = new CardAction();
                    plButton = new CardAction()
                    {
                        Value = dlg.btn1Context,
                        Type  = dlg.btn1Type,
                        Title = dlg.btn1Title
                    };
                    cardButtons.Add(plButton);
                }

                if (dlg.btn2Type != null)
                {
                    if (!(activity.ChannelId == "facebook" && dlg.btn2Title == "나에게 맞는 모델 추천"))
                    {
                        CardAction plButton = new CardAction();
                        HistoryLog("CARD BTN2 START");
                        plButton = new CardAction()
                        {
                            Value = dlg.btn2Context,
                            Type  = dlg.btn2Type,
                            Title = dlg.btn2Title
                        };
                        cardButtons.Add(plButton);
                    }
                }

                if (dlg.btn3Type != null)
                {
                    CardAction plButton = new CardAction();

                    HistoryLog("CARD BTN3 START");
                    plButton = new CardAction()
                    {
                        Value = dlg.btn3Context,
                        Type  = dlg.btn3Type,
                        Title = dlg.btn3Title
                    };
                    cardButtons.Add(plButton);
                }

                if (dlg.btn4Type != null)
                {
                    CardAction plButton = new CardAction();
                    HistoryLog("CARD BTN4 START");
                    plButton = new CardAction()
                    {
                        Value = dlg.btn4Context,
                        Type  = dlg.btn4Type,
                        Title = dlg.btn4Title
                    };
                    cardButtons.Add(plButton);
                }

                if (!string.IsNullOrEmpty(dlg.cardDivision))
                {
                    cardDiv = dlg.cardDivision;
                }

                if (!string.IsNullOrEmpty(dlg.cardValue))
                {
                    //cardVal = priceMediaDlgList[i].cardValue.Replace();
                    cardVal = dlg.cardValue;
                }
                HistoryLog("!!!!!FB CARD BTN1 START channelID.Equals(facebook) && cardButtons.Count < 1 && cardImages.Count < 1");
                HeroCard plCard = new UserHeroCard();
                if (activity.ChannelId == "facebook" && string.IsNullOrEmpty(dlg.cardTitle))
                {
                    HistoryLog("FB CARD BTN1 START channelID.Equals(facebook) && string.IsNullOrEmpty(card.cardTitle)");
                    plCard = new UserHeroCard()
                    {
                        Title         = "선택해 주세요",
                        Text          = dlg.cardText,
                        Images        = cardImages,
                        Buttons       = cardButtons,
                        Card_division = cardDiv,
                        Card_value    = cardVal
                    };
                    returnAttachment = plCard.ToAttachment();
                }
                else if (activity.ChannelId == "facebook" && string.IsNullOrEmpty(dlg.cardValue))
                {
                    HistoryLog("FB CARD BTN1 START channelID.Equals(facebook) && string.IsNullOrEmpty(card.cardValue)");
                    plCard = new UserHeroCard()
                    {
                        Title   = dlg.cardTitle,
                        Images  = cardImages,
                        Buttons = cardButtons
                    };
                    returnAttachment = plCard.ToAttachment();
                }
                else
                {
                    HistoryLog("!!!!!!!!FB CARD BTN1 START channelID.Equals(facebook) && string.IsNullOrEmpty(card.cardTitle)");
                    plCard = new UserHeroCard()
                    {
                        Title         = dlg.cardTitle,
                        Text          = dlg.cardText,
                        Images        = cardImages,
                        Buttons       = cardButtons,
                        Card_division = cardDiv,
                        Card_value    = cardVal
                    };
                    returnAttachment = plCard.ToAttachment();
                }
            }
            else
            {
                Debug.WriteLine("Dialog Type Error : " + dlg.dlgType);
            }
            return(returnAttachment);
        }
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity, CancellationToken cancellationToken)
        {
            var connectorClient = new ConnectorClient(new Uri(activity.ServiceUrl));

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

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

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

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

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

                    await connectorClient.Conversations.ReplyToActivityAsync(replyActivity);

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

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

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

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

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

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

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

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

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

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

                    await Conversation.SendAsync(messageActivity, () => new Dialogs.RootDialog());

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

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

            return(response);
        }
Ejemplo n.º 17
0
        public Attachment getAttachmentFromDialog(CardList card, Activity activity)
        {
            ConnectorClient connector        = new ConnectorClient(new Uri(activity.ServiceUrl));
            Attachment      returnAttachment = new Attachment();

            string cardDiv = "";
            string cardVal = "";

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

            HistoryLog("CARD IMG START");
            if (card.imgUrl != null)
            {
                HistoryLog("FB CARD IMG " + card.imgUrl);
                cardImages.Add(new CardImage(url: card.imgUrl));
            }


            HistoryLog("CARD BTN1 START");


            if (activity.ChannelId.Equals("facebook") && card.btn1Type == null && !string.IsNullOrEmpty(card.cardDivision) && card.cardDivision.Equals("play") && !string.IsNullOrEmpty(card.cardValue))
            {
                CardAction plButton = new CardAction();
                plButton = new CardAction()
                {
                    Value = card.cardValue,
                    Type  = "openUrl",
                    Title = "영상보기"
                };
                cardButtons.Add(plButton);
            }
            else if (card.btn1Type != null)
            {
                CardAction plButton = new CardAction();
                plButton = new CardAction()
                {
                    Value = card.btn1Context,
                    Type  = card.btn1Type,
                    Title = card.btn1Title
                };
                cardButtons.Add(plButton);
            }

            if (card.btn2Type != null)
            {
                CardAction plButton = new CardAction();
                HistoryLog("CARD BTN2 START");
                plButton = new CardAction()
                {
                    Value = card.btn2Context,
                    Type  = card.btn2Type,
                    Title = card.btn2Title
                };
                cardButtons.Add(plButton);
            }

            if (card.btn3Type != null)
            {
                CardAction plButton = new CardAction();

                HistoryLog("CARD BTN3 START");
                plButton = new CardAction()
                {
                    Value = card.btn3Context,
                    Type  = card.btn3Type,
                    Title = card.btn3Title
                };
                cardButtons.Add(plButton);
            }

            if (card.btn4Type != null)
            {
                CardAction plButton = new CardAction();
                HistoryLog("CARD BTN4 START");
                plButton = new CardAction()
                {
                    Value = card.btn4Context,
                    Type  = card.btn4Type,
                    Title = card.btn4Title
                };
                cardButtons.Add(plButton);
            }



            if (!string.IsNullOrEmpty(card.cardDivision))
            {
                cardDiv = card.cardDivision;
            }

            if (!string.IsNullOrEmpty(card.cardValue))
            {
                //cardVal = priceMediaDlgList[i].cardValue.Replace();
                cardVal = card.cardValue;
            }


            if (activity.ChannelId.Equals("facebook") && cardButtons.Count < 1 && cardImages.Count < 1)
            {
                HistoryLog("FB CARD BTN1 START channelID.Equals(facebook) && cardButtons.Count < 1 && cardImages.Count < 1");
                Activity reply_facebook = activity.CreateReply();
                reply_facebook.Recipient = activity.From;
                reply_facebook.Type      = "message";
                HistoryLog("facebook  card Text : " + card.cardText);
                reply_facebook.Text = card.cardText;
                var reply_ment_facebook = connector.Conversations.SendToConversationAsync(reply_facebook);
            }
            else
            {
                HistoryLog("!!!!!FB CARD BTN1 START channelID.Equals(facebook) && cardButtons.Count < 1 && cardImages.Count < 1");
                HeroCard plCard = new UserHeroCard();
                if (activity.ChannelId == "facebook" && string.IsNullOrEmpty(card.cardValue))
                {
                    HistoryLog("FB CARD BTN1 START channelID.Equals(facebook) && string.IsNullOrEmpty(card.cardValue)");
                    plCard = new UserHeroCard()
                    {
                        Title   = card.cardTitle,
                        Images  = cardImages,
                        Buttons = cardButtons,
                        Gesture = card.gesture //2018-04-24 : 제스처 추가
                    };
                    returnAttachment = plCard.ToAttachment();
                }
                else
                {
                    HistoryLog("!!!!!!!FB CARD BTN1 START channelID.Equals(facebook) && string.IsNullOrEmpty(card.cardValue)");
                    if (activity.ChannelId == "facebook" && string.IsNullOrEmpty(card.cardTitle))
                    {
                        HistoryLog("FB CARD BTN1 START channelID.Equals(facebook) && string.IsNullOrEmpty(card.cardTitle)");
                        plCard = new UserHeroCard()
                        {
                            Title         = "선택해 주세요",
                            Text          = card.cardText,
                            Images        = cardImages,
                            Buttons       = cardButtons,
                            Card_division = cardDiv,
                            Card_value    = cardVal,
                            Gesture       = card.gesture //2018-04-24 : 제스처 추가
                        };
                        returnAttachment = plCard.ToAttachment();
                    }
                    else
                    {
                        HistoryLog("!!!!!!!!FB CARD BTN1 START channelID.Equals(facebook) && string.IsNullOrEmpty(card.cardTitle)");
                        plCard = new UserHeroCard()
                        {
                            Title         = card.cardTitle,
                            Text          = card.cardText,
                            Images        = cardImages,
                            Buttons       = cardButtons,
                            Card_division = cardDiv,
                            Card_value    = cardVal,
                            Gesture       = card.gesture //2018-04-24 : 제스처 추가
                        };
                        returnAttachment = plCard.ToAttachment();
                    }
                }
            }

            //HeroCard plCard = new UserHeroCard()
            //{
            //    Title = card.cardTitle,
            //    Text = card.cardText,
            //    Images = cardImages,
            //    Buttons = cardButtons,
            //    Card_division = cardDiv,
            //    Card_value = cardVal
            //};
            //returnAttachment = plCard.ToAttachment();

            return(returnAttachment);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            StateClient stateClient = activity.GetStateClient();
            BotData     userData    = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

            if (activity.Type == ActivityTypes.Message)
            {
                ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
                // holds response to displayto user
                string answer = "I'm sorry. I didn't understand that. Try: \"What can we cook for dinner?\" or  \"What ingredients are we missing?\"";

                Rootobject luisObj = await LUISClient.ParseUserInput(activity.Text);

                if (luisObj.intents.Length > 0)
                {
                    switch (luisObj.intents[0].intent) // assumption: first intent is highest score
                    {
                    case "":
                        answer = "I'm sorry. I didn't understand that. You can add and remove ingredients from your list or try to find a recipe!";
                        break;

                    case "greeting":
                        answer = "Hello! Feeling hungry and adventurous? You can add and remove ingredients from your list or try to find a recipe! Ask for help and more examples!";
                        break;

                    case "help":
                        // populate the commands and examples
                        var commandList = "";
                        var commandHelp = new string[6];
                        commandHelp[0] = "Add ingredients: \"Add milk, butter and eggs to my list.\"\n";
                        commandHelp[1] = "Remove ingredients: \"Remove butter and eggs from my list.\"\n";
                        commandHelp[2] = "Show your ingredients list: \"Please show me my list.\"\n";
                        commandHelp[3] = "Start a new list: \"Start a new list.\" or \"Clear my list.\"\n";
                        commandHelp[4] = "Find a recipe: \"What can we cook tonight?\"\n";
                        commandHelp[5] = "Show your missing ingredients: \"What ingredients are we missing?\"\n";

                        // add the commands to the answer string to be displayed
                        for (int i = 0; i < commandHelp.Length; i++)
                        {
                            commandList += (i + 1) + ". " + commandHelp[i] + '\n';
                        }

                        answer = "Here are the actions you can do with examples: \n" + commandList;
                        break;

                    case "addList":
                        // add ingredient(s) to the list
                        // create array to hold entities
                        string[] items = new string[luisObj.entities.Length];

                        // parse the entities and pass in
                        for (int i = 0; i < luisObj.entities.Length; i++)
                        {
                            items[i] = luisObj.entities[i].entity;
                        }

                        // Store the values into a local text file
                        var IngredientsListAdd = new StateList();
                        IngredientsListAdd.AddIngredients(items);

                        answer = "Successfully added ingredients.";
                        break;

                    case "removeList":
                        // remove ingredient(s) to the list
                        // create array to hold entities
                        string[] removeItems = new string[luisObj.entities.Length];

                        // parse the entities and pass in
                        for (int i = 0; i < luisObj.entities.Length; i++)
                        {
                            removeItems[i] = luisObj.entities[i].entity;
                        }

                        // Remove the values from the local text file
                        var IngredientsListRemove = new StateList();
                        IngredientsListRemove.RemoveIngredients(removeItems);

                        answer = "Successfully removed ingredients.";
                        break;

                    case "newList":
                        // clear the current list to start new
                        var IngredientsListClear = new StateList();
                        IngredientsListClear.clearIngredients();

                        answer = "Successfully cleared the ingredients list. Add more ingredients back!";
                        break;

                    case "displayList":
                        // read current ingredients list
                        var IngredientsListRead = new StateList();
                        var list      = IngredientsListRead.ReadIngredients();
                        var listItems = "";

                        // check if list is currently empty
                        if (list.Length == 0)
                        {
                            answer = "Your list is currently empty. Add more ingredients!";
                            break;
                        }

                        for (int i = 0; i < list.Length; i++)
                        {
                            listItems += (i + 1) + ". " + list[i] + '\n';
                        }

                        answer = "You currently have: \n" + listItems;
                        break;

                    case "findRecipe":
                        // read current ingredients list
                        var IngredientsListAPI = new StateList();
                        var arg = IngredientsListAPI.ReadIngredients();

                        // empty list check
                        if (arg.Length == 0)
                        {
                            answer = "It looks like your ingredients list is empty. Try adding some ingredients then searching for a recipe!";
                            break;
                        }

                        var API_arg = "I have";
                        for (int i = 0; i < arg.Length; i++)
                        {
                            if ((i + 1) == arg.Length)
                            {
                                // last item in array
                                API_arg += " " + arg[i];
                            }
                            else
                            {
                                API_arg += " " + arg[i] + ",";
                            }
                        }

                        var caller = new CallAPI();

                        if (!caller.isLimitHit())
                        {
                            // Initialize recipeResult to hold json info
                            // Call first API to obtain recipe from ingredients
                            var recipeResult = new JsonRecipe();
                            recipeResult = caller.GetRecipe(API_arg);


                            // Initialize recipeResult to hold json info
                            // Call second API to obtain recipe link from recipeId
                            var recipeLink = new JsonLink();
                            recipeLink = caller.GetLink(recipeResult.id.ToString());


                            // reply back to user with the recipe options
                            Activity replyMessage        = activity;
                            Activity replyToConversation = replyMessage.CreateReply("May I interest you in..");
                            replyToConversation.Recipient   = replyMessage.From;
                            replyToConversation.Type        = "message";
                            replyToConversation.Attachments = new List <Attachment>();
                            List <CardImage> cardImages = new List <CardImage>();
                            cardImages.Add(new CardImage(url: recipeResult.image));
                            List <CardAction> cardButtons = new List <CardAction>();
                            CardAction        plButton    = new CardAction()
                            {
                                Value = recipeLink.sourceUrl,
                                Type  = "openUrl",
                                Title = "Let's Get Cooking!"
                            };
                            cardButtons.Add(plButton);
                            HeroCard plCard = new HeroCard()
                            {
                                Title    = recipeResult.title,
                                Subtitle = "Recommended by " + recipeResult.likes.ToString() + " others!",
                                Images   = cardImages,
                                Buttons  = cardButtons
                            };
                            Attachment plAttachment = plCard.ToAttachment();
                            replyToConversation.Attachments.Add(plAttachment);
                            var replyCard = await connector.Conversations.SendToConversationAsync(replyToConversation);

                            // Load our current ingredients list we we can cross check and mark what we already have.
                            var IngredientsListGrocery = new StateList();
                            var inventoryList          = IngredientsListGrocery.ReadIngredients();

                            // GetIngredients - complete ingredients from the API response
                            // Load the list into a sorted dictionary with the aisle for user's convenience
                            // Before we load into the dictionary, cross-check to see if we already have the item
                            int counter = 0;
                            var dict    = new SortedDictionary <string, string>();
                            foreach (var item in recipeLink.extendedIngredients)
                            {
                                for (int searchIndex = 0; searchIndex < inventoryList.Length; searchIndex++)
                                {
                                    if (inventoryList[searchIndex] == item.name)
                                    {
                                        item.aisle = "At Home!";
                                    }
                                }
                                dict.Add(item.name, item.aisle);
                                counter++;
                            }

                            // create two arrays, keys = ingredeints, value = aisle.
                            var keyArray   = new string[counter];
                            var valueArray = new string[counter];
                            int index      = 0;
                            foreach (KeyValuePair <string, string> item in dict.OrderBy(key => key.Value))
                            {
                                keyArray[index]   = item.Key;
                                valueArray[index] = item.Value;
                                index++;
                            }

                            // Save userData as properties in user session
                            userData.SetProperty <string[]>("foodList", keyArray);
                            userData.SetProperty <string[]>("aisleList", valueArray);
                            await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                        }
                        answer = "It looks like you may be missing some ingredients! Try: \"Send me a grocery list!\"";
                        break;

                    case "getShoppingList":
                        // check if we have found a recipe first
                        if (userData.GetProperty <string[]>("foodList") == null)
                        {
                            answer = "We need to find you a recipe first! Try: \"Find me a recipe!\"";
                            break;
                        }

                        // Retrieve ShoppingList from state
                        var foodList  = userData.GetProperty <string[]>("foodList");
                        var aisleList = userData.GetProperty <string[]>("aisleList");
                        var toBuy     = "";

                        // print the cross-checked grocery list for the user
                        for (int i = 0; i < foodList.Length; i++)
                        {
                            toBuy += (i + 1) + ". " + foodList[i] + " (" + aisleList[i] + ")" + '\n';
                        }
                        answer = "Shopping List: \n" + toBuy;
                        break;
                    }
                }
                else
                {
                    //run out of calls.. try again tomorrow... order out?..pizza #
                    answer = "Sorry! Kitchen is closed.. Time to order out! (425) 453-7200 [Domino's Pizza Bellevue Square]";
                }

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

            return(response);
        }
Ejemplo n.º 19
0
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            if (activity.Type == ActivityTypes.Message)
            {
                if (activity.Attachments.Count > 0)
                {
                    Face[] faces = await UploadAndDetectFaces(activity.Attachments[0].ContentUrl);


                    ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
                    Activity        reply     = activity.CreateReply($"Age:{faces[0].FaceAttributes.Age}");
                    await connector.Conversations.ReplyToActivityAsync(reply);
                }
                else
                {
                    await Conversation.SendAsync(activity, MakeRootDialog);
                }

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


                //// Parse the user's meaning via Language Understanding (LUIS) in Cognitive Services
                //YasudaLUIS Luis = await LUIS.ParseUserInput(activity.Text);
                //string strRet = string.Empty;

                //if (Luis.intents.Count() > 0)
                //{
                //    var talent = string.Empty;
                //    var MediaType = string.Empty;

                //    switch (Luis.intents[0].intent)
                //    {
                //        case "ShowMeMedia":
                //            // call
                //            talent = Luis.entities.Count() > 0 ? Luis.entities[0].entity : "";
                //            MediaType = Luis.entities.Count() > 1 ? Luis.entities[1].entity : "";
                //            strRet = $"Talent: {talent} / Media {MediaType} ";
                //            break;
                //        case "RecommandMedia":
                //            // call
                //            talent = "Akarui Yasumura";
                //            MediaType = Luis.entities.Count() > 1 ? Luis.entities[1].entity : "";
                //            strRet = $"Talent: {talent} / Media {MediaType} ";
                //            break;
                //        default:
                //            strRet = "Hi! I'm the Yasuda Bot. I help your fun time :)." + "\n" +
                //                @"Simple Ask me like ""show me {talent Name} Video""." + "\n" +
                //                "Enjoy!"
                //                ;
                //            break;
                //    }

                //    if (talent != string.Empty)
                //    {

                //        BingVideoSearchData Videos = await BingVideoSearch.VideoSearch(talent, "ja-jp");
                //        if (Videos.value.Count() > 0)
                //        {
                //            strRet = $"Title:{Videos.value[0].name}. URL:{Videos.value[0].contentUrl}";
                //        }
                //    }

                //}
                //else
                //{
                //    strRet = "I'm sorry but I don't understand what you're asking";
                //}

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

            return(response);
        }
Ejemplo n.º 20
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)
            {
                ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

                Activity reply = activity.CreateReply($"Sorry,  {activity.From.Name}, I did not understand?");

                String msgString = activity.Text.ToLower();

                if (msgString.Contains("help"))
                {
                    reply = activity.CreateReply("You can ask me to:\n - Get Tasks\n - Approve/Reject Task [TaskID]\n - Start Process");
                }
                if (msgString.Contains("id"))
                {
                    reply = activity.CreateReply($"ID: {activity.From.Id}");
                }
                else if (msgString.Contains("hello") || msgString.CompareTo("hi") == 0)
                {
                    reply = activity.CreateReply($"Greetings {activity.From.Name}, I am K2 bot.. pleased to meet you!");
                }
                else if (msgString.Contains("tasks"))
                {
                    reply = activity.CreateReply($"Here is a list of your tasks:\n 1 - Leave Request 1\n 2 - Leave Request 3");
                }
                else if (msgString.Contains("finish"))
                {
                    reply = activity.CreateReply($"Thanks for your approval,  {activity.From.Name}.\nThis task is now complete.");
                }
                else if (msgString.Contains("set token="))
                {
                    String tokenvalue = msgString.Substring(10, msgString.Length - 10);
                    _ConversationKeys[activity.Conversation.Id] = tokenvalue;
                    reply = activity.CreateReply($"Setting your Token Value to: {tokenvalue}");
                }
                else if (msgString.Contains("set device="))
                {
                    if (_ConversationKeys.ContainsKey(activity.Conversation.Id))
                    {
                        String deviceName = msgString.Substring(11, msgString.Length - 11);
                        _TokenDevices[activity.Conversation.Id] = deviceName;
                        reply = activity.CreateReply($"Setting your active Device to: {deviceName}");
                    }
                    else
                    {
                        reply = activity.CreateReply($"Sorry, your token value has not been set yet.");
                    }
                }
                else if (msgString.Contains("get token"))
                {
                    if (_ConversationKeys.ContainsKey(activity.Conversation.Id))
                    {
                        String tokenvalue = _ConversationKeys[activity.Conversation.Id];
                        reply = activity.CreateReply($"Your Token Value is: {tokenvalue}");
                    }
                    else
                    {
                        reply = activity.CreateReply($"Sorry, your token value has not been set yet.");
                    }
                }
                else if (msgString.Contains("device list"))
                {
                    if (_ConversationKeys.ContainsKey(activity.Conversation.Id))
                    {
                        String tokenvalue = _ConversationKeys[activity.Conversation.Id];

                        String replyString = "Your Device list:";

                        ParticleAPI           particle = new ParticleAPI(tokenvalue);
                        List <ParticleDevice> devices  = particle.GetDeviceList();
                        foreach (ParticleDevice device in devices)
                        {
                            replyString += $"\n\r  {device.name} - {device.id} ";
                            if (device.connected)
                            {
                                replyString += " (Online)";
                            }
                        }

                        reply = activity.CreateReply(replyString);
                    }
                    else
                    {
                        reply = activity.CreateReply($"Sorry, your token value has not been set yet.");
                    }
                }
                else if (msgString.Contains("method list"))
                {
                    if (_ConversationKeys.ContainsKey(activity.Conversation.Id))
                    {
                        String tokenvalue = _ConversationKeys[activity.Conversation.Id];

                        if (_TokenDevices.ContainsKey(activity.Conversation.Id))
                        {
                            String deviceID = _TokenDevices[activity.Conversation.Id];

                            String replyString = "Method List: ";

                            ParticleAPI particle = new ParticleAPI(tokenvalue);

                            ParticleDevice device = particle.GetDeviceDetails(deviceID);

                            if (device.functions.Count > 0)
                            {
                                foreach (string funcname in device.functions)
                                {
                                    replyString += $"\n\r  {funcname}";
                                }
                            }
                            else
                            {
                                replyString = "No Methods published for this device";
                            }

                            reply = activity.CreateReply(replyString);
                        }
                        else
                        {
                            reply = activity.CreateReply($"Sorry, your active Device has not been set yet.");
                        }
                    }
                    else
                    {
                        reply = activity.CreateReply($"Sorry, your token value has not been set yet.");
                    }
                }
                else if (msgString.Contains("call method"))
                {
                    String methodName = msgString.Substring(12, msgString.Length - 12);
                    String tokenvalue = _ConversationKeys[activity.Conversation.Id];
                    String deviceID   = _TokenDevices[activity.Conversation.Id];

                    ParticleAPI particle = new ParticleAPI(tokenvalue);
                    particle.CallDeviceFunction(deviceID, methodName, "bar");

                    reply = activity.CreateReply($"Calling Method: {methodName}");
                }

                //Send Response..
                await connector.Conversations.ReplyToActivityAsync(reply);
            }
            else
            {
                HandleSystemMessage(activity);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
Ejemplo n.º 21
0
 public ImportXlsConnector(ConnectorClient connectorClient)
 {
     this._connectorClient = connectorClient;
 }
Ejemplo n.º 22
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)
            {
                //Call to get the LUIS entity
                LuisResult stockLuisModel = await GetLUISEntity(activity.Text);


                var res = BestResultFrom(new[] { stockLuisModel });
                //Check if the LUIS model has returned the entity
                if (stockLuisModel.Intents.Count > 0)
                {
                    //Connector used in conversation
                    ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
                    string          strStock;

                    //Call to get the stock price
                    switch (res.BestIntent.Intent)
                    {
                    case "StockPrice":
                        strStock = (res.Result.Entities.Count != 0)
                                ? "The Stock value for " + res.Result.Entities[0].Entity + ": is" +
                                   await GetStock(res.Result.Entities[0].Entity)
                                : "You did not mention the ticker symbol";

                        break;

                    case "GetTemperature":
                        strStock =
                            (res.Result.Entities.Count != 0)
                                        ? "The weather forecast for  " + res.Result.Entities[0].Entity + " :" +
                            await GetWeather(res.Result.Entities[0].Entity)
                                        : "You did not mention the City";

                        break;

                    case "Greet":
                        strStock = "What can I do for you?";
                        break;

                    case "Marry":
                        strStock = "How much money do you have?";
                        break;

                    case "State":
                        strStock = "Hi, I am fine, how are you?";
                        break;

                    case "prompt":
                        strStock = "You can ask me questions like:" +
                                   "What is the weather in Newyork today?" +
                                   "        What is the price for MSFT?" +
                                   "        Ask me questions about chat bots.";
                        break;

                    case "Help":
                        strStock = "You can ask me questions like:" +
                                   "What is the weather in Irvine today?" +
                                   "        What is the price for MSFT ?" +
                                   "        Ask me questions about chat bots.";
                        break;

                    case "Express":
                        strStock = "If you ask me, I would say they are.";
                        break;

                    case "Capability":
                        strStock = "I can do a lot , just ask";
                        break;

                    case "sing":

                        strStock = "Hmm.. my inventors didn’t make me that smart." + "You can ask me questions like:" +
                                   "What is the weather in Newyork today?" +
                                   "        What is the price for MSFT?" +
                                   "        Ask me questions about chat bots.";
                        break;

                    case "Please":
                        strStock = "Hmm… you are hard to please.Tell me what you want me to do.";
                        break;

                    case "None":
                        strStock = "Sorry I was not able to find the stock price for :" + res.Result.Query;
                        break;

                    default:
                        strStock = "";
                        break;
                    }
                    // return our reply to the user
                    var reply = activity.CreateReply(strStock);
                    await connector.Conversations.ReplyToActivityAsync(reply);
                }

                // return our reply to the user
            }
            else
            {
                HandleSystemMessage(activity);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
Ejemplo n.º 23
0
        private static async Task SendNotification(IDialogContext context, Activity reply, string memberId, string notificationType)
        {
            var userId  = memberId.Trim();
            var botId   = context.Activity.Recipient.Id;
            var botName = context.Activity.Recipient.Name;

            var channelData     = context.Activity.GetChannelData <TeamsChannelData>();
            var connectorClient = new ConnectorClient(new Uri(context.Activity.ServiceUrl));

            var parameters = new ConversationParameters
            {
                Bot         = new ChannelAccount(botId, botName),
                Members     = new ChannelAccount[] { new ChannelAccount(userId) },
                ChannelData = new TeamsChannelData
                {
                    Tenant = channelData.Tenant,
                }
            };

            var conversationResource = await connectorClient.Conversations.CreateConversationAsync(parameters);

            var replyMessage = Activity.CreateMessageActivity();

            replyMessage.From         = new ChannelAccount(botId, botName);
            replyMessage.Conversation = new ConversationAccount(id: conversationResource.Id.ToString());
            replyMessage.ChannelData  = new TeamsChannelData()
            {
                Notification = new NotificationInfo(true)
            };

            switch (notificationType)
            {
            case "Weather":
                reply.Summary = "Here are weather updates";
                break;

            case "OperationsDelay":
                reply.Summary = "Operation delay due to bad weather";
                break;

            case "SocialEvents":
                reply.Summary = "Here are few social events";
                break;

            default:
                break;
            }

            replyMessage.Attachments = reply.Attachments;

            replyMessage.AttachmentLayout = reply.AttachmentLayout;

            try
            {
                await connectorClient.Conversations.SendToConversationAsync(conversationResource.Id, (Activity)replyMessage);
            }
            catch (Exception ex)
            {
                // Log the exception.
                Console.WriteLine(ex);
            }
        }
        private async Task HandleActions(IDialogContext context, Activity activity)
        {
            string type = string.Empty;

            var details = JsonConvert.DeserializeObject <ResponseData>(activity.Value.ToString());

            if (details.id == null)
            {
                await context.PostAsync("Please select at least one team to archive.");

                return;
            }
            var teamsToArchive = details.id.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();

            var token = await context.GetUserTokenAsync(ConnectionName).ConfigureAwait(false);

            if (token == null || token.Token == null)
            {
                await SendOAuthCardAsync(context, activity);

                return;
            }
            GraphAPIHelper helper       = new GraphAPIHelper();
            var            successCount = 0;

            foreach (var teamId in teamsToArchive)
            {
                if (!await helper.ArchiveTeamAsync(token.Token, teamId))
                {
                    await context.PostAsync("Failed to archive team with teamId: " + teamId);
                }
                else
                {
                    successCount++;
                }
            }

            ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
            var             reply     = activity.CreateReply();

            var Card = new AdaptiveCard()
            {
                Body = new List <AdaptiveElement>()
                {
                    new AdaptiveTextBlock()
                    {
                        Text = "Archive Team", Size = AdaptiveTextSize.Large, Weight = AdaptiveTextWeight.Bolder
                    },
                    new AdaptiveTextBlock()
                    {
                        Text = $"Archive complete. Successful count: {successCount}"
                    },
                }
            };

            var attachment = new Attachment()
            {
                ContentType = AdaptiveCard.ContentType,
                Content     = Card
            };

            reply.Attachments.Add(attachment);

            await connector.Conversations.UpdateActivityAsync(activity.Conversation.Id, activity.ReplyToId, reply);

            // await context.Update(reply);
        }
        private async Task HandleAdminEditTeamSettings(string msgId, ConnectorClient connectorClient, Activity activity, string senderAadId)
        {
            var teamContext = ActivityHelper.ParseCardActionData <TeamContext>(activity);

            await this.bot.EditTeamSettings(connectorClient, activity.CreateReply(), teamContext.TeamId, teamContext.TeamName);
        }
Ejemplo n.º 26
0
        private async Task <DailyChallengeEntriesStatus> CheckWhetherAllEntriesReceived(WaterfallStepContext stepContext, CancellationToken cancellationToken, DailyChallenge dailyChallenge, DailyChallengeInfo info)
        {
            try
            {
                // Fill in the "standard" properties for BotMessageReceived
                // and add our own property.
                Logger.LogInformation("Checking whether all entries received");
                DailyChallengeEntriesStatus currentStatus = new DailyChallengeEntriesStatus()
                {
                    allResultsReceived = false
                };

                List <DailyChallengeEntry> todayEntries = dailyChallenge.entries;
                if (info.users == null)
                {
                    info.users = new List <DailyChallengeUser>();
                }
                List <DailyChallengeUser> challengeUsers = new List <DailyChallengeUser>();

                var microsoftAppId       = Configuration["MicrosoftAppId"];
                var microsoftAppPassword = Configuration["MicrosoftAppPassword"];

                var connector = new ConnectorClient(new Uri(stepContext.Context.Activity.ServiceUrl), microsoftAppId, microsoftAppPassword);
                var response  = await connector.Conversations.GetConversationMembersWithHttpMessagesAsync(stepContext.Context.Activity.Conversation.Id);

                //var response = (await connectorClient.Conversations.GetConversationMembersAsync());
                foreach (var user in response.Body)
                {
                    challengeUsers.Add(new DailyChallengeUser()
                    {
                        id       = user.Id,
                        username = user.Name
                    });
                }

                int userCount           = challengeUsers.Count;
                int usersWithEntryCount = 0;

                foreach (var user in challengeUsers)
                {
                    if (todayEntries.Exists(matchingItem => matchingItem.userName == user.username))
                    {
                        usersWithEntryCount++;
                    }
                }

                if (usersWithEntryCount >= userCount)
                {
                    currentStatus.allResultsReceived = true;
                }

                currentStatus.userCount           = userCount;
                currentStatus.usersWithEntryCount = usersWithEntryCount;
                return(currentStatus);
            }
            catch (Exception exp)
            {
                Logger.LogError(exp, $"Error checking whether all entries received: {exp.Message} - {exp.StackTrace}", null);
                throw exp;
            }
        }
Ejemplo n.º 27
0
        private async Task <Activity> HandleSystemMessage(Activity message)
        {
            if (message.ServiceUrl == "https://directline.botframework.com/")
            {
                string input = "hello world, direct line";

                Activity userMessage = new Activity
                {
                    From      = new ChannelAccount(),
                    Text      = input,
                    Type      = Connector.DirectLine.ActivityTypes.Message,
                    ChannelId = "8c8e13d4-fb54-4777-aea2-7b6ace72bd92"
                };

                //await Conversation.SendAsync(userMessage, () => new EchoDialog());
            }
            else if (message.Type == ActivityTypes.DeleteUserData)
            {
                // Implement user deletion here
                // If we handle user deletion, return a real message
            }
            else if (message.Type == ActivityTypes.ConversationUpdate && message.MembersAdded != null && message.MembersAdded.Any(x => x.Name == null))
            {
                // Handle conversation state changes, like members being added and removed
                // Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info
                // Not available in all channels

                // Fetch the members in the current conversation
                //var connector = new ConnectorClient(new Uri("http://hack005.ngrok.io"));
                var connector = new ConnectorClient(new Uri(message.ServiceUrl));
                var members   = await connector.Conversations.GetConversationMembersAsync(message.Conversation.Id);


                var teamID = message.Conversation.Id;


                var registerDto = new RegisterDto()
                {
                    TeamId  = teamID,
                    Members = members.Select(x => new TeamMemberDto()
                    {
                        Id   = x.Properties.GetValue("objectId").ToString(),
                        Name = x.Name
                    }).ToList()
                };

                using (var httpclient = new HttpClient())
                {
                    var response = await httpclient.PostAsJsonAsync("https://msopenhackeu.azurewebsites.net/api/trivia/register", registerDto);
                }


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

            return(null);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            // Global values
            bool   boolAskedForUserName = false;
            string strUserName          = "";

            if (activity.Type == ActivityTypes.Message)
            {
                // Get any saved values
                StateClient sc       = activity.GetStateClient();
                BotData     userData = sc.BotState.GetPrivateConversationData(
                    activity.ChannelId, activity.Conversation.Id, activity.From.Id);
                boolAskedForUserName = userData.GetProperty <bool>("AskedForUserName");
                strUserName          = userData.GetProperty <string>("UserName") ?? "";
                // Create text for a reply message
                StringBuilder strReplyMessage = new StringBuilder();
                if (boolAskedForUserName == false) // Never asked for name
                {
                    strReplyMessage.Append("Hello, I am Agri Bot");
                    strReplyMessage.Append("\n");
                    strReplyMessage.Append("You can say anything");
                    strReplyMessage.Append("\n");
                    strReplyMessage.Append("to me and I will repeat it back");
                    strReplyMessage.Append("\n\n");
                    strReplyMessage.Append("What is your name?");
                    // Set BotUserData
                    userData.SetProperty <bool>("AskedForUserName", true);
                }
                else // Have asked for name
                {
                    if (strUserName == "") // Name was never provided
                    {
                        // If we have asked for a username but it has not been set
                        // the current response is the user name
                        strReplyMessage.Append("Hello " + activity.Text + " ! ");
                        // Set BotUserData
                        userData.SetProperty <string>("UserName", activity.Text);
                    }
                    else // Name was provided
                    {
                        strReplyMessage.Append(strUserName + ", You said agri: " + activity.Text);
                    }
                }
                // Save BotUserData
                sc.BotState.SetPrivateConversationData(
                    activity.ChannelId, activity.Conversation.Id, activity.From.Id, userData);
                // Create a reply message
                ConnectorClient connector    = new ConnectorClient(new Uri(activity.ServiceUrl));
                Activity        replyMessage = activity.CreateReply(strReplyMessage.ToString());
                await connector.Conversations.ReplyToActivityAsync(replyMessage);
            }
            else
            {
                Activity replyMessage = HandleSystemMessage(activity);
                if (replyMessage != null)
                {
                    ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
                    await connector.Conversations.ReplyToActivityAsync(replyMessage);
                }
            }
            // Return response
            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
        private static async Task AddUserToDatabase(IDialogContext context, TokenResponse tokenResponse)
        {
            var client = new SimpleGraphClient(tokenResponse.Token);

            User me = null;
            //User manager = null;
            var profilePhotoUrl = string.Empty;

            try
            {
                me = await client.GetMe();

                // manager = await client.GetManager();
                var photo = await client.GetProfilePhoto();

                var    fileName  = me.Id + "-ProflePhoto.png";
                string imagePath = System.Web.Hosting.HostingEnvironment.MapPath("~/ProfilePhotos/");
                if (!System.IO.Directory.Exists(imagePath))
                {
                    System.IO.Directory.CreateDirectory(imagePath);
                }
                imagePath += fileName;

                using (var fileStream = System.IO.File.Create(imagePath))
                {
                    photo.Seek(0, SeekOrigin.Begin);
                    photo.CopyTo(fileStream);
                }
                profilePhotoUrl = ApplicationSettings.BaseUrl + "/ProfilePhotos/" + fileName;
            }
            catch (Exception ex)
            {
                ErrorLogService.LogError(ex);
                profilePhotoUrl = null;
            }

            ConnectorClient connector   = new ConnectorClient(new Uri(context.Activity.ServiceUrl));
            var             channelData = context.Activity.GetChannelData <TeamsChannelData>();
            var             employee    = new Employee()
            {
                Name               = me.DisplayName,
                EmailId            = me.UserPrincipalName,
                UserUniqueId       = context.Activity.From.Id, // For proactive messages
                TenantId           = channelData.Tenant.Id,
                DemoManagerEmailId = string.Empty,
                JobTitle           = me.JobTitle ?? me.UserPrincipalName,
                LeaveBalance       = new LeaveBalance
                {
                    OptionalLeave = 2,
                    PaidLeave     = 20,
                    SickLeave     = 10
                },
                AzureADId = me.Id,
                PhotoPath = profilePhotoUrl,
            };
            var employeeDoc = await DocumentDBRepository.CreateItemAsync(employee);

            context.ConversationData.SetValue(GetProfileKey(context.Activity), employee);

            var msg  = context.MakeMessage();
            var card = EchoBot.SetManagerCard(); // WelcomeLeaveCard(employee.Name.Split(' ').First());

            msg.Attachments.Add(card);
            await context.PostAsync(msg);
        }
        /// <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)
            {
                ConnectorClient connector     = new ConnectorClient(new Uri(activity.ServiceUrl));
                Activity        reply         = activity.CreateReply();
                Activity        reply_cat     = activity.CreateReply();
                Activity        reply_tag     = activity.CreateReply();
                Activity        reply_face    = activity.CreateReply();
                Activity        reply_emotion = activity.CreateReply();
                Activity        reply_img     = activity.CreateReply();
                Activity        reply_bt      = activity.CreateReply();
                //List<Activity> reply_ptt_list=null;
                //db
                var cb = new SqlConnectionStringBuilder();
                cb.DataSource     = "nbadata.database.windows.net";
                cb.UserID         = "nbadata";
                cb.Password       = "******";
                cb.InitialCatalog = "NBADATA";
                //----s
                if (activity.Attachments?.Count > 0 && activity.Attachments.First().ContentType.StartsWith("image"))
                {
                    var url = activity.Attachments.First().ContentUrl;
                    //emotion api
                    EmotionServiceClient emo_client = new EmotionServiceClient("95a490338ba54f908c05e65d82e14b69", "https://westus.api.cognitive.microsoft.com/emotion/v1.0");
                    var emo_result = await emo_client.RecognizeAsync(url);

                    //辨識圖片
                    VisionServiceClient client = new VisionServiceClient("cf9176a0c5dd4784ad4cc3467a778924", "https://westcentralus.api.cognitive.microsoft.com/vision/v1.0");
                    //VisualFeature[] { VisualFeature.Description }矩陣列舉,在此指使用描述
                    var result = await client.AnalyzeImageAsync(url, new VisualFeature[] { VisualFeature.Description, VisualFeature.Categories, VisualFeature.Faces, VisualFeature.ImageType, VisualFeature.Tags });

                    var celebritiesResult = await client.AnalyzeImageInDomainAsync(url, "celebrities");

                    string tag_name = "Picture tags: ";
                    foreach (var item in result.Tags)
                    {
                        tag_name += item.Name.ToString() + ",";
                    }
                    //string cat_name = "Categories of picture: ";
                    string cname = JObject.Parse(celebritiesResult.Result.ToString())["celebrities"].ToString();
                    if (cname.Length > 2)
                    {
                        cname = JObject.Parse(JObject.Parse(celebritiesResult.Result.ToString())["celebrities"][0].ToString())["name"].ToString();
                    }
                    string cele = JObject.Parse(celebritiesResult.Result.ToString())["celebrities"].ToString();
                    if (cele.Length > 2)
                    {
                        cele = "Probably " + JObject.Parse(JObject.Parse(celebritiesResult.Result.ToString())["celebrities"][0].ToString())["name"].ToString();
                    }
                    else
                    {
                        cele = "unrecognized man";
                    }
                    //foreach (var item in result.Categories) cat_name += item.Name.ToString() + "\t";

                    /*string face = "Face in picture: ";
                     * if (result.Faces.Length == 0) face += "No face.";
                     * foreach (var item in result.Faces) face += "Gender: "+ item.Gender.ToString() + "\t"+"Age: "+item.Age.ToString()+"\n";
                     */
                    string emo = "Emotion detection: ";
                    if (emo_result.Length == 0)
                    {
                        emo += "No face.";
                    }
                    foreach (var item in emo_result)
                    {
                        if (item.Scores.Anger > 0.01)
                        {
                            emo += "Anger, ";
                        }
                        if (item.Scores.Contempt > 0.01)
                        {
                            emo += "Contempt, ";
                        }
                        if (item.Scores.Disgust > 0.01)
                        {
                            emo += "Disgust, ";
                        }
                        if (item.Scores.Fear > 0.01)
                        {
                            emo += "Fear, ";
                        }
                        if (item.Scores.Happiness > 0.01)
                        {
                            emo += "Happiness, ";
                        }
                        if (item.Scores.Neutral > 0.01)
                        {
                            emo += "Neutral, ";
                        }
                        if (item.Scores.Sadness > 0.01)
                        {
                            emo += "Sadness, ";
                        }
                        if (item.Scores.Surprise > 0.01)
                        {
                            emo += "Surprise, ";
                        }
                    }



                    reply.Text = "Description: " + result.Description.Captions.First().Text;
                    //reply_cat.Text = cat_name;
                    //reply_tag.Text = tag_name;
                    //reply_face.Text = face;
                    reply_emotion.Text = emo;
                    reply_img.Text     = cele;
                    if (reply_img.Text != "unrecognized man")
                    {
                        Service(reply_bt, cname);
                    }
                }
                else
                {
                    if (activity.Text.Contains("&"))
                    {
                        //reply.Text = activity.Text.Substring(0, activity.Text.IndexOf('-'));
                        switch (activity.Text.Substring(0, activity.Text.IndexOf('&')))
                        {
                        case "PTT":
                            //reply.Text = activity.Text.Substring(activity.Text.IndexOf('&') +1 , (activity.Text.Length - activity.Text.IndexOf('&') -1));
                            // select ptt by name
                            using (var connection = new SqlConnection(cb.ConnectionString))
                            {
                                connection.Open();
                                reply.Text = Submit_PTT_Select(connection, activity.Text.Substring(activity.Text.IndexOf('&') + 1, (activity.Text.Length - activity.Text.IndexOf('&') - 1)));
                            }
                            break;

                        case "career stat":
                            //reply.Text = activity.Text.Substring(activity.Text.IndexOf('&') +1 , (activity.Text.Length - activity.Text.IndexOf('&') -1));
                            // select stat by name
                            using (var connection = new SqlConnection(cb.ConnectionString))
                            {
                                connection.Open();
                                reply.Text = Submit_Player_Stat_Select(connection, activity.Text.Substring(activity.Text.IndexOf('&') + 1, (activity.Text.Length - activity.Text.IndexOf('&') - 1)));
                            }
                            break;

                        default:
                            reply.Text = activity.Text;
                            break;
                        }
                    }
                    else
                    {
                        /*string message = string.Empty;
                         * try
                         * {
                         *  var audioAttachment2 = activity.Attachments?.FirstOrDefault(a => a.ContentType.Equals("video/mp4") || a.ContentType.Contains("audio") || a.ContentType.Contains("video"));
                         *  var audioAttachment = activity.Attachments?.FirstOrDefault(a => a.ContentType.Equals("audio/wav") || a.ContentType.Equals("application/octet-stream"));
                         *  if (audioAttachment != null)
                         *  {
                         *
                         *      var stream = await GetAudioStream(connector, audioAttachment);
                         *      var text = await this.speechService.GetTextFromAudioAsync(stream);
                         *      message = ProcessText(text);
                         *      reply = activity.CreateReply(message);
                         *      await connector.Conversations.ReplyToActivityAsync(reply);
                         *
                         *  }
                         *  else if (audioAttachment2 != null)
                         *  {
                         *
                         *      IncomingFacebookVoiceMessage voice = new IncomingFacebookVoiceMessage(activity);
                         *      try
                         *      {
                         *
                         *          if (voice != null)
                         *          {
                         *
                         *              //Download original MP4 voice message
                         *              voice.DownloadFile();
                         *              throw new Exception("ddffdfdfdfdfdfdfdfdffdf");
                         *              var mp4 = voice.GetLocalPathAndFileName();
                         *
                         *              //Convert MP4 to WAV
                         *              var wavFolder = "D:" + @"\" + "home" + @"\" + "site" + @"\" + "wwwroot" + @"\" + "bin" + @"\" + "en";
                         *              var converter = new AudioFileFormatConverter(mp4, wavFolder);
                         *              var wav = converter.ConvertMP4ToWAV();
                         *
                         *
                         *              //Convert .WAV file to text
                         *              var bing = new MicrosoftCognitiveSpeechService(); //gets the path + filename
                         *
                         *
                         *
                         *              // convert string to stream
                         *
                         *              byte[] data = File.ReadAllBytes(wav);
                         *              //byte[] byteArray = Encoding.ASCII.GetBytes(contents);
                         *              MemoryStream stream = new MemoryStream(data);
                         *
                         *
                         *
                         *
                         *
                         *              var text = await this.speechService.GetTextFromAudioAsync(stream); //takes path+filename to WAV file, returns text
                         *
                         *              if (string.IsNullOrWhiteSpace(text))
                         *              {
                         *                  message = "Looks like you didn't say anything.";
                         *              }
                         *              else
                         *              {
                         *                  message = text;
                         *              }
                         *
                         *              //Clean up files from disk
                         *              voice.RemoveFromDisk();
                         *              converter.RemoveTargetFileFromDisk();
                         *          }
                         *
                         *      }
                         *      catch (Exception ex)
                         *      {
                         *          message = "Woah! " + ex.Message.Trim().Trim('.') + "!";
                         *      }
                         *
                         *
                         *
                         *  }
                         *  else
                         *  {
                         *      message = "Did you upload an audio file? I'm more of an audible person. Try sending me a wav file";
                         *  }
                         * }
                         * catch (Exception e)
                         * {
                         *  message = "Oops! Something went wrong. Try again later";
                         *  if (e is HttpException)
                         *  {
                         *      var httpCode = (e as HttpException).GetHttpCode();
                         *      if (httpCode == 401 || httpCode == 403)
                         *      {
                         *          message += $" [{e.Message} - hint: check your API KEY at web.config]";
                         *      }
                         *      else if (httpCode == 408)
                         *      {
                         *          message += $" [{e.Message} - hint: try send an audio shorter than 15 segs]";
                         *      }
                         *  }
                         *
                         *  Trace.TraceError(e.ToString());
                         * }
                         */
                        //-----------------------------------------

                        using (LuisClient client = new LuisClient("16f5717a-ee86-4074-abf4-603c9d6cd733", "c74954db4ddb4000bb6865cf07c2ad36"))
                        {
                            var result = await client.Predict(activity.Text);

                            List <string> Teams = new List <string>();
                            List <string> Date = new List <string>();
                            string        Players = "", temp, teamdate = "", playerdate = "";

                            List <string> OUTPUT = new List <string>();// team team date



                            foreach (var OneItem in result.Entities)
                            {
                                foreach (var Item in OneItem.Value)
                                {
                                    //reply.Text += Item.ParentType + "   " + Item.Value + "\n";
                                    //reply.Text += Item.Name + "   " + Item.Value + "   " + Item.Score + "   ";
                                    foreach (var r in Item.Resolution)
                                    {
                                        //reply.Text += r.Value.ToString() + "  \n";
                                        temp = r.Value.ToString();

                                        if (Item.Name == "Teams")
                                        {
                                            Teams.Add(temp);
                                        }
                                        else if (Item.Name == "Players")
                                        {
                                            Players = temp;
                                        }
                                        else if (Item.Name == "builtin.number")
                                        {
                                            Date.Add(temp);
                                        }
                                        //    Teams.Add(r.Value.ToString());
                                    }
                                }
                                //reply.Text += "Key = " + OneItem.Key + ", Value = " + OneItem.Value[0].Value + "\n";
                            }

                            //string[] DATE = Date.ToArray();
                            //reply.Text += Date.Count;
                            int digit = 1;
                            if (Date.Count > 1)
                            {
                                if (Date.Count == 2)
                                {
                                    teamdate   += "2017";
                                    playerdate += "2017";
                                    digit       = 0;
                                }
                                else
                                {
                                    teamdate   += Date[0];
                                    playerdate += Date[0];
                                }
                                int tem;
                                for (int i = digit; i < Date.Count; i++)
                                {
                                    tem = Convert.ToInt32(Date[i]);
                                    if (tem < 10)
                                    {
                                        temp        = Convert.ToString(tem);
                                        playerdate += "/" + temp;
                                        teamdate   += "/0" + temp;
                                    }
                                    else
                                    {
                                        playerdate += "/" + Date[i];
                                        teamdate   += "/" + Date[i];
                                    }
                                }
                            }
                            //reply.Text += result.TopScoringIntent.Name;

                            if (result.TopScoringIntent.Name == "Games" && teamdate != "")
                            {
                                for (int i = 0; i < Teams.Count; i++)
                                {
                                    Teams[i] = Teams[i].Remove(Teams[i].Length - 4, 4);
                                    Teams[i] = Teams[i].Remove(0, 6);
                                    OUTPUT.Add(Teams[i]);
                                    //reply.Text += Teams[i] + " ";
                                }
                                //reply.Text += teamdate;
                                OUTPUT.Add(teamdate);
                                //////////input Teams & Date
                            }
                            else if (result.TopScoringIntent.Name == "Personal Performance")
                            {
                                Players = Players.Remove(Players.Length - 4, 4);
                                Players = Players.Remove(0, 6);
                                //reply.Text += Players + playerdate;
                                OUTPUT.Add(Players);
                                if (playerdate != "")
                                {
                                    OUTPUT.Add(playerdate);
                                }
                                /////////input Players & Date
                            }
                            //else
                            //    reply.Text = "Please enter more details.";
                            //reply.Text += OUTPUT.Count;
                            switch (OUTPUT.Count)
                            {
                            case 3:    //team+team+date
                                //reply.Text += OUTPUT[0];
                                //reply.Text += OUTPUT[1];
                                //reply.Text += OUTPUT[2];
                                using (var connection = new SqlConnection(cb.ConnectionString))
                                {
                                    connection.Open();
                                    //reply.Text = OUTPUT[2]+OUTPUT[0]+ OUTPUT[1] ;
                                    reply.Text = Submit_Team_Select(connection, OUTPUT[2], OUTPUT[0], OUTPUT[1]);
                                }
                                break;

                            case 2:    //player+date
                                //reply.Text += OUTPUT[0];
                                //reply.Text += OUTPUT[1];
                                using (var connection = new SqlConnection(cb.ConnectionString))
                                {
                                    connection.Open();
                                    reply.Text = Submit_Player_Stat_Select(connection, OUTPUT[0], OUTPUT[1]);
                                }
                                break;

                            case 1:    //player
                                //reply.Text += OUTPUT[0];
                                Service(reply_bt, OUTPUT[0]);
                                break;

                            default:
                                reply.Text = "Please enter more details.";
                                break;
                            }
                            //reply.Text = team1 + team2 + player + dt;
                        }
                    }
                }



                await connector.Conversations.ReplyToActivityAsync(reply);

                //await connector.Conversations.ReplyToActivityAsync(reply_cat);

                /*await connector.Conversations.ReplyToActivityAsync(reply_tag);
                 * await connector.Conversations.ReplyToActivityAsync(reply_face);*/
                await connector.Conversations.ReplyToActivityAsync(reply_emotion);

                await connector.Conversations.ReplyToActivityAsync(reply_img);

                await connector.Conversations.ReplyToActivityAsync(reply_bt);

                /*foreach (var item in reply_ptt_list)
                 * {
                 *  await connector.Conversations.ReplyToActivityAsync(item);
                 * }*/
            }



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

            return(response);
        }