/// <summary> /// Posts the given activity to the bot using Direct Line client. /// </summary> /// <param name="activity">The activity to send.</param> /// <returns>The resoure response.</returns> private async Task <DirectLineSendResult> PostActivityAsync(string conversationId, Activity activity) { ResourceResponse resourceResponse = null; var conversationContext = string.IsNullOrEmpty(conversationId) ? null : _conversationCache.GetConversation(new IdAndTimestamp(conversationId)); var conversation = conversationContext?.Conversation; using (DirectLineClient directLineClient = new DirectLineClient(_directLineSecret)) { // TODO conversation.ExpiresIn if (conversation == null) { conversation = directLineClient.Conversations.StartConversation(); _conversationCache.PutConversation( new IdAndTimestamp(conversation.ConversationId), new ConversationContext(conversation, "")); } else { directLineClient.Conversations.ReconnectToConversation(conversation.ConversationId); } resourceResponse = await directLineClient.Conversations.PostActivityAsync(conversation.ConversationId, activity); } return(new DirectLineSendResult(conversation, resourceResponse.Id)); }
/// <summary> /// Polls the bot continuously until it gets a response. /// </summary> /// <param name="client">The Direct Line client.</param> /// <param name="conversationId">The conversation ID.</param> /// <returns>Returns the bot's answer.</returns> private static async Task <string> ReadBotMessagesAsync(DirectLineClient client, string conversationId) { string watermark = null; var answer = string.Empty; // Poll the bot for replies once per second. while (answer.Equals(string.Empty)) { // Retrieve the activity sent from the bot. var activitySet = await client.Conversations.GetActivitiesAsync(conversationId, watermark); watermark = activitySet?.Watermark; // Extract the activities sent from the bot. var activities = from x in activitySet.Activities where x.From.Id == botId select x; // Analyze each activity in the activity set. foreach (var activity in activities) { if (activity.Type == ActivityTypes.Message && activity.Text != "Welcome to Echo Bot.") { answer = activity.Text; } } // Wait for one second before polling the bot again. await Task.Delay(TimeSpan.FromSeconds(1)).ConfigureAwait(false); return(answer); } return(answer); }
private async Task OnRecordCompleted(RecordOutcomeEvent recordOutcomeEvent) { Trace.TraceInformation(DateTime.Now + " RecordCompleted " + recordOutcomeEvent.ConversationResult.Id); // Convert the audio to text if (recordOutcomeEvent.RecordOutcome.Outcome == Outcome.Success) { var text = await GetResultFromRecording(recordOutcomeEvent); var client = new DirectLineClient(directLineSecret); var callState = this.callStateMap[recordOutcomeEvent.ConversationResult.Id]; Activity userMessage = GenerateActivity(text, callState); Trace.TraceInformation(DateTime.Now + " Posting message to message controller"); // The result below contains the conversationId, as well as an incrementing number for each back and forth var resulttt = await client.Conversations.PostActivityAsync(callState.Conversation.ConversationId, userMessage); var actionList = await GetActionListOnRecordCompleted(client, callState); recordOutcomeEvent.ResultingWorkflow.Actions = actionList; } //recordOutcomeEvent.ResultingWorkflow.Links = null; //this.callStateMap.Remove(recordOutcomeEvent.ConversationResult.Id); }
public static async Task RefreshTokensAsync( Conversation conversation, DirectLineClient client, CancellationToken cancelToken) { const int ToMilliseconds = 1000; const int BeforeExpiration = 60000; var runTask = Task.Run(async() => { try { int millisecondsToRefresh = ((int)conversation.ExpiresIn * ToMilliseconds) - BeforeExpiration; while (true) { await Task.Delay(millisecondsToRefresh); await client.Conversations.ReconnectToConversationAsync( conversation.ConversationId, Message.Watermark, cancelToken); } } catch (OperationCanceledException oce) { Console.WriteLine(oce.Message); } }); await Task.FromResult(0); }
public async Task <IActionResult> Index() { try { var tokenClient = new DirectLineClient(new Uri("https://directline.botframework.com/"), new DirectLineClientCredentials("H-mIGKOIXJ8.M0P2_afqawnF1Yzbur8kVYgkrbaGtcoSnjP1nv11NZU")); tokenClient.Tokens.GenerateTokenForNewConversation(); Conversation _conversation = await tokenClient.Conversations.StartConversationAsync().ConfigureAwait(false); var user = new ChannelAccount() { Id = "123", Name = "Fred" }; var response = await tokenClient.Conversations.PostActivityAsync(_conversation.ConversationId, new Activity() { Type = "message", Text = "Hello", From = user }).ConfigureAwait(false); ActivitySet activites = await tokenClient.Conversations.GetActivitiesAsync(_conversation.ConversationId); this.ReceiveActivities(activites); return(View()); } catch (Exception) { return(NotFound()); } }
public static string StartConversation(string directLineSecret) { using (var directLineClient = new DirectLineClient(directLineSecret)) { return(directLineClient.Conversations.StartConversation().ConversationId); } }
private async Task RespondPowerVirtualAgentsBotReplyAsync(DirectLineClient client, RelayConversation currentConversation, ITurnContext <IMessageActivity> turnContext) { var retryMax = WaitForBotResponseMaxMilSec / PollForBotResponseIntervalMilSec; for (int retry = 0; retry < retryMax; retry++) { // Get bot response using directlineClient, // response contains whole conversation history including user & bot's message ActivitySet response = await client.Conversations.GetActivitiesAsync(currentConversation.ConversationtId, currentConversation.WaterMark); // Filter bot's reply message from response List <DirectLineActivity> botResponses = response?.Activities?.Where(x => x.Type == DirectLineActivityTypes.Message && string.Equals(x.From.Name, _botService.GetBotName(), StringComparison.Ordinal)).ToList(); if (botResponses?.Count() > 0) { if (int.Parse(response?.Watermark ?? "0") <= int.Parse(currentConversation.WaterMark ?? "0")) { // means user sends new message, should break previous response poll return; } currentConversation.WaterMark = response.Watermark; await turnContext.SendActivitiesAsync(_responseConverter.ConvertToBotSchemaActivities(botResponses).ToArray()); } Thread.Sleep(PollForBotResponseIntervalMilSec); } }
private static async Task OpenWebsocketListner(DirectLineClient client, string streamUrl, string conversationId) { using (var webSocketClient = new WebSocket(streamUrl)) { webSocketClient.OnMessage += WebSocketClient_OnMessage; // You have to specify TLS version to 1.2 or connection will be failed in handshake. webSocketClient.SslConfiguration.EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12; webSocketClient.Connect(); 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(conversationId, userMessage); } } } } }
/// <summary> /// Start a Power Virtual Agent bot conversation /// for an external Azure Bot Service channel conversation /// </summary> /// <returns>Created Power Virtual Agent bot conversation</returns> /// <param name="externalCID">external Azure Bot Service channel conversation ID</param> public async Task <RelayConversation> StartBotConversationAsync(string externalCID, IBotService botService) { string token = await botService.GetTokenAsync(); using (var directLineClient = new DirectLineClient(token)) { var conversation = await directLineClient.Conversations.StartConversationAsync(); string conversationId = conversation?.ConversationId; if (string.IsNullOrEmpty(conversationId)) { throw new TaskCanceledException("Exception caught: directline failed to create conversation using retrieved token"); } var newBotConversation = new RelayConversation() { Token = token, ConversationtId = conversationId, WaterMark = null, }; ConversationRouter[externalCID] = newBotConversation; } return(ConversationRouter[externalCID]); }
private static async Task StartConversation() { var token = await s_botService.GetTokenAsync(); using (var directLineClient = new DirectLineClient(token)) { var conversation = await directLineClient.Conversations.StartConversationAsync(); var conversationtId = conversation.ConversationId; string inputMessage; while (!string.Equals(inputMessage = GetUserInput(), s_endConversationMessage, StringComparison.OrdinalIgnoreCase)) { // Send user message using directlineClient await directLineClient.Conversations.PostActivityAsync(conversationtId, new Activity() { Type = ActivityTypes.Message, From = new ChannelAccount { Id = "userId", Name = "userName" }, Text = inputMessage, TextFormat = "plain", Locale = "en-Us", }); Console.WriteLine($"{_botDisplayName}:"); Thread.Sleep(_botReplyWaitIntervalInMilSec); // Get bot response using directlinClient List <Activity> responses = await GetBotResponseActivitiesAsync(directLineClient, conversationtId); BotReply(responses); } } }
// GET: Response public async Task <TwiMLResult> Index(VoiceRequest request) { DirectLineClient client = new DirectLineClient(Constants.BotDirectLineSecret); string conversationId = Request.QueryString[Constants.ConversationIdQSKey]; if (string.IsNullOrEmpty(conversationId)) { var conversation = await client.Conversations.StartConversationAsync(); conversationId = conversation.ConversationId; } Activity userMessage = new Activity { From = new ChannelAccount("Twilio"), Text = Request["SpeechResult"], Type = ActivityTypes.Message }; await client.Conversations.PostActivityAsync(conversationId, userMessage); var result = await client.Conversations.GetActivitiesAsync(conversationId); var botStringResponse = result.Activities[result.Activities.Count - 1].Text; var response = new VoiceResponse(); var urlRedirect = GetRedirectUrl(conversationId, botStringResponse); response.Redirect(urlRedirect, method: "GET"); return(TwiML(response)); }
/// <summary> /// Use directlineClient to get bot response /// </summary> /// <returns>List of DirectLine activities</returns> /// <param name="directLineClient">directline client</param> /// <param name="conversationtId">current conversation ID</param> /// <param name="botName">name of bot to connect to</param> private static async Task <List <Activity> > GetBotResponseActivitiesAsync(DirectLineClient directLineClient, string conversationtId) { ActivitySet response = null; List <Activity> result = new List <Activity>(); do { response = await directLineClient.Conversations.GetActivitiesAsync(conversationtId, _watermark); if (response == null) { // response can be null if directLineClient token expires Console.WriteLine("Conversation expired. Press any key to exit."); Console.Read(); directLineClient.Dispose(); Environment.Exit(0); } _watermark = response?.Watermark; result = response?.Activities?.Where(x => x.Type == ActivityTypes.Message && string.Equals(x.From.Name, s_botService.BotName, StringComparison.Ordinal)).ToList(); if (result != null && result.Any()) { return(result); } Thread.Sleep(1000); } while (response != null && response.Activities.Any()); return(new List <Activity>()); }
private static async Task StartBotConversation() { DirectLineClient client = new DirectLineClient(directLineSecret); var conversation = await client.Conversations.NewConversationAsync(); 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) { Message userMessage = new Message { FromProperty = fromUser, Text = input }; await client.Conversations.PostMessageAsync(conversation.ConversationId, userMessage); } } } }
public BotConnection(BotObject bot) { // Todo: restore previous converstation if there was one // https://github.com/tompaana/twitter-bot-fw-integration/blob/master/TwitterBotFWIntegration/DirectLineManager.cs this.bot = bot; if (CrossSecureStorage.Current.HasKey(ConversationIdKey)) { if (int.TryParse(CrossSecureStorage.Current.GetValue(WatermarkKey), out var watermarkNumber)) { if (watermarkNumber > 1) { // shows the last message of Florence when reopened this.watermark = (watermarkNumber - 2).ToString(); } } else { this.watermark = watermarkNumber.ToString(); } } else { // Obtain a token using the Direct Line secret var tokenResponse = new DirectLineClient(bot.DirectLineSecret).Tokens.GenerateTokenForNewConversation(); // Use token to create conversation using (this.directLineClient = new DirectLineClient(tokenResponse.Token)) { this.directLineClient.Conversations.StartConversation(); CrossSecureStorage.Current.SetValue(ConversationIdKey, tokenResponse.ConversationId); } } }
/// <summary> /// Polls for new messages (activities). /// </summary> /// <param name="conversationId"> /// The ID of the conversation. /// </param> /// <returns> /// The <see cref="Task"/>. /// </returns> public async Task PollMessagesAsync(string conversationId = null) { if (!string.IsNullOrEmpty(conversationId) || !string.IsNullOrEmpty(this.ConversationId)) { conversationId = string.IsNullOrEmpty(conversationId) ? this.ConversationId : conversationId; ActivitySet activitySet = null; using (var directLineClient = new DirectLineClient(this.DirectLineSecret)) { directLineClient.Conversations.ReconnectToConversation(conversationId); activitySet = await directLineClient.Conversations.GetActivitiesAsync(conversationId, this.watermark); } if (activitySet != null) { this.watermark = activitySet.Watermark; var activities = (from activity in activitySet.Activities select activity).ToList(); if (this.synchronizationContext != null) { this.synchronizationContext.Post((o) => this.ActivitiesReceived?.Invoke(this, activities), null); } else { this.ActivitiesReceived?.Invoke(this, activities); } } } }
private async Task ReadBotMessageAsync(DirectLineClient client, string conversationId) { String watermark = null; while (true) { var activitySet = await client.Conversations.GetActivitiesAsync(conversationId, watermark); watermark = activitySet.Watermark; var activities = from x in activitySet.Activities where x.From.Id == botId select x; foreach (Activity activity in activities) { if (activity.Text != null) { String message = activity.Text; if (InvokeRequired) { BeginInvoke(new MethodInvoker(delegate { ModeloRespuesta rta = new ModeloRespuesta(); string rta_fin = rta.GenRespuesta(message); Console.WriteLine("Bot said: " + message + " Shown as " + rta_fin); if (!realizarAccion(message, rta_fin)) { add_respuesta("No tienes acceso a esta función"); } })); } } } } }
/// <summary> /// Sends the given message to the bot. /// </summary> /// <param name="messageText"> /// The message to send. /// </param> /// <returns> /// Message ID if successful. Null otherwise. /// </returns> public async Task <string> SendMessageAsync(string messageText) { ResourceResponse resourceResponse; using (var directLineClient = new DirectLineClient(this.DirectLineSecret)) { if (string.IsNullOrEmpty(this.ConversationId)) { this.ConversationId = StartConversation(this.DirectLineSecret); } else { directLineClient.Conversations.ReconnectToConversation(this.ConversationId); } resourceResponse = await directLineClient.Conversations.PostActivityAsync( this.ConversationId, new Activity { From = new ChannelAccount( $"{this.ConversationId}_direct", $"{this.ConversationId}_direct"), Type = ActivityTypes.Message, Text = messageText }); } if (resourceResponse == null) { return(null); } this.StartPolling(); return(resourceResponse.Id); }
public void Dispose() { if (client == null) { return; } var userActivity = new Activity { From = new ChannelAccount(Constants.Email, Constants.Username), Type = ActivityTypes.EndOfConversation }; client.Conversations.PostActivityAsync(conversation.ConversationId, userActivity); client.Dispose(); client = null; conversation = null; webSocket.OnMessage -= WebSocket_OnMessage; webSocket.OnClose -= WebSocket_OnClose; webSocket.OnError -= WebSocket_OnError; if (webSocket.IsAlive) { webSocket.CloseAsync(); } webSocket = null; viewModel = null; }
private async Task ReadBotMessagesAsync(DirectLineClient _client, string conversationId) { // You can optionally set watermark -this is last message id seen by bot //It is for paging: string watermark = null; while (true) { //Get all messages returned by bot: var messages = await _directLineClient.Conversations.GetMessagesAsync(conversationId, watermark); watermark = messages?.Watermark; var messagesFromBotText = from x in messages.Messages where x.FromProperty == "FacialIdentificationBot" select x; //Iterate through all messages: foreach (Microsoft.Bot.Connector.DirectLine.Models.Message message in messagesFromBotText) { if (!_messagesFromBot.Contains(message)) { _messagesFromBot.Add(message); SendBotMessageToIoTHub(message); } } } }
public BotDirectLineService(MainPageViewModel viewModel) { this.viewModel = viewModel; Device.StartTimer(TimeSpan.FromMinutes(9), () => { try { if (client != null && client.Tokens != null) { client.Tokens.RefreshTokenAsync(); } } catch (Exception) { client = null; conversation = null; webSocket = null; } return(true); }); botConnectionRenewer = new Timer(new TimerCallback(OnTokenExpiredCallback), this, TimeSpan.FromMinutes(5), TimeSpan.FromMilliseconds(-1)); }
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); } } } }
/// <summary> /// Gets the latest activity set of the current conversation. /// </summary> /// <returns>The latest activity set or null, if no conversation or no activities since the last time we checked.</returns> private async Task <ActivitySet> GetActivitySetAsync() { ActivitySet activitySet = null; if (_conversation != null) { using (DirectLineClient directLineClient = new DirectLineClient(_botSecret)) { directLineClient.Conversations.ReconnectToConversation(_conversation.ConversationId); if (string.IsNullOrEmpty(_watermark)) { activitySet = await directLineClient.Conversations.GetActivitiesAsync(_conversation.ConversationId); } else { activitySet = await directLineClient.Conversations.GetActivitiesAsync(_conversation.ConversationId, _watermark); } } if (activitySet != null) { _watermark = activitySet.Watermark; } } return(activitySet); }
/// <summary> /// Constructor to initialize our service /// </summary> /// <param name="config">Configuration Interface</param> public ScorpioDirectLineClient(IConfiguration config) { _config = config; _client = new DirectLineClient(_config["Bot:Secret"]); fromUser = _config["Bot:FromUser"]; conversationMappings = new Dictionary <string, string>(); }
public ReceiveMessageFromBotClass(DirectLineClient botClient, string botId, ulong channelId) { BotId = botId; BotClient = botClient; ChannelId = channelId; ConnectToConversion(false); }
public MainPage() { this.InitializeComponent(); client = new DirectLineClient(directLineSecret); conversation = client.Conversations.StartConversation(); }
private static async Task ReadBotMessagesAsync(DirectLineClient client, string conversationId) { string watermark = null; while (true) { var activitySet = await client.Conversations.GetActivitiesAsync(conversationId, watermark); watermark = activitySet?.Watermark; var activities = from x in activitySet.Activities where x.From.Id == botId select x; foreach (Activity activity in activities) { byte[] temp = Encoding.UTF8.GetBytes(activity.Text); string message = Encoding.UTF8.GetString(temp); Console.WriteLine(message); Console.Write("Command> "); } await Task.Delay(TimeSpan.FromSeconds(0.1)).ConfigureAwait(false); } }
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); }
private static async Task ReadBotMessagesAsync(DirectLineClient client, string conversationId) { string watermark = null; while (true) { var activitySet = await client.Conversations.GetActivitiesAsync(conversationId, watermark); watermark = activitySet?.Watermark; var activities = from x in activitySet.Activities where x.From.Id == botId select x; foreach (Activity activity in activities) { Console.WriteLine(activity.Text); if (activity.Text.Contains("Hello")) { Console.Write("Test Pass \n"); } Console.Write("Command> "); } await Task.Delay(TimeSpan.FromSeconds(1)).ConfigureAwait(false); } }
public async Task <ClientInfo> StartConversation() { HttpCookie cookie = HttpContext.Current.Request.Cookies["UserId"]; string id; if (cookie == null) { id = Guid.NewGuid().ToString(); HttpCookie newCookie = new HttpCookie("UserId", id); newCookie.Expires = DateTime.MaxValue; //HttpContext.Current.Response.Cookies.Add(newCookie); } else { id = cookie.Value; } DirectLineClient client = new DirectLineClient(directLineSecret); Conversation conversation = await client.Conversations.StartConversationAsync(); HttpContext.Current.Session["conversation"] = conversation; id = "BenEmanuel"; ClientInfo info = new ClientInfo(id, conversation.ConversationId, conversation.StreamUrl, conversation.Token); return(info); }
public DirectLineHelper(TestContext testContext) { client = new DirectLineClient(testContext.Properties["DirectLineSecret"].ToString()); userId = testContext.Properties["UserId"].ToString(); conversationId = client.Conversations.StartConversation().ConversationId; watermark = null; }