public async Task OnTurn(ITurnContext context) { // Only handle message activities if (context.Activity.Type != ActivityTypes.Message) { return; } ConversationReference self = TurnContext.GetConversationReference(context.Activity); // If you're connected, forward your message ConversationReference otherRef = connectionManager.ConnectedTo(self); if (otherRef != null) { await ForwardTo(context, otherRef); return; } // If you're waiting, you need to be patient if (connectionManager.IsWaiting(self)) { await context.SendActivity("You are still waiting for someone"); return; } // You're new! IList <Connection> pending = connectionManager.GetWaitingConnections(); if (pending.Count > 0) { // Found someone to pair you with ConversationReference waitingRef = pending[0].References.Ref0; connectionManager.CompleteConnection(waitingRef, self); await SendTo(context, "You have been connected to someone who just joined", waitingRef); await context.SendActivity("You have been connected to someone who was waiting"); } else { // No one to pair you with, so try to wait for someone try { connectionManager.StartConnection(self); await context.SendActivity("You are now waiting for someone"); } catch { // startConnection() threw because there's already a connection await context.SendActivity("Sorry, I can't connect you"); } } }
private JobData CreateJob(ITurnContext context, Dictionary <int, JobData> jobLog) { int number = 5; var job = new JobData { JobNumber = number, Conversation = TurnContext.GetConversationReference(context.Activity) }; jobLog.Add(job.JobNumber, job); return(job); }
public Task OnTurn(ITurnContext context) { // Only handle message activities if (context.Activity.Type != ActivityTypes.Message) { return(Task.CompletedTask); } ConversationReference self = TurnContext.GetConversationReference(context.Activity); return(ForwardTo(context, self)); }
public async Task OnTurn(ITurnContext turnContext) { // turnContext.Responded will be false if qna doesn't know how to answer. An example is 'how do I install office 365'. if (!turnContext.Responded && turnContext.Activity.Type == ActivityTypes.Message) { var conversationReference = TurnContext.GetConversationReference(turnContext.Activity); var filepath = Path.Combine(hostingEnvironment.WebRootPath, "resume.json"); File.WriteAllText(filepath, JsonConvert.SerializeObject(conversationReference)); await turnContext.SendActivity($"Sorry, I don't know how to answer that automatically, we will get an answer to you ASAP and get back to you. Your reference number is {String.Format("{0:X}", conversationReference.ActivityId.GetHashCode())}"); } }
public async Task Do(LoggerBotContext context) { var userId = context.Activity.From.Id; var serviceUrl = context.Activity.ServiceUrl; var botId = "28:" + LoggerBot.MicrosoftAppCredentials.MicrosoftAppId; var botName = "PlaceholderName"; var connectorClient = new ConnectorClient( baseUri: new Uri(serviceUrl), microsoftAppId: LoggerBot.MicrosoftAppCredentials.MicrosoftAppId, microsoftAppPassword: LoggerBot.MicrosoftAppCredentials.MicrosoftAppPassword); dynamic channelDataNew = new ExpandoObject(); dynamic tenantObj = new ExpandoObject(); tenantObj.id = "72f988bf-86f1-41af-91ab-2d7cd011db47"; channelDataNew.tenant = tenantObj; var parameters = new ConversationParameters { Bot = new ChannelAccount(botId, botName), Members = new ChannelAccount[] { new ChannelAccount(userId) }, ChannelData = channelDataNew, }; ConversationResourceResponse conversationResource = await connectorClient.Conversations.CreateConversationAsync(parameters); if (conversationResource != null) { var createdActivity = new Activity { From = new ChannelAccount(userId), Recipient = new ChannelAccount(botId, botName), Conversation = new ConversationAccount( id: conversationResource.Id, isGroup: false, name: "PlaceholderName"), ChannelId = "msteams", ServiceUrl = serviceUrl, }; ConversationReference conversationReference = TurnContext.GetConversationReference(createdActivity); await context.Adapter.ContinueConversation( LoggerBot.MicrosoftAppCredentials.MicrosoftAppId, conversationReference, async (ctx) => { await ctx.SendActivity("Proactive Message"); }); } }
public async Task OnTurn(ITurnContext context, MiddlewareSet.NextDelegate next) { var authToken = TokenStorage.LoadConfiguration(context.Activity.Conversation.Id); if (authToken == null) { if (context.Activity.UserHasJustSentMessage() || context.Activity.UserHasJustJoinedConversation()) { var conversationReference = TurnContext.GetConversationReference(context.Activity); var serializedCookie = WebUtility.UrlEncode(JsonConvert.SerializeObject(conversationReference)); var signInUrl = AzureAdExtensions.GetUserConsentLoginUrl(AzureAdTenant, AppClientId, AppRedirectUri, PermissionsRequested, serializedCookie); var activity = context.Activity.CreateReply(); activity.AddSignInCard(signInUrl); await context.SendActivity(activity); } } else if (authToken.ExpiresIn < DateTime.Now.AddMinutes(-10)) { if (context.Activity.UserHasJustSentMessage() || context.Activity.UserHasJustJoinedConversation()) { var client = new HttpClient(); var accessToken = await AzureAdExtensions.GetAccessTokenUsingRefreshToken(client, AzureAdTenant, authToken.RefreshToken, AppClientId, AppRedirectUri, AppClientSecret, PermissionsRequested); // have to save it authToken = new ConversationAuthToken(context.Activity.Conversation.Id) { AccessToken = accessToken.accessToken, RefreshToken = accessToken.refreshToken, ExpiresIn = accessToken.refreshTokenExpiresIn }; TokenStorage.SaveConfiguration(authToken); // make the authtoken available to downstream pipeline components context.Services.Add(AUTH_TOKEN_KEY, authToken); await next(); } } else { // make the authtoken available to downstream pipeline components context.Services.Add(AUTH_TOKEN_KEY, authToken); await next(); } }
public async Task OnTurn(ITurnContext context) { var state = ConversationState <Dictionary <string, object> > .Get(context); var state2 = context.GetConversationState <State>(); // state2.name = "Valeriia"; var dc = dialogs.CreateContext(context, state); if (context.Activity.Type == ActivityTypes.Message) { await dc.Continue(); if (!context.Responded) { if (context.Activity.Text.ToLowerInvariant().Contains("proactive")) { var jobLog = GetJobLog(context); var job = CreateJob(context, jobLog); var appId = "f68cf47c-cbdd-4f23-9eda-71cca9dc4632"; var conversation = TurnContext.GetConversationReference(context.Activity); await context.SendActivity($"We're starting job {job.JobNumber} for you. We'll notify you when it's complete."); var adapter = context.Adapter; await Task.Run(() => { Thread.Sleep(5000); // Perform bookkeeping and send the proactive message. CompleteJob(adapter, appId, conversation, job.JobNumber); }); } else { await dc.Begin("greetings"); } } } }
public async Task OnTurn(ITurnContext context) { if (context.Activity.Type is ActivityTypes.Message) { var message = context.Activity; //check mentions in the message -> MSTEAMS if (context.Activity.ChannelId == "msteams") { Mention[] m = context.Activity.GetMentions(); for (int i = 0; i < m.Length; i++) { if (m[i].Mentioned.Id == context.Activity.Recipient.Id) { //Bot is in the @mention list. //The below example will strip the bot name out of the message, so you can parse it as if it wasn't included. Note that the Text object will contain the full bot name, if applicable. if (m[i].Text != null) { message.Text = message.Text.Replace(m[i].Text, "").Trim(); } } } } //when user ask about info in VSTS, he/she should be authenticated if (message.AsMessageActivity().Text == "vsts") { //check in the DB if there is a valid token for the specific user CosmosDbHelper cdh = new CosmosDbHelper("VSTSDb", "VSTSToken"); var tk = await cdh.ReadTokenFromDB("VSTSDb", "VSTSToken", context.Activity.From.Id); if (tk != null) { //TODO: query VSTS to retrieve information await context.SendActivity("Here there will be the result of a custom query..."); } else { //if there isn't a token for the user get ConversationReference var cf = TurnContext.GetConversationReference(context.Activity); //and generate the URL for user authentication var url = AuthenticationHelper.GenerateAuthorizeUrl(cf); Activity replyToConversation = message.CreateReply(); replyToConversation.Attachments = new List <Attachment>(); List <CardAction> cardButtons = new List <CardAction>(); CardAction plButton = new CardAction() { Value = url, Type = "openUrl", Title = "Connect" }; cardButtons.Add(plButton); SigninCard plCard = new SigninCard(text: "You need to authorize me", buttons: cardButtons); Attachment plAttachment = plCard.ToAttachment(); replyToConversation.Attachments.Add(plAttachment); var reply = await context.SendActivity(replyToConversation); await context.SendActivity(url); } } else { // send the information about the Activity, at the moment //TODO: manage other features for the bot await context.SendActivity( $"ConversationId " + context.Activity.Conversation.Id + "\n" + "BotId " + context.Activity.Recipient.Id + "\n" + "BotName " + context.Activity.Name + "\n" + "tenantId " + context.Activity.ChannelData); } } }
public async Task OnTurn(ITurnContext context) { // Welcome message when user or agent joins conversation if (context.Activity.Type == ActivityTypes.ConversationUpdate) { if (context.Activity.MembersAdded.Any(m => m.Id != context.Activity.Recipient.Id)) { string msg = IsAgent(context) ? "Say 'list' to list pending users, or say a user ID to connect to" : "Say 'agent' to connect to an agent"; await context.SendActivity(msg); return; } } // Ignore non-message activities if (context.Activity.Type != ActivityTypes.Message) { return; } // If connected, forward activity ConversationReference self = TurnContext.GetConversationReference(context.Activity); ConversationReference connectedTo = connectionManager.ConnectedTo(self); if (connectedTo != null) { await ForwardTo(context, connectedTo); return; } // Agent code if (IsAgent(context)) { IList <Connection> pending = connectionManager.GetWaitingConnections(); if (context.Activity.Text == "list") { // Send agent a list of pending users var pendingStrs = pending.Select(c => $"{c.References.Ref0.User.Name} ({c.References.Ref0.User.Id})"); await context.SendActivity(pendingStrs.Count() > 0?string.Join("\n\n", pendingStrs) : "No users waiting"); return; } else { // Assume the agent said a pending user's id. Find that user // TODO: this is kind of messy b/c Connection is a value type Connection conn = pending.FirstOrDefault(p => p.References.Ref0.User.Id == context.Activity.Text); if (conn.References.Ref0 == null) { await context.SendActivity($"No pending user with id {context.Activity.Text}"); return; } // Connect to the pending user connectionManager.CompleteConnection(conn.References.Ref0, self); // Send message to both user and agent await SendTo(context, $"You are connected to {context.Activity.From.Name}", conn.References.Ref0); await context.SendActivity($"You are connected to {conn.References.Ref0.User.Name}"); return; } } // User code else { if (context.Activity.Text == "agent") { // Start waiting for an agent connectionManager.StartConnection(self); await context.SendActivity("Waiting for an agent... say 'stop' to stop waiting"); return; } else if (context.Activity.Text == "stop") { // Stop waiting for an agent connectionManager.RemoveConnection(self); await context.SendActivity("Stopped waiting"); return; } else { // Echo bot await context.SendActivity($"You said: {context.Activity.Text}"); return; } } }