예제 #1
0
        protected override async Task OnPostbackAsync(PostbackEvent ev)
        {
            string text = "";

            switch (ev.Postback.Data)
            {
            case "Date":
                text = "You chose the date: " + ev.Postback.Params.Date;
                break;

            case "Time":
                text = "You chose the time: " + ev.Postback.Params.Time;
                break;

            case "DateTime":
                text = "You chose the date-time: " + ev.Postback.Params.DateTime;
                break;

            default:
                text = "Your postback is " + ev.Postback.Data;
                break;
            }

            dl.Activity sendMessage = new dl.Activity()
            {
                Type = "message",
                Text = text,
                From = new dl.ChannelAccount(ev.Source.Id, ev.Source.Id)
            };

            // Send the message, then fetch and reply messages,
            await dlClient.Conversations.PostActivityAsync(conversationId, sendMessage);

            await GetAndReplyMessages(ev.ReplyToken, ev.Source.Id);
        }
        /// <summary>
        /// Convert single DirectLine activity into IMessageActivity instance
        /// </summary>
        /// <returns>IMessageActivity object as a message in a conversation</returns>
        /// <param name="directLineActivity">directline activity</param>
        public IMessageActivity ConvertToBotSchemaActivity(DirectLine.Activity directLineActivity)
        {
            if (directLineActivity == null)
            {
                return(null);
            }

            var dlAttachments = directLineActivity.Attachments;

            if (dlAttachments != null && dlAttachments.Count() > 0)
            {
                return(ConvertToAttachmentActivity(directLineActivity));
            }

            if (directLineActivity.SuggestedActions != null)
            {
                return(ConvertToSuggestedActionsAcitivity(directLineActivity));
            }

            if (!string.IsNullOrEmpty(directLineActivity.Text))
            {
                return(MessageFactory.Text(directLineActivity.Text));
            }

            return(null);
        }
예제 #3
0
        /// <summary>
        /// Reply the location user send.
        /// </summary>
        private async Task HandleLocationAsync(string replyToken, LocationEventMessage location, string userId)
        {
            dl.Activity sendMessage = new dl.Activity()
            {
                Type     = "message",
                Text     = location.Title,
                From     = new dl.ChannelAccount(userId, userId),
                Entities = new List <Entity>()
                {
                    new Entity()
                    {
                        Type       = "Place",
                        Properties = JObject.FromObject(new Place(address: location.Address,
                                                                  geo: new dl.GeoCoordinates(
                                                                      latitude: (double)location.Latitude,
                                                                      longitude: (double)location.Longitude,
                                                                      name: location.Title),
                                                                  name: location.Title))
                    }
                }
            };

            // Send the message, then fetch and reply messages,
            await dlClient.Conversations.PostActivityAsync(conversationId, sendMessage);

            await GetAndReplyMessages(replyToken, userId);
        }
예제 #4
0
        public string GetBotResponseTest(String input)
        {
            //Create an activity to recieved the returned text
            Microsoft.Bot.Connector.DirectLine.Activity temp = new Microsoft.Bot.Connector.DirectLine.Activity();

            //establish a retry counter, to give the BOT time to respond, in the future this can correspond to a timeout requirement
            int tryCounter = 0;

            //Send the first message to the bot to establish the connection
            Program.setBotMessage(input);
            //"Hello Bot, What is my total GPA"

            //retry for awhile initially
            while (tryCounter < 50000001)
            {
                //Look to see of the BOT has responded
                temp = Program.getBotMessage();

                //The BOTInterction program sets text of ERROR if there are no responses from the BOT
                if (!temp.Text.Contains("ERROR"))
                {
                    //Burp out the text to the console.
                    Console.WriteLine("Recieved Text Contains: " + temp.Text);
                    // StringAssert.Contains(temp.Text, "myGPA intent");
                    break;
                }

                tryCounter++;
            }
            return(temp.Text);
        }
예제 #5
0
        /// <inheritdoc/>
        public override async Task SendActivityAsync(BotActivity activity, CancellationToken cancellationToken)
        {
            if (_conversation == null)
            {
                await StartConversationAsync().ConfigureAwait(false);

                if (activity.Type == ActivityTypes.ConversationUpdate)
                {
                    // StartConversationAsync sends a ConversationUpdate automatically.
                    // Ignore the activity sent if it is the first one we are sending to the bot and it is a ConversationUpdate.
                    // This can happen with recorded scripts where we get a conversation update from the transcript that we don't
                    // want to use.
                    return;
                }
            }

            var activityPost = new Activity
            {
                From = new ChannelAccount(_user),
                Text = activity.Text,
                Type = activity.Type
            };

            _logger.LogDebug($"{DateTime.Now} Sending activity to conversation {_conversation.ConversationId}");
            _logger.LogDebug(JsonConvert.SerializeObject(activityPost, Formatting.Indented));

            await _dlClient.Conversations.PostActivityAsync(_conversation.ConversationId, activityPost, cancellationToken).ConfigureAwait(false);
        }
예제 #6
0
        //This test, tests the connection to the bot
        public void InitBotConnectionTest()
        {
            bool Init_Message_Interaction_Complete = false;

            //Send the first message to the bot to establish the connection
            Program.setBotMessage("Hello");

            //Create an activity to recieved the returned text
            Microsoft.Bot.Connector.DirectLine.Activity temp = new Microsoft.Bot.Connector.DirectLine.Activity();

            //See if the bot has responded
            temp = Program.getBotMessage();

            //establish a retry counter, to give the BOT time to respond, in the future this can correspond to a timeout requirement
            int tryCounter = 0;

            //retry for awhile initially
            while (tryCounter < 50000001)
            {
                //The BOTInterction program sets text of ERROR if there are no responses from the BOT
                if (!temp.Text.Contains("ERROR"))
                {
                    //Burp out the text to the console.
                    Console.WriteLine("Recieved Text Contains: " + temp.Text);

                    //Set a small logic flag
                    Init_Message_Interaction_Complete = true;
                    break;
                }

                //Look to see of the BOT has responded
                temp = Program.getBotMessage();

                //Increment the counter
                tryCounter++;
            }

            //Ok got initial response, now reset the counter to look for the message echo
            tryCounter = 0;
            if (Init_Message_Interaction_Complete)
            {
                while (tryCounter < 50000001)
                {
                    //Try to get the BOT response
                    temp = Program.getBotMessage();

                    //If there is a response
                    if (!temp.Text.Contains("ERROR"))
                    {
                        Console.WriteLine("Recieved Text Contains: " + temp.Text);

                        //Here is the actual test Pass/Fall Test, we sent "Hello", we expect the returned message to contain "Hello".
                        StringAssert.Contains(temp.Text, "Hello");
                        break;
                    }

                    tryCounter++;
                }
            }
        }
예제 #7
0
        /// <inheritdoc/>
        public override async Task SendActivityAsync(BotActivity activity, CancellationToken cancellationToken)
        {
            if (_conversation == null)
            {
                await CreateConversationAsync().ConfigureAwait(false);

                if (activity.Type == ActivityTypes.ConversationUpdate)
                {
                    // CreateConversationAsync sends a ConversationUpdate automatically.
                    // Ignore the activity sent if it is the first one we are sending to the bot and it is a ConversationUpdate.
                    // This can happen with recorded scripts where we get a conversation update from the transcript that we don't
                    // want to use.
                    return;
                }
            }

            var activityPost = new Activity
            {
                From = new ChannelAccount(_user),
                Text = activity.Text,
                Type = activity.Type
            };

            await _dlClient.Conversations.PostActivityAsync(_conversation.ConversationId, activityPost, cancellationToken).ConfigureAwait(false);
        }
예제 #8
0
        private static async Task StartBotConversation()
        {
            DirectLineClient client = new DirectLineClient(directLineSecret);

            var conversation = await client.Conversations.StartConversationAsync();

            new System.Threading.Thread(async() => await ReadBotMessagesAsync(client, conversation.ConversationId)).Start();

            Console.Write("Command> ");

            while (true)
            {
                string input = Console.ReadLine().Trim();

                if (input.ToLower() == "exit")
                {
                    break;
                }
                else
                {
                    if (input.Length > 0)
                    {
                        Activity userMessage = new Activity
                        {
                            From = new ChannelAccount(fromUser),
                            Text = input,
                            Type = ActivityTypes.Message
                        };

                        await client.Conversations.PostActivityAsync(conversation.ConversationId, userMessage);
                    }
                }
            }
        }
        public async Task HandleTextMessage()
        {
            var textMessage = JsonConvert.DeserializeObject <TextMessage>(lineEvent.Message.ToString());

            dl.Activity sendMessage = new dl.Activity()
            {
                Type = "message",
                Text = textMessage.Text,
                From = new dl.ChannelAccount(lineEvent.Source.UserId, lineEvent.Source.UserId)
            };

            // Send the message, then fetch and reply messages,
            try
            {
                await dlClient.Conversations.PostActivityAsync(conversationId, sendMessage);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            try
            {
                await GetAndReplyMessages();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
        string SendToBotFramework(string sessionId, string text)
        {
            dlClient = new DirectLineClient(directLineSecret);
            if (!conversations.ContainsKey(sessionId))
            {
                // start a new conversation
                conversations[sessionId] = dlClient.Conversations.StartConversation();
                watermarks[sessionId]    = null;
            }
            else
            {
                dlClient.Conversations.ReconnectToConversation(conversations[sessionId].ConversationId,
                                                               watermarks[sessionId]);
            }
            Microsoft.Bot.Connector.DirectLine.Activity msg = new Microsoft.Bot.Connector.DirectLine.Activity
            {
                From = new ChannelAccount(sessionId),
                Text = text,
                Type = ActivityTypes.Message
            };

            dlClient.Conversations.PostActivity(conversations[sessionId].ConversationId, msg);
            var activitySet = dlClient.Conversations.GetActivities(conversations[sessionId].ConversationId, watermarks[sessionId]);

            watermarks[sessionId] = activitySet.Watermark;

            var activities = from x in activitySet.Activities
                             where x.From.Id == botId
                             select x;

            return(activities.FirstOrDefault().Text);
        }
        public async Task HandleLocationMessage()
        {
            var locationMessage = JsonConvert.DeserializeObject <LocationMessage>(lineEvent.Message.ToString());

            dl.Activity sendMessage = new dl.Activity()
            {
                Type = "message",
                Text = locationMessage.Title,
                From = new ChannelAccount(lineEvent.Source.UserId, lineEvent.Source.UserId),
                //From = new ChannelAccount(lineEvent.Source.UserId, lineEvent.Source.UserId),
                Entities = new List <Entity>()
                {
                    new Entity()
                    {
                        Type       = "Place",
                        Properties = JObject.FromObject(new Place(address: locationMessage.Address,
                                                                  geo: new dl.GeoCoordinates(
                                                                      latitude: locationMessage.Latitude,
                                                                      longitude: locationMessage.Longitude,
                                                                      name: locationMessage.Title),
                                                                  name: locationMessage.Title))
                    }
                }
            };

            // Send the message, then fetch and reply messages,
            await dlClient.Conversations.PostActivityAsync(conversationId, sendMessage);

            await GetAndReplyMessages();
        }
예제 #12
0
        public async Task <ActionResult <BotGatewayResponse> > InitAssistantAsync([FromBody] Activity activity, CancellationToken cancellationToken = default(CancellationToken))
        {
            var ti0          = DateTime.Now;
            var conversation = await _directLineClient.Conversations.StartConversationAsync(cancellationToken);

            var elapsed = DateTime.Now.Subtract(ti0).TotalMilliseconds;

            ti0 = DateTime.Now;
            var response = await _directLineClient.Conversations.PostActivityAsync(conversation.ConversationId, activity, cancellationToken);

            elapsed = DateTime.Now.Subtract(ti0).TotalMilliseconds;
            // TODO: Init shouldn't return a response, this seems to be a bug.
            var r = await GetResponses(conversation.ConversationId, null, _directLineClient, cancellationToken);

            var initResponse = new BotGatewayResponse
            {
                Activities = new List <Activity> {
                    GetFakeActivity()
                },
                ConversationId = conversation.ConversationId,
                Watermark      = r.Watermark
            };

            return(new ActionResult <BotGatewayResponse>(Ok(initResponse)));
        }
 public async Task SendMessageAsync(string message)
 {
     Microsoft.Bot.Connector.DirectLine.Activity activity = new Microsoft.Bot.Connector.DirectLine.Activity
     {
         From = Account,
         Text = message,
         Type = Microsoft.Bot.Connector.DirectLine.ActivityTypes.Message
     };
     await Client.Conversations.PostActivityAsync(MainConversation.ConversationId, activity);
 }
        private IMessageActivity ConvertToSuggestedActionsAcitivity(DirectLine.Activity directLineActivity)
        {
            var directLineSuggestedActions = directLineActivity.SuggestedActions;

            return(MessageFactory.SuggestedActions(
                       actions: directLineSuggestedActions.Actions?.Select(action => action.Title).ToList(),
                       text: directLineActivity.Text,
                       ssml: directLineActivity.Speak,
                       inputHint: directLineActivity.InputHint));
        }
예제 #15
0
        public void WhenIConnectToTheAccountAnd(KeyValuePair <string, string> teamProject)
        {
            var activity = new Activity
            {
                Type = ActivityTypes.Message,
                From = new ChannelAccount(Config.UserName, Config.UserName),
                Text = FormattableString.Invariant($"connect {Config.Account} {teamProject.Value}")
            };

            Config.Client.Conversations.PostActivity(Config.ConversationId, activity);
        }
예제 #16
0
        public void WhenISay(string message)
        {
            var activity = new Activity
            {
                Type = ActivityTypes.Message,
                From = new ChannelAccount(Config.UserName, Config.UserName),
                Text = message
            };

            Config.Client.Conversations.PostActivity(Config.ConversationId, activity);
        }
예제 #17
0
        private static Activity GetInitActivity(ChannelAccount channelAccount, string locale, object channelData)
        {
            var activity = new Activity
            {
                From        = channelAccount,
                Type        = ActivityTypes.Event,
                Locale      = locale,
                ChannelData = channelData
            };

            return(activity);
        }
예제 #18
0
        public async Task HandlePostbackEvent()
        {
            dl.Activity sendMessage = new dl.Activity()
            {
                Type = "message",
                Text = lineEvent.Postback.Data,
                From = new dl.ChannelAccount(lineEvent.Source.UserId, lineEvent.Source.UserId)
            };
            // Send the message, then fetch and reply messages,
            await dlClient.Conversations.PostActivityAsync(conversationId, sendMessage);

            await GetAndReplyMessages();
        }
예제 #19
0
        private static Activity BuildMessageActivity(ChannelAccount channelAccount, string utterance, string locale, object channelData)
        {
            var activity = new Activity
            {
                From        = channelAccount,
                Type        = ActivityTypes.Message,
                Text        = utterance,
                Locale      = locale,
                ChannelData = channelData
            };

            return(activity);
        }
예제 #20
0
        /// &lt;summary&gt;
        /// Drives the user's conversation with the bot.
        /// &lt;/summary&gt;
        /// &lt;returns&gt;&lt;/returns&gt;
        private static async Task StartBotConversation()
        {
            // Create a new Direct Line client.
            DirectLineClient client = new DirectLineClient(directLineSecret);

            // Start the conversation.
            var conversation = await client.Conversations.StartConversationAsync();

            // Start the bot message reader in a separate thread.
            new System.Threading.Thread(async() => await ReadBotMessagesAsync(client, conversation.ConversationId)).Start();

            // Prompt the user to start talking to the bot.
            Console.Write("Conversation ID: " + conversation.ConversationId + Environment.NewLine);
            Console.Write("Type your message (or \"exit\" to end): ");

            // Loop until the user chooses to exit this loop.
            while (true)
            {
                // Accept the input from the user.
                string input = Console.ReadLine().Trim();

                // Check to see if the user wants to exit.
                if (input.ToLower() == "exit")
                {
                    // Exit the app if the user requests it.
                    break;
                }
                else
                {
                    if (input.Length > 0)
                    {
                        // Create a message activity with the text the user entered.
                        Activity userMessage = new Activity
                        {
                            From = new ChannelAccount(fromUser),
                            Text = input,
                            Type = ActivityTypes.Message
                        };

                        Console.Write("input to send " + userMessage.Text + " type " + userMessage.Type + Environment.NewLine);

                        // Send the message activity to the bot.
                        await client.Conversations.PostActivityAsync(conversation.ConversationId, userMessage);
                    }
                }
            }
        }
예제 #21
0
        /// <summary>
        /// Sends the BotFramework a message
        /// We await the completion of this task so the code does not get ahead of the BotFramework
        /// </summary>
        /// <param name="message"> Message to send </param>
        /// <param name="clientConversationId"> Client Session Id </param>
        /// <returns></returns>
        public async Task SendBotMessage(string message, string clientConversationId)
        {
            string conversationId = GetConversationId(clientConversationId);

            if (message.Length > 0)
            {
                // Create a message activity with the text the user entered.
                Microsoft.Bot.Connector.DirectLine.Activity userMessage = new Microsoft.Bot.Connector.DirectLine.Activity
                {
                    From = new ChannelAccount(fromUser),
                    Text = message,
                    Type = ActivityTypes.Message
                };

                // Send the message activity to the bot.
                await _client.Conversations.PostActivityAsync(conversationId, userMessage);
            }
        }
        private IMessageActivity ConvertToAttachmentActivity(DirectLine.Activity directLineActivity)
        {
            var botSchemaAttachments = directLineActivity.Attachments.Select(
                directLineAttachment => new Attachment()
            {
                ContentType  = directLineAttachment.ContentType,
                ContentUrl   = directLineAttachment.ContentUrl,
                Content      = directLineAttachment.Content,
                Name         = directLineAttachment.Name,
                ThumbnailUrl = directLineAttachment.ThumbnailUrl,
            }).ToList();

            return(MessageFactory.Attachment(
                       botSchemaAttachments,
                       text: directLineActivity.Text,
                       ssml: directLineActivity.Speak,
                       inputHint: directLineActivity.InputHint));
        }
예제 #23
0
        private async Task HandleTextAsync(string replyToken, string userMessage, string userId)
        {
            dl.Activity sendMessage = new dl.Activity()
            {
                Type = "message",
                Text = userMessage,
                From = new dl.ChannelAccount(userId, userId)
            };

            // Send the message, then fetch and reply messages,
            try
            {
                await dlClient.Conversations.PostActivityAsync(conversationId, sendMessage);
            }
            catch (Exception ex)
            {
            }

            await GetAndReplyMessages(replyToken, userId);
        }
예제 #24
0
        static async Task Main(string[] args)
        {
            var creds  = new DirectLineClientCredentials(botDirectLineSecret);
            var client = new DirectLineClient(creds);

            var conversation = await client.Conversations.StartConversationAsync();

            using (var webSocketClient = new WebSocket(conversation.StreamUrl))
            {
                webSocketClient.OnMessage += WebSocketClient_OnMessage;
                webSocketClient.SslConfiguration.EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12;
                webSocketClient.Connect();

                // Optional, helps provide additional context on the user for some skills/scenarios
                await SendStartupEvents(client, conversation);

                while (true)
                {
                    var input = System.Console.ReadLine().Trim();

                    if (input.ToLower() == "exit")
                    {
                        break;
                    }
                    else
                    {
                        if (input.Length > 0)
                        {
                            var userMessage = new Activity
                            {
                                From = new ChannelAccount(fromUserId, fromUserName),
                                Text = input,
                                Type = ActivityTypes.Message
                            };

                            await client.Conversations.PostActivityAsync(conversation.ConversationId, userMessage);
                        }
                    }
                }
            }
        }
예제 #25
0
        private static async Task StartBotConversationAsync()
        {
            // Obtain a token using the Direct Line secret
            var tokenResponse = await new DirectLineClient(directLineSecret).Tokens.GenerateTokenForNewConversationAsync();

            // Use token to create conversation
            var directLineClient = new DirectLineClient(tokenResponse.Token);
            var conversation     = await directLineClient.Conversations.StartConversationAsync();

            Console.Write("\nCommand> ");

            using (var webSocketClient = new WebSocket(conversation.StreamUrl))
            {
                webSocketClient.OnMessage += WebSocketClient_OnMessage;
                webSocketClient.Connect();

                while (true)
                {
                    var input = Console.ReadLine().Trim();
                    if (input.ToLower() == "exit")
                    {
                        break;
                    }
                    else
                    {
                        if (input.Length > 0)
                        {
                            var userMessage = new Activity
                            {
                                From = new ChannelAccount(fromUser),
                                Text = input,
                                Type = ActivityTypes.Message
                            };

                            await directLineClient.Conversations.PostActivityAsync(conversation.ConversationId, userMessage);
                        }
                    }
                }
            }
        }
예제 #26
0
        /// <summary>
        /// These are sample startup events used in the Virtual Assistant for setting
        /// locale and providing a user's current coordinates.
        /// </summary>
        private static async Task SendStartupEvents(DirectLineClient client, Conversation conversation)
        {
            var locationEvent = new Activity
            {
                Name  = "VA.Location",
                From  = new ChannelAccount(fromUserId, fromUserName),
                Type  = ActivityTypes.Event,
                Value = "47.659291, -122.140633"
            };

            await client.Conversations.PostActivityAsync(conversation.ConversationId, locationEvent);

            var timezoneEvent = new Activity
            {
                Name  = "VA.Timezone",
                From  = new ChannelAccount(fromUserId, fromUserName),
                Type  = ActivityTypes.Event,
                Value = "Pacific Standard Time"
            };

            await client.Conversations.PostActivityAsync(conversation.ConversationId, timezoneEvent);
        }
예제 #27
0
        public async Task <ActionResult <BotGatewayResponse> > SendActivityAsync(string conversationId, string watermark, [FromBody] Activity activity, CancellationToken cancellationToken = default(CancellationToken))
        {
            // Reconnect and post (run them in parallel).
            var stopwatch     = Stopwatch.StartNew();
            var reconnectTask = _directLineClient.Conversations.ReconnectToConversationAsync(conversationId, watermark, cancellationToken);

            // TODO: how do we check error handling if we don't await...
            var postTask = _directLineClient.Conversations.PostActivityAsync(conversationId, activity, cancellationToken);

            Task.WaitAll(reconnectTask);
            var reconnectTime = stopwatch.ElapsedMilliseconds;

            var responses = await GetResponses(conversationId, watermark, _directLineClient, cancellationToken);

            responses.Diagnostics.ReconnectAndPostDuration = reconnectTime;

            return(new ActionResult <BotGatewayResponse>(Ok(responses)));
        }
예제 #28
0
        private async Task <BotGatewayResponse> SendActivityAsync(string conversationId, string watermark, DirectLineGatewayProxy dlGatewayProxy, CancellationToken cancellationToken, Activity activity)
        {
            Console.WriteLine("Sending activity...");
            if (_renderOutgoingActivities)
            {
                ConsoleOut.RenderActivity(activity, ConsoleColor.Blue);
            }

            var stopWatch    = Stopwatch.StartNew();
            var lastResponse = await dlGatewayProxy.SendActivityAsync(conversationId, watermark, activity, cancellationToken);

            var clientRoundtripTime = stopWatch.ElapsedMilliseconds;

            Console.WriteLine("Done.");
            RenderResponse(lastResponse, clientRoundtripTime);
            return(lastResponse);
        }
예제 #29
0
        //public static DirectLineClient client;
        //public static Microsoft.Bot.Connector.DirectLine.Conversation dconversation;
        //public static string watermark = null;
        //public static ConnectorClient connector;
        //public static Microsoft.Bot.Connector.Activity activity;

        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> Post([FromBody] Microsoft.Bot.Connector.Activity int_activity)
        {
            UserStuff user = null;

            if (users.ContainsKey(int_activity.From.Id))
            {
                user = users[int_activity.From.Id];
            }
            else
            {
                users[int_activity.From.Id] = new UserStuff()
                {
                    activity = int_activity
                };
                user = users[int_activity.From.Id];
            }

            try
            {
                if (int_activity.Type == Microsoft.Bot.Connector.ActivityTypes.Message)
                {
                    Trace.WriteLine("Got Message");
                    Trace.WriteLine(int_activity.ToString());
                    //create connector service
                    user.connector = new ConnectorClient(new Uri(int_activity.ServiceUrl));

                    //var rply = int_activity.CreateReply($"Successful connection for {JsonConvert.SerializeObject(int_activity, Formatting.Indented)}");
                    //await user.connector.Conversations.ReplyToActivityAsync(rply);
                    //conv = await connector.Conversations.CreateDirectConversationAsync(activity.Recipient, activity.From);
                    //activity.Conversation.Id = conv.Id;

                    if (user.client == null)
                    {
                        user.client = new DirectLineClient(directLineSecret);
                    }

                    if (user.dconversation == null)
                    {
                        user.dconversation = await user.client.Conversations.StartConversationAsync();

                        new System.Threading.Thread(async() => await user.ReadBotMessagesAsync()).Start();
                    }

                    // send user's input to health service bot
                    Microsoft.Bot.Connector.DirectLine.Activity dact = new Microsoft.Bot.Connector.DirectLine.Activity()
                    {
                        From = new Microsoft.Bot.Connector.DirectLine.ChannelAccount("some user"),
                        Text = int_activity.Text,
                        Type = Microsoft.Bot.Connector.DirectLine.ActivityTypes.Message
                    };
                    await user.client.Conversations.PostActivityAsync(user.dconversation.ConversationId, dact);
                }
                else
                {
                    HandleSystemMessage(int_activity);
                }
                var response = Request.CreateResponse(HttpStatusCode.OK);
                return(response);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                throw;
            }
        }
        private async Task <Microsoft.Bot.Connector.DirectLine.Activity> PostToAgentBotAsync(Microsoft.Bot.Connector.DirectLine.Activity activityFromUser)
        {
            var directLineSecret = Configuration.ConfigurationHelper.GetString("AgentBot_DirectLine_Secret");
            var agentStatusDB    = Configuration.ConfigurationHelper.GetString("BotStatusDBConnectionString");
            var dc           = new DirectLineClient(directLineSecret);
            var agentStorage = new AgentStatusStorage(agentStatusDB);
            var agent        = await agentStorage.QueryAgentStatusAsync(activityFromUser.Recipient.Id);

            ConversationStatus convStatus = null;

            //var agentConversations = await agentStorage.QueryConversationStatusAsync(agent.Id);

            try
            {
                var uri = new Uri("https://directline.botframework.com");
                DirectLineClientCredentials creds  = new DirectLineClientCredentials(directLineSecret);                                //lot into the bot framework
                DirectLineClient            client = new DirectLineClient(uri, creds);                                                 //connect the client
                Microsoft.Bot.Connector.DirectLine.Conversations convs = new Microsoft.Bot.Connector.DirectLine.Conversations(client); //get the list of conversations belonging to the bot? Or does this start a new collection of conversations?

                Microsoft.Bot.Connector.DirectLine.Conversation conversation = null;
                if (string.IsNullOrEmpty(_agentConversationId))
                {
                    conversation         = dc.Conversations.StartConversation();
                    _agentConversationId = conversation.ConversationId;
                }
                else
                {
                    conversation = new Microsoft.Bot.Connector.DirectLine.Conversation()
                    {
                        ConversationId = _agentConversationId,
                    };
                }
                Logger.Info($"activityFromUser - From.Name:{activityFromUser.From.Name} - From.Id:{activityFromUser.From.Id}");
                Logger.Info($"activityFromUser - Recipient.Name:{activityFromUser.Recipient.Name} - Recipient.Id:{activityFromUser.Recipient.Name}");
                var toAgent = new Microsoft.Bot.Connector.DirectLine.Activity
                {
                    Type = Microsoft.Bot.Connector.DirectLine.ActivityTypes.Message,
                    Text = activityFromUser.Text,
                    From = new Microsoft.Bot.Connector.DirectLine.ChannelAccount
                    {
                        Id   = activityFromUser.From.Id,/*activityFromUser.From.Id,*/
                        Name = $"{activityFromUser.From.Name}@ocsuser"
                    },
                    Recipient   = activityFromUser.Recipient,
                    ChannelId   = agent.ChannelId,
                    ChannelData = new DirectLineChannelData
                    {
                        RoundTrip      = 0,
                        ConversationId = _agentConversationId,
                        UserID         = activityFromUser.From.Id,
                        UserName       = activityFromUser.From.Name
                    }
                };

                var resp = await dc.Conversations.PostActivityAsync(
                    conversation.ConversationId,
                    toAgent);

                Logger.Info($"OCSBot::Dialog:PostToAgent() - {JsonConvert.SerializeObject(toAgent)}");
                //convStatus = (await agentStorage.QueryConversationStatusAsync(agent.Id)).OrderByDescending(o => o.Timestamp).FirstOrDefault();
                //convStatus.OCSDirectlineConversationId = conversation.ConversationId;
                //convStatus.OCSEndUserId = activityFromUser.From.Id;
                //convStatus.OCSEndUserName = activityFromUser.From.Name;
                //convStatus.OCSBotName = activityFromUser.Recipient.Name;
                //convStatus.OCSBotId = activityFromUser.Recipient.Id;
                //await agentStorage.UpdateConversationStatusAsync(convStatus);
                return(null);
            }
            catch (Exception exp)
            {
                Logger.Info($"OCSBot::PostToAgent() - Exception while posting to Agent:{exp.Message}");
                throw;
            }
        }