1
0
Fork 1
mirror of https://github.com/TeamOctolings/Octobot.git synced 2025-01-31 09:09:00 +03:00
Octobot/src/Commands/BanCommandGroup.cs

301 lines
12 KiB
C#
Raw Normal View History

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Text;
The Milestone Commit (#48) mctaylors: - updated readme 7 times (and only adding new logo from /about) - [removed](https://github.com/TeamOctolings/Boyfriend/pull/48/commits/aeeb3d4399c31df70b47ccdf59f6963fdb68e9ec) bot footer from created event embed on the second try - [changed](https://github.com/TeamOctolings/Boyfriend/pull/48/commits/4b9b91d9e4d2289d9aad4e600f5ca6a424638a6e) cdn from discord to upload.systems Octol1ttle: - Guild settings code has been overhauled. Instead of instances of a `GuildConfiguration` class being (de-)serialized when used with listing and setting options provided by reflection, there are now multiple `Option` classes responsible for the type of option they are storing. The classes support getting a value, validating and setting values with Results, and getting a user-friendly representation of these values. This makes use of polymorphism, providing clean and easier to use and refactor code. - Gateway event responders have been split into their own separate files, which should make it easier to find and modify responders when needed. - Warning suppressions regarding unused and never instantiated classes have been replaced by `[ImplicitUse]` annotations provided by `JetBrains.Annotations`. This avoids hiding real issues and provides a better way to suppress false warnings while being explicit. - It is no longer possible to execute some slash commands if they are run without the correct permissions - Dependencies are now more explicitly defined neroduckale: - Made easter eggs case-insensitive --------- Signed-off-by: Macintosh II <95250141+mctaylors@users.noreply.github.com> Signed-off-by: Octol1ttle <l1ttleofficial@outlook.com> Co-authored-by: Octol1ttle <l1ttleofficial@outlook.com> Co-authored-by: nrdk <neroduck@vk.com>
2023-07-18 15:25:02 +03:00
using JetBrains.Annotations;
using Octobot.Data;
using Octobot.Extensions;
using Octobot.Parsers;
using Octobot.Services;
using Octobot.Services.Update;
using Remora.Commands.Attributes;
using Remora.Commands.Groups;
using Remora.Discord.API.Abstractions.Objects;
using Remora.Discord.API.Abstractions.Rest;
The Milestone Commit (#48) mctaylors: - updated readme 7 times (and only adding new logo from /about) - [removed](https://github.com/TeamOctolings/Boyfriend/pull/48/commits/aeeb3d4399c31df70b47ccdf59f6963fdb68e9ec) bot footer from created event embed on the second try - [changed](https://github.com/TeamOctolings/Boyfriend/pull/48/commits/4b9b91d9e4d2289d9aad4e600f5ca6a424638a6e) cdn from discord to upload.systems Octol1ttle: - Guild settings code has been overhauled. Instead of instances of a `GuildConfiguration` class being (de-)serialized when used with listing and setting options provided by reflection, there are now multiple `Option` classes responsible for the type of option they are storing. The classes support getting a value, validating and setting values with Results, and getting a user-friendly representation of these values. This makes use of polymorphism, providing clean and easier to use and refactor code. - Gateway event responders have been split into their own separate files, which should make it easier to find and modify responders when needed. - Warning suppressions regarding unused and never instantiated classes have been replaced by `[ImplicitUse]` annotations provided by `JetBrains.Annotations`. This avoids hiding real issues and provides a better way to suppress false warnings while being explicit. - It is no longer possible to execute some slash commands if they are run without the correct permissions - Dependencies are now more explicitly defined neroduckale: - Made easter eggs case-insensitive --------- Signed-off-by: Macintosh II <95250141+mctaylors@users.noreply.github.com> Signed-off-by: Octol1ttle <l1ttleofficial@outlook.com> Co-authored-by: Octol1ttle <l1ttleofficial@outlook.com> Co-authored-by: nrdk <neroduck@vk.com>
2023-07-18 15:25:02 +03:00
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 Octobot.Commands;
/// <summary>
/// Handles commands related to ban management: /ban and /unban.
/// </summary>
The Milestone Commit (#48) mctaylors: - updated readme 7 times (and only adding new logo from /about) - [removed](https://github.com/TeamOctolings/Boyfriend/pull/48/commits/aeeb3d4399c31df70b47ccdf59f6963fdb68e9ec) bot footer from created event embed on the second try - [changed](https://github.com/TeamOctolings/Boyfriend/pull/48/commits/4b9b91d9e4d2289d9aad4e600f5ca6a424638a6e) cdn from discord to upload.systems Octol1ttle: - Guild settings code has been overhauled. Instead of instances of a `GuildConfiguration` class being (de-)serialized when used with listing and setting options provided by reflection, there are now multiple `Option` classes responsible for the type of option they are storing. The classes support getting a value, validating and setting values with Results, and getting a user-friendly representation of these values. This makes use of polymorphism, providing clean and easier to use and refactor code. - Gateway event responders have been split into their own separate files, which should make it easier to find and modify responders when needed. - Warning suppressions regarding unused and never instantiated classes have been replaced by `[ImplicitUse]` annotations provided by `JetBrains.Annotations`. This avoids hiding real issues and provides a better way to suppress false warnings while being explicit. - It is no longer possible to execute some slash commands if they are run without the correct permissions - Dependencies are now more explicitly defined neroduckale: - Made easter eggs case-insensitive --------- Signed-off-by: Macintosh II <95250141+mctaylors@users.noreply.github.com> Signed-off-by: Octol1ttle <l1ttleofficial@outlook.com> Co-authored-by: Octol1ttle <l1ttleofficial@outlook.com> Co-authored-by: nrdk <neroduck@vk.com>
2023-07-18 15:25:02 +03:00
[UsedImplicitly]
public class BanCommandGroup : CommandGroup
{
private readonly IDiscordRestChannelAPI _channelApi;
private readonly ICommandContext _context;
private readonly IFeedbackService _feedback;
private readonly IDiscordRestGuildAPI _guildApi;
private readonly GuildDataService _guildData;
private readonly IDiscordRestUserAPI _userApi;
private readonly Utility _utility;
public BanCommandGroup(
ICommandContext context, IDiscordRestChannelAPI channelApi, GuildDataService guildData,
IFeedbackService feedback, IDiscordRestGuildAPI guildApi, IDiscordRestUserAPI userApi,
Utility utility)
{
_context = context;
_channelApi = channelApi;
_guildData = guildData;
_feedback = feedback;
_guildApi = guildApi;
_userApi = userApi;
_utility = utility;
}
/// <summary>
/// A slash command that bans a Discord user with the specified reason.
/// </summary>
/// <param name="target">The user to ban.</param>
/// <param name="stringDuration">The duration for this ban. The user will be automatically unbanned after this duration.</param>
/// <param name="reason">
/// The reason for this ban. Must be encoded with <see cref="StringExtensions.EncodeHeader" /> when passed to
/// <see cref="IDiscordRestGuildAPI.CreateGuildBanAsync" />.
/// </param>
/// <returns>
/// 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.
/// </returns>
/// <seealso cref="ExecuteUnban" />
[Command("ban", "бан")]
The Milestone Commit (#48) mctaylors: - updated readme 7 times (and only adding new logo from /about) - [removed](https://github.com/TeamOctolings/Boyfriend/pull/48/commits/aeeb3d4399c31df70b47ccdf59f6963fdb68e9ec) bot footer from created event embed on the second try - [changed](https://github.com/TeamOctolings/Boyfriend/pull/48/commits/4b9b91d9e4d2289d9aad4e600f5ca6a424638a6e) cdn from discord to upload.systems Octol1ttle: - Guild settings code has been overhauled. Instead of instances of a `GuildConfiguration` class being (de-)serialized when used with listing and setting options provided by reflection, there are now multiple `Option` classes responsible for the type of option they are storing. The classes support getting a value, validating and setting values with Results, and getting a user-friendly representation of these values. This makes use of polymorphism, providing clean and easier to use and refactor code. - Gateway event responders have been split into their own separate files, which should make it easier to find and modify responders when needed. - Warning suppressions regarding unused and never instantiated classes have been replaced by `[ImplicitUse]` annotations provided by `JetBrains.Annotations`. This avoids hiding real issues and provides a better way to suppress false warnings while being explicit. - It is no longer possible to execute some slash commands if they are run without the correct permissions - Dependencies are now more explicitly defined neroduckale: - Made easter eggs case-insensitive --------- Signed-off-by: Macintosh II <95250141+mctaylors@users.noreply.github.com> Signed-off-by: Octol1ttle <l1ttleofficial@outlook.com> Co-authored-by: Octol1ttle <l1ttleofficial@outlook.com> Co-authored-by: nrdk <neroduck@vk.com>
2023-07-18 15:25:02 +03:00
[DiscordDefaultMemberPermissions(DiscordPermission.BanMembers)]
[DiscordDefaultDMPermission(false)]
[RequireContext(ChannelContext.Guild)]
[RequireDiscordPermission(DiscordPermission.BanMembers)]
[RequireBotDiscordPermissions(DiscordPermission.BanMembers)]
[Description("Ban user")]
The Milestone Commit (#48) mctaylors: - updated readme 7 times (and only adding new logo from /about) - [removed](https://github.com/TeamOctolings/Boyfriend/pull/48/commits/aeeb3d4399c31df70b47ccdf59f6963fdb68e9ec) bot footer from created event embed on the second try - [changed](https://github.com/TeamOctolings/Boyfriend/pull/48/commits/4b9b91d9e4d2289d9aad4e600f5ca6a424638a6e) cdn from discord to upload.systems Octol1ttle: - Guild settings code has been overhauled. Instead of instances of a `GuildConfiguration` class being (de-)serialized when used with listing and setting options provided by reflection, there are now multiple `Option` classes responsible for the type of option they are storing. The classes support getting a value, validating and setting values with Results, and getting a user-friendly representation of these values. This makes use of polymorphism, providing clean and easier to use and refactor code. - Gateway event responders have been split into their own separate files, which should make it easier to find and modify responders when needed. - Warning suppressions regarding unused and never instantiated classes have been replaced by `[ImplicitUse]` annotations provided by `JetBrains.Annotations`. This avoids hiding real issues and provides a better way to suppress false warnings while being explicit. - It is no longer possible to execute some slash commands if they are run without the correct permissions - Dependencies are now more explicitly defined neroduckale: - Made easter eggs case-insensitive --------- Signed-off-by: Macintosh II <95250141+mctaylors@users.noreply.github.com> Signed-off-by: Octol1ttle <l1ttleofficial@outlook.com> Co-authored-by: Octol1ttle <l1ttleofficial@outlook.com> Co-authored-by: nrdk <neroduck@vk.com>
2023-07-18 15:25:02 +03:00
[UsedImplicitly]
public async Task<Result> ExecuteBanAsync(
[Description("User to ban")] IUser target,
[Description("Ban reason")] [MaxLength(256)]
string reason,
[Description("Ban duration")] [Option("duration")]
string? stringDuration = null)
{
if (!_context.TryGetContextIDs(out var guildId, out var channelId, out var executorId))
{
return new ArgumentInvalidError(nameof(_context), "Unable to retrieve necessary IDs from command context");
}
// The bot's avatar is used when sending error messages
var botResult = await _userApi.GetCurrentUserAsync(CancellationToken);
if (!botResult.IsDefined(out var bot))
{
return Result.FromError(botResult);
}
var executorResult = await _userApi.GetUserAsync(executorId, CancellationToken);
if (!executorResult.IsDefined(out var executor))
{
return Result.FromError(executorResult);
}
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);
if (stringDuration is null)
{
return await BanUserAsync(executor, target, reason, null, guild, data, channelId, bot,
CancellationToken);
}
var parseResult = TimeSpanParser.TryParse(stringDuration);
if (!parseResult.IsDefined(out var duration))
{
var failedEmbed = new EmbedBuilder()
.WithSmallTitle(Messages.InvalidTimeSpan, bot)
.WithColour(ColorsList.Red)
.Build();
return await _feedback.SendContextualEmbedResultAsync(failedEmbed, ct: CancellationToken);
}
return await BanUserAsync(executor, target, reason, duration, guild, data, channelId, bot, CancellationToken);
}
private async Task<Result> BanUserAsync(
IUser executor, IUser target, string reason, TimeSpan? duration, IGuild guild, GuildData data, Snowflake channelId,
IUser bot, CancellationToken ct = default)
{
var existingBanResult = await _guildApi.GetGuildBanAsync(guild.ID, target.ID, ct);
if (existingBanResult.IsDefined())
{
var failedEmbed = new EmbedBuilder().WithSmallTitle(Messages.UserAlreadyBanned, bot)
.WithColour(ColorsList.Red).Build();
return await _feedback.SendContextualEmbedResultAsync(failedEmbed, ct: ct);
}
var interactionResult
= await _utility.CheckInteractionsAsync(guild.ID, executor.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, bot)
.WithColour(ColorsList.Red).Build();
return await _feedback.SendContextualEmbedResultAsync(errorEmbed, ct: ct);
}
var builder = new StringBuilder().AppendBulletPointLine(string.Format(Messages.DescriptionActionReason, reason));
if (duration is not null)
{
builder.AppendBulletPoint(
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(executor)
.WithCurrentTimestamp()
.WithColour(ColorsList.Red)
.Build();
await _channelApi.CreateMessageWithEmbedResultAsync(dmChannel.ID, embedResult: dmEmbed, ct: ct);
}
var banResult = await _guildApi.CreateGuildBanAsync(
guild.ID, target.ID, reason: $"({executor.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, executor, title, description, target, ColorsList.Red, ct: ct);
if (!logResult.IsSuccess)
{
return Result.FromError(logResult.Error);
}
return await _feedback.SendContextualEmbedResultAsync(embed, ct: ct);
}
/// <summary>
/// A slash command that unbans a Discord user with the specified reason.
/// </summary>
/// <param name="target">The user to unban.</param>
/// <param name="reason">
/// The reason for this unban. Must be encoded with <see cref="StringExtensions.EncodeHeader" /> when passed to
/// <see cref="IDiscordRestGuildAPI.RemoveGuildBanAsync" />.
/// </param>
/// <returns>
/// 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.
/// </returns>
/// <seealso cref="ExecuteBanAsync" />
/// <seealso cref="MemberUpdateService.TickMemberDataAsync" />
[Command("unban")]
The Milestone Commit (#48) mctaylors: - updated readme 7 times (and only adding new logo from /about) - [removed](https://github.com/TeamOctolings/Boyfriend/pull/48/commits/aeeb3d4399c31df70b47ccdf59f6963fdb68e9ec) bot footer from created event embed on the second try - [changed](https://github.com/TeamOctolings/Boyfriend/pull/48/commits/4b9b91d9e4d2289d9aad4e600f5ca6a424638a6e) cdn from discord to upload.systems Octol1ttle: - Guild settings code has been overhauled. Instead of instances of a `GuildConfiguration` class being (de-)serialized when used with listing and setting options provided by reflection, there are now multiple `Option` classes responsible for the type of option they are storing. The classes support getting a value, validating and setting values with Results, and getting a user-friendly representation of these values. This makes use of polymorphism, providing clean and easier to use and refactor code. - Gateway event responders have been split into their own separate files, which should make it easier to find and modify responders when needed. - Warning suppressions regarding unused and never instantiated classes have been replaced by `[ImplicitUse]` annotations provided by `JetBrains.Annotations`. This avoids hiding real issues and provides a better way to suppress false warnings while being explicit. - It is no longer possible to execute some slash commands if they are run without the correct permissions - Dependencies are now more explicitly defined neroduckale: - Made easter eggs case-insensitive --------- Signed-off-by: Macintosh II <95250141+mctaylors@users.noreply.github.com> Signed-off-by: Octol1ttle <l1ttleofficial@outlook.com> Co-authored-by: Octol1ttle <l1ttleofficial@outlook.com> Co-authored-by: nrdk <neroduck@vk.com>
2023-07-18 15:25:02 +03:00
[DiscordDefaultMemberPermissions(DiscordPermission.BanMembers)]
[DiscordDefaultDMPermission(false)]
[RequireContext(ChannelContext.Guild)]
[RequireDiscordPermission(DiscordPermission.BanMembers)]
[RequireBotDiscordPermissions(DiscordPermission.BanMembers)]
[Description("Unban user")]
The Milestone Commit (#48) mctaylors: - updated readme 7 times (and only adding new logo from /about) - [removed](https://github.com/TeamOctolings/Boyfriend/pull/48/commits/aeeb3d4399c31df70b47ccdf59f6963fdb68e9ec) bot footer from created event embed on the second try - [changed](https://github.com/TeamOctolings/Boyfriend/pull/48/commits/4b9b91d9e4d2289d9aad4e600f5ca6a424638a6e) cdn from discord to upload.systems Octol1ttle: - Guild settings code has been overhauled. Instead of instances of a `GuildConfiguration` class being (de-)serialized when used with listing and setting options provided by reflection, there are now multiple `Option` classes responsible for the type of option they are storing. The classes support getting a value, validating and setting values with Results, and getting a user-friendly representation of these values. This makes use of polymorphism, providing clean and easier to use and refactor code. - Gateway event responders have been split into their own separate files, which should make it easier to find and modify responders when needed. - Warning suppressions regarding unused and never instantiated classes have been replaced by `[ImplicitUse]` annotations provided by `JetBrains.Annotations`. This avoids hiding real issues and provides a better way to suppress false warnings while being explicit. - It is no longer possible to execute some slash commands if they are run without the correct permissions - Dependencies are now more explicitly defined neroduckale: - Made easter eggs case-insensitive --------- Signed-off-by: Macintosh II <95250141+mctaylors@users.noreply.github.com> Signed-off-by: Octol1ttle <l1ttleofficial@outlook.com> Co-authored-by: Octol1ttle <l1ttleofficial@outlook.com> Co-authored-by: nrdk <neroduck@vk.com>
2023-07-18 15:25:02 +03:00
[UsedImplicitly]
public async Task<Result> ExecuteUnban(
[Description("User to unban")] IUser target,
[Description("Unban reason")] [MaxLength(256)]
string reason)
{
if (!_context.TryGetContextIDs(out var guildId, out var channelId, out var executorId))
{
return new ArgumentInvalidError(nameof(_context), "Unable to retrieve necessary IDs from command context");
}
// The bot's avatar is used when sending error messages
var botResult = await _userApi.GetCurrentUserAsync(CancellationToken);
if (!botResult.IsDefined(out var bot))
{
return Result.FromError(botResult);
}
// Needed to get the tag and avatar
var executorResult = await _userApi.GetUserAsync(executorId, CancellationToken);
if (!executorResult.IsDefined(out var executor))
{
return Result.FromError(executorResult);
}
var data = await _guildData.GetData(guildId, CancellationToken);
Messages.Culture = GuildSettings.Language.Get(data.Settings);
return await UnbanUserAsync(executor, target, reason, guildId, data, channelId, bot, CancellationToken);
}
private async Task<Result> UnbanUserAsync(
IUser executor, IUser target, string reason, Snowflake guildId, GuildData data, Snowflake channelId,
IUser bot, CancellationToken ct = default)
{
var existingBanResult = await _guildApi.GetGuildBanAsync(guildId, target.ID, ct);
if (!existingBanResult.IsDefined())
{
var errorEmbed = new EmbedBuilder().WithSmallTitle(Messages.UserNotBanned, bot)
.WithColour(ColorsList.Red).Build();
return await _feedback.SendContextualEmbedResultAsync(errorEmbed, ct: ct);
}
var unbanResult = await _guildApi.RemoveGuildBanAsync(
guildId, target.ID, $"({executor.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().AppendBulletPoint(string.Format(Messages.DescriptionActionReason, reason));
var logResult = _utility.LogActionAsync(
data.Settings, channelId, executor, title, description.ToString(), target, ColorsList.Green, ct: ct);
if (!logResult.IsSuccess)
{
return Result.FromError(logResult.Error);
}
return await _feedback.SendContextualEmbedResultAsync(embed, ct: ct);
}
}