public async Task AddPlayerAsync(IGuildUser user, string teamName) { Verify.IsNotNull(user, nameof(user)); bool addPlayerSuccessful = false; ulong teamRoleId = default(ulong); await this.DoReadWriteActionOnCurrentTournamentAsync( currentTournament => { // Rewrite exit-early, then choose whether we add the role or not if (!currentTournament.TryGetTeamFromName(teamName, out Team team)) { this.Logger.Debug("Player {id} could not be added to nonexistent {teamName}", user.Id, teamName); return(this.SendChannelMessage(BotStrings.TeamDoesNotExist(teamName))); } Player player = new Player() { Id = user.Id, Team = team }; if (!currentTournament.TryAddPlayer(player)) { this.Logger.Debug("Player {id} already on team; not added to {teamName}", user.Id, teamName); return(this.SendChannelMessage(BotStrings.PlayerIsAlreadyOnTeam(user.Mention))); } if (!currentTournament.IsTorunamentInPlayStage()) { addPlayerSuccessful = true; return(Task.CompletedTask); } KeyValuePair <Team, ulong> teamRoleIdPair = currentTournament.TournamentRoles.TeamRoleIds .FirstOrDefault(kvp => kvp.Key == team); if (teamRoleIdPair.Key != team) { // We can't add the role to the player. So undo adding the player to the tournament this.Logger.Debug( "Player {id} could not be added because role for {teamName} does not exist", user.Id, teamName); currentTournament.TryRemovePlayer(player.Id); return(this.SendChannelMessage( BotStrings.PlayerCannotBeAddedToTeamWithNoRole(user.Mention, teamName))); } teamRoleId = teamRoleIdPair.Value; addPlayerSuccessful = true; return(Task.CompletedTask); }); if (!addPlayerSuccessful) { return; } IRole teamRole = null; if (teamRoleId != default(ulong)) { teamRole = this.Context.Guild.GetRole(teamRoleId); await user.AddRoleAsync(teamRole, RequestOptionsSettings.Default); } this.Logger.Debug( "Player {0} successfully added to team {1}. Role added: {2}", user.Id, teamName, teamRole != null); await this.SendChannelMessage(BotStrings.AddPlayerSuccessful(user.Mention, teamName)); }