mirror of
https://github.com/TeamOctolings/Octobot.git
synced 2025-05-01 11:39:55 +03:00
Tidy up project structure, fix bug with edit logging (#47)
The project structure has been changed because the previous one had everything in 1 folder. From this PR onwards, the following is true: - The source code is stored in `src/` - `*.resx` and `Messages.Designer.cs` is stored in `locale/` - Documentation is stored on the wiki and in `docs/` - Miscellaneous files, such as dotfiles, are stored in the root folder of the repository This PR additionally fixes an issue that would cause logs of edited messages to not be syntax highlighted. This happened because the responder of edited messages was changed to use the universal `InBlockCode` extension method which did not support syntax highlighting until this PR This PR additionally changes CODEOWNERS to be more reliable. Previously, it would be possible for some PRs to be unable to be approved because the only person who can approve them is the same person who opened the PR. --------- Signed-off-by: Octol1ttle <l1ttleofficial@outlook.com>
This commit is contained in:
parent
2dd9f023ef
commit
3eb17b96c5
29 changed files with 180 additions and 179 deletions
96
src/Boyfriend.cs
Normal file
96
src/Boyfriend.cs
Normal file
|
@ -0,0 +1,96 @@
|
|||
using Boyfriend.Commands;
|
||||
using Boyfriend.Services;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Remora.Commands.Extensions;
|
||||
using Remora.Discord.API.Abstractions.Gateway.Commands;
|
||||
using Remora.Discord.API.Abstractions.Objects;
|
||||
using Remora.Discord.API.Objects;
|
||||
using Remora.Discord.Caching.Extensions;
|
||||
using Remora.Discord.Caching.Services;
|
||||
using Remora.Discord.Commands.Extensions;
|
||||
using Remora.Discord.Commands.Services;
|
||||
using Remora.Discord.Gateway;
|
||||
using Remora.Discord.Gateway.Extensions;
|
||||
using Remora.Discord.Hosting.Extensions;
|
||||
using Remora.Discord.Interactivity.Extensions;
|
||||
using Remora.Rest.Core;
|
||||
|
||||
namespace Boyfriend;
|
||||
|
||||
public class Boyfriend {
|
||||
public static readonly AllowedMentions NoMentions = new(
|
||||
Array.Empty<MentionType>(), Array.Empty<Snowflake>(), Array.Empty<Snowflake>());
|
||||
|
||||
public static async Task Main(string[] args) {
|
||||
var host = CreateHostBuilder(args).UseConsoleLifetime().Build();
|
||||
var services = host.Services;
|
||||
|
||||
var slashService = services.GetRequiredService<SlashService>();
|
||||
// Providing a guild ID to this call will result in command duplicates!
|
||||
// To get rid of them, provide the ID of the guild containing duplicates,
|
||||
// comment out calls to WithCommandGroup in CreateHostBuilder
|
||||
// then launch the bot again and remove the guild ID
|
||||
await slashService.UpdateSlashCommandsAsync();
|
||||
|
||||
await host.RunAsync();
|
||||
}
|
||||
|
||||
private static IHostBuilder CreateHostBuilder(string[] args) {
|
||||
return Host.CreateDefaultBuilder(args)
|
||||
.AddDiscordService(
|
||||
services => {
|
||||
var configuration = services.GetRequiredService<IConfiguration>();
|
||||
|
||||
return configuration.GetValue<string?>("BOT_TOKEN")
|
||||
?? throw new InvalidOperationException(
|
||||
"No bot token has been provided. Set the "
|
||||
+ "BOT_TOKEN environment variable to a valid token.");
|
||||
}
|
||||
).ConfigureServices(
|
||||
(_, services) => {
|
||||
services.Configure<DiscordGatewayClientOptions>(
|
||||
options => options.Intents |= GatewayIntents.MessageContents
|
||||
| GatewayIntents.GuildMembers
|
||||
| GatewayIntents.GuildScheduledEvents);
|
||||
services.Configure<CacheSettings>(
|
||||
settings => {
|
||||
settings.SetDefaultAbsoluteExpiration(TimeSpan.FromHours(1));
|
||||
settings.SetDefaultSlidingExpiration(TimeSpan.FromMinutes(30));
|
||||
settings.SetAbsoluteExpiration<IMessage>(TimeSpan.FromDays(7));
|
||||
settings.SetSlidingExpiration<IMessage>(TimeSpan.FromDays(7));
|
||||
});
|
||||
|
||||
services.AddTransient<IConfigurationBuilder, ConfigurationBuilder>()
|
||||
.AddDiscordCaching()
|
||||
.AddDiscordCommands(true)
|
||||
.AddPreparationErrorEvent<ErrorLoggingPreparationErrorEvent>()
|
||||
.AddPostExecutionEvent<ErrorLoggingPostExecutionEvent>()
|
||||
.AddInteractivity()
|
||||
.AddInteractionGroup<InteractionResponders>()
|
||||
.AddSingleton<GuildDataService>()
|
||||
.AddSingleton<UtilityService>()
|
||||
.AddHostedService<GuildUpdateService>()
|
||||
.AddCommandTree()
|
||||
.WithCommandGroup<AboutCommandGroup>()
|
||||
.WithCommandGroup<BanCommandGroup>()
|
||||
.WithCommandGroup<ClearCommandGroup>()
|
||||
.WithCommandGroup<KickCommandGroup>()
|
||||
.WithCommandGroup<MuteCommandGroup>()
|
||||
.WithCommandGroup<PingCommandGroup>()
|
||||
.WithCommandGroup<RemindCommandGroup>()
|
||||
.WithCommandGroup<SettingsCommandGroup>();
|
||||
var responderTypes = typeof(Boyfriend).Assembly
|
||||
.GetExportedTypes()
|
||||
.Where(t => t.IsResponder());
|
||||
foreach (var responderType in responderTypes) services.AddResponder(responderType);
|
||||
}
|
||||
).ConfigureLogging(
|
||||
c => c.AddConsole()
|
||||
.AddFilter("System.Net.Http.HttpClient.*.LogicalHandler", LogLevel.Warning)
|
||||
.AddFilter("System.Net.Http.HttpClient.*.ClientHandler", LogLevel.Warning)
|
||||
);
|
||||
}
|
||||
}
|
18
src/ColorsList.cs
Normal file
18
src/ColorsList.cs
Normal file
|
@ -0,0 +1,18 @@
|
|||
using System.Drawing;
|
||||
|
||||
namespace Boyfriend;
|
||||
|
||||
/// <summary>
|
||||
/// Contains all colors used in embeds.
|
||||
/// </summary>
|
||||
public static class ColorsList {
|
||||
public static readonly Color Default = Color.Gray;
|
||||
public static readonly Color Red = Color.Firebrick;
|
||||
public static readonly Color Green = Color.PaleGreen;
|
||||
public static readonly Color Yellow = Color.Gold;
|
||||
public static readonly Color Blue = Color.RoyalBlue;
|
||||
public static readonly Color Magenta = Color.Orchid;
|
||||
public static readonly Color Cyan = Color.LightSkyBlue;
|
||||
public static readonly Color Black = Color.Black;
|
||||
public static readonly Color White = Color.WhiteSmoke;
|
||||
}
|
75
src/Commands/AboutCommandGroup.cs
Normal file
75
src/Commands/AboutCommandGroup.cs
Normal file
|
@ -0,0 +1,75 @@
|
|||
using System.ComponentModel;
|
||||
using System.Text;
|
||||
using Boyfriend.Services;
|
||||
using Remora.Commands.Attributes;
|
||||
using Remora.Commands.Groups;
|
||||
using Remora.Discord.API.Abstractions.Rest;
|
||||
using Remora.Discord.Commands.Contexts;
|
||||
using Remora.Discord.Commands.Feedback.Services;
|
||||
using Remora.Discord.Extensions.Embeds;
|
||||
using Remora.Discord.Extensions.Formatting;
|
||||
using Remora.Results;
|
||||
|
||||
// ReSharper disable ClassNeverInstantiated.Global
|
||||
// ReSharper disable UnusedMember.Global
|
||||
|
||||
namespace Boyfriend.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to show information about this bot: /about.
|
||||
/// </summary>
|
||||
public class AboutCommandGroup : CommandGroup {
|
||||
private static readonly string[] Developers = { "Octol1ttle", "mctaylors", "neroduckale" };
|
||||
private readonly ICommandContext _context;
|
||||
private readonly GuildDataService _dataService;
|
||||
private readonly FeedbackService _feedbackService;
|
||||
private readonly IDiscordRestUserAPI _userApi;
|
||||
|
||||
public AboutCommandGroup(
|
||||
ICommandContext context, GuildDataService dataService,
|
||||
FeedbackService feedbackService, IDiscordRestUserAPI userApi) {
|
||||
_context = context;
|
||||
_dataService = dataService;
|
||||
_feedbackService = feedbackService;
|
||||
_userApi = userApi;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A slash command that shows information about this bot.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A feedback sending result which may or may not have succeeded.
|
||||
/// </returns>
|
||||
[Command("about")]
|
||||
[Description("Shows Boyfriend's developers")]
|
||||
public async Task<Result> SendAboutBotAsync() {
|
||||
if (!_context.TryGetContextIDs(out var guildId, out _, out _))
|
||||
return Result.FromError(
|
||||
new ArgumentNullError(nameof(_context), "Unable to retrieve necessary IDs from command context"));
|
||||
|
||||
var currentUserResult = await _userApi.GetCurrentUserAsync(CancellationToken);
|
||||
if (!currentUserResult.IsDefined(out var currentUser))
|
||||
return Result.FromError(currentUserResult);
|
||||
|
||||
var cfg = await _dataService.GetConfiguration(guildId.Value, CancellationToken);
|
||||
Messages.Culture = cfg.GetCulture();
|
||||
|
||||
var builder = new StringBuilder().AppendLine(Markdown.Bold(Messages.AboutTitleDevelopers));
|
||||
foreach (var dev in Developers)
|
||||
builder.AppendLine($"@{dev} — {$"AboutDeveloper@{dev}".Localized()}");
|
||||
|
||||
builder.AppendLine()
|
||||
.AppendLine(Markdown.Bold(Messages.AboutTitleWiki))
|
||||
.AppendLine("https://github.com/TeamOctolings/Boyfriend/wiki");
|
||||
|
||||
var embed = new EmbedBuilder().WithSmallTitle(Messages.AboutBot, currentUser)
|
||||
.WithDescription(builder.ToString())
|
||||
.WithColour(ColorsList.Cyan)
|
||||
.WithImageUrl(
|
||||
"https://media.discordapp.net/attachments/837385840946053181/1125009665592393738/boyfriend.png")
|
||||
.Build();
|
||||
if (!embed.IsDefined(out var built)) return Result.FromError(embed);
|
||||
|
||||
return (Result)await _feedbackService.SendContextualEmbedAsync(built, ct: CancellationToken);
|
||||
}
|
||||
}
|
273
src/Commands/BanCommandGroup.cs
Normal file
273
src/Commands/BanCommandGroup.cs
Normal file
|
@ -0,0 +1,273 @@
|
|||
using System.ComponentModel;
|
||||
using System.Text;
|
||||
using Boyfriend.Services;
|
||||
using Remora.Commands.Attributes;
|
||||
using Remora.Commands.Groups;
|
||||
using Remora.Discord.API.Abstractions.Objects;
|
||||
using Remora.Discord.API.Abstractions.Rest;
|
||||
using Remora.Discord.API.Objects;
|
||||
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.Results;
|
||||
|
||||
// ReSharper disable ClassNeverInstantiated.Global
|
||||
// ReSharper disable UnusedMember.Global
|
||||
|
||||
namespace Boyfriend.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// Handles commands related to ban management: /ban and /unban.
|
||||
/// </summary>
|
||||
public class BanCommandGroup : CommandGroup {
|
||||
private readonly IDiscordRestChannelAPI _channelApi;
|
||||
private readonly ICommandContext _context;
|
||||
private readonly GuildDataService _dataService;
|
||||
private readonly FeedbackService _feedbackService;
|
||||
private readonly IDiscordRestGuildAPI _guildApi;
|
||||
private readonly IDiscordRestUserAPI _userApi;
|
||||
private readonly UtilityService _utility;
|
||||
|
||||
public BanCommandGroup(
|
||||
ICommandContext context, IDiscordRestChannelAPI channelApi, GuildDataService dataService,
|
||||
FeedbackService feedbackService, IDiscordRestGuildAPI guildApi, IDiscordRestUserAPI userApi,
|
||||
UtilityService utility) {
|
||||
_context = context;
|
||||
_channelApi = channelApi;
|
||||
_dataService = dataService;
|
||||
_feedbackService = feedbackService;
|
||||
_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="duration">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="Extensions.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="UnbanUserAsync" />
|
||||
[Command("ban", "бан")]
|
||||
[RequireContext(ChannelContext.Guild)]
|
||||
[RequireDiscordPermission(DiscordPermission.BanMembers)]
|
||||
[RequireBotDiscordPermissions(DiscordPermission.BanMembers)]
|
||||
[Description("Ban user")]
|
||||
public async Task<Result> BanUserAsync(
|
||||
[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 Result.FromError(
|
||||
new ArgumentNullError(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 data = await _dataService.GetData(guildId.Value, CancellationToken);
|
||||
var cfg = data.Configuration;
|
||||
Messages.Culture = data.Culture;
|
||||
|
||||
var existingBanResult = await _guildApi.GetGuildBanAsync(guildId.Value, target.ID, CancellationToken);
|
||||
if (existingBanResult.IsDefined()) {
|
||||
var embed = new EmbedBuilder().WithSmallTitle(Messages.UserAlreadyBanned, currentUser)
|
||||
.WithColour(ColorsList.Red).Build();
|
||||
|
||||
if (!embed.IsDefined(out var alreadyBuilt))
|
||||
return Result.FromError(embed);
|
||||
|
||||
return (Result)await _feedbackService.SendContextualEmbedAsync(alreadyBuilt, ct: CancellationToken);
|
||||
}
|
||||
|
||||
var interactionResult
|
||||
= await _utility.CheckInteractionsAsync(guildId.Value, userId.Value, target.ID, "Ban", CancellationToken);
|
||||
if (!interactionResult.IsSuccess)
|
||||
return Result.FromError(interactionResult);
|
||||
|
||||
Result<Embed> responseEmbed;
|
||||
if (interactionResult.Entity is not null) {
|
||||
responseEmbed = new EmbedBuilder().WithSmallTitle(interactionResult.Entity, currentUser)
|
||||
.WithColour(ColorsList.Red).Build();
|
||||
} else {
|
||||
var userResult = await _userApi.GetUserAsync(userId.Value, CancellationToken);
|
||||
if (!userResult.IsDefined(out var user))
|
||||
return Result.FromError(userResult);
|
||||
|
||||
var builder = new StringBuilder().AppendLine(string.Format(Messages.DescriptionActionReason, reason));
|
||||
if (duration is not null)
|
||||
builder.Append(
|
||||
string.Format(
|
||||
Messages.DescriptionActionExpiresAt,
|
||||
Markdown.Timestamp(DateTimeOffset.UtcNow.Add(duration.Value))));
|
||||
var description = builder.ToString();
|
||||
|
||||
var dmChannelResult = await _userApi.CreateDMAsync(target.ID, CancellationToken);
|
||||
if (dmChannelResult.IsDefined(out var dmChannel)) {
|
||||
var guildResult = await _guildApi.GetGuildAsync(guildId.Value, ct: CancellationToken);
|
||||
if (!guildResult.IsDefined(out var guild))
|
||||
return Result.FromError(guildResult);
|
||||
|
||||
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: CancellationToken);
|
||||
}
|
||||
|
||||
var banResult = await _guildApi.CreateGuildBanAsync(
|
||||
guildId.Value, target.ID, reason: $"({user.GetTag()}) {reason}".EncodeHeader(),
|
||||
ct: CancellationToken);
|
||||
if (!banResult.IsSuccess)
|
||||
return Result.FromError(banResult.Error);
|
||||
var memberData = data.GetMemberData(target.ID);
|
||||
memberData.BannedUntil
|
||||
= duration is not null ? DateTimeOffset.UtcNow.Add(duration.Value) : DateTimeOffset.MaxValue;
|
||||
memberData.Roles.Clear();
|
||||
|
||||
responseEmbed = new EmbedBuilder().WithSmallTitle(
|
||||
string.Format(Messages.UserBanned, target.GetTag()), target)
|
||||
.WithColour(ColorsList.Green).Build();
|
||||
|
||||
if ((cfg.PublicFeedbackChannel is not 0 && cfg.PublicFeedbackChannel != channelId.Value)
|
||||
|| (cfg.PrivateFeedbackChannel is not 0 && cfg.PrivateFeedbackChannel != channelId.Value)) {
|
||||
var logEmbed = new EmbedBuilder().WithSmallTitle(
|
||||
string.Format(Messages.UserBanned, target.GetTag()), target)
|
||||
.WithDescription(description)
|
||||
.WithActionFooter(user)
|
||||
.WithCurrentTimestamp()
|
||||
.WithColour(ColorsList.Red)
|
||||
.Build();
|
||||
|
||||
if (!logEmbed.IsDefined(out var logBuilt))
|
||||
return Result.FromError(logEmbed);
|
||||
|
||||
var builtArray = new[] { logBuilt };
|
||||
// Not awaiting to reduce response time
|
||||
if (cfg.PublicFeedbackChannel != channelId.Value)
|
||||
_ = _channelApi.CreateMessageAsync(
|
||||
cfg.PublicFeedbackChannel.ToDiscordSnowflake(), embeds: builtArray,
|
||||
ct: CancellationToken);
|
||||
if (cfg.PrivateFeedbackChannel != cfg.PublicFeedbackChannel
|
||||
&& cfg.PrivateFeedbackChannel != channelId.Value)
|
||||
_ = _channelApi.CreateMessageAsync(
|
||||
cfg.PrivateFeedbackChannel.ToDiscordSnowflake(), embeds: builtArray,
|
||||
ct: CancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
if (!responseEmbed.IsDefined(out var built))
|
||||
return Result.FromError(responseEmbed);
|
||||
|
||||
return (Result)await _feedbackService.SendContextualEmbedAsync(built, ct: CancellationToken);
|
||||
}
|
||||
|
||||
/// <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="Extensions.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="BanUserAsync" />
|
||||
/// <seealso cref="GuildUpdateService.TickGuildAsync"/>
|
||||
[Command("unban")]
|
||||
[RequireContext(ChannelContext.Guild)]
|
||||
[RequireDiscordPermission(DiscordPermission.BanMembers)]
|
||||
[RequireBotDiscordPermissions(DiscordPermission.BanMembers)]
|
||||
[Description("Unban user")]
|
||||
public async Task<Result> UnbanUserAsync(
|
||||
[Description("User to unban")] IUser target,
|
||||
[Description("Unban reason")] string reason) {
|
||||
if (!_context.TryGetContextIDs(out var guildId, out var channelId, out var userId))
|
||||
return Result.FromError(
|
||||
new ArgumentNullError(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 cfg = await _dataService.GetConfiguration(guildId.Value, CancellationToken);
|
||||
Messages.Culture = cfg.GetCulture();
|
||||
|
||||
var existingBanResult = await _guildApi.GetGuildBanAsync(guildId.Value, target.ID, CancellationToken);
|
||||
if (!existingBanResult.IsDefined()) {
|
||||
var embed = new EmbedBuilder().WithSmallTitle(Messages.UserNotBanned, currentUser)
|
||||
.WithColour(ColorsList.Red).Build();
|
||||
|
||||
if (!embed.IsDefined(out var alreadyBuilt))
|
||||
return Result.FromError(embed);
|
||||
|
||||
return (Result)await _feedbackService.SendContextualEmbedAsync(alreadyBuilt, ct: CancellationToken);
|
||||
}
|
||||
|
||||
// Needed to get the tag and avatar
|
||||
var userResult = await _userApi.GetUserAsync(userId.Value, CancellationToken);
|
||||
if (!userResult.IsDefined(out var user))
|
||||
return Result.FromError(userResult);
|
||||
|
||||
var unbanResult = await _guildApi.RemoveGuildBanAsync(
|
||||
guildId.Value, target.ID, $"({user.GetTag()}) {reason}".EncodeHeader(),
|
||||
ct: CancellationToken);
|
||||
if (!unbanResult.IsSuccess)
|
||||
return Result.FromError(unbanResult.Error);
|
||||
|
||||
var responseEmbed = new EmbedBuilder().WithSmallTitle(
|
||||
string.Format(Messages.UserUnbanned, target.GetTag()), target)
|
||||
.WithColour(ColorsList.Green).Build();
|
||||
|
||||
if ((cfg.PublicFeedbackChannel is not 0 && cfg.PublicFeedbackChannel != channelId.Value)
|
||||
|| (cfg.PrivateFeedbackChannel is not 0 && cfg.PrivateFeedbackChannel != channelId.Value)) {
|
||||
var logEmbed = new EmbedBuilder().WithSmallTitle(
|
||||
string.Format(Messages.UserUnbanned, target.GetTag()), target)
|
||||
.WithDescription(string.Format(Messages.DescriptionActionReason, reason))
|
||||
.WithActionFooter(user)
|
||||
.WithCurrentTimestamp()
|
||||
.WithColour(ColorsList.Green)
|
||||
.Build();
|
||||
|
||||
if (!logEmbed.IsDefined(out var logBuilt))
|
||||
return Result.FromError(logEmbed);
|
||||
|
||||
var builtArray = new[] { logBuilt };
|
||||
|
||||
// Not awaiting to reduce response time
|
||||
if (cfg.PublicFeedbackChannel != channelId.Value)
|
||||
_ = _channelApi.CreateMessageAsync(
|
||||
cfg.PublicFeedbackChannel.ToDiscordSnowflake(), embeds: builtArray,
|
||||
ct: CancellationToken);
|
||||
if (cfg.PrivateFeedbackChannel != cfg.PublicFeedbackChannel
|
||||
&& cfg.PrivateFeedbackChannel != channelId.Value)
|
||||
_ = _channelApi.CreateMessageAsync(
|
||||
cfg.PrivateFeedbackChannel.ToDiscordSnowflake(), embeds: builtArray,
|
||||
ct: CancellationToken);
|
||||
}
|
||||
|
||||
if (!responseEmbed.IsDefined(out var built))
|
||||
return Result.FromError(responseEmbed);
|
||||
|
||||
return (Result)await _feedbackService.SendContextualEmbedAsync(built, ct: CancellationToken);
|
||||
}
|
||||
}
|
120
src/Commands/ClearCommandGroup.cs
Normal file
120
src/Commands/ClearCommandGroup.cs
Normal file
|
@ -0,0 +1,120 @@
|
|||
using System.ComponentModel;
|
||||
using System.Text;
|
||||
using Boyfriend.Services;
|
||||
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;
|
||||
|
||||
// ReSharper disable ClassNeverInstantiated.Global
|
||||
// ReSharper disable UnusedMember.Global
|
||||
|
||||
namespace Boyfriend.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to clear messages in a channel: /clear.
|
||||
/// </summary>
|
||||
public class ClearCommandGroup : CommandGroup {
|
||||
private readonly IDiscordRestChannelAPI _channelApi;
|
||||
private readonly ICommandContext _context;
|
||||
private readonly GuildDataService _dataService;
|
||||
private readonly FeedbackService _feedbackService;
|
||||
private readonly IDiscordRestUserAPI _userApi;
|
||||
|
||||
public ClearCommandGroup(
|
||||
IDiscordRestChannelAPI channelApi, ICommandContext context, GuildDataService dataService,
|
||||
FeedbackService feedbackService, IDiscordRestUserAPI userApi) {
|
||||
_channelApi = channelApi;
|
||||
_context = context;
|
||||
_dataService = dataService;
|
||||
_feedbackService = feedbackService;
|
||||
_userApi = userApi;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A slash command that clears messages in the channel it was executed.
|
||||
/// </summary>
|
||||
/// <param name="amount">The amount of messages to clear.</param>
|
||||
/// <returns>
|
||||
/// A feedback sending result which may or may not have succeeded. A successful result does not mean that any messages
|
||||
/// were cleared and vice-versa.
|
||||
/// </returns>
|
||||
[Command("clear", "очистить")]
|
||||
[RequireContext(ChannelContext.Guild)]
|
||||
[RequireDiscordPermission(DiscordPermission.ManageMessages)]
|
||||
[RequireBotDiscordPermissions(DiscordPermission.ManageMessages)]
|
||||
[Description("Remove multiple messages")]
|
||||
public async Task<Result> ClearMessagesAsync(
|
||||
[Description("Number of messages to remove (2-100)")] [MinValue(2)] [MaxValue(100)]
|
||||
int amount) {
|
||||
if (!_context.TryGetContextIDs(out var guildId, out var channelId, out var userId))
|
||||
return Result.FromError(
|
||||
new ArgumentNullError(nameof(_context), "Unable to retrieve necessary IDs from command context"));
|
||||
|
||||
var messagesResult = await _channelApi.GetChannelMessagesAsync(
|
||||
channelId.Value, limit: amount + 1, ct: CancellationToken);
|
||||
if (!messagesResult.IsDefined(out var messages))
|
||||
return Result.FromError(messagesResult);
|
||||
|
||||
var cfg = await _dataService.GetConfiguration(guildId.Value, CancellationToken);
|
||||
Messages.Culture = cfg.GetCulture();
|
||||
|
||||
var idList = new List<Snowflake>(messages.Count);
|
||||
var builder = new StringBuilder().AppendLine(Mention.Channel(channelId.Value)).AppendLine();
|
||||
for (var i = messages.Count - 1; i >= 1; i--) { // '>= 1' to skip last message ('Boyfriend is thinking...')
|
||||
var message = messages[i];
|
||||
idList.Add(message.ID);
|
||||
builder.AppendLine(string.Format(Messages.MessageFrom, Mention.User(message.Author)));
|
||||
builder.Append(message.Content.InBlockCode());
|
||||
}
|
||||
|
||||
var description = builder.ToString();
|
||||
|
||||
var userResult = await _userApi.GetUserAsync(userId.Value, CancellationToken);
|
||||
if (!userResult.IsDefined(out var user))
|
||||
return Result.FromError(userResult);
|
||||
|
||||
var deleteResult = await _channelApi.BulkDeleteMessagesAsync(
|
||||
channelId.Value, idList, user.GetTag().EncodeHeader(), CancellationToken);
|
||||
if (!deleteResult.IsSuccess)
|
||||
return Result.FromError(deleteResult.Error);
|
||||
|
||||
// The current user's avatar is used when sending messages
|
||||
var currentUserResult = await _userApi.GetCurrentUserAsync(CancellationToken);
|
||||
if (!currentUserResult.IsDefined(out var currentUser))
|
||||
return Result.FromError(currentUserResult);
|
||||
|
||||
var title = string.Format(Messages.MessagesCleared, amount.ToString());
|
||||
if (cfg.PrivateFeedbackChannel is not 0 && cfg.PrivateFeedbackChannel != channelId.Value) {
|
||||
var logEmbed = new EmbedBuilder().WithSmallTitle(title, currentUser)
|
||||
.WithDescription(description)
|
||||
.WithActionFooter(user)
|
||||
.WithCurrentTimestamp()
|
||||
.WithColour(ColorsList.Red)
|
||||
.Build();
|
||||
|
||||
if (!logEmbed.IsDefined(out var logBuilt))
|
||||
return Result.FromError(logEmbed);
|
||||
|
||||
// Not awaiting to reduce response time
|
||||
if (cfg.PrivateFeedbackChannel != channelId.Value)
|
||||
_ = _channelApi.CreateMessageAsync(
|
||||
cfg.PrivateFeedbackChannel.ToDiscordSnowflake(), embeds: new[] { logBuilt },
|
||||
ct: CancellationToken);
|
||||
}
|
||||
|
||||
var embed = new EmbedBuilder().WithSmallTitle(title, currentUser)
|
||||
.WithColour(ColorsList.Green).Build();
|
||||
if (!embed.IsDefined(out var built)) return Result.FromError(embed);
|
||||
|
||||
return (Result)await _feedbackService.SendContextualEmbedAsync(built, ct: CancellationToken);
|
||||
}
|
||||
}
|
62
src/Commands/ErrorLoggingEvents.cs
Normal file
62
src/Commands/ErrorLoggingEvents.cs
Normal file
|
@ -0,0 +1,62 @@
|
|||
using Microsoft.Extensions.Logging;
|
||||
using Remora.Discord.Commands.Contexts;
|
||||
using Remora.Discord.Commands.Services;
|
||||
using Remora.Results;
|
||||
|
||||
// ReSharper disable ClassNeverInstantiated.Global
|
||||
|
||||
namespace Boyfriend.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// Handles error logging for slash commands that couldn't be successfully prepared.
|
||||
/// </summary>
|
||||
public class ErrorLoggingPreparationErrorEvent : IPreparationErrorEvent {
|
||||
private readonly ILogger<ErrorLoggingPreparationErrorEvent> _logger;
|
||||
|
||||
public ErrorLoggingPreparationErrorEvent(ILogger<ErrorLoggingPreparationErrorEvent> logger) {
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Logs a warning using the injected <see cref="ILogger" /> if the <paramref name="preparationResult" /> has not
|
||||
/// succeeded.
|
||||
/// </summary>
|
||||
/// <param name="context">The context of the slash command. Unused.</param>
|
||||
/// <param name="preparationResult">The result whose success is checked.</param>
|
||||
/// <param name="ct">The cancellation token for this operation. Unused.</param>
|
||||
/// <returns>A result which has succeeded.</returns>
|
||||
public Task<Result> PreparationFailed(
|
||||
IOperationContext context, IResult preparationResult, CancellationToken ct = default) {
|
||||
if (!preparationResult.IsSuccess)
|
||||
_logger.LogWarning("Error in slash command preparation.\n{ErrorMessage}", preparationResult.Error.Message);
|
||||
|
||||
return Task.FromResult(Result.FromSuccess());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles error logging for slash command groups.
|
||||
/// </summary>
|
||||
public class ErrorLoggingPostExecutionEvent : IPostExecutionEvent {
|
||||
private readonly ILogger<ErrorLoggingPostExecutionEvent> _logger;
|
||||
|
||||
public ErrorLoggingPostExecutionEvent(ILogger<ErrorLoggingPostExecutionEvent> logger) {
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Logs a warning using the injected <see cref="ILogger" /> if the <paramref name="commandResult" /> has not
|
||||
/// succeeded.
|
||||
/// </summary>
|
||||
/// <param name="context">The context of the slash command. Unused.</param>
|
||||
/// <param name="commandResult">The result whose success is checked.</param>
|
||||
/// <param name="ct">The cancellation token for this operation. Unused.</param>
|
||||
/// <returns>A result which has succeeded.</returns>
|
||||
public Task<Result> AfterExecutionAsync(
|
||||
ICommandContext context, IResult commandResult, CancellationToken ct = default) {
|
||||
if (!commandResult.IsSuccess)
|
||||
_logger.LogWarning("Error in slash command execution.\n{ErrorMessage}", commandResult.Error.Message);
|
||||
|
||||
return Task.FromResult(Result.FromSuccess());
|
||||
}
|
||||
}
|
164
src/Commands/KickCommandGroup.cs
Normal file
164
src/Commands/KickCommandGroup.cs
Normal file
|
@ -0,0 +1,164 @@
|
|||
using System.ComponentModel;
|
||||
using Boyfriend.Services;
|
||||
using Remora.Commands.Attributes;
|
||||
using Remora.Commands.Groups;
|
||||
using Remora.Discord.API.Abstractions.Objects;
|
||||
using Remora.Discord.API.Abstractions.Rest;
|
||||
using Remora.Discord.API.Objects;
|
||||
using Remora.Discord.Commands.Conditions;
|
||||
using Remora.Discord.Commands.Contexts;
|
||||
using Remora.Discord.Commands.Feedback.Services;
|
||||
using Remora.Discord.Extensions.Embeds;
|
||||
using Remora.Results;
|
||||
|
||||
// ReSharper disable ClassNeverInstantiated.Global
|
||||
// ReSharper disable UnusedMember.Global
|
||||
|
||||
namespace Boyfriend.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to kick members of a guild: /kick.
|
||||
/// </summary>
|
||||
public class KickCommandGroup : CommandGroup {
|
||||
private readonly IDiscordRestChannelAPI _channelApi;
|
||||
private readonly ICommandContext _context;
|
||||
private readonly GuildDataService _dataService;
|
||||
private readonly FeedbackService _feedbackService;
|
||||
private readonly IDiscordRestGuildAPI _guildApi;
|
||||
private readonly IDiscordRestUserAPI _userApi;
|
||||
private readonly UtilityService _utility;
|
||||
|
||||
public KickCommandGroup(
|
||||
ICommandContext context, IDiscordRestChannelAPI channelApi, GuildDataService dataService,
|
||||
FeedbackService feedbackService, IDiscordRestGuildAPI guildApi, IDiscordRestUserAPI userApi,
|
||||
UtilityService utility) {
|
||||
_context = context;
|
||||
_channelApi = channelApi;
|
||||
_dataService = dataService;
|
||||
_feedbackService = feedbackService;
|
||||
_guildApi = guildApi;
|
||||
_userApi = userApi;
|
||||
_utility = utility;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A slash command that kicks a Discord member with the specified reason.
|
||||
/// </summary>
|
||||
/// <param name="target">The member to kick.</param>
|
||||
/// <param name="reason">
|
||||
/// The reason for this kick. Must be encoded with <see cref="Extensions.EncodeHeader" /> when passed to
|
||||
/// <see cref="IDiscordRestGuildAPI.RemoveGuildMemberAsync" />.
|
||||
/// </param>
|
||||
/// <returns>
|
||||
/// A feedback sending result which may or may not have succeeded. A successful result does not mean that the member
|
||||
/// was kicked and vice-versa.
|
||||
/// </returns>
|
||||
[Command("kick", "кик")]
|
||||
[RequireContext(ChannelContext.Guild)]
|
||||
[RequireDiscordPermission(DiscordPermission.KickMembers)]
|
||||
[RequireBotDiscordPermissions(DiscordPermission.KickMembers)]
|
||||
[Description("Kick member")]
|
||||
public async Task<Result> KickUserAsync(
|
||||
[Description("Member to kick")] IUser target,
|
||||
[Description("Kick reason")] string reason) {
|
||||
if (!_context.TryGetContextIDs(out var guildId, out var channelId, out var userId))
|
||||
return Result.FromError(
|
||||
new ArgumentNullError(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 data = await _dataService.GetData(guildId.Value, CancellationToken);
|
||||
var cfg = data.Configuration;
|
||||
Messages.Culture = cfg.GetCulture();
|
||||
|
||||
var memberResult = await _guildApi.GetGuildMemberAsync(guildId.Value, target.ID, CancellationToken);
|
||||
if (!memberResult.IsSuccess) {
|
||||
var embed = new EmbedBuilder().WithSmallTitle(Messages.UserNotFoundShort, currentUser)
|
||||
.WithColour(ColorsList.Red).Build();
|
||||
|
||||
if (!embed.IsDefined(out var alreadyBuilt))
|
||||
return Result.FromError(embed);
|
||||
|
||||
return (Result)await _feedbackService.SendContextualEmbedAsync(alreadyBuilt, ct: CancellationToken);
|
||||
}
|
||||
|
||||
var interactionResult
|
||||
= await _utility.CheckInteractionsAsync(guildId.Value, userId.Value, target.ID, "Kick", CancellationToken);
|
||||
if (!interactionResult.IsSuccess)
|
||||
return Result.FromError(interactionResult);
|
||||
|
||||
Result<Embed> responseEmbed;
|
||||
if (interactionResult.Entity is not null) {
|
||||
responseEmbed = new EmbedBuilder().WithSmallTitle(interactionResult.Entity, currentUser)
|
||||
.WithColour(ColorsList.Red).Build();
|
||||
} else {
|
||||
var userResult = await _userApi.GetUserAsync(userId.Value, CancellationToken);
|
||||
if (!userResult.IsDefined(out var user))
|
||||
return Result.FromError(userResult);
|
||||
|
||||
var dmChannelResult = await _userApi.CreateDMAsync(target.ID, CancellationToken);
|
||||
if (dmChannelResult.IsDefined(out var dmChannel)) {
|
||||
var guildResult = await _guildApi.GetGuildAsync(guildId.Value, ct: CancellationToken);
|
||||
if (!guildResult.IsDefined(out var guild))
|
||||
return Result.FromError(guildResult);
|
||||
|
||||
var dmEmbed = new EmbedBuilder().WithGuildTitle(guild)
|
||||
.WithTitle(Messages.YouWereKicked)
|
||||
.WithDescription(string.Format(Messages.DescriptionActionReason, reason))
|
||||
.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: CancellationToken);
|
||||
}
|
||||
|
||||
var kickResult = await _guildApi.RemoveGuildMemberAsync(
|
||||
guildId.Value, target.ID, $"({user.GetTag()}) {reason}".EncodeHeader(),
|
||||
ct: CancellationToken);
|
||||
if (!kickResult.IsSuccess)
|
||||
return Result.FromError(kickResult.Error);
|
||||
data.GetMemberData(target.ID).Roles.Clear();
|
||||
|
||||
responseEmbed = new EmbedBuilder().WithSmallTitle(
|
||||
string.Format(Messages.UserKicked, target.GetTag()), target)
|
||||
.WithColour(ColorsList.Green).Build();
|
||||
|
||||
if ((cfg.PublicFeedbackChannel is not 0 && cfg.PublicFeedbackChannel != channelId.Value)
|
||||
|| (cfg.PrivateFeedbackChannel is not 0 && cfg.PrivateFeedbackChannel != channelId.Value)) {
|
||||
var logEmbed = new EmbedBuilder().WithSmallTitle(
|
||||
string.Format(Messages.UserKicked, target.GetTag()), target)
|
||||
.WithDescription(string.Format(Messages.DescriptionActionReason, reason))
|
||||
.WithActionFooter(user)
|
||||
.WithCurrentTimestamp()
|
||||
.WithColour(ColorsList.Red)
|
||||
.Build();
|
||||
|
||||
if (!logEmbed.IsDefined(out var logBuilt))
|
||||
return Result.FromError(logEmbed);
|
||||
|
||||
var builtArray = new[] { logBuilt };
|
||||
// Not awaiting to reduce response time
|
||||
if (cfg.PublicFeedbackChannel != channelId.Value)
|
||||
_ = _channelApi.CreateMessageAsync(
|
||||
cfg.PublicFeedbackChannel.ToDiscordSnowflake(), embeds: builtArray,
|
||||
ct: CancellationToken);
|
||||
if (cfg.PrivateFeedbackChannel != cfg.PublicFeedbackChannel
|
||||
&& cfg.PrivateFeedbackChannel != channelId.Value)
|
||||
_ = _channelApi.CreateMessageAsync(
|
||||
cfg.PrivateFeedbackChannel.ToDiscordSnowflake(), embeds: builtArray,
|
||||
ct: CancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
if (!responseEmbed.IsDefined(out var built))
|
||||
return Result.FromError(responseEmbed);
|
||||
|
||||
return (Result)await _feedbackService.SendContextualEmbedAsync(built, ct: CancellationToken);
|
||||
}
|
||||
}
|
255
src/Commands/MuteCommandGroup.cs
Normal file
255
src/Commands/MuteCommandGroup.cs
Normal file
|
@ -0,0 +1,255 @@
|
|||
using System.ComponentModel;
|
||||
using System.Text;
|
||||
using Boyfriend.Services;
|
||||
using Remora.Commands.Attributes;
|
||||
using Remora.Commands.Groups;
|
||||
using Remora.Discord.API.Abstractions.Objects;
|
||||
using Remora.Discord.API.Abstractions.Rest;
|
||||
using Remora.Discord.API.Objects;
|
||||
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.Results;
|
||||
|
||||
// ReSharper disable ClassNeverInstantiated.Global
|
||||
// ReSharper disable UnusedMember.Global
|
||||
|
||||
namespace Boyfriend.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// Handles commands related to mute management: /mute and /unmute.
|
||||
/// </summary>
|
||||
public class MuteCommandGroup : CommandGroup {
|
||||
private readonly IDiscordRestChannelAPI _channelApi;
|
||||
private readonly ICommandContext _context;
|
||||
private readonly GuildDataService _dataService;
|
||||
private readonly FeedbackService _feedbackService;
|
||||
private readonly IDiscordRestGuildAPI _guildApi;
|
||||
private readonly IDiscordRestUserAPI _userApi;
|
||||
private readonly UtilityService _utility;
|
||||
|
||||
public MuteCommandGroup(
|
||||
ICommandContext context, IDiscordRestChannelAPI channelApi, GuildDataService dataService,
|
||||
FeedbackService feedbackService, IDiscordRestGuildAPI guildApi, IDiscordRestUserAPI userApi,
|
||||
UtilityService utility) {
|
||||
_context = context;
|
||||
_channelApi = channelApi;
|
||||
_dataService = dataService;
|
||||
_feedbackService = feedbackService;
|
||||
_guildApi = guildApi;
|
||||
_userApi = userApi;
|
||||
_utility = utility;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A slash command that mutes a Discord member with the specified reason.
|
||||
/// </summary>
|
||||
/// <param name="target">The member to mute.</param>
|
||||
/// <param name="duration">The duration for this mute. The member will be automatically unmuted after this duration.</param>
|
||||
/// <param name="reason">
|
||||
/// The reason for this mute. Must be encoded with <see cref="Extensions.EncodeHeader" /> when passed to
|
||||
/// <see cref="IDiscordRestGuildAPI.ModifyGuildMemberAsync" />.
|
||||
/// </param>
|
||||
/// <returns>
|
||||
/// A feedback sending result which may or may not have succeeded. A successful result does not mean that the member
|
||||
/// was muted and vice-versa.
|
||||
/// </returns>
|
||||
/// <seealso cref="UnmuteUserAsync" />
|
||||
[Command("mute", "мут")]
|
||||
[RequireContext(ChannelContext.Guild)]
|
||||
[RequireDiscordPermission(DiscordPermission.ModerateMembers)]
|
||||
[RequireBotDiscordPermissions(DiscordPermission.ModerateMembers)]
|
||||
[Description("Mute member")]
|
||||
public async Task<Result> MuteUserAsync(
|
||||
[Description("Member to mute")] IUser target,
|
||||
[Description("Mute reason")] string reason,
|
||||
[Description("Mute duration")] TimeSpan duration) {
|
||||
if (!_context.TryGetContextIDs(out var guildId, out var channelId, out var userId))
|
||||
return Result.FromError(
|
||||
new ArgumentNullError(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 memberResult = await _guildApi.GetGuildMemberAsync(guildId.Value, target.ID, CancellationToken);
|
||||
if (!memberResult.IsSuccess) {
|
||||
var embed = new EmbedBuilder().WithSmallTitle(Messages.UserNotFoundShort, currentUser)
|
||||
.WithColour(ColorsList.Red).Build();
|
||||
|
||||
if (!embed.IsDefined(out var alreadyBuilt))
|
||||
return Result.FromError(embed);
|
||||
|
||||
return (Result)await _feedbackService.SendContextualEmbedAsync(alreadyBuilt, ct: CancellationToken);
|
||||
}
|
||||
|
||||
var interactionResult
|
||||
= await _utility.CheckInteractionsAsync(
|
||||
guildId.Value, userId.Value, target.ID, "Mute", CancellationToken);
|
||||
if (!interactionResult.IsSuccess)
|
||||
return Result.FromError(interactionResult);
|
||||
|
||||
var data = await _dataService.GetData(guildId.Value, CancellationToken);
|
||||
var cfg = data.Configuration;
|
||||
Messages.Culture = data.Culture;
|
||||
|
||||
Result<Embed> responseEmbed;
|
||||
if (interactionResult.Entity is not null) {
|
||||
responseEmbed = new EmbedBuilder().WithSmallTitle(interactionResult.Entity, currentUser)
|
||||
.WithColour(ColorsList.Red).Build();
|
||||
} else {
|
||||
var userResult = await _userApi.GetUserAsync(userId.Value, CancellationToken);
|
||||
if (!userResult.IsDefined(out var user))
|
||||
return Result.FromError(userResult);
|
||||
|
||||
var until = DateTimeOffset.UtcNow.Add(duration); // >:)
|
||||
var muteResult = await _guildApi.ModifyGuildMemberAsync(
|
||||
guildId.Value, target.ID, reason: $"({user.GetTag()}) {reason}".EncodeHeader(),
|
||||
communicationDisabledUntil: until, ct: CancellationToken);
|
||||
if (!muteResult.IsSuccess)
|
||||
return Result.FromError(muteResult.Error);
|
||||
|
||||
responseEmbed = new EmbedBuilder().WithSmallTitle(
|
||||
string.Format(Messages.UserMuted, target.GetTag()), target)
|
||||
.WithColour(ColorsList.Green).Build();
|
||||
|
||||
if ((cfg.PublicFeedbackChannel is not 0 && cfg.PublicFeedbackChannel != channelId.Value)
|
||||
|| (cfg.PrivateFeedbackChannel is not 0 && cfg.PrivateFeedbackChannel != channelId.Value)) {
|
||||
var builder = new StringBuilder().AppendLine(string.Format(Messages.DescriptionActionReason, reason))
|
||||
.Append(
|
||||
string.Format(
|
||||
Messages.DescriptionActionExpiresAt, Markdown.Timestamp(until)));
|
||||
|
||||
var logEmbed = new EmbedBuilder().WithSmallTitle(
|
||||
string.Format(Messages.UserMuted, target.GetTag()), target)
|
||||
.WithDescription(builder.ToString())
|
||||
.WithActionFooter(user)
|
||||
.WithCurrentTimestamp()
|
||||
.WithColour(ColorsList.Red)
|
||||
.Build();
|
||||
|
||||
if (!logEmbed.IsDefined(out var logBuilt))
|
||||
return Result.FromError(logEmbed);
|
||||
|
||||
var builtArray = new[] { logBuilt };
|
||||
// Not awaiting to reduce response time
|
||||
if (cfg.PublicFeedbackChannel != channelId.Value)
|
||||
_ = _channelApi.CreateMessageAsync(
|
||||
cfg.PublicFeedbackChannel.ToDiscordSnowflake(), embeds: builtArray,
|
||||
ct: CancellationToken);
|
||||
if (cfg.PrivateFeedbackChannel != cfg.PublicFeedbackChannel
|
||||
&& cfg.PrivateFeedbackChannel != channelId.Value)
|
||||
_ = _channelApi.CreateMessageAsync(
|
||||
cfg.PrivateFeedbackChannel.ToDiscordSnowflake(), embeds: builtArray,
|
||||
ct: CancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
if (!responseEmbed.IsDefined(out var built))
|
||||
return Result.FromError(responseEmbed);
|
||||
|
||||
return (Result)await _feedbackService.SendContextualEmbedAsync(built, ct: CancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A slash command that unmutes a Discord member with the specified reason.
|
||||
/// </summary>
|
||||
/// <param name="target">The member to unmute.</param>
|
||||
/// <param name="reason">
|
||||
/// The reason for this unmute. Must be encoded with <see cref="Extensions.EncodeHeader" /> when passed to
|
||||
/// <see cref="IDiscordRestGuildAPI.ModifyGuildMemberAsync" />.
|
||||
/// </param>
|
||||
/// <returns>
|
||||
/// A feedback sending result which may or may not have succeeded. A successful result does not mean that the member
|
||||
/// was unmuted and vice-versa.
|
||||
/// </returns>
|
||||
/// <seealso cref="MuteUserAsync" />
|
||||
/// <seealso cref="GuildUpdateService.TickGuildAsync"/>
|
||||
[Command("unmute", "размут")]
|
||||
[RequireContext(ChannelContext.Guild)]
|
||||
[RequireDiscordPermission(DiscordPermission.ModerateMembers)]
|
||||
[RequireBotDiscordPermissions(DiscordPermission.ModerateMembers)]
|
||||
[Description("Unmute member")]
|
||||
public async Task<Result> UnmuteUserAsync(
|
||||
[Description("Member to unmute")] IUser target,
|
||||
[Description("Unmute reason")] string reason) {
|
||||
if (!_context.TryGetContextIDs(out var guildId, out var channelId, out var userId))
|
||||
return Result.FromError(
|
||||
new ArgumentNullError(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 cfg = await _dataService.GetConfiguration(guildId.Value, CancellationToken);
|
||||
Messages.Culture = cfg.GetCulture();
|
||||
|
||||
var memberResult = await _guildApi.GetGuildMemberAsync(guildId.Value, target.ID, CancellationToken);
|
||||
if (!memberResult.IsSuccess) {
|
||||
var embed = new EmbedBuilder().WithSmallTitle(Messages.UserNotFoundShort, currentUser)
|
||||
.WithColour(ColorsList.Red).Build();
|
||||
|
||||
if (!embed.IsDefined(out var alreadyBuilt))
|
||||
return Result.FromError(embed);
|
||||
|
||||
return (Result)await _feedbackService.SendContextualEmbedAsync(alreadyBuilt, ct: CancellationToken);
|
||||
}
|
||||
|
||||
var interactionResult
|
||||
= await _utility.CheckInteractionsAsync(
|
||||
guildId.Value, userId.Value, target.ID, "Unmute", CancellationToken);
|
||||
if (!interactionResult.IsSuccess)
|
||||
return Result.FromError(interactionResult);
|
||||
|
||||
// Needed to get the tag and avatar
|
||||
var userResult = await _userApi.GetUserAsync(userId.Value, CancellationToken);
|
||||
if (!userResult.IsDefined(out var user))
|
||||
return Result.FromError(userResult);
|
||||
|
||||
var unmuteResult = await _guildApi.ModifyGuildMemberAsync(
|
||||
guildId.Value, target.ID, $"({user.GetTag()}) {reason}".EncodeHeader(),
|
||||
communicationDisabledUntil: null, ct: CancellationToken);
|
||||
if (!unmuteResult.IsSuccess)
|
||||
return Result.FromError(unmuteResult.Error);
|
||||
|
||||
var responseEmbed = new EmbedBuilder().WithSmallTitle(
|
||||
string.Format(Messages.UserUnmuted, target.GetTag()), target)
|
||||
.WithColour(ColorsList.Green).Build();
|
||||
|
||||
if ((cfg.PublicFeedbackChannel is not 0 && cfg.PublicFeedbackChannel != channelId.Value)
|
||||
|| (cfg.PrivateFeedbackChannel is not 0 && cfg.PrivateFeedbackChannel != channelId.Value)) {
|
||||
var logEmbed = new EmbedBuilder().WithSmallTitle(
|
||||
string.Format(Messages.UserUnmuted, target.GetTag()), target)
|
||||
.WithDescription(string.Format(Messages.DescriptionActionReason, reason))
|
||||
.WithActionFooter(user)
|
||||
.WithCurrentTimestamp()
|
||||
.WithColour(ColorsList.Green)
|
||||
.Build();
|
||||
|
||||
if (!logEmbed.IsDefined(out var logBuilt))
|
||||
return Result.FromError(logEmbed);
|
||||
|
||||
var builtArray = new[] { logBuilt };
|
||||
|
||||
// Not awaiting to reduce response time
|
||||
if (cfg.PublicFeedbackChannel != channelId.Value)
|
||||
_ = _channelApi.CreateMessageAsync(
|
||||
cfg.PublicFeedbackChannel.ToDiscordSnowflake(), embeds: builtArray,
|
||||
ct: CancellationToken);
|
||||
if (cfg.PrivateFeedbackChannel != cfg.PublicFeedbackChannel
|
||||
&& cfg.PrivateFeedbackChannel != channelId.Value)
|
||||
_ = _channelApi.CreateMessageAsync(
|
||||
cfg.PrivateFeedbackChannel.ToDiscordSnowflake(), embeds: builtArray,
|
||||
ct: CancellationToken);
|
||||
}
|
||||
|
||||
if (!responseEmbed.IsDefined(out var built))
|
||||
return Result.FromError(responseEmbed);
|
||||
|
||||
return (Result)await _feedbackService.SendContextualEmbedAsync(built, ct: CancellationToken);
|
||||
}
|
||||
}
|
79
src/Commands/PingCommandGroup.cs
Normal file
79
src/Commands/PingCommandGroup.cs
Normal file
|
@ -0,0 +1,79 @@
|
|||
using System.ComponentModel;
|
||||
using Boyfriend.Services;
|
||||
using Remora.Commands.Attributes;
|
||||
using Remora.Commands.Groups;
|
||||
using Remora.Discord.API.Abstractions.Rest;
|
||||
using Remora.Discord.Commands.Contexts;
|
||||
using Remora.Discord.Commands.Feedback.Services;
|
||||
using Remora.Discord.Extensions.Embeds;
|
||||
using Remora.Discord.Gateway;
|
||||
using Remora.Results;
|
||||
|
||||
// ReSharper disable ClassNeverInstantiated.Global
|
||||
// ReSharper disable UnusedMember.Global
|
||||
|
||||
namespace Boyfriend.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to get the time taken for the gateway to respond to the last heartbeat: /ping
|
||||
/// </summary>
|
||||
public class PingCommandGroup : CommandGroup {
|
||||
private readonly IDiscordRestChannelAPI _channelApi;
|
||||
private readonly DiscordGatewayClient _client;
|
||||
private readonly ICommandContext _context;
|
||||
private readonly GuildDataService _dataService;
|
||||
private readonly FeedbackService _feedbackService;
|
||||
private readonly IDiscordRestUserAPI _userApi;
|
||||
|
||||
public PingCommandGroup(
|
||||
IDiscordRestChannelAPI channelApi, ICommandContext context, DiscordGatewayClient client,
|
||||
GuildDataService dataService, FeedbackService feedbackService, IDiscordRestUserAPI userApi) {
|
||||
_channelApi = channelApi;
|
||||
_context = context;
|
||||
_client = client;
|
||||
_dataService = dataService;
|
||||
_feedbackService = feedbackService;
|
||||
_userApi = userApi;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A slash command that shows time taken for the gateway to respond to the last heartbeat.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A feedback sending result which may or may not have succeeded.
|
||||
/// </returns>
|
||||
[Command("ping", "пинг")]
|
||||
[Description("Get bot latency")]
|
||||
public async Task<Result> SendPingAsync() {
|
||||
if (!_context.TryGetContextIDs(out var guildId, out var channelId, out _))
|
||||
return Result.FromError(
|
||||
new ArgumentNullError(nameof(_context), "Unable to retrieve necessary IDs from command context"));
|
||||
|
||||
var currentUserResult = await _userApi.GetCurrentUserAsync(CancellationToken);
|
||||
if (!currentUserResult.IsDefined(out var currentUser))
|
||||
return Result.FromError(currentUserResult);
|
||||
|
||||
var cfg = await _dataService.GetConfiguration(guildId.Value, CancellationToken);
|
||||
Messages.Culture = cfg.GetCulture();
|
||||
|
||||
var latency = _client.Latency.TotalMilliseconds;
|
||||
if (latency is 0) {
|
||||
// No heartbeat has occurred, estimate latency from local time and "Boyfriend is thinking..." message
|
||||
var lastMessageResult = await _channelApi.GetChannelMessagesAsync(
|
||||
channelId.Value, limit: 1, ct: CancellationToken);
|
||||
if (!lastMessageResult.IsDefined(out var lastMessage))
|
||||
return Result.FromError(lastMessageResult);
|
||||
latency = DateTimeOffset.UtcNow.Subtract(lastMessage.Single().Timestamp).TotalMilliseconds;
|
||||
}
|
||||
|
||||
var embed = new EmbedBuilder().WithSmallTitle(currentUser.GetTag(), currentUser)
|
||||
.WithTitle($"Beep{Random.Shared.Next(1, 4)}".Localized())
|
||||
.WithDescription($"{latency:F0}{Messages.Milliseconds}")
|
||||
.WithColour(latency < 250 ? ColorsList.Green : latency < 500 ? ColorsList.Yellow : ColorsList.Red)
|
||||
.WithCurrentTimestamp()
|
||||
.Build();
|
||||
if (!embed.IsDefined(out var built)) return Result.FromError(embed);
|
||||
|
||||
return (Result)await _feedbackService.SendContextualEmbedAsync(built, ct: CancellationToken);
|
||||
}
|
||||
}
|
75
src/Commands/RemindCommandGroup.cs
Normal file
75
src/Commands/RemindCommandGroup.cs
Normal file
|
@ -0,0 +1,75 @@
|
|||
using System.ComponentModel;
|
||||
using Boyfriend.Data;
|
||||
using Boyfriend.Services;
|
||||
using Remora.Commands.Attributes;
|
||||
using Remora.Commands.Groups;
|
||||
using Remora.Discord.API.Abstractions.Rest;
|
||||
using Remora.Discord.Commands.Contexts;
|
||||
using Remora.Discord.Commands.Feedback.Services;
|
||||
using Remora.Discord.Extensions.Embeds;
|
||||
using Remora.Discord.Extensions.Formatting;
|
||||
using Remora.Results;
|
||||
|
||||
// ReSharper disable ClassNeverInstantiated.Global
|
||||
// ReSharper disable UnusedMember.Global
|
||||
|
||||
namespace Boyfriend.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to manage reminders: /remind
|
||||
/// </summary>
|
||||
public class RemindCommandGroup : CommandGroup {
|
||||
private readonly ICommandContext _context;
|
||||
private readonly GuildDataService _dataService;
|
||||
private readonly FeedbackService _feedbackService;
|
||||
private readonly IDiscordRestUserAPI _userApi;
|
||||
|
||||
public RemindCommandGroup(
|
||||
ICommandContext context, GuildDataService dataService, FeedbackService feedbackService,
|
||||
IDiscordRestUserAPI userApi) {
|
||||
_context = context;
|
||||
_dataService = dataService;
|
||||
_feedbackService = feedbackService;
|
||||
_userApi = userApi;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A slash command that schedules a reminder with the specified text.
|
||||
/// </summary>
|
||||
/// <param name="in">The period of time which must pass before the reminder will be sent.</param>
|
||||
/// <param name="message">The text of the reminder.</param>
|
||||
/// <returns>A feedback sending result which may or may not have succeeded.</returns>
|
||||
[Command("remind")]
|
||||
[Description("Create a reminder")]
|
||||
public async Task<Result> AddReminderAsync(
|
||||
[Description("After what period of time mention the reminder")]
|
||||
TimeSpan @in,
|
||||
[Description("Reminder message")] string message) {
|
||||
if (!_context.TryGetContextIDs(out var guildId, out var channelId, out var userId))
|
||||
return Result.FromError(
|
||||
new ArgumentNullError(nameof(_context), "Unable to retrieve necessary IDs from command context"));
|
||||
|
||||
var userResult = await _userApi.GetUserAsync(userId.Value, CancellationToken);
|
||||
if (!userResult.IsDefined(out var user))
|
||||
return Result.FromError(userResult);
|
||||
|
||||
var remindAt = DateTimeOffset.UtcNow.Add(@in);
|
||||
|
||||
(await _dataService.GetMemberData(guildId.Value, userId.Value, CancellationToken)).Reminders.Add(
|
||||
new Reminder {
|
||||
RemindAt = remindAt,
|
||||
Channel = channelId.Value,
|
||||
Text = message
|
||||
});
|
||||
|
||||
var embed = new EmbedBuilder().WithSmallTitle(string.Format(Messages.ReminderCreated, user.GetTag()), user)
|
||||
.WithDescription(string.Format(Messages.DescriptionReminderCreated, Markdown.Timestamp(remindAt)))
|
||||
.WithColour(ColorsList.Green)
|
||||
.Build();
|
||||
|
||||
if (!embed.IsDefined(out var built))
|
||||
return Result.FromError(embed);
|
||||
|
||||
return (Result)await _feedbackService.SendContextualEmbedAsync(built, ct: CancellationToken);
|
||||
}
|
||||
}
|
154
src/Commands/SettingsCommandGroup.cs
Normal file
154
src/Commands/SettingsCommandGroup.cs
Normal file
|
@ -0,0 +1,154 @@
|
|||
using System.ComponentModel;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using Boyfriend.Data;
|
||||
using Boyfriend.Services;
|
||||
using Remora.Commands.Attributes;
|
||||
using Remora.Commands.Groups;
|
||||
using Remora.Discord.API.Abstractions.Rest;
|
||||
using Remora.Discord.Commands.Contexts;
|
||||
using Remora.Discord.Commands.Feedback.Services;
|
||||
using Remora.Discord.Extensions.Embeds;
|
||||
using Remora.Discord.Extensions.Formatting;
|
||||
using Remora.Results;
|
||||
|
||||
// ReSharper disable ClassNeverInstantiated.Global
|
||||
// ReSharper disable UnusedMember.Global
|
||||
|
||||
namespace Boyfriend.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// Handles the commands to list and modify per-guild settings: /settings and /settings list.
|
||||
/// </summary>
|
||||
public class SettingsCommandGroup : CommandGroup {
|
||||
private readonly ICommandContext _context;
|
||||
private readonly GuildDataService _dataService;
|
||||
private readonly FeedbackService _feedbackService;
|
||||
private readonly IDiscordRestUserAPI _userApi;
|
||||
|
||||
public SettingsCommandGroup(
|
||||
ICommandContext context, GuildDataService dataService,
|
||||
FeedbackService feedbackService, IDiscordRestUserAPI userApi) {
|
||||
_context = context;
|
||||
_dataService = dataService;
|
||||
_feedbackService = feedbackService;
|
||||
_userApi = userApi;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A slash command that lists current per-guild settings.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A feedback sending result which may or may not have succeeded.
|
||||
/// </returns>
|
||||
[Command("settingslist")]
|
||||
[Description("Shows settings list for this server")]
|
||||
public async Task<Result> ListSettingsAsync() {
|
||||
if (!_context.TryGetContextIDs(out var guildId, out _, out _))
|
||||
return Result.FromError(
|
||||
new ArgumentNullError(nameof(_context), "Unable to retrieve necessary IDs from command context"));
|
||||
|
||||
var currentUserResult = await _userApi.GetCurrentUserAsync(CancellationToken);
|
||||
if (!currentUserResult.IsDefined(out var currentUser))
|
||||
return Result.FromError(currentUserResult);
|
||||
|
||||
var cfg = await _dataService.GetConfiguration(guildId.Value, CancellationToken);
|
||||
Messages.Culture = cfg.GetCulture();
|
||||
|
||||
var builder = new StringBuilder();
|
||||
|
||||
foreach (var setting in typeof(GuildConfiguration).GetProperties()) {
|
||||
builder.Append(Markdown.InlineCode(setting.Name))
|
||||
.Append(": ");
|
||||
var something = setting.GetValue(cfg);
|
||||
if (something!.GetType() == typeof(List<GuildConfiguration.NotificationReceiver>)) {
|
||||
var list = (something as List<GuildConfiguration.NotificationReceiver>);
|
||||
builder.AppendLine(string.Join(", ", list!.Select(v => Markdown.InlineCode(v.ToString()))));
|
||||
} else { builder.AppendLine(Markdown.InlineCode(something.ToString()!)); }
|
||||
}
|
||||
|
||||
var embed = new EmbedBuilder().WithSmallTitle(Messages.SettingsListTitle, currentUser)
|
||||
.WithDescription(builder.ToString())
|
||||
.WithColour(ColorsList.Default)
|
||||
.Build();
|
||||
if (!embed.IsDefined(out var built)) return Result.FromError(embed);
|
||||
|
||||
return (Result)await _feedbackService.SendContextualEmbedAsync(built, ct: CancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A slash command that modifies per-guild settings.
|
||||
/// </summary>
|
||||
/// <param name="setting">The setting to modify.</param>
|
||||
/// <param name="value">The new value of the setting.</param>
|
||||
/// <returns>A feedback sending result which may or may not have succeeded.</returns>
|
||||
[Command("settings")]
|
||||
[Description("Change settings for this server")]
|
||||
public async Task<Result> EditSettingsAsync(
|
||||
[Description("The setting whose value you want to change")]
|
||||
string setting,
|
||||
[Description("Setting value")] string value) {
|
||||
if (!_context.TryGetContextIDs(out var guildId, out _, out _))
|
||||
return Result.FromError(
|
||||
new ArgumentNullError(nameof(_context), "Unable to retrieve necessary IDs from command context"));
|
||||
|
||||
var currentUserResult = await _userApi.GetCurrentUserAsync(CancellationToken);
|
||||
if (!currentUserResult.IsDefined(out var currentUser))
|
||||
return Result.FromError(currentUserResult);
|
||||
|
||||
var cfg = await _dataService.GetConfiguration(guildId.Value, CancellationToken);
|
||||
Messages.Culture = cfg.GetCulture();
|
||||
|
||||
PropertyInfo? property = null;
|
||||
|
||||
try {
|
||||
foreach (var prop in typeof(GuildConfiguration).GetProperties())
|
||||
if (string.Equals(setting, prop.Name, StringComparison.CurrentCultureIgnoreCase))
|
||||
property = prop;
|
||||
if (property == null || !property.CanWrite)
|
||||
throw new ApplicationException(Messages.SettingDoesntExist);
|
||||
var type = property.PropertyType;
|
||||
|
||||
if (value is "reset" or "default") { property.SetValue(cfg, null); } else if (type == typeof(string)) {
|
||||
if (setting == "language" && value is not ("ru" or "en" or "mctaylors-ru"))
|
||||
throw new ApplicationException(Messages.LanguageNotSupported);
|
||||
property.SetValue(cfg, value);
|
||||
} else {
|
||||
try {
|
||||
if (type == typeof(bool))
|
||||
property.SetValue(cfg, Convert.ToBoolean(value));
|
||||
|
||||
if (type == typeof(ulong)) {
|
||||
var id = Convert.ToUInt64(value);
|
||||
|
||||
property.SetValue(cfg, id);
|
||||
}
|
||||
} catch (Exception e) when (e is FormatException or OverflowException) {
|
||||
throw new ApplicationException(Messages.InvalidSettingValue);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
var failedEmbed = new EmbedBuilder().WithSmallTitle(Messages.SettingNotChanged, currentUser)
|
||||
.WithDescription(e.Message)
|
||||
.WithColour(ColorsList.Red)
|
||||
.Build();
|
||||
if (!failedEmbed.IsDefined(out var failedBuilt)) return Result.FromError(failedEmbed);
|
||||
|
||||
return (Result)await _feedbackService.SendContextualEmbedAsync(failedBuilt, ct: CancellationToken);
|
||||
}
|
||||
|
||||
var builder = new StringBuilder();
|
||||
|
||||
builder.Append(Markdown.InlineCode(setting))
|
||||
.Append($" {Messages.SettingIsNow} ")
|
||||
.Append(Markdown.InlineCode(value));
|
||||
|
||||
var embed = new EmbedBuilder().WithSmallTitle(Messages.SettingSuccessfullyChanged, currentUser)
|
||||
.WithDescription(builder.ToString())
|
||||
.WithColour(ColorsList.Green)
|
||||
.Build();
|
||||
if (!embed.IsDefined(out var built)) return Result.FromError(embed);
|
||||
|
||||
return (Result)await _feedbackService.SendContextualEmbedAsync(built, ct: CancellationToken);
|
||||
}
|
||||
}
|
90
src/Data/GuildConfiguration.cs
Normal file
90
src/Data/GuildConfiguration.cs
Normal file
|
@ -0,0 +1,90 @@
|
|||
using System.Globalization;
|
||||
using Remora.Discord.API.Abstractions.Objects;
|
||||
|
||||
namespace Boyfriend.Data;
|
||||
|
||||
/// <summary>
|
||||
/// Stores per-guild settings that can be set by a member
|
||||
/// with <see cref="DiscordPermission.ManageGuild" /> using the /settings command
|
||||
/// </summary>
|
||||
public class GuildConfiguration {
|
||||
/// <summary>
|
||||
/// Represents a scheduled event notification receiver.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Used to selectively mention guild members when a scheduled event has started or is about to start.
|
||||
/// </remarks>
|
||||
public enum NotificationReceiver {
|
||||
Interested,
|
||||
Role
|
||||
}
|
||||
|
||||
public static readonly Dictionary<string, CultureInfo> CultureInfoCache = new() {
|
||||
{ "en", new CultureInfo("en-US") },
|
||||
{ "ru", new CultureInfo("ru-RU") },
|
||||
{ "mctaylors-ru", new CultureInfo("tt-RU") }
|
||||
};
|
||||
|
||||
public string Language { get; set; } = "en";
|
||||
|
||||
/// <summary>
|
||||
/// Controls what message should be sent in <see cref="PublicFeedbackChannel" /> when a new member joins the server.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <list type="bullet">
|
||||
/// <item>No message will be sent if set to "off", "disable" or "disabled".</item>
|
||||
/// <item><see cref="Messages.DefaultWelcomeMessage" /> will be sent if set to "default" or "reset"</item>
|
||||
/// </list>
|
||||
/// </remarks>
|
||||
/// <seealso cref="GuildMemberAddResponder" />
|
||||
public string WelcomeMessage { get; set; } = "default";
|
||||
|
||||
/// <summary>
|
||||
/// Controls whether or not the <see cref="Messages.Ready" /> message should be sent
|
||||
/// in <see cref="PrivateFeedbackChannel" /> on startup.
|
||||
/// </summary>
|
||||
/// <seealso cref="GuildCreateResponder" />
|
||||
public bool ReceiveStartupMessages { get; set; }
|
||||
|
||||
public bool RemoveRolesOnMute { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Controls whether or not a guild member's roles are returned if he/she leaves and then joins back.
|
||||
/// </summary>
|
||||
/// <remarks>Roles will not be returned if the member left the guild because of /ban or /kick.</remarks>
|
||||
public bool ReturnRolesOnRejoin { get; set; }
|
||||
|
||||
public bool AutoStartEvents { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Controls what channel should all public messages be sent to.
|
||||
/// </summary>
|
||||
public ulong PublicFeedbackChannel { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Controls what channel should all private, moderator-only messages be sent to.
|
||||
/// </summary>
|
||||
public ulong PrivateFeedbackChannel { get; set; }
|
||||
|
||||
public ulong EventNotificationChannel { get; set; }
|
||||
public ulong DefaultRole { get; set; }
|
||||
public ulong MuteRole { get; set; }
|
||||
public ulong EventNotificationRole { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Controls what guild members should be mentioned when a scheduled event has started or is about to start.
|
||||
/// </summary>
|
||||
/// <seealso cref="NotificationReceiver" />
|
||||
public List<NotificationReceiver> EventStartedReceivers { get; set; }
|
||||
= new() { NotificationReceiver.Interested, NotificationReceiver.Role };
|
||||
|
||||
/// <summary>
|
||||
/// Controls the amount of time before a scheduled event to send a reminder in <see cref="EventNotificationChannel" />.
|
||||
/// </summary>
|
||||
public TimeSpan EventEarlyNotificationOffset { get; set; } = TimeSpan.Zero;
|
||||
|
||||
// Do not convert this to a property, else serialization will be attempted
|
||||
public CultureInfo GetCulture() {
|
||||
return CultureInfoCache[Language];
|
||||
}
|
||||
}
|
41
src/Data/GuildData.cs
Normal file
41
src/Data/GuildData.cs
Normal file
|
@ -0,0 +1,41 @@
|
|||
using System.Globalization;
|
||||
using Remora.Rest.Core;
|
||||
|
||||
namespace Boyfriend.Data;
|
||||
|
||||
/// <summary>
|
||||
/// Stores information about a guild. This information is not accessible via the Discord API.
|
||||
/// </summary>
|
||||
/// <remarks>This information is stored on disk as a JSON file.</remarks>
|
||||
public class GuildData {
|
||||
public readonly GuildConfiguration Configuration;
|
||||
public readonly string ConfigurationPath;
|
||||
|
||||
public readonly Dictionary<ulong, MemberData> MemberData;
|
||||
public readonly string MemberDataPath;
|
||||
|
||||
public readonly Dictionary<ulong, ScheduledEventData> ScheduledEvents;
|
||||
public readonly string ScheduledEventsPath;
|
||||
|
||||
public GuildData(
|
||||
GuildConfiguration configuration, string configurationPath,
|
||||
Dictionary<ulong, ScheduledEventData> scheduledEvents, string scheduledEventsPath,
|
||||
Dictionary<ulong, MemberData> memberData, string memberDataPath) {
|
||||
Configuration = configuration;
|
||||
ConfigurationPath = configurationPath;
|
||||
ScheduledEvents = scheduledEvents;
|
||||
ScheduledEventsPath = scheduledEventsPath;
|
||||
MemberData = memberData;
|
||||
MemberDataPath = memberDataPath;
|
||||
}
|
||||
|
||||
public CultureInfo Culture => Configuration.GetCulture();
|
||||
|
||||
public MemberData GetMemberData(Snowflake userId) {
|
||||
if (MemberData.TryGetValue(userId.Value, out var existing)) return existing;
|
||||
|
||||
var newData = new MemberData(userId.Value, null);
|
||||
MemberData.Add(userId.Value, newData);
|
||||
return newData;
|
||||
}
|
||||
}
|
18
src/Data/MemberData.cs
Normal file
18
src/Data/MemberData.cs
Normal file
|
@ -0,0 +1,18 @@
|
|||
using Remora.Rest.Core;
|
||||
|
||||
namespace Boyfriend.Data;
|
||||
|
||||
/// <summary>
|
||||
/// Stores information about a member
|
||||
/// </summary>
|
||||
public class MemberData {
|
||||
public MemberData(ulong id, DateTimeOffset? bannedUntil) {
|
||||
Id = id;
|
||||
BannedUntil = bannedUntil;
|
||||
}
|
||||
|
||||
public ulong Id { get; }
|
||||
public DateTimeOffset? BannedUntil { get; set; }
|
||||
public List<Snowflake> Roles { get; set; } = new();
|
||||
public List<Reminder> Reminders { get; } = new();
|
||||
}
|
9
src/Data/Reminder.cs
Normal file
9
src/Data/Reminder.cs
Normal file
|
@ -0,0 +1,9 @@
|
|||
using Remora.Rest.Core;
|
||||
|
||||
namespace Boyfriend.Data;
|
||||
|
||||
public struct Reminder {
|
||||
public DateTimeOffset RemindAt;
|
||||
public string Text;
|
||||
public Snowflake Channel;
|
||||
}
|
17
src/Data/ScheduledEventData.cs
Normal file
17
src/Data/ScheduledEventData.cs
Normal file
|
@ -0,0 +1,17 @@
|
|||
using Remora.Discord.API.Abstractions.Objects;
|
||||
|
||||
namespace Boyfriend.Data;
|
||||
|
||||
/// <summary>
|
||||
/// Stores information about scheduled events. This information is not provided by the Discord API.
|
||||
/// </summary>
|
||||
/// <remarks>This information is stored on disk as a JSON file.</remarks>
|
||||
public class ScheduledEventData {
|
||||
public ScheduledEventData(GuildScheduledEventStatus status) {
|
||||
Status = status;
|
||||
}
|
||||
|
||||
public bool EarlyNotificationSent { get; set; }
|
||||
public DateTimeOffset? ActualStartTime { get; set; }
|
||||
public GuildScheduledEventStatus Status { get; set; }
|
||||
}
|
335
src/EventResponders.cs
Normal file
335
src/EventResponders.cs
Normal file
|
@ -0,0 +1,335 @@
|
|||
using Boyfriend.Data;
|
||||
using Boyfriend.Services;
|
||||
using DiffPlex.DiffBuilder;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Remora.Discord.API.Abstractions.Gateway.Events;
|
||||
using Remora.Discord.API.Abstractions.Objects;
|
||||
using Remora.Discord.API.Abstractions.Rest;
|
||||
using Remora.Discord.Caching;
|
||||
using Remora.Discord.Caching.Services;
|
||||
using Remora.Discord.Extensions.Embeds;
|
||||
using Remora.Discord.Extensions.Formatting;
|
||||
using Remora.Discord.Gateway.Responders;
|
||||
using Remora.Rest.Core;
|
||||
using Remora.Results;
|
||||
|
||||
// ReSharper disable UnusedType.Global
|
||||
|
||||
namespace Boyfriend;
|
||||
|
||||
/// <summary>
|
||||
/// Handles sending a <see cref="Messages.Ready" /> message to a guild that has just initialized if that guild
|
||||
/// has <see cref="GuildConfiguration.ReceiveStartupMessages" /> enabled
|
||||
/// </summary>
|
||||
public class GuildCreateResponder : IResponder<IGuildCreate> {
|
||||
private readonly IDiscordRestChannelAPI _channelApi;
|
||||
private readonly GuildDataService _dataService;
|
||||
private readonly ILogger<GuildCreateResponder> _logger;
|
||||
private readonly IDiscordRestUserAPI _userApi;
|
||||
|
||||
public GuildCreateResponder(
|
||||
IDiscordRestChannelAPI channelApi, GuildDataService dataService, ILogger<GuildCreateResponder> logger,
|
||||
IDiscordRestUserAPI userApi) {
|
||||
_channelApi = channelApi;
|
||||
_dataService = dataService;
|
||||
_logger = logger;
|
||||
_userApi = userApi;
|
||||
}
|
||||
|
||||
public async Task<Result> RespondAsync(IGuildCreate gatewayEvent, CancellationToken ct = default) {
|
||||
if (!gatewayEvent.Guild.IsT0) return Result.FromSuccess(); // Guild isn't IAvailableGuild
|
||||
|
||||
var guild = gatewayEvent.Guild.AsT0;
|
||||
_logger.LogInformation("Joined guild \"{Name}\"", guild.Name);
|
||||
|
||||
var guildConfig = await _dataService.GetConfiguration(guild.ID, ct);
|
||||
if (!guildConfig.ReceiveStartupMessages)
|
||||
return Result.FromSuccess();
|
||||
if (guildConfig.PrivateFeedbackChannel is 0)
|
||||
return Result.FromSuccess();
|
||||
|
||||
var currentUserResult = await _userApi.GetCurrentUserAsync(ct);
|
||||
if (!currentUserResult.IsDefined(out var currentUser)) return Result.FromError(currentUserResult);
|
||||
|
||||
Messages.Culture = guildConfig.GetCulture();
|
||||
var i = Random.Shared.Next(1, 4);
|
||||
|
||||
var embed = new EmbedBuilder().WithSmallTitle(currentUser.GetTag(), currentUser)
|
||||
.WithTitle($"Beep{i}".Localized())
|
||||
.WithDescription(Messages.Ready)
|
||||
.WithCurrentTimestamp()
|
||||
.WithColour(ColorsList.Blue)
|
||||
.Build();
|
||||
if (!embed.IsDefined(out var built)) return Result.FromError(embed);
|
||||
|
||||
return (Result)await _channelApi.CreateMessageAsync(
|
||||
guildConfig.PrivateFeedbackChannel.ToDiscordSnowflake(), embeds: new[] { built }, ct: ct);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles logging the contents of a deleted message and the user who deleted the message
|
||||
/// to a guild's <see cref="GuildConfiguration.PrivateFeedbackChannel" /> if one is set.
|
||||
/// </summary>
|
||||
public class MessageDeletedResponder : IResponder<IMessageDelete> {
|
||||
private readonly IDiscordRestAuditLogAPI _auditLogApi;
|
||||
private readonly IDiscordRestChannelAPI _channelApi;
|
||||
private readonly GuildDataService _dataService;
|
||||
private readonly IDiscordRestUserAPI _userApi;
|
||||
|
||||
public MessageDeletedResponder(
|
||||
IDiscordRestAuditLogAPI auditLogApi, IDiscordRestChannelAPI channelApi,
|
||||
GuildDataService dataService, IDiscordRestUserAPI userApi) {
|
||||
_auditLogApi = auditLogApi;
|
||||
_channelApi = channelApi;
|
||||
_dataService = dataService;
|
||||
_userApi = userApi;
|
||||
}
|
||||
|
||||
public async Task<Result> RespondAsync(IMessageDelete gatewayEvent, CancellationToken ct = default) {
|
||||
if (!gatewayEvent.GuildID.IsDefined(out var guildId)) return Result.FromSuccess();
|
||||
|
||||
var guildConfiguration = await _dataService.GetConfiguration(guildId, ct);
|
||||
if (guildConfiguration.PrivateFeedbackChannel is 0) return Result.FromSuccess();
|
||||
|
||||
var messageResult = await _channelApi.GetChannelMessageAsync(gatewayEvent.ChannelID, gatewayEvent.ID, ct);
|
||||
if (!messageResult.IsDefined(out var message)) return Result.FromError(messageResult);
|
||||
if (string.IsNullOrWhiteSpace(message.Content)) return Result.FromSuccess();
|
||||
|
||||
var auditLogResult = await _auditLogApi.GetGuildAuditLogAsync(
|
||||
guildId, actionType: AuditLogEvent.MessageDelete, limit: 1, ct: ct);
|
||||
if (!auditLogResult.IsDefined(out var auditLogPage)) return Result.FromError(auditLogResult);
|
||||
|
||||
var auditLog = auditLogPage.AuditLogEntries.Single();
|
||||
if (!auditLog.Options.IsDefined(out var options))
|
||||
return Result.FromError(new ArgumentNullError(nameof(auditLog.Options)));
|
||||
|
||||
var user = message.Author;
|
||||
if (options.ChannelID == gatewayEvent.ChannelID
|
||||
&& DateTimeOffset.UtcNow.Subtract(auditLog.ID.Timestamp).TotalSeconds <= 2) {
|
||||
var userResult = await _userApi.GetUserAsync(auditLog.UserID!.Value, ct);
|
||||
if (!userResult.IsDefined(out user)) return Result.FromError(userResult);
|
||||
}
|
||||
|
||||
Messages.Culture = guildConfiguration.GetCulture();
|
||||
|
||||
var embed = new EmbedBuilder()
|
||||
.WithSmallTitle(
|
||||
string.Format(
|
||||
Messages.CachedMessageDeleted,
|
||||
message.Author.GetTag()), message.Author)
|
||||
.WithDescription(
|
||||
$"{Mention.Channel(gatewayEvent.ChannelID)}\n{message.Content.InBlockCode()}")
|
||||
.WithActionFooter(user)
|
||||
.WithTimestamp(message.Timestamp)
|
||||
.WithColour(ColorsList.Red)
|
||||
.Build();
|
||||
if (!embed.IsDefined(out var built)) return Result.FromError(embed);
|
||||
|
||||
return (Result)await _channelApi.CreateMessageAsync(
|
||||
guildConfiguration.PrivateFeedbackChannel.ToDiscordSnowflake(), embeds: new[] { built },
|
||||
allowedMentions: Boyfriend.NoMentions, ct: ct);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles logging the difference between an edited message's old and new content
|
||||
/// to a guild's <see cref="GuildConfiguration.PrivateFeedbackChannel" /> if one is set.
|
||||
/// </summary>
|
||||
public class MessageEditedResponder : IResponder<IMessageUpdate> {
|
||||
private readonly CacheService _cacheService;
|
||||
private readonly IDiscordRestChannelAPI _channelApi;
|
||||
private readonly GuildDataService _dataService;
|
||||
private readonly IDiscordRestUserAPI _userApi;
|
||||
|
||||
public MessageEditedResponder(
|
||||
CacheService cacheService, IDiscordRestChannelAPI channelApi, GuildDataService dataService,
|
||||
IDiscordRestUserAPI userApi) {
|
||||
_cacheService = cacheService;
|
||||
_channelApi = channelApi;
|
||||
_dataService = dataService;
|
||||
_userApi = userApi;
|
||||
}
|
||||
|
||||
public async Task<Result> RespondAsync(IMessageUpdate gatewayEvent, CancellationToken ct = default) {
|
||||
if (!gatewayEvent.GuildID.IsDefined(out var guildId))
|
||||
return Result.FromSuccess();
|
||||
var guildConfiguration = await _dataService.GetConfiguration(guildId, ct);
|
||||
if (guildConfiguration.PrivateFeedbackChannel is 0)
|
||||
return Result.FromSuccess();
|
||||
if (!gatewayEvent.Content.IsDefined(out var newContent))
|
||||
return Result.FromSuccess();
|
||||
if (!gatewayEvent.EditedTimestamp.IsDefined(out var timestamp))
|
||||
return Result.FromSuccess(); // The message wasn't actually edited
|
||||
|
||||
if (!gatewayEvent.ChannelID.IsDefined(out var channelId))
|
||||
return Result.FromError(new ArgumentNullError(nameof(gatewayEvent.ChannelID)));
|
||||
if (!gatewayEvent.ID.IsDefined(out var messageId))
|
||||
return Result.FromError(new ArgumentNullError(nameof(gatewayEvent.ID)));
|
||||
|
||||
var cacheKey = new KeyHelpers.MessageCacheKey(channelId, messageId);
|
||||
var messageResult = await _cacheService.TryGetValueAsync<IMessage>(
|
||||
cacheKey, ct);
|
||||
if (!messageResult.IsDefined(out var message)) return Result.FromError(messageResult);
|
||||
if (message.Content == newContent) return Result.FromSuccess();
|
||||
|
||||
// Custom event responders are called earlier than responders responsible for message caching
|
||||
// This means that subsequent edit logs may contain the wrong content
|
||||
// We can work around this by evicting the message from the cache
|
||||
await _cacheService.EvictAsync<IMessage>(cacheKey, ct);
|
||||
// However, since we evicted the message, subsequent edits won't have a cached instance to work with
|
||||
// Getting the message will put it back in the cache, resolving all issues
|
||||
// We don't need to await this since the result is not needed
|
||||
// NOTE: Because this is not awaited, there may be a race condition depending on how fast clients are able to edit their messages
|
||||
// NOTE: Awaiting this might not even solve this if the same responder is called asynchronously
|
||||
_ = _channelApi.GetChannelMessageAsync(channelId, messageId, ct);
|
||||
|
||||
var currentUserResult = await _userApi.GetCurrentUserAsync(ct);
|
||||
if (!currentUserResult.IsDefined(out var currentUser)) return Result.FromError(currentUserResult);
|
||||
|
||||
var diff = InlineDiffBuilder.Diff(message.Content, newContent);
|
||||
|
||||
Messages.Culture = guildConfiguration.GetCulture();
|
||||
|
||||
var embed = new EmbedBuilder()
|
||||
.WithSmallTitle(string.Format(Messages.CachedMessageEdited, message.Author.GetTag()), message.Author)
|
||||
.WithDescription($"https://discord.com/channels/{guildId}/{channelId}/{messageId}\n{diff.AsMarkdown()}")
|
||||
.WithUserFooter(currentUser)
|
||||
.WithTimestamp(timestamp.Value)
|
||||
.WithColour(ColorsList.Yellow)
|
||||
.Build();
|
||||
if (!embed.IsDefined(out var built)) return Result.FromError(embed);
|
||||
|
||||
return (Result)await _channelApi.CreateMessageAsync(
|
||||
guildConfiguration.PrivateFeedbackChannel.ToDiscordSnowflake(), embeds: new[] { built },
|
||||
allowedMentions: Boyfriend.NoMentions, ct: ct);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles sending a guild's <see cref="GuildConfiguration.WelcomeMessage" /> if one is set.
|
||||
/// If <see cref="GuildConfiguration.ReturnRolesOnRejoin"/> is enabled, roles will be returned.
|
||||
/// </summary>
|
||||
/// <seealso cref="GuildConfiguration.WelcomeMessage" />
|
||||
public class GuildMemberAddResponder : IResponder<IGuildMemberAdd> {
|
||||
private readonly IDiscordRestChannelAPI _channelApi;
|
||||
private readonly GuildDataService _dataService;
|
||||
private readonly IDiscordRestGuildAPI _guildApi;
|
||||
|
||||
public GuildMemberAddResponder(
|
||||
IDiscordRestChannelAPI channelApi, GuildDataService dataService, IDiscordRestGuildAPI guildApi) {
|
||||
_channelApi = channelApi;
|
||||
_dataService = dataService;
|
||||
_guildApi = guildApi;
|
||||
}
|
||||
|
||||
public async Task<Result> RespondAsync(IGuildMemberAdd gatewayEvent, CancellationToken ct = default) {
|
||||
if (!gatewayEvent.User.IsDefined(out var user))
|
||||
return Result.FromError(new ArgumentNullError(nameof(gatewayEvent.User)));
|
||||
var data = await _dataService.GetData(gatewayEvent.GuildID, ct);
|
||||
var cfg = data.Configuration;
|
||||
if (cfg.PublicFeedbackChannel is 0 || cfg.WelcomeMessage is "off" or "disable" or "disabled")
|
||||
return Result.FromSuccess();
|
||||
if (cfg.ReturnRolesOnRejoin) {
|
||||
var result = await _guildApi.ModifyGuildMemberAsync(
|
||||
gatewayEvent.GuildID, user.ID, roles: data.GetMemberData(user.ID).Roles, ct: ct);
|
||||
if (!result.IsSuccess) return Result.FromError(result.Error);
|
||||
}
|
||||
|
||||
Messages.Culture = data.Culture;
|
||||
var welcomeMessage = cfg.WelcomeMessage is "default" or "reset"
|
||||
? Messages.DefaultWelcomeMessage
|
||||
: cfg.WelcomeMessage;
|
||||
|
||||
var guildResult = await _guildApi.GetGuildAsync(gatewayEvent.GuildID, ct: ct);
|
||||
if (!guildResult.IsDefined(out var guild)) return Result.FromError(guildResult);
|
||||
|
||||
var embed = new EmbedBuilder()
|
||||
.WithSmallTitle(string.Format(welcomeMessage, user.GetTag(), guild.Name), user)
|
||||
.WithGuildFooter(guild)
|
||||
.WithTimestamp(gatewayEvent.JoinedAt)
|
||||
.WithColour(ColorsList.Green)
|
||||
.Build();
|
||||
if (!embed.IsDefined(out var built)) return Result.FromError(embed);
|
||||
|
||||
return (Result)await _channelApi.CreateMessageAsync(
|
||||
cfg.PublicFeedbackChannel.ToDiscordSnowflake(), embeds: new[] { built },
|
||||
allowedMentions: Boyfriend.NoMentions, ct: ct);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles sending a notification when a scheduled event has been cancelled
|
||||
/// in a guild's <see cref="GuildConfiguration.EventNotificationChannel" /> if one is set.
|
||||
/// </summary>
|
||||
public class GuildScheduledEventDeleteResponder : IResponder<IGuildScheduledEventDelete> {
|
||||
private readonly IDiscordRestChannelAPI _channelApi;
|
||||
private readonly GuildDataService _dataService;
|
||||
|
||||
public GuildScheduledEventDeleteResponder(IDiscordRestChannelAPI channelApi, GuildDataService dataService) {
|
||||
_channelApi = channelApi;
|
||||
_dataService = dataService;
|
||||
}
|
||||
|
||||
public async Task<Result> RespondAsync(IGuildScheduledEventDelete gatewayEvent, CancellationToken ct = default) {
|
||||
var guildData = await _dataService.GetData(gatewayEvent.GuildID, ct);
|
||||
guildData.ScheduledEvents.Remove(gatewayEvent.ID.Value);
|
||||
|
||||
if (guildData.Configuration.EventNotificationChannel is 0)
|
||||
return Result.FromSuccess();
|
||||
|
||||
var embed = new EmbedBuilder()
|
||||
.WithSmallTitle(string.Format(Messages.EventCancelled, gatewayEvent.Name))
|
||||
.WithDescription(":(")
|
||||
.WithColour(ColorsList.Red)
|
||||
.WithCurrentTimestamp()
|
||||
.Build();
|
||||
|
||||
if (!embed.IsDefined(out var built)) return Result.FromError(embed);
|
||||
|
||||
return (Result)await _channelApi.CreateMessageAsync(
|
||||
guildData.Configuration.EventNotificationChannel.ToDiscordSnowflake(), embeds: new[] { built }, ct: ct);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles updating <see cref="MemberData.Roles" /> when a guild member is updated.
|
||||
/// </summary>
|
||||
public class GuildMemberUpdateResponder : IResponder<IGuildMemberUpdate> {
|
||||
private readonly GuildDataService _dataService;
|
||||
|
||||
public GuildMemberUpdateResponder(GuildDataService dataService) {
|
||||
_dataService = dataService;
|
||||
}
|
||||
|
||||
public async Task<Result> RespondAsync(IGuildMemberUpdate gatewayEvent, CancellationToken ct = default) {
|
||||
var memberData = await _dataService.GetMemberData(gatewayEvent.GuildID, gatewayEvent.User.ID, ct);
|
||||
memberData.Roles = gatewayEvent.Roles.ToList();
|
||||
return Result.FromSuccess();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles sending replies to easter egg messages.
|
||||
/// </summary>
|
||||
public class MessageCreateResponder : IResponder<IMessageCreate> {
|
||||
private readonly IDiscordRestChannelAPI _channelApi;
|
||||
|
||||
public MessageCreateResponder(IDiscordRestChannelAPI channelApi) {
|
||||
_channelApi = channelApi;
|
||||
}
|
||||
|
||||
public Task<Result> RespondAsync(IMessageCreate gatewayEvent, CancellationToken ct = default) {
|
||||
_ = _channelApi.CreateMessageAsync(
|
||||
gatewayEvent.ChannelID, ct: ct, content: gatewayEvent.Content switch {
|
||||
"whoami" => "`nobody`",
|
||||
"сука !!" => "`root`",
|
||||
"воооо" => "`removing /...`",
|
||||
"пон" =>
|
||||
"https://cdn.discordapp.com/attachments/837385840946053181/1087236080950055023/vUORS10xPaY-1.jpg",
|
||||
"++++" => "#",
|
||||
_ => default(Optional<string>)
|
||||
});
|
||||
return Task.FromResult(Result.FromSuccess());
|
||||
}
|
||||
}
|
193
src/Extensions.cs
Normal file
193
src/Extensions.cs
Normal file
|
@ -0,0 +1,193 @@
|
|||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using DiffPlex.DiffBuilder.Model;
|
||||
using Remora.Discord.API;
|
||||
using Remora.Discord.API.Abstractions.Objects;
|
||||
using Remora.Discord.API.Objects;
|
||||
using Remora.Discord.Commands.Contexts;
|
||||
using Remora.Discord.Commands.Extensions;
|
||||
using Remora.Discord.Extensions.Embeds;
|
||||
using Remora.Discord.Extensions.Formatting;
|
||||
using Remora.Rest.Core;
|
||||
|
||||
namespace Boyfriend;
|
||||
|
||||
public static class Extensions {
|
||||
/// <summary>
|
||||
/// Adds a footer with the <paramref name="user" />'s avatar and tag (@username or username#0000).
|
||||
/// </summary>
|
||||
/// <param name="builder">The builder to add the footer to.</param>
|
||||
/// <param name="user">The user whose tag and avatar to add.</param>
|
||||
/// <returns>The builder with the added footer.</returns>
|
||||
public static EmbedBuilder WithUserFooter(this EmbedBuilder builder, IUser user) {
|
||||
var avatarUrlResult = CDN.GetUserAvatarUrl(user, imageSize: 256);
|
||||
var avatarUrl = avatarUrlResult.IsSuccess
|
||||
? avatarUrlResult.Entity.AbsoluteUri
|
||||
: CDN.GetDefaultUserAvatarUrl(user, imageSize: 256).Entity.AbsoluteUri;
|
||||
|
||||
return builder.WithFooter(new EmbedFooter(user.GetTag(), avatarUrl));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a footer representing that an action was performed by a <paramref name="user" />.
|
||||
/// </summary>
|
||||
/// <param name="builder">The builder to add the footer to.</param>
|
||||
/// <param name="user">The user that performed the action whose tag and avatar to use.</param>
|
||||
/// <returns>The builder with the added footer.</returns>
|
||||
public static EmbedBuilder WithActionFooter(this EmbedBuilder builder, IUser user) {
|
||||
var avatarUrlResult = CDN.GetUserAvatarUrl(user, imageSize: 256);
|
||||
var avatarUrl = avatarUrlResult.IsSuccess
|
||||
? avatarUrlResult.Entity.AbsoluteUri
|
||||
: CDN.GetDefaultUserAvatarUrl(user, imageSize: 256).Entity.AbsoluteUri;
|
||||
|
||||
return builder.WithFooter(
|
||||
new EmbedFooter($"{Messages.IssuedBy}:\n{user.GetTag()}", avatarUrl));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a title using the author field, making it smaller than using the title field.
|
||||
/// </summary>
|
||||
/// <param name="builder">The builder to add the small title to.</param>
|
||||
/// <param name="text">The text of the small title.</param>
|
||||
/// <param name="avatarSource">The user whose avatar to use in the small title.</param>
|
||||
/// <param name="url">The URL that will be opened if a user clicks on the small title.</param>
|
||||
/// <returns>The builder with the added small title in the author field.</returns>
|
||||
public static EmbedBuilder WithSmallTitle(
|
||||
this EmbedBuilder builder, string text, IUser? avatarSource = null, string? url = default) {
|
||||
Uri? avatarUrl = null;
|
||||
if (avatarSource is not null) {
|
||||
var avatarUrlResult = CDN.GetUserAvatarUrl(avatarSource, imageSize: 256);
|
||||
|
||||
avatarUrl = avatarUrlResult.IsSuccess
|
||||
? avatarUrlResult.Entity
|
||||
: CDN.GetDefaultUserAvatarUrl(avatarSource, imageSize: 256).Entity;
|
||||
}
|
||||
|
||||
builder.Author = new EmbedAuthorBuilder(text, url, avatarUrl?.AbsoluteUri);
|
||||
return builder;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a footer representing that the action was performed in the <paramref name="guild" />.
|
||||
/// </summary>
|
||||
/// <param name="builder">The builder to add the footer to.</param>
|
||||
/// <param name="guild">The guild whose name and icon to use.</param>
|
||||
/// <returns>The builder with the added footer.</returns>
|
||||
public static EmbedBuilder WithGuildFooter(this EmbedBuilder builder, IGuild guild) {
|
||||
var iconUrlResult = CDN.GetGuildIconUrl(guild, imageSize: 256);
|
||||
var iconUrl = iconUrlResult.IsSuccess
|
||||
? iconUrlResult.Entity.AbsoluteUri
|
||||
: default(Optional<string>);
|
||||
|
||||
return builder.WithFooter(new EmbedFooter(guild.Name, iconUrl));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a title representing that the action happened in the <paramref name="guild" />.
|
||||
/// </summary>
|
||||
/// <param name="builder">The builder to add the title to.</param>
|
||||
/// <param name="guild">The guild whose name and icon to use.</param>
|
||||
/// <returns>The builder with the added title.</returns>
|
||||
public static EmbedBuilder WithGuildTitle(this EmbedBuilder builder, IGuild guild) {
|
||||
var iconUrlResult = CDN.GetGuildIconUrl(guild, imageSize: 256);
|
||||
var iconUrl = iconUrlResult.IsSuccess
|
||||
? iconUrlResult.Entity.AbsoluteUri
|
||||
: null;
|
||||
|
||||
builder.Author = new EmbedAuthorBuilder(guild.Name, iconUrl: iconUrl);
|
||||
return builder;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a scheduled event's cover image.
|
||||
/// </summary>
|
||||
/// <param name="builder">The builder to add the image to.</param>
|
||||
/// <param name="eventId">The ID of the scheduled event whose image to use.</param>
|
||||
/// <param name="imageHashOptional">The Optional containing the image hash.</param>
|
||||
/// <returns>The builder with the added cover image.</returns>
|
||||
public static EmbedBuilder WithEventCover(
|
||||
this EmbedBuilder builder, Snowflake eventId, Optional<IImageHash?> imageHashOptional) {
|
||||
if (!imageHashOptional.IsDefined(out var imageHash)) return builder;
|
||||
|
||||
var iconUrlResult = CDN.GetGuildScheduledEventCoverUrl(eventId, imageHash, imageSize: 1024);
|
||||
return iconUrlResult.IsDefined(out var iconUrl) ? builder.WithImageUrl(iconUrl.AbsoluteUri) : builder;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sanitizes a string for use in <see cref="Markdown.BlockCode(string)" /> by inserting zero-width spaces in between
|
||||
/// symbols used to format the string with block code.
|
||||
/// </summary>
|
||||
/// <param name="s">The string to sanitize.</param>
|
||||
/// <returns>The sanitized string that can be safely used in <see cref="Markdown.BlockCode(string)" />.</returns>
|
||||
private static string SanitizeForBlockCode(this string s) {
|
||||
return s.Replace("```", "```");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sanitizes a string (see <see cref="SanitizeForBlockCode" />) and formats the string to use Markdown Block Code formatting with a specified
|
||||
/// language for syntax highlighting.
|
||||
/// </summary>
|
||||
/// <param name="s">The string to sanitize and format.</param>
|
||||
/// <param name="language"></param>
|
||||
/// <returns>The sanitized string formatted to use Markdown Block Code with a specified
|
||||
/// language for syntax highlighting.</returns>
|
||||
public static string InBlockCode(this string s, string language = "") {
|
||||
s = s.SanitizeForBlockCode();
|
||||
return
|
||||
$"```{language}\n{s.SanitizeForBlockCode()}{(s.EndsWith("`") || string.IsNullOrWhiteSpace(s) ? " " : "")}```";
|
||||
}
|
||||
|
||||
public static string Localized(this string key) {
|
||||
return Messages.ResourceManager.GetString(key, Messages.Culture) ?? key;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Encodes a string to allow its transmission in request headers.
|
||||
/// </summary>
|
||||
/// <remarks>Used when encountering "Request headers must contain only ASCII characters".</remarks>
|
||||
/// <param name="s">The string to encode.</param>
|
||||
/// <returns>An encoded string with spaces kept intact.</returns>
|
||||
public static string EncodeHeader(this string s) {
|
||||
return WebUtility.UrlEncode(s).Replace('+', ' ');
|
||||
}
|
||||
|
||||
public static string AsMarkdown(this DiffPaneModel model) {
|
||||
var builder = new StringBuilder();
|
||||
foreach (var line in model.Lines) {
|
||||
if (line.Type is ChangeType.Deleted)
|
||||
builder.Append("-- ");
|
||||
if (line.Type is ChangeType.Inserted)
|
||||
builder.Append("++ ");
|
||||
if (line.Type is not ChangeType.Imaginary)
|
||||
builder.AppendLine(line.Text);
|
||||
}
|
||||
|
||||
return InBlockCode(builder.ToString(), "diff");
|
||||
}
|
||||
|
||||
public static string GetTag(this IUser user) {
|
||||
return user.Discriminator is 0000 ? $"@{user.Username}" : $"{user.Username}#{user.Discriminator:0000}";
|
||||
}
|
||||
|
||||
public static Snowflake ToDiscordSnowflake(this ulong id) {
|
||||
return DiscordSnowflake.New(id);
|
||||
}
|
||||
|
||||
public static TResult? MaxOrDefault<TSource, TResult>(
|
||||
this IEnumerable<TSource> source, Func<TSource, TResult> selector) {
|
||||
var list = source.ToList();
|
||||
return list.Any() ? list.Max(selector) : default;
|
||||
}
|
||||
|
||||
public static bool TryGetContextIDs(
|
||||
this ICommandContext context, [NotNullWhen(true)] out Snowflake? guildId,
|
||||
[NotNullWhen(true)] out Snowflake? channelId, [NotNullWhen(true)] out Snowflake? userId) {
|
||||
guildId = null;
|
||||
channelId = null;
|
||||
userId = null;
|
||||
return context.TryGetGuildID(out guildId)
|
||||
&& context.TryGetChannelID(out channelId)
|
||||
&& context.TryGetUserID(out userId);
|
||||
}
|
||||
}
|
36
src/InteractionResponders.cs
Normal file
36
src/InteractionResponders.cs
Normal file
|
@ -0,0 +1,36 @@
|
|||
using Remora.Discord.API.Abstractions.Objects;
|
||||
using Remora.Discord.Commands.Feedback.Messages;
|
||||
using Remora.Discord.Commands.Feedback.Services;
|
||||
using Remora.Discord.Interactivity;
|
||||
using Remora.Results;
|
||||
|
||||
// ReSharper disable ClassNeverInstantiated.Global
|
||||
// ReSharper disable UnusedMember.Global
|
||||
|
||||
namespace Boyfriend;
|
||||
|
||||
/// <summary>
|
||||
/// Handles responding to various interactions.
|
||||
/// </summary>
|
||||
public class InteractionResponders : InteractionGroup {
|
||||
private readonly FeedbackService _feedbackService;
|
||||
|
||||
public InteractionResponders(FeedbackService feedbackService) {
|
||||
_feedbackService = feedbackService;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A button that will output an ephemeral embed containing the information about a scheduled event.
|
||||
/// </summary>
|
||||
/// <param name="state">The ID of the guild and scheduled event, encoded as "guildId:eventId".</param>
|
||||
/// <returns>An ephemeral feedback sending result which may or may not have succeeded.</returns>
|
||||
[Button("scheduled-event-details")]
|
||||
public async Task<Result> OnStatefulButtonClicked(string? state = null) {
|
||||
if (state is null) return Result.FromError(new ArgumentNullError(nameof(state)));
|
||||
|
||||
var idArray = state.Split(':');
|
||||
return (Result)await _feedbackService.SendContextualAsync(
|
||||
$"https://discord.com/events/{idArray[0]}/{idArray[1]}",
|
||||
options: new FeedbackMessageOptions(MessageFlags: MessageFlags.Ephemeral));
|
||||
}
|
||||
}
|
109
src/Services/GuildDataService.cs
Normal file
109
src/Services/GuildDataService.cs
Normal file
|
@ -0,0 +1,109 @@
|
|||
using System.Collections.Concurrent;
|
||||
using System.Text.Json;
|
||||
using Boyfriend.Data;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Remora.Discord.API.Abstractions.Rest;
|
||||
using Remora.Rest.Core;
|
||||
|
||||
namespace Boyfriend.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Handles saving, loading, initializing and providing <see cref="GuildData" />.
|
||||
/// </summary>
|
||||
public class GuildDataService : IHostedService {
|
||||
private readonly ConcurrentDictionary<Snowflake, GuildData> _datas = new();
|
||||
private readonly IDiscordRestGuildAPI _guildApi;
|
||||
|
||||
// https://github.com/dotnet/aspnetcore/issues/39139
|
||||
public GuildDataService(
|
||||
IHostApplicationLifetime lifetime, IDiscordRestGuildAPI guildApi) {
|
||||
_guildApi = guildApi;
|
||||
lifetime.ApplicationStopping.Register(ApplicationStopping);
|
||||
}
|
||||
|
||||
public Task StartAsync(CancellationToken ct) {
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task StopAsync(CancellationToken ct) {
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private void ApplicationStopping() {
|
||||
SaveAsync(CancellationToken.None).GetAwaiter().GetResult();
|
||||
}
|
||||
|
||||
private async Task SaveAsync(CancellationToken ct) {
|
||||
var tasks = new List<Task>();
|
||||
foreach (var data in _datas.Values) {
|
||||
await using var configStream = File.OpenWrite(data.ConfigurationPath);
|
||||
tasks.Add(JsonSerializer.SerializeAsync(configStream, data.Configuration, cancellationToken: ct));
|
||||
|
||||
await using var eventsStream = File.OpenWrite(data.ScheduledEventsPath);
|
||||
tasks.Add(JsonSerializer.SerializeAsync(eventsStream, data.ScheduledEvents, cancellationToken: ct));
|
||||
|
||||
foreach (var memberData in data.MemberData.Values) {
|
||||
await using var memberDataStream = File.OpenWrite($"{data.MemberDataPath}/{memberData.Id}.json");
|
||||
tasks.Add(JsonSerializer.SerializeAsync(memberDataStream, memberData, cancellationToken: ct));
|
||||
}
|
||||
}
|
||||
|
||||
await Task.WhenAll(tasks);
|
||||
}
|
||||
|
||||
public async Task<GuildData> GetData(Snowflake guildId, CancellationToken ct = default) {
|
||||
return _datas.TryGetValue(guildId, out var data) ? data : await InitializeData(guildId, ct);
|
||||
}
|
||||
|
||||
private async Task<GuildData> InitializeData(Snowflake guildId, CancellationToken ct = default) {
|
||||
var idString = $"{guildId}";
|
||||
var memberDataPath = $"{guildId}/MemberData";
|
||||
var configurationPath = $"{guildId}/Configuration.json";
|
||||
var scheduledEventsPath = $"{guildId}/ScheduledEvents.json";
|
||||
if (!Directory.Exists(idString)) Directory.CreateDirectory(idString);
|
||||
if (!Directory.Exists(memberDataPath)) Directory.CreateDirectory(memberDataPath);
|
||||
if (!File.Exists(configurationPath)) await File.WriteAllTextAsync(configurationPath, "{}", ct);
|
||||
if (!File.Exists(scheduledEventsPath)) await File.WriteAllTextAsync(scheduledEventsPath, "{}", ct);
|
||||
|
||||
await using var configurationStream = File.OpenRead(configurationPath);
|
||||
var configuration
|
||||
= JsonSerializer.DeserializeAsync<GuildConfiguration>(
|
||||
configurationStream, cancellationToken: ct);
|
||||
|
||||
await using var eventsStream = File.OpenRead(scheduledEventsPath);
|
||||
var events
|
||||
= JsonSerializer.DeserializeAsync<Dictionary<ulong, ScheduledEventData>>(
|
||||
eventsStream, cancellationToken: ct);
|
||||
|
||||
var memberData = new Dictionary<ulong, MemberData>();
|
||||
foreach (var dataPath in Directory.GetFiles(memberDataPath)) {
|
||||
await using var dataStream = File.OpenRead(dataPath);
|
||||
var data = await JsonSerializer.DeserializeAsync<MemberData>(dataStream, cancellationToken: ct);
|
||||
if (data is null) continue;
|
||||
var memberResult = await _guildApi.GetGuildMemberAsync(guildId, data.Id.ToDiscordSnowflake(), ct);
|
||||
if (memberResult.IsSuccess)
|
||||
data.Roles = memberResult.Entity.Roles.ToList();
|
||||
|
||||
memberData.Add(data.Id, data);
|
||||
}
|
||||
|
||||
var finalData = new GuildData(
|
||||
await configuration ?? new GuildConfiguration(), configurationPath,
|
||||
await events ?? new Dictionary<ulong, ScheduledEventData>(), scheduledEventsPath,
|
||||
memberData, memberDataPath);
|
||||
while (!_datas.ContainsKey(guildId)) _datas.TryAdd(guildId, finalData);
|
||||
return finalData;
|
||||
}
|
||||
|
||||
public async Task<GuildConfiguration> GetConfiguration(Snowflake guildId, CancellationToken ct = default) {
|
||||
return (await GetData(guildId, ct)).Configuration;
|
||||
}
|
||||
|
||||
public async Task<MemberData> GetMemberData(Snowflake guildId, Snowflake userId, CancellationToken ct = default) {
|
||||
return (await GetData(guildId, ct)).GetMemberData(userId);
|
||||
}
|
||||
|
||||
public ICollection<Snowflake> GetGuildIds() {
|
||||
return _datas.Keys;
|
||||
}
|
||||
}
|
389
src/Services/GuildUpdateService.cs
Normal file
389
src/Services/GuildUpdateService.cs
Normal file
|
@ -0,0 +1,389 @@
|
|||
using Boyfriend.Data;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Remora.Discord.API.Abstractions.Objects;
|
||||
using Remora.Discord.API.Abstractions.Rest;
|
||||
using Remora.Discord.API.Gateway.Commands;
|
||||
using Remora.Discord.API.Objects;
|
||||
using Remora.Discord.Extensions.Embeds;
|
||||
using Remora.Discord.Extensions.Formatting;
|
||||
using Remora.Discord.Gateway;
|
||||
using Remora.Discord.Gateway.Responders;
|
||||
using Remora.Discord.Interactivity;
|
||||
using Remora.Rest.Core;
|
||||
using Remora.Results;
|
||||
|
||||
namespace Boyfriend.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Handles executing guild updates (also called "ticks") once per second.
|
||||
/// </summary>
|
||||
public class GuildUpdateService : BackgroundService {
|
||||
private static readonly (string Name, TimeSpan Duration)[] SongList = {
|
||||
("UNDEAD CORPORATION - The Empress", new TimeSpan(0, 4, 34)),
|
||||
("UNDEAD CORPORATION - Everything will freeze", new TimeSpan(0, 3, 17)),
|
||||
("Splatoon 3 - Rockagilly Blues (Yoko & the Gold Bazookas)", new TimeSpan(0, 3, 37)),
|
||||
("Splatoon 3 - Seep and Destroy", new TimeSpan(0, 2, 42)),
|
||||
("IA - A Tale of Six Trillion Years and a Night", new TimeSpan(0, 3, 40)),
|
||||
("Manuel - Gas Gas Gas", new TimeSpan(0, 3, 17)),
|
||||
("Camellia - Flamewall", new TimeSpan(0, 6, 50))
|
||||
};
|
||||
|
||||
private readonly List<Activity> _activityList = new(1) { new Activity("with Remora.Discord", ActivityType.Game) };
|
||||
|
||||
private readonly IDiscordRestChannelAPI _channelApi;
|
||||
private readonly DiscordGatewayClient _client;
|
||||
private readonly GuildDataService _dataService;
|
||||
private readonly IDiscordRestGuildScheduledEventAPI _eventApi;
|
||||
private readonly IDiscordRestGuildAPI _guildApi;
|
||||
private readonly ILogger<GuildUpdateService> _logger;
|
||||
private readonly IDiscordRestUserAPI _userApi;
|
||||
private readonly UtilityService _utility;
|
||||
|
||||
private DateTimeOffset _nextSongAt = DateTimeOffset.MinValue;
|
||||
private uint _nextSongIndex;
|
||||
|
||||
public GuildUpdateService(
|
||||
IDiscordRestChannelAPI channelApi, DiscordGatewayClient client, GuildDataService dataService,
|
||||
IDiscordRestGuildScheduledEventAPI eventApi, IDiscordRestGuildAPI guildApi, ILogger<GuildUpdateService> logger,
|
||||
IDiscordRestUserAPI userApi, UtilityService utility) {
|
||||
_channelApi = channelApi;
|
||||
_client = client;
|
||||
_dataService = dataService;
|
||||
_eventApi = eventApi;
|
||||
_guildApi = guildApi;
|
||||
_logger = logger;
|
||||
_userApi = userApi;
|
||||
_utility = utility;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Activates a periodic timer with a 1 second interval and adds guild update tasks on each timer tick.
|
||||
/// Additionally, updates the current presence with songs from <see cref="SongList"/>.
|
||||
/// </summary>
|
||||
/// <remarks>If update tasks take longer than 1 second, the next timer tick will be skipped.</remarks>
|
||||
/// <param name="ct">The cancellation token for this operation.</param>
|
||||
protected override async Task ExecuteAsync(CancellationToken ct) {
|
||||
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(1));
|
||||
var tasks = new List<Task>();
|
||||
|
||||
while (await timer.WaitForNextTickAsync(ct)) {
|
||||
var guildIds = _dataService.GetGuildIds();
|
||||
if (guildIds.Count > 0 && DateTimeOffset.UtcNow >= _nextSongAt) {
|
||||
var nextSong = SongList[_nextSongIndex];
|
||||
_activityList[0] = new Activity(nextSong.Name, ActivityType.Listening);
|
||||
_client.SubmitCommand(
|
||||
new UpdatePresence(
|
||||
UserStatus.Online, false, DateTimeOffset.UtcNow, _activityList));
|
||||
_nextSongAt = DateTimeOffset.UtcNow.Add(nextSong.Duration);
|
||||
_nextSongIndex++;
|
||||
if (_nextSongIndex >= SongList.Length) _nextSongIndex = 0;
|
||||
}
|
||||
|
||||
tasks.AddRange(guildIds.Select(id => TickGuildAsync(id, ct)));
|
||||
|
||||
await Task.WhenAll(tasks);
|
||||
tasks.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs an update ("tick") for a guild with the provided <paramref name="guildId" />.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This method does the following:
|
||||
/// <list type="bullet">
|
||||
/// <item>Automatically unbans users once their ban period has expired.</item>
|
||||
/// <item>Automatically grants members the guild's <see cref="GuildConfiguration.DefaultRole"/> if one is set.</item>
|
||||
/// <item>Sends reminders about an upcoming scheduled event.</item>
|
||||
/// <item>Automatically starts scheduled events if <see cref="GuildConfiguration.AutoStartEvents"/> is enabled.</item>
|
||||
/// <item>Sends scheduled event start notifications.</item>
|
||||
/// <item>Sends scheduled event completion notifications.</item>
|
||||
/// <item>Sends reminders to members.</item>
|
||||
/// </list>
|
||||
/// This is done here and not in a <see cref="IResponder{TGatewayEvent}" /> for the following reasons:
|
||||
/// <list type="bullet">
|
||||
/// <item>
|
||||
/// Downtime would affect the reliability of notifications and automatic unbans if this logic were to be in a
|
||||
/// <see cref="IResponder{TGatewayEvent}" />.
|
||||
/// </item>
|
||||
/// <item>The Discord API doesn't provide necessary information about scheduled event updates.</item>
|
||||
/// </list>
|
||||
/// </remarks>
|
||||
/// <param name="guildId">The ID of the guild to update.</param>
|
||||
/// <param name="ct">The cancellation token for this operation.</param>
|
||||
private async Task TickGuildAsync(Snowflake guildId, CancellationToken ct = default) {
|
||||
var data = await _dataService.GetData(guildId, ct);
|
||||
Messages.Culture = data.Culture;
|
||||
var defaultRoleSnowflake = data.Configuration.DefaultRole.ToDiscordSnowflake();
|
||||
|
||||
foreach (var memberData in data.MemberData.Values) {
|
||||
var userId = memberData.Id.ToDiscordSnowflake();
|
||||
|
||||
if (defaultRoleSnowflake.Value is not 0 && !memberData.Roles.Contains(defaultRoleSnowflake))
|
||||
_ = _guildApi.AddGuildMemberRoleAsync(
|
||||
guildId, userId, defaultRoleSnowflake, ct: ct);
|
||||
|
||||
if (DateTimeOffset.UtcNow > memberData.BannedUntil) {
|
||||
var unbanResult = await _guildApi.RemoveGuildBanAsync(
|
||||
guildId, userId, Messages.PunishmentExpired.EncodeHeader(), ct);
|
||||
if (unbanResult.IsSuccess)
|
||||
memberData.BannedUntil = null;
|
||||
else
|
||||
_logger.LogWarning(
|
||||
"Error in automatic user unban request.\n{ErrorMessage}", unbanResult.Error.Message);
|
||||
}
|
||||
|
||||
var userResult = await _userApi.GetUserAsync(userId, ct);
|
||||
if (!userResult.IsDefined(out var user)) continue;
|
||||
|
||||
for (var i = memberData.Reminders.Count - 1; i >= 0; i--) {
|
||||
var reminder = memberData.Reminders[i];
|
||||
if (DateTimeOffset.UtcNow < reminder.RemindAt) continue;
|
||||
|
||||
var embed = new EmbedBuilder().WithSmallTitle(
|
||||
string.Format(Messages.Reminder, user.GetTag()), user)
|
||||
.WithDescription(
|
||||
string.Format(Messages.DescriptionReminder, Markdown.InlineCode(reminder.Text)))
|
||||
.WithColour(ColorsList.Magenta)
|
||||
.Build();
|
||||
|
||||
if (!embed.IsDefined(out var built)) continue;
|
||||
|
||||
var messageResult = await _channelApi.CreateMessageAsync(
|
||||
reminder.Channel, Mention.User(user), embeds: new[] { built }, ct: ct);
|
||||
if (!messageResult.IsSuccess)
|
||||
_logger.LogWarning(
|
||||
"Error in reminder send.\n{ErrorMessage}", messageResult.Error.Message);
|
||||
|
||||
memberData.Reminders.Remove(reminder);
|
||||
}
|
||||
}
|
||||
|
||||
var eventsResult = await _eventApi.ListScheduledEventsForGuildAsync(guildId, ct: ct);
|
||||
if (!eventsResult.IsDefined(out var events)) return;
|
||||
|
||||
if (data.Configuration.EventNotificationChannel is 0) return;
|
||||
|
||||
foreach (var scheduledEvent in events) {
|
||||
if (!data.ScheduledEvents.ContainsKey(scheduledEvent.ID.Value)) {
|
||||
data.ScheduledEvents.Add(scheduledEvent.ID.Value, new ScheduledEventData(scheduledEvent.Status));
|
||||
} else {
|
||||
var storedEvent = data.ScheduledEvents[scheduledEvent.ID.Value];
|
||||
if (storedEvent.Status == scheduledEvent.Status) {
|
||||
if (DateTimeOffset.UtcNow >= scheduledEvent.ScheduledStartTime) {
|
||||
if (data.Configuration.AutoStartEvents
|
||||
&& scheduledEvent.Status is not GuildScheduledEventStatus.Active) {
|
||||
var startResult = await _eventApi.ModifyGuildScheduledEventAsync(
|
||||
guildId, scheduledEvent.ID,
|
||||
status: GuildScheduledEventStatus.Active, ct: ct);
|
||||
if (!startResult.IsSuccess)
|
||||
_logger.LogWarning(
|
||||
"Error in automatic scheduled event start request.\n{ErrorMessage}",
|
||||
startResult.Error.Message);
|
||||
}
|
||||
} else if (data.Configuration.EventEarlyNotificationOffset != TimeSpan.Zero
|
||||
&& !storedEvent.EarlyNotificationSent
|
||||
&& DateTimeOffset.UtcNow
|
||||
>= scheduledEvent.ScheduledStartTime - data.Configuration.EventEarlyNotificationOffset) {
|
||||
var earlyResult = await SendScheduledEventUpdatedMessage(scheduledEvent, data, true, ct);
|
||||
if (earlyResult.IsSuccess)
|
||||
storedEvent.EarlyNotificationSent = true;
|
||||
else
|
||||
_logger.LogWarning(
|
||||
"Error in scheduled event early notification sender.\n{ErrorMessage}",
|
||||
earlyResult.Error.Message);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
storedEvent.Status = scheduledEvent.Status;
|
||||
}
|
||||
|
||||
var result = scheduledEvent.Status switch {
|
||||
GuildScheduledEventStatus.Scheduled =>
|
||||
await SendScheduledEventCreatedMessage(scheduledEvent, data.Configuration, ct),
|
||||
GuildScheduledEventStatus.Active or GuildScheduledEventStatus.Completed =>
|
||||
await SendScheduledEventUpdatedMessage(scheduledEvent, data, false, ct),
|
||||
_ => Result.FromError(new ArgumentOutOfRangeError(nameof(scheduledEvent.Status)))
|
||||
};
|
||||
|
||||
if (!result.IsSuccess)
|
||||
_logger.LogWarning("Error in guild update.\n{ErrorMessage}", result.Error.Message);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles sending a notification, mentioning the <see cref="GuildConfiguration.EventNotificationRole" /> if one is
|
||||
/// set,
|
||||
/// when a scheduled event is created
|
||||
/// in a guild's <see cref="GuildConfiguration.EventNotificationChannel" /> if one is set.
|
||||
/// </summary>
|
||||
/// <param name="scheduledEvent">The scheduled event that has just been created.</param>
|
||||
/// <param name="config">The configuration of the guild containing the scheduled event.</param>
|
||||
/// <param name="ct">The cancellation token for this operation.</param>
|
||||
/// <returns>A notification sending result which may or may not have succeeded.</returns>
|
||||
private async Task<Result> SendScheduledEventCreatedMessage(
|
||||
IGuildScheduledEvent scheduledEvent, GuildConfiguration config, CancellationToken ct = default) {
|
||||
var currentUserResult = await _userApi.GetCurrentUserAsync(ct);
|
||||
if (!currentUserResult.IsDefined(out var currentUser)) return Result.FromError(currentUserResult);
|
||||
|
||||
if (!scheduledEvent.CreatorID.IsDefined(out var creatorId))
|
||||
return Result.FromError(new ArgumentNullError(nameof(scheduledEvent.CreatorID)));
|
||||
var creatorResult = await _userApi.GetUserAsync(creatorId.Value, ct);
|
||||
if (!creatorResult.IsDefined(out var creator)) return Result.FromError(creatorResult);
|
||||
|
||||
string embedDescription;
|
||||
var eventDescription = scheduledEvent.Description is { HasValue: true, Value: not null }
|
||||
? scheduledEvent.Description.Value
|
||||
: string.Empty;
|
||||
switch (scheduledEvent.EntityType) {
|
||||
case GuildScheduledEventEntityType.StageInstance or GuildScheduledEventEntityType.Voice:
|
||||
if (!scheduledEvent.ChannelID.AsOptional().IsDefined(out var channelId))
|
||||
return Result.FromError(new ArgumentNullError(nameof(scheduledEvent.ChannelID)));
|
||||
|
||||
embedDescription = $"{eventDescription}\n\n{Markdown.BlockQuote(
|
||||
string.Format(
|
||||
Messages.DescriptionLocalEventCreated,
|
||||
Markdown.Timestamp(scheduledEvent.ScheduledStartTime),
|
||||
Mention.Channel(channelId)
|
||||
))}";
|
||||
break;
|
||||
case GuildScheduledEventEntityType.External:
|
||||
if (!scheduledEvent.EntityMetadata.AsOptional().IsDefined(out var metadata))
|
||||
return Result.FromError(new ArgumentNullError(nameof(scheduledEvent.EntityMetadata)));
|
||||
if (!scheduledEvent.ScheduledEndTime.AsOptional().IsDefined(out var endTime))
|
||||
return Result.FromError(new ArgumentNullError(nameof(scheduledEvent.ScheduledEndTime)));
|
||||
if (!metadata.Location.IsDefined(out var location))
|
||||
return Result.FromError(new ArgumentNullError(nameof(metadata.Location)));
|
||||
|
||||
embedDescription = $"{eventDescription}\n\n{Markdown.BlockQuote(
|
||||
string.Format(
|
||||
Messages.DescriptionExternalEventCreated,
|
||||
Markdown.Timestamp(scheduledEvent.ScheduledStartTime),
|
||||
Markdown.Timestamp(endTime),
|
||||
Markdown.InlineCode(location)
|
||||
))}";
|
||||
break;
|
||||
default:
|
||||
return Result.FromError(new ArgumentOutOfRangeError(nameof(scheduledEvent.EntityType)));
|
||||
}
|
||||
|
||||
var embed = new EmbedBuilder()
|
||||
.WithSmallTitle(string.Format(Messages.EventCreatedTitle, creator.GetTag()), creator)
|
||||
.WithTitle(scheduledEvent.Name)
|
||||
.WithDescription(embedDescription)
|
||||
.WithEventCover(scheduledEvent.ID, scheduledEvent.Image)
|
||||
.WithUserFooter(currentUser)
|
||||
.WithCurrentTimestamp()
|
||||
.WithColour(ColorsList.White)
|
||||
.Build();
|
||||
if (!embed.IsDefined(out var built)) return Result.FromError(embed);
|
||||
|
||||
var roleMention = config.EventNotificationRole is not 0
|
||||
? Mention.Role(config.EventNotificationRole.ToDiscordSnowflake())
|
||||
: string.Empty;
|
||||
|
||||
var button = new ButtonComponent(
|
||||
ButtonComponentStyle.Primary,
|
||||
Messages.EventDetailsButton,
|
||||
new PartialEmoji(Name: "📋"),
|
||||
CustomIDHelpers.CreateButtonIDWithState(
|
||||
"scheduled-event-details", $"{scheduledEvent.GuildID}:{scheduledEvent.ID}")
|
||||
);
|
||||
|
||||
return (Result)await _channelApi.CreateMessageAsync(
|
||||
config.EventNotificationChannel.ToDiscordSnowflake(), roleMention, embeds: new[] { built },
|
||||
components: new[] { new ActionRowComponent(new[] { button }) }, ct: ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles sending a notification, mentioning the <see cref="GuildConfiguration.EventStartedReceivers" />s,
|
||||
/// when a scheduled event is about to start, has started or completed
|
||||
/// in a guild's <see cref="GuildConfiguration.EventNotificationChannel" /> if one is set.
|
||||
/// </summary>
|
||||
/// <param name="scheduledEvent">The scheduled event that is about to start, has started or completed.</param>
|
||||
/// <param name="data">The data for the guild containing the scheduled event.</param>
|
||||
/// <param name="early">Controls whether or not a reminder for the scheduled event should be sent instead of the event started/completed notification</param>
|
||||
/// <param name="ct">The cancellation token for this operation</param>
|
||||
/// <returns>A reminder/notification sending result which may or may not have succeeded.</returns>
|
||||
private async Task<Result> SendScheduledEventUpdatedMessage(
|
||||
IGuildScheduledEvent scheduledEvent, GuildData data, bool early, CancellationToken ct = default) {
|
||||
var currentUserResult = await _userApi.GetCurrentUserAsync(ct);
|
||||
if (!currentUserResult.IsDefined(out var currentUser)) return Result.FromError(currentUserResult);
|
||||
|
||||
var embed = new EmbedBuilder();
|
||||
string? content = null;
|
||||
if (early)
|
||||
embed.WithSmallTitle(string.Format(Messages.EventEarlyNotification, scheduledEvent.Name), currentUser)
|
||||
.WithColour(ColorsList.Default);
|
||||
else
|
||||
switch (scheduledEvent.Status) {
|
||||
case GuildScheduledEventStatus.Active:
|
||||
data.ScheduledEvents[scheduledEvent.ID.Value].ActualStartTime = DateTimeOffset.UtcNow;
|
||||
|
||||
string embedDescription;
|
||||
switch (scheduledEvent.EntityType) {
|
||||
case GuildScheduledEventEntityType.StageInstance or GuildScheduledEventEntityType.Voice:
|
||||
if (!scheduledEvent.ChannelID.AsOptional().IsDefined(out var channelId))
|
||||
return Result.FromError(new ArgumentNullError(nameof(scheduledEvent.ChannelID)));
|
||||
|
||||
embedDescription = string.Format(
|
||||
Messages.DescriptionLocalEventStarted,
|
||||
Mention.Channel(channelId)
|
||||
);
|
||||
break;
|
||||
case GuildScheduledEventEntityType.External:
|
||||
if (!scheduledEvent.EntityMetadata.AsOptional().IsDefined(out var metadata))
|
||||
return Result.FromError(new ArgumentNullError(nameof(scheduledEvent.EntityMetadata)));
|
||||
if (!scheduledEvent.ScheduledEndTime.AsOptional().IsDefined(out var endTime))
|
||||
return Result.FromError(new ArgumentNullError(nameof(scheduledEvent.ScheduledEndTime)));
|
||||
if (!metadata.Location.IsDefined(out var location))
|
||||
return Result.FromError(new ArgumentNullError(nameof(metadata.Location)));
|
||||
|
||||
embedDescription = string.Format(
|
||||
Messages.DescriptionExternalEventStarted,
|
||||
Markdown.InlineCode(location),
|
||||
Markdown.Timestamp(endTime)
|
||||
);
|
||||
break;
|
||||
default:
|
||||
return Result.FromError(new ArgumentOutOfRangeError(nameof(scheduledEvent.EntityType)));
|
||||
}
|
||||
|
||||
var contentResult = await _utility.GetEventNotificationMentions(
|
||||
scheduledEvent, data.Configuration, ct);
|
||||
if (!contentResult.IsDefined(out content))
|
||||
return Result.FromError(contentResult);
|
||||
|
||||
embed.WithTitle(string.Format(Messages.EventStarted, scheduledEvent.Name))
|
||||
.WithDescription(embedDescription)
|
||||
.WithColour(ColorsList.Green);
|
||||
break;
|
||||
case GuildScheduledEventStatus.Completed:
|
||||
embed.WithTitle(string.Format(Messages.EventCompleted, scheduledEvent.Name))
|
||||
.WithDescription(
|
||||
string.Format(
|
||||
Messages.EventDuration,
|
||||
DateTimeOffset.UtcNow.Subtract(
|
||||
data.ScheduledEvents[scheduledEvent.ID.Value].ActualStartTime
|
||||
?? scheduledEvent.ScheduledStartTime).ToString()))
|
||||
.WithColour(ColorsList.Black);
|
||||
|
||||
data.ScheduledEvents.Remove(scheduledEvent.ID.Value);
|
||||
break;
|
||||
case GuildScheduledEventStatus.Canceled:
|
||||
case GuildScheduledEventStatus.Scheduled:
|
||||
default: return Result.FromError(new ArgumentOutOfRangeError(nameof(scheduledEvent.Status)));
|
||||
}
|
||||
|
||||
var result = embed.WithCurrentTimestamp().Build();
|
||||
|
||||
if (!result.IsDefined(out var built)) return Result.FromError(result);
|
||||
|
||||
return (Result)await _channelApi.CreateMessageAsync(
|
||||
data.Configuration.EventNotificationChannel.ToDiscordSnowflake(),
|
||||
content ?? default(Optional<string>), embeds: new[] { built }, ct: ct);
|
||||
}
|
||||
}
|
140
src/Services/UtilityService.cs
Normal file
140
src/Services/UtilityService.cs
Normal file
|
@ -0,0 +1,140 @@
|
|||
using System.Text;
|
||||
using Boyfriend.Data;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Remora.Discord.API.Abstractions.Objects;
|
||||
using Remora.Discord.API.Abstractions.Rest;
|
||||
using Remora.Discord.Extensions.Formatting;
|
||||
using Remora.Rest.Core;
|
||||
using Remora.Results;
|
||||
|
||||
namespace Boyfriend.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Provides utility methods that cannot be transformed to extension methods because they require usage
|
||||
/// of some Discord APIs.
|
||||
/// </summary>
|
||||
public class UtilityService : IHostedService {
|
||||
private readonly IDiscordRestGuildScheduledEventAPI _eventApi;
|
||||
private readonly IDiscordRestGuildAPI _guildApi;
|
||||
private readonly IDiscordRestUserAPI _userApi;
|
||||
|
||||
public UtilityService(
|
||||
IDiscordRestGuildAPI guildApi, IDiscordRestUserAPI userApi, IDiscordRestGuildScheduledEventAPI eventApi) {
|
||||
_guildApi = guildApi;
|
||||
_userApi = userApi;
|
||||
_eventApi = eventApi;
|
||||
}
|
||||
|
||||
public Task StartAsync(CancellationToken ct) {
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task StopAsync(CancellationToken ct) {
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether or not a member can interact with another member
|
||||
/// </summary>
|
||||
/// <param name="guildId">The ID of the guild in which an operation is being performed.</param>
|
||||
/// <param name="interacterId">The executor of the operation.</param>
|
||||
/// <param name="targetId">The target of the operation.</param>
|
||||
/// <param name="action">The operation.</param>
|
||||
/// <param name="ct">The cancellation token for this operation.</param>
|
||||
/// <returns>
|
||||
/// <list type="bullet">
|
||||
/// <item>A result which has succeeded with a null string if the member can interact with the target.</item>
|
||||
/// <item>
|
||||
/// A result which has succeeded with a non-null string containing the error message if the member cannot
|
||||
/// interact with the target.
|
||||
/// </item>
|
||||
/// <item>A result which has failed if an error occurred during the execution of this method.</item>
|
||||
/// </list>
|
||||
/// </returns>
|
||||
public async Task<Result<string?>> CheckInteractionsAsync(
|
||||
Snowflake guildId, Snowflake interacterId, Snowflake targetId, string action, CancellationToken ct = default) {
|
||||
if (interacterId == targetId)
|
||||
return Result<string?>.FromSuccess($"UserCannot{action}Themselves".Localized());
|
||||
|
||||
var currentUserResult = await _userApi.GetCurrentUserAsync(ct);
|
||||
if (!currentUserResult.IsDefined(out var currentUser))
|
||||
return Result<string?>.FromError(currentUserResult);
|
||||
if (currentUser.ID == targetId)
|
||||
return Result<string?>.FromSuccess($"UserCannot{action}Bot".Localized());
|
||||
|
||||
var guildResult = await _guildApi.GetGuildAsync(guildId, ct: ct);
|
||||
if (!guildResult.IsDefined(out var guild))
|
||||
return Result<string?>.FromError(guildResult);
|
||||
if (targetId == guild.OwnerID) return Result<string?>.FromSuccess($"UserCannot{action}Owner".Localized());
|
||||
|
||||
var targetMemberResult = await _guildApi.GetGuildMemberAsync(guildId, targetId, ct);
|
||||
if (!targetMemberResult.IsDefined(out var targetMember))
|
||||
return Result<string?>.FromSuccess(null);
|
||||
|
||||
var currentMemberResult = await _guildApi.GetGuildMemberAsync(guildId, currentUser.ID, ct);
|
||||
if (!currentMemberResult.IsDefined(out var currentMember))
|
||||
return Result<string?>.FromError(currentMemberResult);
|
||||
|
||||
var rolesResult = await _guildApi.GetGuildRolesAsync(guildId, ct);
|
||||
if (!rolesResult.IsDefined(out var roles))
|
||||
return Result<string?>.FromError(rolesResult);
|
||||
|
||||
var targetRoles = roles.Where(r => targetMember.Roles.Contains(r.ID)).ToList();
|
||||
var botRoles = roles.Where(r => currentMember.Roles.Contains(r.ID));
|
||||
|
||||
var targetBotRoleDiff = targetRoles.MaxOrDefault(r => r.Position) - botRoles.MaxOrDefault(r => r.Position);
|
||||
if (targetBotRoleDiff >= 0)
|
||||
return Result<string?>.FromSuccess($"BotCannot{action}Target".Localized());
|
||||
|
||||
if (interacterId == guild.OwnerID)
|
||||
return Result<string?>.FromSuccess(null);
|
||||
|
||||
var interacterResult = await _guildApi.GetGuildMemberAsync(guildId, interacterId, ct);
|
||||
if (!interacterResult.IsDefined(out var interacter))
|
||||
return Result<string?>.FromError(interacterResult);
|
||||
|
||||
var interacterRoles = roles.Where(r => interacter.Roles.Contains(r.ID));
|
||||
var targetInteracterRoleDiff
|
||||
= targetRoles.MaxOrDefault(r => r.Position) - interacterRoles.MaxOrDefault(r => r.Position);
|
||||
if (targetInteracterRoleDiff >= 0)
|
||||
return Result<string?>.FromSuccess($"UserCannot{action}Target".Localized());
|
||||
|
||||
return Result<string?>.FromSuccess(null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the string mentioning all <see cref="GuildConfiguration.NotificationReceiver" />s related to a scheduled
|
||||
/// event.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// If the guild configuration enables <see cref="GuildConfiguration.NotificationReceiver.Role" />, then the
|
||||
/// <see cref="GuildConfiguration.EventNotificationRole" /> will also be mentioned.
|
||||
/// </remarks>
|
||||
/// <param name="scheduledEvent">
|
||||
/// The scheduled event whose subscribers will be mentioned if the guild configuration enables
|
||||
/// <see cref="GuildConfiguration.NotificationReceiver.Interested" />.
|
||||
/// </param>
|
||||
/// <param name="config">The configuration of the guild containing the scheduled event</param>
|
||||
/// <param name="ct">The cancellation token for this operation.</param>
|
||||
/// <returns>A result containing the string which may or may not have succeeded.</returns>
|
||||
public async Task<Result<string>> GetEventNotificationMentions(
|
||||
IGuildScheduledEvent scheduledEvent, GuildConfiguration config, CancellationToken ct = default) {
|
||||
var builder = new StringBuilder();
|
||||
var receivers = config.EventStartedReceivers;
|
||||
var role = config.EventNotificationRole.ToDiscordSnowflake();
|
||||
var usersResult = await _eventApi.GetGuildScheduledEventUsersAsync(
|
||||
scheduledEvent.GuildID, scheduledEvent.ID, withMember: true, ct: ct);
|
||||
if (!usersResult.IsDefined(out var users)) return Result<string>.FromError(usersResult);
|
||||
|
||||
if (receivers.Contains(GuildConfiguration.NotificationReceiver.Role) && role.Value is not 0)
|
||||
builder.Append($"{Mention.Role(role)} ");
|
||||
if (receivers.Contains(GuildConfiguration.NotificationReceiver.Interested))
|
||||
builder = users.Where(
|
||||
user => {
|
||||
if (!user.GuildMember.IsDefined(out var member)) return true;
|
||||
return !member.Roles.Contains(role);
|
||||
})
|
||||
.Aggregate(builder, (current, user) => current.Append($"{Mention.User(user.User)} "));
|
||||
return builder.ToString();
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue