public async Task <bool> NotifyFailedPullRequestBuild(Build build, string identifier) { SlackUserResponse pullRequestOwner = null; try { pullRequestOwner = await _client.GetUserByEmail(build.PullRequest.AuthorEmail).ConfigureAwait(false); } catch (SlackClientException e) when("users_not_found".Equals(e.Message, StringComparison.OrdinalIgnoreCase)) { // When the user wasn't found we cannot notify them directly, // by leaving pullRequestOwner null the FormatFailedBuild will // create a generic message. } var payload = SlackMessageFormatter.FormatFailedBuild(build, _configuration.Channel, identifier, pullRequestOwner); var success = await _client.PostMessage(payload).ConfigureAwait(false); return(success.Ok); }
public static SlackPayload FormatFailedBuild(Build build, string slackChannel, string updateTs, SlackUserResponse pullRequestOwner) { var payloadBuilder = new SlackPayloadBuilder(); var builder = payloadBuilder .SendsTo(slackChannel) .PostsAsThreadIn(updateTs) .LinksNames(true) .HasPreviewText($"Build of your PR failed."); var buildString = !string.IsNullOrEmpty(build.Url) ? $"<{build.WebUrl}|the build>" : "the build"; if (pullRequestOwner != null) { builder.WithSection(s => s.HasText($"Hey <@{pullRequestOwner.SlackUser.Id}>, {buildString} of this PR failed.")); } else { builder.WithSection(s => s.HasText($"I was unable to find who to tag for this PullRequest, but {buildString} failed.")); } return(builder.Build()); }
/// <summary> /// Method to add/update Slack User,channels and groups information /// </summary> /// <param name="code"></param> /// <returns></returns> public async Task AddSlackUserInformationAsync(string code) { string slackOAuthRequest = string.Format(_stringConstant.SlackOauthRequestUrl, _envVariableRepository.SlackOAuthClientId, _envVariableRepository.SlackOAuthClientSecret, code); string slackOAuthResponse = await _httpClientService.GetAsync(_stringConstant.OAuthAcessUrl, slackOAuthRequest, null, _stringConstant.Bearer); SlackOAuthResponse slackOAuth = JsonConvert.DeserializeObject <SlackOAuthResponse>(slackOAuthResponse); _logger.Info("slackOAuth UserID" + slackOAuth.UserId); bool checkUserIncomingWebHookExist = _incomingWebHookRepository.Any(x => x.UserId == slackOAuth.UserId); if (!checkUserIncomingWebHookExist) { IncomingWebHook slackItem = new IncomingWebHook() { UserId = slackOAuth.UserId, IncomingWebHookUrl = slackOAuth.IncomingWebhook.Url }; _incomingWebHookRepository.Insert(slackItem); await _incomingWebHookRepository.SaveChangesAsync(); } string detailsRequest = string.Format(_stringConstant.SlackUserDetailsUrl, slackOAuth.AccessToken); //get all the slack users of the team string userDetailsResponse = await _httpClientService.GetAsync(_stringConstant.SlackUserListUrl, detailsRequest, null, _stringConstant.Bearer); SlackUserResponse slackUsers = JsonConvert.DeserializeObject <SlackUserResponse>(userDetailsResponse); if (slackUsers.Ok) { SlackUserDetails slackUserDetails = slackUsers.Members?.Find(x => x.UserId == slackOAuth.UserId); _logger.Debug("slackUserDetails" + slackUserDetails.UserId); if (!string.IsNullOrEmpty(slackUserDetails?.Profile?.Email)) { //fetch the details of the user who is authenticated with Promact OAuth server with the given slack user's email _logger.Debug("Profile Email" + slackUserDetails.Profile.Email); ApplicationUser applicationUser = await _userManager.FindByEmailAsync(slackUserDetails.Profile.Email); if (applicationUser != null) { _logger.Debug("slackUserDetails UserID" + slackUserDetails.UserId); applicationUser.SlackUserId = slackUserDetails.UserId; _logger.Debug("applicationUser SlackUserId" + applicationUser.SlackUserId); var succeeded = await _userManager.UpdateAsync(applicationUser); _logger.Debug("applicationUser Object:" + JsonConvert.SerializeObject(applicationUser)); _logger.Debug("Update Application User succeeded" + succeeded.Succeeded); _logger.Debug("Update Application User Errors" + succeeded.Errors); ApplicationUser testApllicationUser = await _userManager.FindByEmailAsync(applicationUser.Email); _logger.Debug("Test Application Slcak UserId" + testApllicationUser.SlackUserId); _logger.Debug("Test ApplicationUser Object:" + JsonConvert.SerializeObject(testApllicationUser)); await _slackUserRepository.AddSlackUserAsync(slackUserDetails); _logger.Debug("Add Slack User Id Done"); //the public channels' details string channelDetailsResponse = await _httpClientService.GetAsync(_stringConstant.SlackChannelListUrl, detailsRequest, null, _stringConstant.Bearer); SlackChannelResponse channels = JsonConvert.DeserializeObject <SlackChannelResponse>(channelDetailsResponse); if (channels.Ok) { _logger.Info("Channels error:" + channels.ErrorMessage); foreach (var channel in channels.Channels) { _logger.Info("Channel:" + channel); await AddChannelGroupAsync(channel); } } else { throw new SlackAuthorizeException(_stringConstant.SlackAuthError + channels.ErrorMessage); } _logger.Info("Slack User Id : " + (await _userManager.FindByEmailAsync(applicationUser.Email)).SlackUserId); //the public groups' details string groupDetailsResponse = await _httpClientService.GetAsync(_stringConstant.SlackGroupListUrl, detailsRequest, null, _stringConstant.Bearer); SlackGroupDetails groups = JsonConvert.DeserializeObject <SlackGroupDetails>(groupDetailsResponse); _logger.Info("Groups:" + groups.ErrorMessage); _logger.Debug("Slack User Id : " + (await _userManager.FindByEmailAsync(applicationUser.Email)).SlackUserId); if (groups.Ok) { foreach (var channel in groups.Groups) { _logger.Info("Group:" + channel); await AddChannelGroupAsync(channel); _logger.Debug("Slack User Id : " + (await _userManager.FindByEmailAsync(applicationUser.Email)).SlackUserId); } } else { throw new SlackAuthorizeException(_stringConstant.SlackAuthError + groups.ErrorMessage); } } else { throw new SlackAuthorizeException(string.Format(_stringConstant.NotInSlackOrNotExpectedUser, slackUserDetails.Profile.Email)); } } else { throw new SlackAuthorizeException(_stringConstant.UserNotInSlack); } } else { throw new SlackAuthorizeException(_stringConstant.SlackAuthError + slackUsers.ErrorMessage); } }