mirror of
https://github.com/TeamOctolings/Octobot.git
synced 2025-04-20 00:43:36 +03:00
Add /mute command (timeouts only) (#44)
Co-authored-by: Octol1ttle <l1ttleofficial@outlook.com>
This commit is contained in:
parent
7a4e20852e
commit
0e3e562b22
13 changed files with 1477 additions and 745 deletions
|
@ -31,6 +31,10 @@ public class Boyfriend {
|
|||
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();
|
||||
|
@ -69,6 +73,7 @@ public class Boyfriend {
|
|||
services.AddTransient<IConfigurationBuilder, ConfigurationBuilder>()
|
||||
.AddDiscordCaching()
|
||||
.AddDiscordCommands(true)
|
||||
.AddPreparationErrorEvent<ErrorLoggingPreparationErrorEvent>()
|
||||
.AddPostExecutionEvent<ErrorLoggingPostExecutionEvent>()
|
||||
.AddInteractivity()
|
||||
.AddInteractionGroup<InteractionResponders>()
|
||||
|
@ -77,7 +82,8 @@ public class Boyfriend {
|
|||
.AddHostedService<GuildUpdateService>()
|
||||
.AddCommandTree()
|
||||
.WithCommandGroup<BanCommandGroup>()
|
||||
.WithCommandGroup<KickCommandGroup>();
|
||||
.WithCommandGroup<KickCommandGroup>()
|
||||
.WithCommandGroup<MuteCommandGroup>();
|
||||
var responderTypes = typeof(Boyfriend).Assembly
|
||||
.GetExportedTypes()
|
||||
.Where(t => t.IsResponder());
|
||||
|
|
|
@ -21,7 +21,7 @@ using Remora.Results;
|
|||
namespace Boyfriend.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// Handles commands related to ban management: /ban and unban.
|
||||
/// Handles commands related to ban management: /ban and /unban.
|
||||
/// </summary>
|
||||
public class BanCommandGroup : CommandGroup {
|
||||
private readonly IDiscordRestChannelAPI _channelApi;
|
||||
|
|
62
Commands/ErrorLoggingEvents.cs
Normal file
62
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());
|
||||
}
|
||||
}
|
|
@ -1,35 +0,0 @@
|
|||
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 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 handler.\n{ErrorMessage}", commandResult.Error.Message);
|
||||
|
||||
return Task.FromResult(Result.FromSuccess());
|
||||
}
|
||||
}
|
|
@ -76,8 +76,8 @@ public class KickCommandGroup : CommandGroup {
|
|||
var cfg = data.Configuration;
|
||||
Messages.Culture = data.Culture;
|
||||
|
||||
var existingKickResult = await _guildApi.GetGuildMemberAsync(guildId.Value, target.ID);
|
||||
if (!existingKickResult.IsSuccess) {
|
||||
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();
|
||||
|
||||
|
|
265
Commands/MuteCommandGroup.cs
Normal file
265
Commands/MuteCommandGroup.cs
Normal file
|
@ -0,0 +1,265 @@
|
|||
using System.ComponentModel;
|
||||
using System.Text;
|
||||
using Boyfriend.Services;
|
||||
using Boyfriend.Services.Data;
|
||||
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.Extensions;
|
||||
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 user with the specified reason.
|
||||
/// </summary>
|
||||
/// <param name="target">The user to mute.</param>
|
||||
/// <param name="duration">The duration for this mute. The user 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 user
|
||||
/// was muted and vice-versa.
|
||||
/// </returns>
|
||||
/// <seealso cref="UnmuteUserAsync" />
|
||||
[Command("mute", "мут")]
|
||||
[RequireContext(ChannelContext.Guild)]
|
||||
[RequireDiscordPermission(DiscordPermission.ModerateMembers)]
|
||||
[RequireBotDiscordPermissions(DiscordPermission.ModerateMembers)]
|
||||
[Description("мутит друга <3")]
|
||||
public async Task<Result> MuteUserAsync(
|
||||
[Description("друг которого нужно замутить ПОТОМУ-ЧТО ОН ЗАЕБАЛ")]
|
||||
IUser target,
|
||||
[Description("причина зачем мутить друга (пиши заебал)")]
|
||||
string reason,
|
||||
TimeSpan duration) {
|
||||
// Data checks
|
||||
if (!_context.TryGetGuildID(out var guildId))
|
||||
return Result.FromError(new ArgumentNullError(nameof(guildId)));
|
||||
if (!_context.TryGetUserID(out var userId))
|
||||
return Result.FromError(new ArgumentNullError(nameof(userId)));
|
||||
if (!_context.TryGetChannelID(out var channelId))
|
||||
return Result.FromError(new ArgumentNullError(nameof(channelId)));
|
||||
|
||||
// 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 user with the specified reason.
|
||||
/// </summary>
|
||||
/// <param name="target">The user 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 user
|
||||
/// 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("ФУНКЦИЯ ФОРС РАЗМУТ КАВАЯ КОЛЕСИКИ!!!!1111111111")]
|
||||
public async Task<Result> UnmuteUserAsync([Description("юзер кого раззамучивать")] IUser target, string reason) {
|
||||
// Data checks
|
||||
if (!_context.TryGetGuildID(out var guildId))
|
||||
return Result.FromError(new ArgumentNullError(nameof(guildId)));
|
||||
if (!_context.TryGetUserID(out var userId))
|
||||
return Result.FromError(new ArgumentNullError(nameof(userId)));
|
||||
if (!_context.TryGetChannelID(out var channelId))
|
||||
return Result.FromError(new ArgumentNullError(nameof(channelId)));
|
||||
|
||||
// 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);
|
||||
}
|
||||
}
|
|
@ -129,7 +129,7 @@ public static class Extensions {
|
|||
}
|
||||
|
||||
public static string GetTag(this IUser user) {
|
||||
return $"{user.Username}#{user.Discriminator:0000}";
|
||||
return user.Discriminator is 0000 ? $"@{user.Username}" : $"{user.Username}#{user.Discriminator:0000}";
|
||||
}
|
||||
|
||||
public static Snowflake ToDiscordSnowflake(this ulong id) {
|
||||
|
|
1815
Messages.Designer.cs
generated
1815
Messages.Designer.cs
generated
File diff suppressed because it is too large
Load diff
|
@ -513,4 +513,7 @@
|
|||
<data name="DescriptionActionExpiresAt" xml:space="preserve">
|
||||
<value>Expires at: {0}</value>
|
||||
</data>
|
||||
<data name="UserAlreadyMuted" xml:space="preserve">
|
||||
<value>This user is already muted!</value>
|
||||
</data>
|
||||
</root>
|
||||
|
|
|
@ -513,4 +513,7 @@
|
|||
<data name="DescriptionActionExpiresAt" xml:space="preserve">
|
||||
<value>Закончится: {0}</value>
|
||||
</data>
|
||||
<data name="UserAlreadyMuted" xml:space="preserve">
|
||||
<value>Этот пользователь уже в муте!</value>
|
||||
</data>
|
||||
</root>
|
||||
|
|
|
@ -513,4 +513,7 @@
|
|||
<data name="DescriptionActionExpiresAt" xml:space="preserve">
|
||||
<value>заживёт: {0}</value>
|
||||
</data>
|
||||
<data name="UserAlreadyMuted" xml:space="preserve">
|
||||
<value>этот шизоид УЖЕ замучился</value>
|
||||
</data>
|
||||
</root>
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
using System.Collections.Concurrent;
|
||||
using System.Text.Json;
|
||||
using Boyfriend.Data;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
|
@ -11,7 +12,7 @@ namespace Boyfriend.Services.Data;
|
|||
/// Handles saving, loading, initializing and providing <see cref="GuildData" />.
|
||||
/// </summary>
|
||||
public class GuildDataService : IHostedService {
|
||||
private readonly Dictionary<Snowflake, GuildData> _datas = new();
|
||||
private readonly ConcurrentDictionary<Snowflake, GuildData> _datas = new();
|
||||
private readonly IDiscordRestGuildAPI _guildApi;
|
||||
private readonly ILogger<GuildDataService> _logger;
|
||||
|
||||
|
@ -85,8 +86,6 @@ public class GuildDataService : IHostedService {
|
|||
var memberResult = await _guildApi.GetGuildMemberAsync(guildId, data.Id.ToDiscordSnowflake(), ct);
|
||||
if (memberResult.IsSuccess)
|
||||
data.Roles = memberResult.Entity.Roles.ToList();
|
||||
else
|
||||
_logger.LogWarning("Error in member retrieval.\n{ErrorMessage}", memberResult.Error.Message);
|
||||
|
||||
memberData.Add(data.Id, data);
|
||||
}
|
||||
|
@ -95,7 +94,7 @@ public class GuildDataService : IHostedService {
|
|||
await configuration ?? new GuildConfiguration(), configurationPath,
|
||||
await events ?? new Dictionary<ulong, ScheduledEventData>(), scheduledEventsPath,
|
||||
memberData, memberDataPath);
|
||||
_datas.Add(guildId, finalData);
|
||||
while (!_datas.ContainsKey(guildId)) _datas.TryAdd(guildId, finalData);
|
||||
return finalData;
|
||||
}
|
||||
|
||||
|
|
|
@ -87,14 +87,9 @@ public class GuildUpdateService : BackgroundService {
|
|||
|
||||
foreach (var memberData in data.MemberData.Values) {
|
||||
var userIdSnowflake = memberData.Id.ToDiscordSnowflake();
|
||||
if (!memberData.Roles.Contains(defaultRoleSnowflake)) {
|
||||
var defaultRoleResult = await _guildApi.AddGuildMemberRoleAsync(
|
||||
if (defaultRoleSnowflake.Value is not 0 && !memberData.Roles.Contains(defaultRoleSnowflake))
|
||||
_ = _guildApi.AddGuildMemberRoleAsync(
|
||||
guildId, userIdSnowflake, defaultRoleSnowflake, ct: ct);
|
||||
if (!defaultRoleResult.IsSuccess)
|
||||
_logger.LogWarning(
|
||||
"Error in automatic default role add request.\n{ErrorMessage}",
|
||||
defaultRoleResult.Error.Message);
|
||||
}
|
||||
|
||||
if (DateTimeOffset.UtcNow > memberData.BannedUntil) {
|
||||
var unbanResult = await _guildApi.RemoveGuildBanAsync(
|
||||
|
|
Loading…
Add table
Reference in a new issue