using System.ComponentModel; using System.Text; using Boyfriend.Data; using Boyfriend.Services; using Boyfriend.Services.Update; using JetBrains.Annotations; using Remora.Commands.Attributes; using Remora.Commands.Groups; using Remora.Discord.API.Abstractions.Objects; using Remora.Discord.API.Abstractions.Rest; using Remora.Discord.Commands.Attributes; using Remora.Discord.Commands.Conditions; using Remora.Discord.Commands.Contexts; using Remora.Discord.Commands.Feedback.Services; using Remora.Discord.Extensions.Embeds; using Remora.Discord.Extensions.Formatting; using Remora.Rest.Core; using Remora.Results; namespace Boyfriend.Commands; /// /// Handles commands related to ban management: /ban and /unban. /// [UsedImplicitly] public class BanCommandGroup : CommandGroup { private readonly IDiscordRestChannelAPI _channelApi; private readonly ICommandContext _context; private readonly FeedbackService _feedback; private readonly IDiscordRestGuildAPI _guildApi; private readonly GuildDataService _guildData; private readonly IDiscordRestUserAPI _userApi; private readonly UtilityService _utility; public BanCommandGroup( ICommandContext context, IDiscordRestChannelAPI channelApi, GuildDataService guildData, FeedbackService feedback, IDiscordRestGuildAPI guildApi, IDiscordRestUserAPI userApi, UtilityService utility) { _context = context; _channelApi = channelApi; _guildData = guildData; _feedback = feedback; _guildApi = guildApi; _userApi = userApi; _utility = utility; } /// /// A slash command that bans a Discord user with the specified reason. /// /// The user to ban. /// The duration for this ban. The user will be automatically unbanned after this duration. /// /// The reason for this ban. Must be encoded with when passed to /// . /// /// /// A feedback sending result which may or may not have succeeded. A successful result does not mean that the user /// was banned and vice-versa. /// /// [Command("ban", "бан")] [DiscordDefaultMemberPermissions(DiscordPermission.BanMembers)] [DiscordDefaultDMPermission(false)] [RequireContext(ChannelContext.Guild)] [RequireDiscordPermission(DiscordPermission.BanMembers)] [RequireBotDiscordPermissions(DiscordPermission.BanMembers)] [Description("Ban user")] [UsedImplicitly] public async Task ExecuteBanAsync( [Description("User to ban")] IUser target, [Description("Ban reason")] string reason, [Description("Ban duration")] TimeSpan? duration = null) { if (!_context.TryGetContextIDs(out var guildId, out var channelId, out var userId)) { return new ArgumentInvalidError(nameof(_context), "Unable to retrieve necessary IDs from command context"); } // The current user's avatar is used when sending error messages var currentUserResult = await _userApi.GetCurrentUserAsync(CancellationToken); if (!currentUserResult.IsDefined(out var currentUser)) { return Result.FromError(currentUserResult); } var userResult = await _userApi.GetUserAsync(userId, CancellationToken); if (!userResult.IsDefined(out var user)) { return Result.FromError(userResult); } var guildResult = await _guildApi.GetGuildAsync(guildId, ct: CancellationToken); if (!guildResult.IsDefined(out var guild)) { return Result.FromError(guildResult); } var data = await _guildData.GetData(guild.ID, CancellationToken); Messages.Culture = GuildSettings.Language.Get(data.Settings); return await BanUserAsync( target, reason, duration, guild, data, channelId, user, currentUser, CancellationToken); } private async Task BanUserAsync( IUser target, string reason, TimeSpan? duration, IGuild guild, GuildData data, Snowflake channelId, IUser user, IUser currentUser, CancellationToken ct = default) { var existingBanResult = await _guildApi.GetGuildBanAsync(guild.ID, target.ID, ct); if (existingBanResult.IsDefined()) { var failedEmbed = new EmbedBuilder().WithSmallTitle(Messages.UserAlreadyBanned, currentUser) .WithColour(ColorsList.Red).Build(); return await _feedback.SendContextualEmbedResultAsync(failedEmbed, ct); } var interactionResult = await _utility.CheckInteractionsAsync(guild.ID, user.ID, target.ID, "Ban", ct); if (!interactionResult.IsSuccess) { return Result.FromError(interactionResult); } if (interactionResult.Entity is not null) { var errorEmbed = new EmbedBuilder().WithSmallTitle(interactionResult.Entity, currentUser) .WithColour(ColorsList.Red).Build(); return await _feedback.SendContextualEmbedResultAsync(errorEmbed, ct); } var builder = new StringBuilder().Append("- ") .AppendLine(string.Format(Messages.DescriptionActionReason, reason)); if (duration is not null) { builder.Append("- ").Append( string.Format( Messages.DescriptionActionExpiresAt, Markdown.Timestamp(DateTimeOffset.UtcNow.Add(duration.Value)))); } var title = string.Format(Messages.UserBanned, target.GetTag()); var description = builder.ToString(); var dmChannelResult = await _userApi.CreateDMAsync(target.ID, ct); if (dmChannelResult.IsDefined(out var dmChannel)) { var dmEmbed = new EmbedBuilder().WithGuildTitle(guild) .WithTitle(Messages.YouWereBanned) .WithDescription(description) .WithActionFooter(user) .WithCurrentTimestamp() .WithColour(ColorsList.Red) .Build(); if (!dmEmbed.IsDefined(out var dmBuilt)) { return Result.FromError(dmEmbed); } await _channelApi.CreateMessageAsync(dmChannel.ID, embeds: new[] { dmBuilt }, ct: ct); } var banResult = await _guildApi.CreateGuildBanAsync( guild.ID, target.ID, reason: $"({user.GetTag()}) {reason}".EncodeHeader(), ct: ct); if (!banResult.IsSuccess) { return Result.FromError(banResult.Error); } var memberData = data.GetOrCreateMemberData(target.ID); memberData.BannedUntil = duration is not null ? DateTimeOffset.UtcNow.Add(duration.Value) : DateTimeOffset.MaxValue; memberData.Roles.Clear(); var embed = new EmbedBuilder().WithSmallTitle( title, target) .WithColour(ColorsList.Green).Build(); var logResult = _utility.LogActionAsync( data.Settings, channelId, user, title, description, target, ColorsList.Red, ct: ct); if (!logResult.IsSuccess) { return Result.FromError(logResult.Error); } return await _feedback.SendContextualEmbedResultAsync(embed, ct); } /// /// A slash command that unbans a Discord user with the specified reason. /// /// The user to unban. /// /// The reason for this unban. Must be encoded with when passed to /// . /// /// /// A feedback sending result which may or may not have succeeded. A successful result does not mean that the user /// was unbanned and vice-versa. /// /// /// [Command("unban")] [DiscordDefaultMemberPermissions(DiscordPermission.BanMembers)] [DiscordDefaultDMPermission(false)] [RequireContext(ChannelContext.Guild)] [RequireDiscordPermission(DiscordPermission.BanMembers)] [RequireBotDiscordPermissions(DiscordPermission.BanMembers)] [Description("Unban user")] [UsedImplicitly] public async Task ExecuteUnban( [Description("User to unban")] IUser target, [Description("Unban reason")] string reason) { if (!_context.TryGetContextIDs(out var guildId, out var channelId, out var userId)) { return new ArgumentInvalidError(nameof(_context), "Unable to retrieve necessary IDs from command context"); } // The current user's avatar is used when sending error messages var currentUserResult = await _userApi.GetCurrentUserAsync(CancellationToken); if (!currentUserResult.IsDefined(out var currentUser)) { return Result.FromError(currentUserResult); } // Needed to get the tag and avatar var userResult = await _userApi.GetUserAsync(userId, CancellationToken); if (!userResult.IsDefined(out var user)) { return Result.FromError(userResult); } var data = await _guildData.GetData(guildId, CancellationToken); Messages.Culture = GuildSettings.Language.Get(data.Settings); return await UnbanUserAsync( target, reason, guildId, data, channelId, user, currentUser, CancellationToken); } private async Task UnbanUserAsync( IUser target, string reason, Snowflake guildId, GuildData data, Snowflake channelId, IUser user, IUser currentUser, CancellationToken ct = default) { var existingBanResult = await _guildApi.GetGuildBanAsync(guildId, target.ID, ct); if (!existingBanResult.IsDefined()) { var errorEmbed = new EmbedBuilder().WithSmallTitle(Messages.UserNotBanned, currentUser) .WithColour(ColorsList.Red).Build(); return await _feedback.SendContextualEmbedResultAsync(errorEmbed, ct); } var unbanResult = await _guildApi.RemoveGuildBanAsync( guildId, target.ID, $"({user.GetTag()}) {reason}".EncodeHeader(), ct); if (!unbanResult.IsSuccess) { return Result.FromError(unbanResult.Error); } data.GetOrCreateMemberData(target.ID).BannedUntil = null; var embed = new EmbedBuilder().WithSmallTitle( string.Format(Messages.UserUnbanned, target.GetTag()), target) .WithColour(ColorsList.Green).Build(); var title = string.Format(Messages.UserUnbanned, target.GetTag()); var description = new StringBuilder().Append("- ") .Append(string.Format(Messages.DescriptionActionReason, reason)); var logResult = _utility.LogActionAsync( data.Settings, channelId, user, title, description.ToString(), target, ColorsList.Green, ct: ct); if (!logResult.IsSuccess) { return Result.FromError(logResult.Error); } return await _feedback.SendContextualEmbedResultAsync(embed, ct); } }