public static async Task <string> CreateAgentConversationEx(IDialogContext context, string topicName, AdaptiveCard cardToSend, UserProfile endUserProfile) { string serviceUrl = GetServiceUrl(context); var agentChannelInfo = await IdTable.GetAgentChannelInfo(); ChannelAccount botMsTeamsChannelAccount = context.Activity.ChannelId == ActivityHelper.SmsChannelId ? await IdTable.GetBotId() : context.Activity.From; using (var connectorClient = await BotConnectorUtility.BuildConnectorClientAsync(serviceUrl)) { try { var channelData = new TeamsChannelData { Channel = agentChannelInfo }; IMessageActivity agentMessage = Activity.CreateMessageActivity(); agentMessage.From = botMsTeamsChannelAccount; agentMessage.Recipient = new ChannelAccount(ConfigurationManager.AppSettings["AgentToAssignVsoTasksTo"]); agentMessage.Type = ActivityTypes.Message; agentMessage.ChannelId = ActivityHelper.MsTeamChannelId; agentMessage.ServiceUrl = serviceUrl; agentMessage.Attachments = new List <Attachment> { new Attachment { ContentType = AdaptiveCard.ContentType, Content = cardToSend } }; var agentMessageActivity = (Activity)agentMessage; ConversationParameters conversationParams = new ConversationParameters( isGroup: true, bot: null, members: null, topicName: topicName, activity: agentMessageActivity, channelData: channelData); var conversationResourceResponse = await BotConnectorUtility.BuildRetryPolicy().ExecuteAsync( async() => await connectorClient.Conversations.CreateConversationAsync(conversationParams)); Trace.TraceInformation( $"[SUCCESS]: CreateAgentConversation. response id ={conversationResourceResponse.Id}"); WebApiConfig.TelemetryClient.TrackEvent("CreateAgentConversation", new Dictionary <string, string> { { "endUser", agentMessage.From.Name }, { "agentConversationId", conversationResourceResponse.Id }, }); return(conversationResourceResponse.Id); } catch (System.Exception e) { WebApiConfig.TelemetryClient.TrackException(e, new Dictionary <string, string> { { "function", "CreateAgentConversation" } }); throw; } } }
/// <summary> /// Creates a user conversation. /// </summary> /// <param name="userDataEntity">The data entity for the user for whom the conversation should be created.</param> /// <param name="maxNumberOfAttempts">The maximum number of request attempts to create the conversation.</param> /// <param name="log">The logger.</param> /// <returns>A <see cref="Task{TResult}"/> representing the result of the asynchronous operation.</returns> public async Task <CreateUserConversationResponse> CreateConversationAsync( UserDataEntity userDataEntity, int maxNumberOfAttempts, ILogger log) { var createConversationResponse = new CreateUserConversationResponse(); // Set the service URL in the trusted list to ensure the SDK includes the token in the request. MicrosoftAppCredentials.TrustServiceUrl(userDataEntity.ServiceUrl); // Create the conversation parameters that will be used when // creating the conversation for that user. var conversationParameters = new ConversationParameters { TenantId = userDataEntity.TenantId, Members = new ChannelAccount[] { new ChannelAccount { Id = userDataEntity.UserId, }, }, }; // Loop through attempts to try and create the conversation for the user. var conversationCreatedSuccessfully = false; for (int i = 1; i <= maxNumberOfAttempts && !conversationCreatedSuccessfully; i++) { try { await this.botAdapter.CreateConversationAsync( channelId : CreateUserConversationService.MicrosoftTeamsChannelId, serviceUrl : userDataEntity.ServiceUrl, credentials : this.appCredentials, conversationParameters : conversationParameters, callback : (turnContext, cancellationToken) => { // If this callback is used, that means the conversation was // created successfully and the information will be in the Activity of // the turnContext. // Set the status code to indicate it was created, set that it was // successfully created, and place that conversationId in the response for // use when sending the notification to the user. createConversationResponse.ResultType = CreateUserConversationResultType.Succeeded; createConversationResponse.StatusCode = (int)HttpStatusCode.Created; createConversationResponse.ConversationId = turnContext.Activity.Conversation.Id; // This is used to signal the conversation was created successfully and to // "break" out of the loop in order to not make multiple attempts. conversationCreatedSuccessfully = true; return(Task.CompletedTask); }, cancellationToken : CancellationToken.None); } catch (ErrorResponseException e) { var errorMessage = $"{e.GetType()}: {e.Message}"; log.LogError(e, $"ERROR: {errorMessage}"); // This exception is thrown when a failure response is received when making the request // to create the conversation. var responseStatusCode = e.Response.StatusCode; createConversationResponse.StatusCode = (int)responseStatusCode; // If the response was a throttled status code or a 5xx status code, // then delay and retry the request. if (responseStatusCode == HttpStatusCode.TooManyRequests || ((int)responseStatusCode >= 500 && (int)responseStatusCode < 600)) { if (responseStatusCode == HttpStatusCode.TooManyRequests) { // If the request was throttled, set the flag for indicating the throttled state. createConversationResponse.ResultType = CreateUserConversationResultType.Throttled; } else { // If the request failed with a 5xx status code, set the flag for indicating the failure // and store the content of the error message. createConversationResponse.ResultType = CreateUserConversationResultType.Failed; createConversationResponse.ErrorMessage = e.Response.Content; } // If the maximum number of attempts has not been reached, delay // for a bit of time to attempt the request again. // Do not delay if already attempted the maximum number of attempts. if (i < maxNumberOfAttempts) { var random = new Random(); await Task.Delay(random.Next(500, 1500)); } } else { // If in this block, then an error has occurred with the service. // Return the failure and do not attempt the request again. createConversationResponse.ResultType = CreateUserConversationResultType.Failed; createConversationResponse.ErrorMessage = e.Response.Content; break; } } } return(createConversationResponse); }
/// <summary> /// Creates a conversation on the specified channel. /// </summary> /// <param name="channelId">The ID for the channel.</param> /// <param name="serviceUrl">The channel's service URL endpoint.</param> /// <param name="credentials">The application credentials for the bot.</param> /// <param name="conversationParameters">The conversation information to use to /// create the conversation.</param> /// <param name="callback">The method to call for the resulting bot turn.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects /// or threads to receive notice of cancellation.</param> /// <returns>A task that represents the work queued to execute.</returns> /// <remarks>To start a conversation, your bot must know its account information /// and the user's account information on that channel. /// Most _channels only support initiating a direct message (non-group) conversation. /// <para>The adapter attempts to create a new conversation on the channel, and /// then sends a <c>conversationUpdate</c> activity through its middleware pipeline /// to the <paramref name="callback"/> method.</para> /// <para>If the conversation is established with the /// specified users, the ID of the activity's <see cref="IActivity.Conversation"/> /// will contain the ID of the new conversation.</para> /// </remarks> public virtual async Task CreateConversationAsync(string channelId, string serviceUrl, MicrosoftAppCredentials credentials, ConversationParameters conversationParameters, BotCallbackHandler callback, CancellationToken cancellationToken) { var connectorClient = CreateConnectorClient(serviceUrl, credentials); var result = await connectorClient.Conversations.CreateConversationAsync(conversationParameters, cancellationToken).ConfigureAwait(false); // Create a conversation update activity to represent the result. var eventActivity = Activity.CreateEventActivity(); eventActivity.Name = "CreateConversation"; eventActivity.ChannelId = channelId; eventActivity.ServiceUrl = serviceUrl; eventActivity.Id = result.ActivityId ?? Guid.NewGuid().ToString("n"); eventActivity.Conversation = new ConversationAccount(id: result.Id); eventActivity.Recipient = conversationParameters.Bot; using (TurnContext context = new TurnContext(this, (Activity)eventActivity)) { ClaimsIdentity claimsIdentity = new ClaimsIdentity(); claimsIdentity.AddClaim(new Claim(AuthenticationConstants.AudienceClaim, credentials.MicrosoftAppId)); claimsIdentity.AddClaim(new Claim(AuthenticationConstants.AppIdClaim, credentials.MicrosoftAppId)); claimsIdentity.AddClaim(new Claim(AuthenticationConstants.ServiceUrlClaim, serviceUrl)); context.TurnState.Add <IIdentity>(BotIdentityKey, claimsIdentity); context.TurnState.Add(connectorClient); await RunPipelineAsync(context, callback, cancellationToken).ConfigureAwait(false); } }
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); } }
protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken) { var teamsChannelId = turnContext.Activity.TeamsGetChannelId(); var message = MessageFactory.Text("good morning"); var serviceUrl = turnContext.Activity.ServiceUrl; var credentials = new MicrosoftAppCredentials(_appId, _appPassword); // there are two scenarios for create conversation // (1) starting a thread within a channel var conversationParameters = new ConversationParameters { IsGroup = true, ChannelData = new { channel = new { id = teamsChannelId } }, Activity = (Activity)message, }; ConversationReference conversationReference = null; await((BotFrameworkAdapter)turnContext.Adapter).CreateConversationAsync( teamsChannelId, serviceUrl, credentials, conversationParameters, (t, ct) => { conversationReference = t.Activity.GetConversationReference(); return(Task.CompletedTask); }, cancellationToken); //// (2) starting a one on one chat //var accounts = (await TeamsInfo.GetMembersAsync(turnContext)).ToArray(); //var account = accounts.First(); //var conversationParameters = new ConversationParameters //{ // IsGroup = false, // Bot = turnContext.Activity.Recipient, // Members = new ChannelAccount[] { account }, // TenantId = turnContext.Activity.Conversation.TenantId, //}; //ConversationReference conversationReference = null; //await ((BotFrameworkAdapter)turnContext.Adapter).CreateConversationAsync( // teamsChannelId, // serviceUrl, // credentials, // conversationParameters, // (t, ct) => // { // conversationReference = t.Activity.GetConversationReference(); // return Task.CompletedTask; // }, // cancellationToken); //await ((BotFrameworkAdapter)turnContext.Adapter).ContinueConversationAsync( // _appId, // conversationReference, // async (t, ct) => // { // await t.SendActivityAsync(MessageFactory.Text("good afternoon"), ct); // await t.SendActivityAsync(MessageFactory.Text("good night"), ct); // }, // cancellationToken); }
public async Task <HttpResponseMessage> Post([FromBody] Activity activity) { using (var connector = new ConnectorClient(new Uri(activity.ServiceUrl))) { var val = activity.Value; if (activity.IsComposeExtensionQuery()) { var response = MessageExtension.HandleMessageExtensionQuery(connector, activity, result); return(response != null ? Request.CreateResponse <ComposeExtensionResponse>(response) : new HttpResponseMessage(HttpStatusCode.OK)); } else { if (activity.Value != null) { result = await GetActivity(activity); } else { await EchoBot.EchoMessage(connector, activity); } } if (activity.Type == ActivityTypes.ConversationUpdate) { for (int i = 0; i < activity.MembersAdded.Count; i++) { if (activity.MembersAdded[i].Id == activity.Recipient.Id) { var reply = activity.CreateReply(); reply.Text = "Hi! I am the Event Management bot for Dev Days 2019 happening in Taiwan. Ask me questions about the event and I can help you find answers Ask me questions like \n\n" + " *\r What is the venue? \r\n\n" + " *\r What tracks are available? \r\n\n" + " *\r Do we have workshops planned? \n\n".Replace("\n", Environment.NewLine); await connector.Conversations.ReplyToActivityAsync(reply); var channelData = activity.GetChannelData <TeamsChannelData>(); if (channelData.Team != null) { ConversationParameters param = new ConversationParameters() { Members = new List <ChannelAccount>() { new ChannelAccount() { Id = activity.From.Id } }, ChannelData = new TeamsChannelData() { Tenant = channelData.Tenant, Notification = new NotificationInfo() { Alert = true } } }; var resource = await connector.Conversations.CreateConversationAsync(param); await connector.Conversations.SendToConversationAsync(resource.Id, reply); } break; } } } return(new HttpResponseMessage(HttpStatusCode.Accepted)); } }
/// <summary> /// CreateConversation() API. /// </summary> /// <remarks> /// Override this method to create a new Conversation. /// /// POST to this method with a /// * Bot being the bot creating the conversation /// * IsGroup set to true if this is not a direct message (default is false) /// * Array containing the members to include in the conversation /// /// The return value is a ResourceResponse which contains a conversation ID /// which is suitable for use /// in the message payload and REST API URIs. /// /// Most channels only support the semantics of bots initiating a direct /// message conversation. An example of how to do that would be: /// /// var resource = await connector.conversations.CreateConversation(new /// ConversationParameters(){ Bot = bot, members = new ChannelAccount[] { new /// ChannelAccount("user1") } ); /// await connect.Conversations.OnSendToConversationAsync(resource.Id, new /// Activity() ... ) ; /// /// end. /// </remarks> /// <param name="claimsIdentity">claimsIdentity for the bot, should have AudienceClaim, AppIdClaim and ServiceUrlClaim.</param> /// <param name='parameters'>Parameters to create the conversation from.</param> /// <param name='cancellationToken'>The cancellation token.</param> /// <returns>task for a conversation resource response.</returns> protected virtual Task <ConversationResourceResponse> OnCreateConversationAsync(ClaimsIdentity claimsIdentity, ConversationParameters parameters, CancellationToken cancellationToken = default) { throw new NotImplementedException(); }
public virtual async Task <IActionResult> CreateConversationAsync([FromBody] ConversationParameters parameters) { var result = await _handler.HandleCreateConversationAsync(HttpContext.Request.Headers["Authorization"], parameters).ConfigureAwait(false); return(new JsonResult(result, HttpHelper.BotMessageSerializerSettings)); }
/// <summary> /// Send Channel Notification. /// </summary> /// <param name="botAccount">connectorClient.</param> /// <param name="serviceUrl">tenantId.</param> /// <param name="channelId">userId.</param> /// <param name="messageText">messageText.</param> /// <param name="attachment">attachment.</param> /// <returns>.</returns> public async Task <NotificationSendStatus> SendChannelNotification(ChannelAccount botAccount, string serviceUrl, string channelId, string messageText, Attachment attachment, string ReflectMessageId = "") { try { var replyMessage = Activity.CreateMessageActivity(); replyMessage.Text = messageText; if (attachment != null) { replyMessage.Attachments.Add(attachment); } MicrosoftAppCredentials.TrustServiceUrl(serviceUrl, DateTime.MaxValue); using (var connectorClient = new ConnectorClient(new Uri(serviceUrl), _configuration["MicrosoftAppId"], _configuration["MicrosoftAppPassword"])) { var parameters = new ConversationParameters { Bot = botAccount, ChannelData = new TeamsChannelData { Channel = new ChannelInfo(channelId), Notification = new NotificationInfo() { Alert = true } }, IsGroup = true, Activity = (Activity)replyMessage }; var exponentialBackoffRetryStrategy = new ExponentialBackoff( 3, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(20), TimeSpan.FromSeconds(1)); // Define the Retry Policy var retryPolicy = new RetryPolicy(new BotSdkTransientExceptionDetectionStrategy(), exponentialBackoffRetryStrategy); if (ReflectMessageId == "") { var conversationResource = await connectorClient.Conversations.CreateConversationAsync(parameters); return(new NotificationSendStatus() { MessageId = conversationResource.Id, IsSuccessful = true }); } else { var conversationId = $"{channelId};messageid={ReflectMessageId}"; var replyActivity = MessageFactory.Attachment(attachment); replyActivity.Conversation = new ConversationAccount(id: conversationId); var resultfeedback = await connectorClient.Conversations.SendToConversationAsync((Activity)replyActivity); return(new NotificationSendStatus() { MessageId = resultfeedback.Id, IsSuccessful = true }); } } } catch (Exception ex) { return(new NotificationSendStatus() { IsSuccessful = false, FailureMessage = ex.Message }); } }
private async Task <Activity> HandleSystemMessage(Activity message) { if (message.Type == ActivityTypes.DeleteUserData) { // Implement user deletion here // If we handle user deletion, return a real message } else if (message.Type == ActivityTypes.ConversationUpdate) { // 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 if (message.MembersAdded.Any(m => m.Id.Contains(message.Recipient.Id))) { try { var connectorClient = new ConnectorClient(new Uri(message.ServiceUrl)); var channelData = message.GetChannelData <TeamsChannelData>(); var TeamorConversationId = channelData.Team != null ? channelData.Team.Id : message.Conversation.Id; if (channelData.Team == null) { await AddtoDatabase(message, TeamorConversationId, message.From.Id); //await Conversation.SendAsync(message, () => new EchoBot()); ThumbnailCard card = EchoBot.GetWelcomeMessage(); var reply = message.CreateReply(); reply.TextFormat = TextFormatTypes.Xml; reply.Attachments.Add(card.ToAttachment()); await connectorClient.Conversations.ReplyToActivityAsync(reply); return(null); } var members = await connectorClient.Conversations.GetConversationMembersAsync(TeamorConversationId); foreach (var meb in members) { await AddtoDatabase(message, TeamorConversationId, meb.Id); ThumbnailCard card = EchoBot.GetWelcomeMessage(); //ThumbnailCard card = EchoBot.GetHelpMessage(); var replyMessage = Activity.CreateMessageActivity(); var parameters = new ConversationParameters { Members = new ChannelAccount[] { new ChannelAccount(meb.Id) }, ChannelData = new TeamsChannelData { Tenant = channelData.Tenant, Notification = new NotificationInfo() { Alert = true } } }; var conversationResource = await connectorClient.Conversations.CreateConversationAsync(parameters); replyMessage.ChannelData = new TeamsChannelData() { Notification = new NotificationInfo(true) }; replyMessage.Conversation = new ConversationAccount(id: conversationResource.Id.ToString()); replyMessage.TextFormat = TextFormatTypes.Xml; replyMessage.Attachments.Add(card.ToAttachment()); await connectorClient.Conversations.SendToConversationAsync((Activity)replyMessage); } return(null); } catch (Exception ex) { return(null); } // Bot Installation // Bot is added. Let's send welcome message. //var connectorClient = new ConnectorClient(new Uri(message.ServiceUrl)); } // For Add new member for (int i = 0; i < message.MembersAdded.Count; i++) { if (message.MembersAdded[i].Id != message.Recipient.Id) { try { var connectorClient = new ConnectorClient(new Uri(message.ServiceUrl)); var userId = message.MembersAdded[i].Id; var channelData = message.GetChannelData <TeamsChannelData>(); var user = new UserDetails(); var TeamorConversationId = channelData.Team != null ? channelData.Team.Id : message.Conversation.Id; //string emailid = await GetUserEmailId(userId, message.ServiceUrl, TeamorConversationId); //user.EmaildId = emailid; user.EmaildId = await GetUserEmailId(userId, message.ServiceUrl, TeamorConversationId); user.UserId = userId; user.UserName = await GetUserName(userId, message.ServiceUrl, TeamorConversationId); var parameters = new ConversationParameters { Members = new ChannelAccount[] { new ChannelAccount(userId) }, ChannelData = new TeamsChannelData { Tenant = channelData.Tenant, Notification = new NotificationInfo() { Alert = true } } }; var conversationResource = await connectorClient.Conversations.CreateConversationAsync(parameters); var replyMessage = Activity.CreateMessageActivity(); replyMessage.ChannelData = new TeamsChannelData() { Notification = new NotificationInfo(true) }; replyMessage.Conversation = new ConversationAccount(id: conversationResource.Id.ToString()); var name = await GetUserName(userId, message.ServiceUrl, TeamorConversationId); if (name != null) { name = name.Split(' ').First(); } user.Type = Helper.Constants.NewUser; var existinguserRecord = await DocumentDBRepository.GetItemsAsync <UserDetails>(u => u.EmaildId == user.EmaildId && u.Type == Helper.Constants.NewUser); if (existinguserRecord.Count() == 0) { var NewUserRecord = await DocumentDBRepository.CreateItemAsync(user); } ThumbnailCard card = EchoBot.GetWelcomeMessage(); replyMessage.Attachments.Add(card.ToAttachment()); await connectorClient.Conversations.SendToConversationAsync((Activity)replyMessage); } catch (Exception ex) { Console.WriteLine(ex); } } } } 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); }
public virtual Task <ActionResult <ConversationResourceResponse> > CreateConversationAsync([FromBody] ConversationParameters parameters) { throw new NotSupportedException("CreateConversationAsync is not supported"); }
/// <summary> /// CreateConversation() API for Skill. /// </summary> /// <remarks> /// Create a new Conversation. /// /// POST to this method with a /// * Bot being the bot creating the conversation /// * IsGroup set to true if this is not a direct message (default is false) /// * Array containing the members to include in the conversation /// /// The return value is a ResourceResponse which contains a conversation id /// which is suitable for use /// in the message payload and REST API uris. /// /// Most channels only support the semantics of bots initiating a direct /// message conversation. An example of how to do that would be: /// /// var resource = await connector.conversations.CreateConversation(new /// ConversationParameters(){ Bot = bot, members = new ChannelAccount[] { new /// ChannelAccount("user1") } ); /// await connect.Conversations.SendToConversationAsync(resource.Id, new /// Activity() ... ) ; /// /// end. /// </remarks> /// <param name="bot">The <see cref="IBot"/> instance.</param> /// <param name="claimsIdentity">claimsIdentity for the bot, should have AudienceClaim, AppIdClaim and ServiceUrlClaim.</param> /// <param name='conversationId'>conversationId.</param> /// <param name='parameters'>Parameters to create the conversation from.</param> /// <param name='cancellationToken'>The cancellation token.</param> /// <returns>task for a conversation resource response.</returns> public virtual Task <ConversationResourceResponse> CreateConversationAsync(IBot bot, ClaimsIdentity claimsIdentity, string conversationId, ConversationParameters parameters, CancellationToken cancellationToken = default) { return(InvokeChannelApiAsync <ConversationResourceResponse>(bot, claimsIdentity, ChannelApiMethods.CreateConversation, conversationId, parameters)); }
/// <summary> /// Send the given attachment to the specified team. /// </summary> /// <param name="rewardCycleEntity">Reward cycle model object.</param> /// <returns>A task that sends notification card in channel.</returns> private async Task SendCardToTeamAsync(RewardCycleEntity rewardCycleEntity) { try { var awardsList = await this.awardsStorageProvider.GetAwardsAsync(rewardCycleEntity.TeamId); var valuesfromTaskModule = new TaskModuleResponseDetails() { RewardCycleStartDate = rewardCycleEntity.RewardCycleStartDate, RewardCycleEndDate = rewardCycleEntity.RewardCycleEndDate, RewardCycleId = rewardCycleEntity.CycleId, }; var teamDetails = await this.teamStorageProvider.GetTeamDetailAsync(rewardCycleEntity.TeamId); string serviceUrl = teamDetails.ServiceUrl; MicrosoftAppCredentials.TrustServiceUrl(serviceUrl); string teamsChannelId = rewardCycleEntity.TeamId; var conversationReference = new ConversationReference() { ChannelId = Channel, Bot = new ChannelAccount() { Id = this.microsoftAppCredentials.MicrosoftAppId }, ServiceUrl = serviceUrl, Conversation = new ConversationAccount() { ConversationType = ChannelConversationType, IsGroup = true, Id = teamsChannelId, TenantId = teamsChannelId }, }; this.logger.LogInformation($"sending notification to channelId- {teamsChannelId}"); await retryPolicy.ExecuteAsync(async() => { try { var conversationParameters = new ConversationParameters() { ChannelData = new TeamsChannelData() { Team = new TeamInfo() { Id = rewardCycleEntity.TeamId }, Channel = new ChannelInfo() { Id = rewardCycleEntity.TeamId } }, Activity = (Activity)MessageFactory.Carousel(NominateCarouselCard.GetAwardsCard(this.options.Value.AppBaseUri, awardsList, this.localizer, valuesfromTaskModule)), Bot = new ChannelAccount() { Id = this.microsoftAppCredentials.MicrosoftAppId }, IsGroup = true, TenantId = this.options.Value.TenantId, }; await((BotFrameworkAdapter)this.adapter).CreateConversationAsync( Channel, serviceUrl, this.microsoftAppCredentials, conversationParameters, async(conversationTurnContext, conversationCancellationToken) => { Activity mentionActivity = MessageFactory.Text(this.localizer.GetString("NominationReminderNotificationText")); await((BotFrameworkAdapter)this.adapter).ContinueConversationAsync( this.microsoftAppCredentials.MicrosoftAppId, conversationTurnContext.Activity.GetConversationReference(), async(continueConversationTurnContext, continueConversationCancellationToken) => { mentionActivity.ApplyConversationReference(conversationTurnContext.Activity.GetConversationReference()); await continueConversationTurnContext.SendActivityAsync(mentionActivity, continueConversationCancellationToken); }, conversationCancellationToken); }, default); } catch (Exception ex) { this.logger.LogError(ex, "Error while performing retry logic to send notification to channel."); throw; } }); } catch (Exception ex) { this.logger.LogError(ex, "Error while sending notification to channel from background service."); } }
public static async Task <ConversationResourceResponse> CreateAgentConversation(ChannelInfo targetChannelInfo, AdaptiveCard card, string topicName, ConnectorClient connector, int vsoTicketNumber, IMessageActivity endUserActivity) { try { var channelData = new TeamsChannelData { Channel = targetChannelInfo }; IMessageActivity agentMessage = Activity.CreateMessageActivity(); agentMessage.From = endUserActivity.Recipient; agentMessage.Recipient = new ChannelAccount(ConfigurationManager.AppSettings["AgentToAssignVsoTasksTo"]); agentMessage.Type = ActivityTypes.Message; agentMessage.ChannelId = ActivityHelper.MsTeamChannelId; agentMessage.ServiceUrl = endUserActivity.ServiceUrl; agentMessage.Attachments = new List <Attachment> { new Attachment { ContentType = AdaptiveCard.ContentType, Content = card } }; var agentMessageActivity = (Activity)agentMessage; ConversationParameters conversationParams = new ConversationParameters( isGroup: true, bot: null, members: null, topicName: topicName, activity: agentMessageActivity, channelData: channelData); var conversationResourceResponse = await BotConnectorUtility.BuildRetryPolicy().ExecuteAsync(async() => await connector.Conversations.CreateConversationAsync(conversationParams)); Trace.TraceInformation($"[SUCCESS]: CreateAgentConversation. " + $"response id ={conversationResourceResponse.Id} vsoId={vsoTicketNumber} "); WebApiConfig.TelemetryClient.TrackEvent("CreateAgentConversation", new Dictionary <string, string> { { "endUser", agentMessage.From.Name }, { "agentConversationId", conversationResourceResponse.Id }, { "vsoId", vsoTicketNumber.ToString() }, }); return(conversationResourceResponse); } catch (System.Exception e) { WebApiConfig.TelemetryClient.TrackException(e, new Dictionary <string, string> { { "function", "CreateAgentConversation" }, { "endUser", endUserActivity.Recipient.Name }, { "vsoId", vsoTicketNumber.ToString() } }); throw; } }
public Task <HttpOperationResponse <object> > CreateConversationWithHttpMessagesAsync( ConversationParameters parameters, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = new CancellationToken()) { return(null); }
public async Task <StatusCodes> sendDirectCardAsync(Opportunity opportunity, UserProfile sendTo, string requestId = "") { _logger.LogInformation($"RequestId: {requestId} - CardNotificationService_sendDirectCardAsync called."); var channelId = "19:[email protected]"; var channelData = new TeamsChannelData { Channel = new ChannelInfo(channelId) //Notification = new NotificationInfo(true) }; var botAccount = new ChannelAccount("28:f1336ec9-ee95-4e1a-83cf-43b3571f37e7", "Proposal Manager onterawe"); var userAccount = new ChannelAccount(sendTo.Fields.UserPrincipalName, sendTo.DisplayName); //var conversationId = (await _connectorClient.Conversations.CreateDirectConversationAsync(botAccount, userAccount)).Id; var conversationId = "None yet"; var responseCreate = new JObject(); try { var respCreateConversation = await _connectorClient.Conversations.CreateDirectConversationAsync(botAccount, userAccount); //var respCreateConversation = _connectorClient.Conversations.CreateOrGetDirectConversation(botAccount, userAccount, "9ec16324-e534-4d84-81de-59a03f343e20"); conversationId = respCreateConversation.Id; responseCreate = JObject.FromObject(respCreateConversation); } catch (Exception ex) { _logger.LogError($"RequestId: {requestId} - CardNotificationService_sendDirectCardAsync CreateDirectConversationAsync error: {ex}"); } // [email protected] var recepientsList = new List <ChannelAccount>(); recepientsList.Add(userAccount); IMessageActivity newMessage = Activity.CreateMessageActivity(); newMessage.Type = ActivityTypes.Message; newMessage.From = botAccount; newMessage.Recipient = userAccount; newMessage.ChannelId = "msteams"; newMessage.Text = $"New opportunity via sendDirectCardAsync CreateConversationAsync conversationId: {conversationId}"; newMessage.AddMentionToText(userAccount, MentionTextLocation.AppendText, "@Proposal Manager onterawe"); ConversationParameters conversationParams = new ConversationParameters( isGroup: true, bot: botAccount, members: recepientsList, topicName: "Proposal Manager", channelData: channelData, activity: (Activity)newMessage); var result = await _connectorClient.Conversations.CreateConversationAsync(conversationParams); conversationParams.Activity.Text = "Before GetConversationMembersAsync"; result = await _connectorClient.Conversations.CreateConversationAsync(conversationParams); var members = await _connectorClient.Conversations.GetConversationMembersAsync(result.ActivityId); //newMessage.Conversation = new ConversationAccount(id: result.ActivityId); newMessage.Text = $"New opportunity via sendDirectCardAsync SendToConversationAsync {members}"; conversationParams.Activity = (Activity)newMessage; result = await _connectorClient.Conversations.CreateConversationAsync(conversationParams); //var result2 = await _connectorClient.Conversations.SendToConversationAsync((Activity)newMessage); //var result = await _connectorClient.Conversations.CreateDirectConversationAsync(botAccount, userAccount, newMessage); _logger.LogInformation($"RequestId: {requestId} - CardNotificationService_sendDirectCardAsync result.Id {result.Id}"); _logger.LogInformation($"RequestId: {requestId} - CardNotificationService_sendDirectCardAsync result.ServiceUrl {result.ServiceUrl}"); return(StatusCodes.Status200OK); }
public static async Task Main(string[] args) { //Teams internal id string teamInternalId = "19:[email protected]"; string serviceUrl = "https://smba.trafficmanager.net/emea/"; //the upn of the user who should recieve the personal message string mentionUserPrincipalName = "*****@*****.**"; //Office 365/Azure AD tenant id for the string tenantId = ""; //From the Bot Channel Registration string botClientID = "bbfc3f45-1a8d-47eb-99f5-dca58ac8a46d"; string botClientSecret = ""; var connectorClient = new ConnectorClient(new Uri(serviceUrl), new MicrosoftAppCredentials(botClientID, botClientSecret)); dynamic jsonObject = new JObject(); //jsonObject.givenName = "Ravi"; //jsonObject.surname = "Chandra"; //jsonObject.email = "*****@*****.**"; //jsonObject.userPrincipalName = "*****@*****.**"; //jsonObject.tenantId = "a7b57368-7e7b-4r5r5b-b3c5-e3ec26cc53der"; //jsonObject.userRole = "user"; jsonObject.givenName = "Reader"; jsonObject.surname = "1"; jsonObject.email = "*****@*****.**"; jsonObject.userPrincipalName = "*****@*****.**"; jsonObject.tenantId = "a7b5tg56368-7essss7b-4e76-b3c5-e3ec26c45tr3de"; jsonObject.userRole = "user"; //Manually fetch user details. Recipient user doesnt have to be in any Team //var user = new ChannelAccount { // AadObjectId = "624d2b21-cfc6-40af-b757-3acfed9cb4a7", // Id = "29:1KL4qDZSwZ7T-5U4b8ghA7cBNdSLanItMvVtIp_HhgJlh_ZLaPTbos7T5hLbDYVwzEcCLpt7dvZk1fNpBo0l8yw", // Name = "Reader1", // Properties = jsonObject, // Role = "null" //}; //Automatically fetch user details. User has to memember of the Team where BOT installed. Teams internal id. Uncomment to use it. var user = await((Microsoft.Bot.Connector.Conversations)connectorClient.Conversations).GetConversationMemberAsync(mentionUserPrincipalName, teamInternalId, default); var personalMessageActivity = MessageFactory.Text($"Ravis Skynet is active. Machine is taking control!"); var conversationParameters = new ConversationParameters() { ChannelData = new TeamsChannelData { Tenant = new TenantInfo { Id = tenantId, } }, Members = new List <ChannelAccount>() { user }, }; var response = await connectorClient.Conversations.CreateConversationAsync(conversationParameters); await connectorClient.Conversations.SendToConversationAsync(response.Id, personalMessageActivity); }
public async Task <StatusCodes> sendNotificationCardAsync(string opportunityName, string channelId, IList <UserProfile> sendToList, string messageText, string requestId = "") { _logger.LogInformation($"RequestId: {requestId} - CardNotificationService_sendNotificationCardAsync main called."); Guard.Against.NullOrEmpty(opportunityName, "sendNotificationCardAsync opportunityName is null or empty", requestId); Guard.Against.NullOrEmpty(channelId, "sendNotificationCardAsync channelId is null or empty", requestId); var sendList = sendToList.ToList(); var botAccount = new ChannelAccount(_appOptions.BotId, _appOptions.BotName); var userAccount = new ChannelAccount(); if (sendList.Count > 0) { userAccount = new ChannelAccount(sendList[0].Fields.UserPrincipalName, sendList[0].DisplayName); } else { userAccount = botAccount; } var channelData = new TeamsChannelData { Channel = new ChannelInfo(channelId), Notification = new NotificationInfo(true) }; IMessageActivity newMessage = Activity.CreateMessageActivity(); newMessage.Type = ActivityTypes.Message; newMessage.Text = messageText; newMessage.Summary = $"Opportunity: {opportunityName}"; //var heroCard = new HeroCard //{ // Title = "Test title", // Subtitle = "Test Subtitle", // Text = $"Some text" // //Buttons = new List<CardAction> { new CardAction(ActionTypes.OpenUrl, title: Constants.cardButtonTitle, value: notificationRequest.DeepLink) } //}; //newMessage.Attachments.Add(heroCard.ToAttachment()); var recepientsList = new List <ChannelAccount>(); foreach (var item in sendList) { if (!String.IsNullOrEmpty(item.DisplayName)) { newMessage.AddMentionToText(new ChannelAccount(item.Id, item.DisplayName), MentionTextLocation.AppendText, $"@{item.DisplayName}"); recepientsList.Add(new ChannelAccount(item.Fields.UserPrincipalName, item.DisplayName)); } } if (recepientsList.Count == 0) { recepientsList = null; } else { if (String.IsNullOrEmpty(recepientsList[0].Id)) { recepientsList = null; } } ConversationParameters conversationParams = new ConversationParameters( isGroup: true, bot: botAccount, //members: null, members: recepientsList, topicName: "Proposal Manager", activity: (Activity)newMessage, channelData: channelData); var result = await _connectorClient.Conversations.CreateConversationAsync(conversationParams); return(StatusCodes.Status200OK); }
/// <summary> /// Create a new Conversation. /// </summary> /// <param name="authHeader">The authentication header.</param> /// <param name="parameters">Parameters to create the conversation from.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>A <see cref="Task{TResult}"/> representing the result of the asynchronous operation.</returns> public async Task <ConversationResourceResponse> HandleCreateConversationAsync(string authHeader, ConversationParameters parameters, CancellationToken cancellationToken = default) { var claimsIdentity = await AuthenticateAsync(authHeader).ConfigureAwait(false); return(await OnCreateConversationAsync(claimsIdentity, parameters, cancellationToken).ConfigureAwait(false)); }
private async Task <Activity> HandleSystemMessage(Activity message) { if (message.Type == ActivityTypes.DeleteUserData) { // Implement user deletion here // If we handle user deletion, return a real message } else if (message.Type == ActivityTypes.ConversationUpdate) { // 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 for (int i = 0; i < message.MembersAdded.Count; i++) { if (message.MembersAdded[i].Id == message.Recipient.Id) { // Bot is added. Let's send welcome message. message.Text = "hi"; await Conversation.SendAsync(message, () => new RootDialog()); break; } else { try { var userId = message.MembersAdded[i].Id; var channelData = message.GetChannelData <TeamsChannelData>(); var connectorClient = new ConnectorClient(new Uri(message.ServiceUrl)); var parameters = new ConversationParameters { Members = new ChannelAccount[] { new ChannelAccount(userId) }, ChannelData = new TeamsChannelData { Tenant = channelData.Tenant, Notification = new NotificationInfo() { Alert = true } } }; var conversationResource = await connectorClient.Conversations.CreateConversationAsync(parameters); var replyMessage = Activity.CreateMessageActivity(); replyMessage.ChannelData = new TeamsChannelData() { Notification = new NotificationInfo(true) }; replyMessage.Conversation = new ConversationAccount(id: conversationResource.Id.ToString()); var name = message.MembersAdded[i].Name; if (name != null) { name = name.Split(' ').First(); } replyMessage.Attachments.Add(EchoBot.WelcomeLeaveCard(name, false)); await connectorClient.Conversations.SendToConversationAsync((Activity)replyMessage); } catch (Exception ex) { ErrorLogService.LogError(ex); } } } } 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 } return(null); }
/// <summary> /// Creates a conversation on the specified channel. /// </summary> /// <param name="channelId">The ID for the channel.</param> /// <param name="serviceUrl">The channel's service URL endpoint.</param> /// <param name="credentials">The application credentials for the bot.</param> /// <param name="conversationParameters">The conversation information to use to /// create the conversation.</param> /// <param name="callback">The method to call for the resulting bot turn.</param> /// <returns>A task that represents the work queued to execute.</returns> /// <remarks>To start a conversation, your bot must know its account information /// and the user's account information on that channel. /// Most channels only support initiating a direct message (non-group) conversation. /// <para>The adapter attempts to create a new conversation on the channel, and /// then sends a <c>conversationUpdate</c> activity through its middleware pipeline /// to the <paramref name="callback"/> method.</para> /// <para>If the conversation is established with the /// specified users, the ID of the activity's <see cref="IActivity.Conversation"/> /// will contain the ID of the new conversation.</para> /// </remarks> public virtual async Task CreateConversation(string channelId, string serviceUrl, MicrosoftAppCredentials credentials, ConversationParameters conversationParameters, Func <ITurnContext, Task> callback) { var connectorClient = this.CreateConnectorClient(serviceUrl, credentials); var result = await connectorClient.Conversations.CreateConversationAsync(conversationParameters).ConfigureAwait(false); // Create a conversation update activity to represent the result. var conversationUpdate = Activity.CreateConversationUpdateActivity(); conversationUpdate.ChannelId = channelId; conversationUpdate.TopicName = conversationParameters.TopicName; conversationUpdate.ServiceUrl = serviceUrl; conversationUpdate.MembersAdded = conversationParameters.Members; conversationUpdate.Id = result.ActivityId ?? Guid.NewGuid().ToString("n"); conversationUpdate.Conversation = new ConversationAccount(id: result.Id); conversationUpdate.Recipient = conversationParameters.Bot; using (TurnContext context = new TurnContext(this, (Activity)conversationUpdate)) { await this.RunPipeline(context, callback).ConfigureAwait(false); } }
public override Task CreateConversationAsync(string botAppId, string channelId, string serviceUrl, string audience, ConversationParameters conversationParameters, BotCallbackHandler callback, CancellationToken cancellationToken) { AppId = botAppId; ChannelId = channelId; ServiceUrl = serviceUrl; Audience = audience; ConversationParameters = conversationParameters; var activity = new Activity { Id = _activityId, Conversation = new ConversationAccount { Id = _conversationId } }; var mockTurnContext = new Mock <ITurnContext>(); mockTurnContext.Setup(tc => tc.Activity).Returns(activity); callback(mockTurnContext.Object, cancellationToken); return(Task.CompletedTask); }
public Task <HttpOperationResponse <ConversationResourceResponse> > CreateConversationWithHttpMessagesAsync(ConversationParameters parameters, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default) { throw new NotImplementedException(); }
public async Task <Result <System.Dynamic.ExpandoObject> > CheckSentences(Activity activity) { var wordsEntity = await wordCache.GetAsync(); var words = wordsEntity.Select(x => x.Word); // Get the conversation id so the bot answers. var conversationId = activity.From.Id.ToString(); // Get a valid token string token = await this.GetBotApiToken(); dynamic message = new ExpandoObject(); // send the message back using (var client = new System.Net.Http.HttpClient()) { // I'm using dynamic here to make the code simpler message.type = "message/text"; message.text = "TEST TEST TEST"; var senderEmail = Environment.GetEnvironmentVariable("BOBTHEBOT_SENDER_EMAIL"); var senderName = Environment.GetEnvironmentVariable("BOBTHEBOT_SENDER_NAME"); var recipientEmail = Environment.GetEnvironmentVariable("BOBTHEBOT_RECIPIENT_EMAIL"); var recipientName = Environment.GetEnvironmentVariable("BOBTHEBOT_RECIPIENT_NAME"); string messages = activity.Text.ToString(); string from = activity.From.Name.ToString(); string conv = activity.Conversation.Id; var group = conv.Split("|").Last().Split("\"").First(); if (words.Any(c => messages.ToLower().Contains(c.ToLower()))) { //var msg = MailHelper.CreateSingleEmail( // new EmailAddress(senderEmail, senderName), // new EmailAddress("*****@*****.**", recipientName), // "Subject", // "", // messages + " from " + from + " at " + group); //var response2 = await sendGridClient.SendEmailAsync(msg); // Set the toekn in the authorization header. client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); var appCredentials = new MicrosoftAppCredentials(configurationRoot); var connector = new ConnectorClient(new Uri(activity.ServiceUrl), appCredentials); // var asd = await connector.Conversations.GetConversationMembersAsync(qwe); //var newActovity = new Activity(id: "2cb6eb60-761b-11e8-b7ed-f79c3f4b062e", // serviceUrl:activity.ServiceUrl, // replyToId: "9aec9e40-7611-11e8-b7ed-f79c3f4b062e", // type:"text", // textFormat:"plain", // channelId:"emulator", // channelData: "9aec9e40-7611-11e8-b7ed-f79c3f4b062e"); //var qwfsv = activity.Recipient; //activity.Recipient.Name = "Bot"; //activity.Recipient.Id = "bea98650-748a-11e8-a3ac-fb4c46d160e7"; var length = (activity.Text ?? string.Empty).Length; var reply = activity.CreateReply($"You send {activity.Text} which was{length} characters!"); //var asd = new Activity(ChannelAccount(r reply.Recipient.Id == "bea98650-748a-11e8-a3ac-fb4c46d160e7"; // var asd = new Activity() await connector.Conversations.ReplyToActivityAsync(reply); //var asd = await connector.Conversations.CreateConversationAsync(new ConversationParameters()); //await client.PostAsJsonAsync( //"http://*****:*****@contoso.com", "Agent")); ConversationParameters parameters = new ConversationParameters(true, new ChannelAccount("sip:[email protected]", "Bot"), participants, "TestTopic"); ConversationResourceResponse response = connector.Conversations.CreateConversationAsync(parameters).Result; // await client.PostAsJsonAsync<ExpandoObject>( //$"https://api.skype.net/v3/conversations/{conversationId}/activities", //message as ExpandoObject); } } return(Result.Ok(message)); }
public async Task CreateConversationOverloadProperlySetsTenantId() { // Arrange const string activityIdName = "ActivityId"; const string activityIdValue = "SendActivityId"; const string conversationIdName = "Id"; const string conversationIdValue = "NewConversationId"; const string tenantIdValue = "theTenantId"; const string eventActivityName = "CreateConversation"; Func <Task <HttpResponseMessage> > createResponseMessage = () => { var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK); response.Content = new StringContent(new JObject { { activityIdName, activityIdValue }, { conversationIdName, conversationIdValue } }.ToString()); return(Task.FromResult(response)); }; var mockCredentialProvider = new Mock <ICredentialProvider>(); var mockHttpMessageHandler = new Mock <HttpMessageHandler>(); mockHttpMessageHandler.Protected() .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()) .Returns((HttpRequestMessage request, CancellationToken cancellationToken) => createResponseMessage()); var httpClient = new HttpClient(mockHttpMessageHandler.Object); var adapter = new BotFrameworkAdapter(mockCredentialProvider.Object, customHttpClient: httpClient); var activity = new Activity("test") { ChannelId = Channels.Msteams, ServiceUrl = "https://fake.service.url", ChannelData = new JObject { ["tenant"] = new JObject { ["id"] = tenantIdValue }, }, Conversation = new ConversationAccount { TenantId = tenantIdValue }, }; var parameters = new ConversationParameters() { Activity = new Activity() { ChannelData = activity.ChannelData, }, }; var reference = activity.GetConversationReference(); var credentials = new MicrosoftAppCredentials(string.Empty, string.Empty, httpClient); Activity newActivity = null; Task UpdateParameters(ITurnContext turnContext, CancellationToken cancellationToken) { newActivity = turnContext.Activity; return(Task.CompletedTask); } // Act await adapter.CreateConversationAsync(activity.ChannelId, activity.ServiceUrl, credentials, parameters, UpdateParameters, reference, new CancellationToken()); // Assert - all values set correctly Assert.AreEqual(tenantIdValue, JObject.FromObject(newActivity.ChannelData)["tenant"]["tenantId"]); Assert.AreEqual(activityIdValue, newActivity.Id); Assert.AreEqual(conversationIdValue, newActivity.Conversation.Id); Assert.AreEqual(tenantIdValue, newActivity.Conversation.TenantId); Assert.AreEqual(eventActivityName, newActivity.Name); }
protected override async Task <ConversationResourceResponse> OnCreateConversationAsync(ClaimsIdentity claimsIdentity, ConversationParameters parameters, CancellationToken cancellationToken = default) { // This call will be used in Teams scenarios. // Scenario #1 - creating a thread with an activity in a Channel in a Team // In order to know the serviceUrl in the case of Teams we would need to look it up based upon the TeamsChannelData. // The inbound activity will contain the TeamsChannelData and so will the ConversationParameters. // Scenario #2 - starting a one on one conversation with a particular user // - needs further analysis - var backServiceUrl = "http://tempuri"; //var (backConversationId, backServiceUrl) = _factory.GetConversationInfo(string.Empty); var connectorClient = GetConnectorClient(backServiceUrl); return(await connectorClient.Conversations.CreateConversationAsync(parameters, cancellationToken)); }
public static async Task <string> SendNotification(IDialogContext context, string userOrChannelId, string messageText, Microsoft.Bot.Connector.Attachment attachment, string updateMessageId) { var userId = userOrChannelId.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, Notification = new NotificationInfo() { Alert = true } }, IsGroup = false }; try { 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) }; replyMessage.Text = messageText; replyMessage.TextFormat = TextFormatTypes.Markdown; if (attachment != null) { replyMessage.Attachments.Add(attachment); // .Add(attachment);// EchoBot.ManagerViewCard(employee, leaveDetails)); //replyMessage.AttachmentLayout = AttachmentLayoutTypes.Carousel; } if (string.IsNullOrEmpty(updateMessageId)) { var resourceResponse = await connectorClient.Conversations.SendToConversationAsync(conversationResource.Id, (Activity)replyMessage); return(null); //return resourceResponse.Id; } else { await connectorClient.Conversations.UpdateActivityAsync(conversationResource.Id, updateMessageId, (Activity)replyMessage); return(updateMessageId); // Just return the same Id. } } catch (Exception ex) { // Handle the error. var msg = context.MakeMessage(); msg.Text = ex.Message; await context.PostAsync(msg); return(null); } }
public async Task <ConversationResourceResponse> TestOnCreateConversationAsync(ClaimsIdentity claimsIdentity, ConversationParameters parameters, CancellationToken cancellationToken = default) { return(await OnCreateConversationAsync(claimsIdentity, parameters, cancellationToken).ConfigureAwait(false)); }
private async Task <CreateConversationResponse> CreateConversationAsync( string teamsUserId, string tenantId, string serviceUrl, int maxAttempts, MicrosoftAppCredentials credentials, ILogger log) { if (string.IsNullOrEmpty(teamsUserId)) { throw new ArgumentException($"'{nameof(teamsUserId)}' cannot be null or empty", nameof(teamsUserId)); } if (string.IsNullOrEmpty(tenantId)) { throw new ArgumentException($"'{nameof(tenantId)}' cannot be null or empty", nameof(tenantId)); } if (string.IsNullOrEmpty(serviceUrl)) { throw new ArgumentException($"'{nameof(serviceUrl)}' cannot be null or empty", nameof(serviceUrl)); } if (log is null) { throw new ArgumentNullException(nameof(log)); } var conversationParameters = new ConversationParameters { TenantId = tenantId, Members = new ChannelAccount[] { new ChannelAccount { Id = teamsUserId, }, }, }; var response = new CreateConversationResponse(); try { var retryPolicy = this.GetRetryPolicy(maxAttempts, log); await retryPolicy.ExecuteAsync(async() => await this.botAdapter.CreateConversationAsync( channelId: ConversationService.MicrosoftTeamsChannelId, serviceUrl: serviceUrl, credentials: credentials, conversationParameters: conversationParameters, callback: (turnContext, cancellationToken) => { // Success. response.Result = Result.Succeeded; response.StatusCode = (int)HttpStatusCode.Created; response.ConversationId = turnContext.Activity.Conversation.Id; return(Task.CompletedTask); }, cancellationToken: CancellationToken.None)); } catch (ErrorResponseException e) { var errorMessage = $"{e.GetType()}: {e.Message}"; log.LogError(e, $"Failed to create conversation. Exception message: {errorMessage}"); var statusCode = e.Response.StatusCode; response.StatusCode = (int)statusCode; response.ErrorMessage = e.Response.Content; response.Result = statusCode == HttpStatusCode.TooManyRequests ? Result.Throttled : Result.Failed; } return(response); }
public async Task <IActionResult> PostMessage([FromBody] NewMessage content) { int errPoint = 0; string errContent = string.Empty; string addingChannelNotification = string.Empty; string messageHeader = string.Empty; string messageContent = string.Empty; string messageFooter = string.Empty; bool mentionsPlaced = false; string orgUrl = string.Empty; // if the BotId or TenantId is left blank - we can use hard-coded values // for our Bot in Azure and our Client's Tenant if (String.IsNullOrEmpty(content.botId)) { content.botId = _appId; } if (String.IsNullOrEmpty(content.tenantId) && !String.IsNullOrEmpty(_tenantId)) { content.tenantId = _tenantId; } if (String.IsNullOrEmpty(content.tenantId)) { throw new InvalidOperationException("No Tenant Id is available to the Bot!"); } // NOTE: This concept of embedding the Tenant Id in the Config File for the Bot // is great for demostration purposes or for a bespoke Bot - // but would pose problems if the Bot was to be used in Multiple Tenants // or packaged as an App for multiple Clients try { errPoint = 101; // the following URL will change depending on what Region your Azure Bot Service is running from! // EUROPE: string serviceUrl = @"https://smba.trafficmanager.net/emea/"; string serviceUrl = @"https://smba.trafficmanager.net/amer"; MicrosoftAppCredentials.TrustServiceUrl(serviceUrl); errPoint = 102; var credentials = new MicrosoftAppCredentials(_appId, _appPassword); errPoint = 103; var connector = new ConnectorClient(new Uri(serviceUrl), credentials); errPoint = 104; TeamsChannelData tcd = new TeamsChannelData(); tcd.Channel = new ChannelInfo(content.channelId); tcd.Team = new TeamInfo(content.teamId); tcd.Tenant = new TenantInfo(content.tenantId); string fullMessage = string.Empty; if (content.body != null) { fullMessage = content.body.content; } else { fullMessage = "Message passed to the Notify Controller: [no_body]"; } bool posted = false; // create the conversation var conversationParameter = new ConversationParameters { Activity = MessageFactory.Text(fullMessage), Bot = new ChannelAccount { Id = content.botId, Role = "Bot" }, ChannelData = tcd, IsGroup = true, TenantId = content.tenantId }; // Post as New Conversation or to Existing Conversation if (!string.IsNullOrWhiteSpace(content.conversationId)) { // Post to Existing Conversation errPoint = 41; errContent += "ConversationId: (" + content.conversationId + "), "; try { // as conversation id has been supplied, this is a response to a thread conversationParameter.Activity.Conversation = new ConversationAccount { Id = content.conversationId }; var response = await connector.Conversations.SendToConversationAsync( conversationParameter.Activity); posted = true; return(new JsonResult(response)); } catch (Exception ex) { // if we fail to post to an existing conversation // (say if the conversation has been deleted?) // then still post out as a regular message posted = false; errContent += "FAILED to post to Existing Conversation: " + ex.Message + " | "; conversationParameter.Activity.Conversation = null; } } if (posted == false) { var response = await connector.Conversations.CreateConversationAsync( conversationParameter); return(new JsonResult(response)); } return(null); } catch (Exception ex) { return(new JsonResult("TeamBot --> NotifyController --> PostMessage[" + errPoint + "] :: " + ex.Message)); } }