i can't be bothered to keep track of these changes

This commit is contained in:
l1ttleO 2022-06-06 20:39:47 +05:00
parent 790f77aa49
commit 36d844148e
Signed by: Octol1ttle
GPG key ID: B77C34313AEE1FFF
15 changed files with 649 additions and 926 deletions

View file

@ -19,30 +19,28 @@ public static class Boyfriend {
private static readonly Game Activity = new("Retrospecter - Genocide", ActivityType.Listening); private static readonly Game Activity = new("Retrospecter - Genocide", ActivityType.Listening);
private static readonly Dictionary<ulong, Dictionary<string, string>> GuildConfigDictionary = new(); private static readonly Dictionary<ulong, Dictionary<string, string>> GuildConfigDictionary = new();
private static readonly Dictionary<ulong, Dictionary<ulong, ReadOnlyCollection<ulong>>> RemovedRolesDictionary = private static readonly Dictionary<ulong, Dictionary<ulong, ReadOnlyCollection<ulong>>> RemovedRolesDictionary =
new(); new();
private static readonly Dictionary<string, string> EmptyGuildConfig = new();
private static readonly Dictionary<ulong, ReadOnlyCollection<ulong>> EmptyRemovedRoles = new();
public static readonly Dictionary<string, string> DefaultConfig = new() { public static readonly Dictionary<string, string> DefaultConfig = new() {
{"Lang", "en"}, { "Lang", "en" },
{"Prefix", "!"}, { "Prefix", "!" },
{"RemoveRolesOnMute", "false"}, { "RemoveRolesOnMute", "false" },
{"SendWelcomeMessages", "true"}, { "SendWelcomeMessages", "true" },
{"ReceiveStartupMessages", "false"}, { "ReceiveStartupMessages", "false" },
{"FrowningFace", "true"}, { "FrowningFace", "true" },
{"WelcomeMessage", Messages.DefaultWelcomeMessage}, { "WelcomeMessage", Messages.DefaultWelcomeMessage },
{"EventStartedReceivers", "interested,role"}, { "EventStartedReceivers", "interested,role" },
{"StarterRole", "0"}, { "StarterRole", "0" },
{"MuteRole", "0"}, { "MuteRole", "0" },
{"EventNotifyReceiverRole", "0"}, { "EventNotifyReceiverRole", "0" },
{"AdminLogChannel", "0"}, { "AdminLogChannel", "0" },
{"BotLogChannel", "0"}, { "BotLogChannel", "0" },
{"EventCreatedChannel", "0"}, { "EventCreatedChannel", "0" },
{"EventStartedChannel", "0"}, { "EventStartedChannel", "0" },
{"EventCancelledChannel", "0"}, { "EventCancelledChannel", "0" },
{"EventCompletedChannel", "0"} { "EventCompletedChannel", "0" }
}; };
public static void Main() { public static void Main() {
@ -79,7 +77,7 @@ public static class Boyfriend {
public static Dictionary<string, string> GetGuildConfig(ulong id) { public static Dictionary<string, string> GetGuildConfig(ulong id) {
if (!RemovedRolesDictionary.ContainsKey(id)) if (!RemovedRolesDictionary.ContainsKey(id))
RemovedRolesDictionary.Add(id, EmptyRemovedRoles); RemovedRolesDictionary.Add(id, new Dictionary<ulong, ReadOnlyCollection<ulong>>());
if (GuildConfigDictionary.ContainsKey(id)) return GuildConfigDictionary[id]; if (GuildConfigDictionary.ContainsKey(id)) return GuildConfigDictionary[id];
@ -88,15 +86,19 @@ public static class Boyfriend {
if (!File.Exists(path)) File.Create(path).Dispose(); if (!File.Exists(path)) File.Create(path).Dispose();
var json = File.ReadAllText(path); var json = File.ReadAllText(path);
var config = JsonConvert.DeserializeObject<Dictionary<string, string>>(json) ?? EmptyGuildConfig; var config = JsonConvert.DeserializeObject<Dictionary<string, string>>(json)
?? new Dictionary<string, string>();
foreach (var key in DefaultConfig.Keys) if (config.Keys.Count < DefaultConfig.Keys.Count) {
if (!config.ContainsKey(key)) // ReSharper disable once ForeachCanBePartlyConvertedToQueryUsingAnotherGetEnumerator
config.Add(key, DefaultConfig[key]); // Avoids a closure allocation with the config variable
foreach (var key in DefaultConfig.Keys)
foreach (var key in config.Keys) if (!config.ContainsKey(key))
if (!DefaultConfig.ContainsKey(key)) config.Add(key, DefaultConfig[key]);
} else if (config.Keys.Count > DefaultConfig.Keys.Count) {
foreach (var key in config.Keys.Where(key => !DefaultConfig.ContainsKey(key)))
config.Remove(key); config.Remove(key);
}
GuildConfigDictionary.Add(id, config); GuildConfigDictionary.Add(id, config);
@ -111,8 +113,8 @@ public static class Boyfriend {
if (!File.Exists(path)) File.Create(path); if (!File.Exists(path)) File.Create(path);
var json = File.ReadAllText(path); var json = File.ReadAllText(path);
var removedRoles = JsonConvert.DeserializeObject<Dictionary<ulong, ReadOnlyCollection<ulong>>>(json) ?? var removedRoles = JsonConvert.DeserializeObject<Dictionary<ulong, ReadOnlyCollection<ulong>>>(json)
EmptyRemovedRoles; ?? new Dictionary<ulong, ReadOnlyCollection<ulong>>();
RemovedRolesDictionary.Add(id, removedRoles); RemovedRolesDictionary.Add(id, removedRoles);
@ -121,9 +123,8 @@ public static class Boyfriend {
public static SocketGuild FindGuild(ulong channel) { public static SocketGuild FindGuild(ulong channel) {
if (GuildCache.ContainsKey(channel)) return GuildCache[channel]; if (GuildCache.ContainsKey(channel)) return GuildCache[channel];
foreach (var guild in Client.Guilds) foreach (var guild in Client.Guilds) {
foreach (var x in guild.Channels) { if (guild.Channels.All(x => x.Id != channel)) continue;
if (x.Id != channel) continue;
GuildCache.Add(channel, guild); GuildCache.Add(channel, guild);
return guild; return guild;
} }

View file

@ -15,10 +15,10 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Discord.Net" Version="3.6.1"/> <PackageReference Include="Discord.Net" Version="3.7.2"/>
<PackageReference Include="Humanizer.Core" Version="2.14.1"/> <PackageReference Include="Humanizer.Core" Version="2.14.1"/>
<PackageReference Include="Humanizer.Core.ru" Version="2.14.1"/> <PackageReference Include="Humanizer.Core.ru" Version="2.14.1"/>
<PackageReference Include="Newtonsoft.Json" Version="13.0.1"/> <PackageReference Include="Newtonsoft.Json" Version="13.0.2-beta1"/>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View file

@ -8,7 +8,6 @@ using Discord.WebSocket;
namespace Boyfriend; namespace Boyfriend;
public static class CommandHandler { public static class CommandHandler {
public static readonly Command[] Commands = { public static readonly Command[] Commands = {
new BanCommand(), new ClearCommand(), new HelpCommand(), new BanCommand(), new ClearCommand(), new HelpCommand(),
new KickCommand(), new MuteCommand(), new PingCommand(), new KickCommand(), new MuteCommand(), new PingCommand(),
@ -34,9 +33,7 @@ public static class CommandHandler {
var config = Boyfriend.GetGuildConfig(guild.Id); var config = Boyfriend.GetGuildConfig(guild.Id);
Regex regex; Regex regex;
if (RegexCache.ContainsKey(config["Prefix"])) { if (RegexCache.ContainsKey(config["Prefix"])) { regex = RegexCache[config["Prefix"]]; } else {
regex = RegexCache[config["Prefix"]];
} else {
regex = new Regex(Regex.Escape(config["Prefix"])); regex = new Regex(Regex.Escape(config["Prefix"]));
RegexCache.Add(config["Prefix"], regex); RegexCache.Add(config["Prefix"], regex);
} }
@ -61,13 +58,14 @@ public static class CommandHandler {
if (currentLine != list.Length) continue; if (currentLine != list.Length) continue;
if (ConfigWriteScheduled) await Boyfriend.WriteGuildConfig(guild.Id); if (ConfigWriteScheduled) await Boyfriend.WriteGuildConfig(guild.Id);
await context.Message.ReplyAsync(StackedReplyMessage.ToString(), false, null, AllowedMentions.None); await message.ReplyAsync(StackedReplyMessage.ToString(), false, null, AllowedMentions.None);
var adminChannel = Utils.GetAdminLogChannel(guild.Id); var adminChannel = Utils.GetAdminLogChannel(guild.Id);
var systemChannel = guild.SystemChannel; var systemChannel = guild.SystemChannel;
if (adminChannel != null) if (StackedPrivateFeedback.Length > 0 && adminChannel != null && adminChannel.Id != message.Channel.Id)
await Utils.SilentSendAsync(adminChannel, StackedPrivateFeedback.ToString()); await Utils.SilentSendAsync(adminChannel, StackedPrivateFeedback.ToString());
if (systemChannel != null) if (StackedPublicFeedback.Length > 0 && systemChannel != null && systemChannel.Id != adminChannel?.Id
&& systemChannel.Id != message.Channel.Id)
await Utils.SilentSendAsync(systemChannel, StackedPublicFeedback.ToString()); await Utils.SilentSendAsync(systemChannel, StackedPublicFeedback.ToString());
} }
} }

View file

@ -5,7 +5,7 @@ using Discord.WebSocket;
namespace Boyfriend.Commands; namespace Boyfriend.Commands;
public class BanCommand : Command { public class BanCommand : Command {
public override string[] Aliases { get; } = {"ban", "бан"}; public override string[] Aliases { get; } = { "ban", "бан" };
public override int ArgsLengthRequired => 2; public override int ArgsLengthRequired => 2;
public override async Task Run(SocketCommandContext context, string[] args) { public override async Task Run(SocketCommandContext context, string[] args) {
@ -17,7 +17,7 @@ public class BanCommand : Command {
} }
var guild = context.Guild; var guild = context.Guild;
var author = (SocketGuildUser) context.User; var author = (SocketGuildUser)context.User;
var permissionCheckResponse = CommandHandler.HasPermission(ref author, GuildPermission.BanMembers); var permissionCheckResponse = CommandHandler.HasPermission(ref author, GuildPermission.BanMembers);
if (permissionCheckResponse != "") { if (permissionCheckResponse != "") {
@ -40,6 +40,11 @@ public class BanCommand : Command {
if (duration.TotalSeconds < 0) { if (duration.TotalSeconds < 0) {
Warn(Messages.DurationParseFailed); Warn(Messages.DurationParseFailed);
reason = Utils.JoinString(ref args, 1); reason = Utils.JoinString(ref args, 1);
if (reason == "") {
Error(Messages.ReasonRequired, false);
return;
}
} }
await BanUser(guild, author, toBan, duration, reason); await BanUser(guild, author, toBan, duration, reason);
@ -50,12 +55,12 @@ public class BanCommand : Command {
var guildBanMessage = $"({author}) {reason}"; var guildBanMessage = $"({author}) {reason}";
await Utils.SendDirectMessage(toBan, await Utils.SendDirectMessage(toBan,
string.Format(Messages.YouWereBanned, author.Mention, guild.Name, Utils.WrapInline(reason))); string.Format(Messages.YouWereBanned, author.Mention, guild.Name, Utils.Wrap(reason)));
await guild.AddBanAsync(toBan, 0, guildBanMessage); await guild.AddBanAsync(toBan, 0, guildBanMessage);
var feedback = string.Format(Messages.FeedbackUserBanned, toBan.Mention, var feedback = string.Format(Messages.FeedbackUserBanned, toBan.Mention,
Utils.GetHumanizedTimeOffset(ref duration), Utils.WrapInline(reason)); Utils.GetHumanizedTimeOffset(ref duration), Utils.Wrap(reason));
Success(feedback, author.Mention, false, false); Success(feedback, author.Mention, false, false);
await Utils.SendFeedback(feedback, guild.Id, author.Mention, true); await Utils.SendFeedback(feedback, guild.Id, author.Mention, true);
@ -65,8 +70,7 @@ public class BanCommand : Command {
await UnbanCommand.UnbanUser(guild, guild.CurrentUser, toBan, Messages.PunishmentExpired); await UnbanCommand.UnbanUser(guild, guild.CurrentUser, toBan, Messages.PunishmentExpired);
} }
var task = new Task(DelayUnban); new Task(DelayUnban).Start();
task.Start();
} }
} }
} }

View file

@ -4,7 +4,6 @@ using Discord.Commands;
namespace Boyfriend.Commands; namespace Boyfriend.Commands;
public abstract class Command { public abstract class Command {
public abstract string[] Aliases { get; } public abstract string[] Aliases { get; }
public abstract int ArgsLengthRequired { get; } public abstract int ArgsLengthRequired { get; }

View file

@ -5,11 +5,11 @@ using Discord.WebSocket;
namespace Boyfriend.Commands; namespace Boyfriend.Commands;
public class KickCommand : Command { public class KickCommand : Command {
public override string[] Aliases { get; } = {"kick", "кик", "выгнать"}; public override string[] Aliases { get; } = { "kick", "кик", "выгнать" };
public override int ArgsLengthRequired => 2; public override int ArgsLengthRequired => 2;
public override async Task Run(SocketCommandContext context, string[] args) { public override async Task Run(SocketCommandContext context, string[] args) {
var author = (SocketGuildUser) context.User; var author = (SocketGuildUser)context.User;
var permissionCheckResponse = CommandHandler.HasPermission(ref author, GuildPermission.KickMembers); var permissionCheckResponse = CommandHandler.HasPermission(ref author, GuildPermission.KickMembers);
if (permissionCheckResponse != "") { if (permissionCheckResponse != "") {
@ -34,7 +34,7 @@ public class KickCommand : Command {
Success( Success(
string.Format(Messages.FeedbackMemberKicked, toKick.Mention, string.Format(Messages.FeedbackMemberKicked, toKick.Mention,
Utils.WrapInline(Utils.JoinString(ref args, 1))), author.Mention); Utils.Wrap(Utils.JoinString(ref args, 1))), author.Mention);
} }
private static async Task KickMember(IGuild guild, SocketUser author, SocketGuildUser toKick, string reason) { private static async Task KickMember(IGuild guild, SocketUser author, SocketGuildUser toKick, string reason) {
@ -42,7 +42,7 @@ public class KickCommand : Command {
var guildKickMessage = $"({author}) {reason}"; var guildKickMessage = $"({author}) {reason}";
await Utils.SendDirectMessage(toKick, await Utils.SendDirectMessage(toKick,
string.Format(Messages.YouWereKicked, authorMention, guild.Name, Utils.WrapInline(reason))); string.Format(Messages.YouWereKicked, authorMention, guild.Name, Utils.Wrap(reason)));
await toKick.KickAsync(guildKickMessage); await toKick.KickAsync(guildKickMessage);
} }

View file

@ -6,7 +6,7 @@ using Discord.WebSocket;
namespace Boyfriend.Commands; namespace Boyfriend.Commands;
public class MuteCommand : Command { public class MuteCommand : Command {
public override string[] Aliases { get; } = {"mute", "timeout", "заглушить", "мут"}; public override string[] Aliases { get; } = { "mute", "timeout", "заглушить", "мут" };
public override int ArgsLengthRequired => 2; public override int ArgsLengthRequired => 2;
public override async Task Run(SocketCommandContext context, string[] args) { public override async Task Run(SocketCommandContext context, string[] args) {
@ -17,6 +17,11 @@ public class MuteCommand : Command {
if (duration.TotalSeconds < 0) { if (duration.TotalSeconds < 0) {
Warn(Messages.DurationParseFailed); Warn(Messages.DurationParseFailed);
reason = Utils.JoinString(ref args, 1); reason = Utils.JoinString(ref args, 1);
if (reason == "") {
Error(Messages.ReasonRequired, false);
return;
}
} }
if (toMute == null) { if (toMute == null) {
@ -28,15 +33,9 @@ public class MuteCommand : Command {
var role = Utils.GetMuteRole(ref guild); var role = Utils.GetMuteRole(ref guild);
if (role != null) { if (role != null) {
var hasMuteRole = false; if (toMute.Roles.Contains(role) || (toMute.TimedOutUntil != null &&
foreach (var x in toMute.Roles) { toMute.TimedOutUntil.Value.ToUnixTimeMilliseconds() >
if (x != role) continue; DateTimeOffset.Now.ToUnixTimeMilliseconds())) {
hasMuteRole = true;
break;
}
if (hasMuteRole || (toMute.TimedOutUntil != null && toMute.TimedOutUntil.Value.ToUnixTimeMilliseconds() >
DateTimeOffset.Now.ToUnixTimeMilliseconds())) {
Error(Messages.MemberAlreadyMuted, false); Error(Messages.MemberAlreadyMuted, false);
return; return;
} }
@ -51,7 +50,7 @@ public class MuteCommand : Command {
Warn(Messages.RolesReturned); Warn(Messages.RolesReturned);
} }
var author = (SocketGuildUser) context.User; var author = (SocketGuildUser)context.User;
var permissionCheckResponse = CommandHandler.HasPermission(ref author, GuildPermission.ModerateMembers); var permissionCheckResponse = CommandHandler.HasPermission(ref author, GuildPermission.ModerateMembers);
if (permissionCheckResponse != "") { if (permissionCheckResponse != "") {
@ -69,7 +68,7 @@ public class MuteCommand : Command {
Success( Success(
string.Format(Messages.FeedbackMemberMuted, toMute.Mention, Utils.GetHumanizedTimeOffset(ref duration), string.Format(Messages.FeedbackMemberMuted, toMute.Mention, Utils.GetHumanizedTimeOffset(ref duration),
Utils.WrapInline(reason)), author.Mention, true); Utils.Wrap(reason)), author.Mention, true);
} }
private static async Task MuteMember(SocketGuild guild, SocketUser author, SocketGuildUser toMute, private static async Task MuteMember(SocketGuild guild, SocketUser author, SocketGuildUser toMute,
@ -88,7 +87,7 @@ public class MuteCommand : Command {
await toMute.RemoveRoleAsync(role); await toMute.RemoveRoleAsync(role);
rolesRemoved.Add(userRole.Id); rolesRemoved.Add(userRole.Id);
} catch (HttpException e) { } catch (HttpException e) {
Warn(string.Format(Messages.RoleRemovalFailed, $"<@&{userRole}>", Utils.WrapInline(e.Reason))); Warn(string.Format(Messages.RoleRemovalFailed, $"<@&{userRole}>", Utils.Wrap(e.Reason)));
} }
Boyfriend.GetRemovedRoles(guild.Id).Add(toMute.Id, rolesRemoved.AsReadOnly()); Boyfriend.GetRemovedRoles(guild.Id).Add(toMute.Id, rolesRemoved.AsReadOnly());
@ -100,8 +99,7 @@ public class MuteCommand : Command {
await UnmuteCommand.UnmuteMember(guild, guild.CurrentUser, toMute, Messages.PunishmentExpired); await UnmuteCommand.UnmuteMember(guild, guild.CurrentUser, toMute, Messages.PunishmentExpired);
} }
var task = new Task(DelayUnmute); new Task(DelayUnmute).Start();
task.Start();
} }
} }
@ -111,6 +109,7 @@ public class MuteCommand : Command {
Error(Messages.DurationRequiredForTimeOuts, false); Error(Messages.DurationRequiredForTimeOuts, false);
return; return;
} }
if (toMute.IsBot) { if (toMute.IsBot) {
Error(Messages.CannotTimeOutBot, false); Error(Messages.CannotTimeOutBot, false);
return; return;
@ -119,4 +118,4 @@ public class MuteCommand : Command {
await toMute.SetTimeOutAsync(duration, requestOptions); await toMute.SetTimeOutAsync(duration, requestOptions);
} }
} }
} }

View file

@ -5,11 +5,11 @@ using Discord.WebSocket;
namespace Boyfriend.Commands; namespace Boyfriend.Commands;
public class SettingsCommand : Command { public class SettingsCommand : Command {
public override string[] Aliases { get; } = {"settings", "config", "настройки", "конфиг"}; public override string[] Aliases { get; } = { "settings", "config", "настройки", "конфиг" };
public override int ArgsLengthRequired => 0; public override int ArgsLengthRequired => 0;
public override Task Run(SocketCommandContext context, string[] args) { public override Task Run(SocketCommandContext context, string[] args) {
var author = (SocketGuildUser) context.User; var author = (SocketGuildUser)context.User;
var permissionCheckResponse = CommandHandler.HasPermission(ref author, GuildPermission.ManageGuild); var permissionCheckResponse = CommandHandler.HasPermission(ref author, GuildPermission.ManageGuild);
if (permissionCheckResponse != "") { if (permissionCheckResponse != "") {
@ -41,7 +41,7 @@ public class SettingsCommand : Command {
if (IsBool(currentValue)) if (IsBool(currentValue))
currentValue = YesOrNo(currentValue == "true"); currentValue = YesOrNo(currentValue == "true");
else else
format = Utils.WrapInline("{0}")!; format = Utils.Wrap("{0}")!;
} }
currentSettings.Append($"{Utils.GetMessage($"Settings{setting.Key}")} (`{setting.Key}`): ") currentSettings.Append($"{Utils.GetMessage($"Settings{setting.Key}")} (`{setting.Key}`): ")
@ -56,9 +56,11 @@ public class SettingsCommand : Command {
var selectedSetting = args[0].ToLower(); var selectedSetting = args[0].ToLower();
var exists = false; var exists = false;
foreach (var setting in Boyfriend.DefaultConfig) { // ReSharper disable once ForeachCanBePartlyConvertedToQueryUsingAnotherGetEnumerator
if (selectedSetting != setting.Key.ToLower()) continue; // The performance impact is not worth it
selectedSetting = setting.Key; foreach (var setting in Boyfriend.DefaultConfig.Keys) {
if (selectedSetting != setting.ToLower()) continue;
selectedSetting = setting;
exists = true; exists = true;
break; break;
} }
@ -78,9 +80,7 @@ public class SettingsCommand : Command {
Error(Messages.InvalidSettingValue, false); Error(Messages.InvalidSettingValue, false);
return Task.CompletedTask; return Task.CompletedTask;
} }
} else { } else { value = "reset"; }
value = "reset";
}
if (IsBool(Boyfriend.DefaultConfig[selectedSetting]) && !IsBool(value)) { if (IsBool(Boyfriend.DefaultConfig[selectedSetting]) && !IsBool(value)) {
value = value switch { value = value switch {
@ -99,7 +99,7 @@ public class SettingsCommand : Command {
var mention = Utils.ParseMention(value); var mention = Utils.ParseMention(value);
if (mention != 0) value = mention.ToString(); if (mention != 0) value = mention.ToString();
var formatting = Utils.WrapInline("{0}")!; var formatting = Utils.Wrap("{0}")!;
if (selectedSetting.EndsWith("Channel")) if (selectedSetting.EndsWith("Channel"))
formatting = "<#{0}>"; formatting = "<#{0}>";
if (selectedSetting.EndsWith("Role")) if (selectedSetting.EndsWith("Role"))
@ -131,6 +131,8 @@ public class SettingsCommand : Command {
return Task.CompletedTask; return Task.CompletedTask;
} }
if (selectedSetting == "MuteRole") Utils.RemoveMuteRoleFromCache(ulong.Parse(config[selectedSetting]));
config[selectedSetting] = value; config[selectedSetting] = value;
} }
@ -153,4 +155,4 @@ public class SettingsCommand : Command {
private static bool IsBool(string value) { private static bool IsBool(string value) {
return value is "true" or "false"; return value is "true" or "false";
} }
} }

View file

@ -5,11 +5,11 @@ using Discord.WebSocket;
namespace Boyfriend.Commands; namespace Boyfriend.Commands;
public class UnbanCommand : Command { public class UnbanCommand : Command {
public override string[] Aliases { get; } = {"unban", "разбан"}; public override string[] Aliases { get; } = { "unban", "разбан" };
public override int ArgsLengthRequired => 2; public override int ArgsLengthRequired => 2;
public override async Task Run(SocketCommandContext context, string[] args) { public override async Task Run(SocketCommandContext context, string[] args) {
var author = (SocketGuildUser) context.User; var author = (SocketGuildUser)context.User;
var permissionCheckResponse = CommandHandler.HasPermission(ref author, GuildPermission.BanMembers); var permissionCheckResponse = CommandHandler.HasPermission(ref author, GuildPermission.BanMembers);
if (permissionCheckResponse != "") { if (permissionCheckResponse != "") {
@ -38,8 +38,8 @@ public class UnbanCommand : Command {
var requestOptions = Utils.GetRequestOptions($"({author}) {reason}"); var requestOptions = Utils.GetRequestOptions($"({author}) {reason}");
await guild.RemoveBanAsync(toUnban, requestOptions); await guild.RemoveBanAsync(toUnban, requestOptions);
var feedback = string.Format(Messages.FeedbackUserUnbanned, toUnban.Mention, Utils.WrapInline(reason)); var feedback = string.Format(Messages.FeedbackUserUnbanned, toUnban.Mention, Utils.Wrap(reason));
Success(feedback, author.Mention, false, false); Success(feedback, author.Mention, false, false);
await Utils.SendFeedback(feedback, guild.Id, author.Mention, true); await Utils.SendFeedback(feedback, guild.Id, author.Mention, true);
} }
} }

View file

@ -5,11 +5,11 @@ using Discord.WebSocket;
namespace Boyfriend.Commands; namespace Boyfriend.Commands;
public class UnmuteCommand : Command { public class UnmuteCommand : Command {
public override string[] Aliases { get; } = {"unmute", "размут"}; public override string[] Aliases { get; } = { "unmute", "размут" };
public override int ArgsLengthRequired => 2; public override int ArgsLengthRequired => 2;
public override async Task Run(SocketCommandContext context, string[] args) { public override async Task Run(SocketCommandContext context, string[] args) {
var author = (SocketGuildUser) context.User; var author = (SocketGuildUser)context.User;
var permissionCheckResponse = CommandHandler.HasPermission(ref author, GuildPermission.ModerateMembers); var permissionCheckResponse = CommandHandler.HasPermission(ref author, GuildPermission.ModerateMembers);
if (permissionCheckResponse != "") { if (permissionCheckResponse != "") {
@ -40,13 +40,6 @@ public class UnmuteCommand : Command {
var role = Utils.GetMuteRole(ref guild); var role = Utils.GetMuteRole(ref guild);
if (role != null) { if (role != null) {
var muted = false;
foreach (var x in toUnmute.Roles) {
if (x != role) continue;
muted = true;
break;
}
var rolesRemoved = Boyfriend.GetRemovedRoles(guild.Id); var rolesRemoved = Boyfriend.GetRemovedRoles(guild.Id);
if (rolesRemoved.ContainsKey(toUnmute.Id)) { if (rolesRemoved.ContainsKey(toUnmute.Id)) {
@ -55,9 +48,7 @@ public class UnmuteCommand : Command {
CommandHandler.ConfigWriteScheduled = true; CommandHandler.ConfigWriteScheduled = true;
} }
if (muted) { if (toUnmute.Roles.Contains(role)) { await toUnmute.RemoveRoleAsync(role, requestOptions); } else {
await toUnmute.RemoveRoleAsync(role, requestOptions);
} else {
Error(Messages.MemberNotMuted, false); Error(Messages.MemberNotMuted, false);
return; return;
} }
@ -71,7 +62,7 @@ public class UnmuteCommand : Command {
await toUnmute.RemoveTimeOutAsync(); await toUnmute.RemoveTimeOutAsync();
} }
var feedback = string.Format(Messages.FeedbackMemberUnmuted, toUnmute.Mention, Utils.WrapInline(reason)); var feedback = string.Format(Messages.FeedbackMemberUnmuted, toUnmute.Mention, Utils.Wrap(reason));
Success(feedback, author.Mention, false, false); Success(feedback, author.Mention, false, false);
await Utils.SendFeedback(feedback, guild.Id, author.Mention, true); await Utils.SendFeedback(feedback, guild.Id, author.Mention, true);
} }

View file

@ -1,6 +1,7 @@
using Boyfriend.Commands; using Boyfriend.Commands;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Discord.Rest;
using Discord.WebSocket; using Discord.WebSocket;
namespace Boyfriend; namespace Boyfriend;
@ -42,21 +43,23 @@ public class EventHandler {
Utils.SetCurrentLanguage(guild.Id); Utils.SetCurrentLanguage(guild.Id);
var mention = msg.Author.Mention;
await Task.Delay(500);
var auditLogEntry = (await guild.GetAuditLogsAsync(1).FlattenAsync()).First(); var auditLogEntry = (await guild.GetAuditLogsAsync(1).FlattenAsync()).First();
var mention = auditLogEntry.User.Mention; if (auditLogEntry.Data is MessageDeleteAuditLogData data && msg.Author.Id == data.Target.Id)
if (auditLogEntry.Action != ActionType.MessageDeleted || mention = auditLogEntry.User.Mention;
DateTimeOffset.Now.Subtract(auditLogEntry.CreatedAt).TotalMilliseconds > 500 ||
auditLogEntry.User.IsBot) mention = msg.Author.Mention;
await Utils.SendFeedback( await Utils.SendFeedback(
string.Format(Messages.CachedMessageDeleted, msg.Author.Mention, Utils.MentionChannel(channel.Id), string.Format(Messages.CachedMessageDeleted, msg.Author.Mention, Utils.MentionChannel(channel.Id),
Utils.WrapAsNeeded(msg.CleanContent)), guild.Id, mention); Utils.Wrap(msg.CleanContent)), guild.Id, mention);
} }
private static async Task MessageReceivedEvent(SocketMessage messageParam) { private static async Task MessageReceivedEvent(SocketMessage messageParam) {
if (messageParam is not SocketUserMessage message) return; if (messageParam is not SocketUserMessage message) return;
var user = (SocketGuildUser) message.Author; var user = (SocketGuildUser)message.Author;
var guild = user.Guild; var guild = user.Guild;
var guildConfig = Boyfriend.GetGuildConfig(guild.Id); var guildConfig = Boyfriend.GetGuildConfig(guild.Id);
@ -98,10 +101,12 @@ public class EventHandler {
Utils.SetCurrentLanguage(guildId); Utils.SetCurrentLanguage(guildId);
var isLimitedSpace = msg.CleanContent.Length + messageSocket.CleanContent.Length < 1940;
await Utils.SendFeedback( await Utils.SendFeedback(
string.Format(Messages.CachedMessageEdited, Utils.MentionChannel(channel.Id), string.Format(Messages.CachedMessageEdited, Utils.MentionChannel(channel.Id),
Utils.WrapAsNeeded(msg.CleanContent), Utils.WrapAsNeeded(messageSocket.Content)), guildId, Utils.Wrap(msg.CleanContent, isLimitedSpace), Utils.Wrap(messageSocket.CleanContent, isLimitedSpace)),
msg.Author.Mention); guildId, msg.Author.Mention);
} }
private static async Task UserJoinedEvent(SocketGuildUser user) { private static async Task UserJoinedEvent(SocketGuildUser user) {
@ -127,11 +132,11 @@ public class EventHandler {
if (role != null) if (role != null)
roleMention = $"{role.Mention} "; roleMention = $"{role.Mention} ";
var location = Utils.WrapInline(scheduledEvent.Location) ?? Utils.MentionChannel(scheduledEvent.Channel.Id); var location = Utils.Wrap(scheduledEvent.Location) ?? Utils.MentionChannel(scheduledEvent.Channel.Id);
await Utils.SilentSendAsync(channel, await Utils.SilentSendAsync(channel,
string.Format(Messages.EventCreated, "\n", roleMention, scheduledEvent.Creator.Mention, string.Format(Messages.EventCreated, "\n", roleMention, scheduledEvent.Creator.Mention,
Utils.WrapInline(scheduledEvent.Name), location, Utils.Wrap(scheduledEvent.Name), location,
scheduledEvent.StartTime.ToUnixTimeSeconds().ToString(), Utils.Wrap(scheduledEvent.Description)), scheduledEvent.StartTime.ToUnixTimeSeconds().ToString(), Utils.Wrap(scheduledEvent.Description)),
true); true);
} }
@ -142,7 +147,7 @@ public class EventHandler {
var eventConfig = Boyfriend.GetGuildConfig(guild.Id); var eventConfig = Boyfriend.GetGuildConfig(guild.Id);
var channel = guild.GetTextChannel(Convert.ToUInt64(eventConfig["EventCancelledChannel"])); var channel = guild.GetTextChannel(Convert.ToUInt64(eventConfig["EventCancelledChannel"]));
if (channel != null) if (channel != null)
await channel.SendMessageAsync(string.Format(Messages.EventCancelled, Utils.WrapInline(scheduledEvent.Name), await channel.SendMessageAsync(string.Format(Messages.EventCancelled, Utils.Wrap(scheduledEvent.Name),
eventConfig["FrowningFace"] == "true" ? $" {Messages.SettingsFrowningFace}" : "")); eventConfig["FrowningFace"] == "true" ? $" {Messages.SettingsFrowningFace}" : ""));
} }
@ -158,12 +163,12 @@ public class EventHandler {
if (receivers.Contains("role") && role != null) mentions.Append($"{role.Mention} "); if (receivers.Contains("role") && role != null) mentions.Append($"{role.Mention} ");
if (receivers.Contains("users") || receivers.Contains("interested")) if (receivers.Contains("users") || receivers.Contains("interested"))
foreach (var user in await scheduledEvent.GetUsersAsync(15)) mentions = (await scheduledEvent.GetUsersAsync(15)).Aggregate(mentions,
mentions = mentions.Append($"{user.Mention} "); (current, user) => current.Append($"{user.Mention} "));
await channel.SendMessageAsync(string.Format(Messages.EventStarted, mentions, await channel.SendMessageAsync(string.Format(Messages.EventStarted, mentions,
Utils.WrapInline(scheduledEvent.Name), Utils.Wrap(scheduledEvent.Name),
Utils.WrapInline(scheduledEvent.Location) ?? Utils.MentionChannel(scheduledEvent.Channel.Id))); Utils.Wrap(scheduledEvent.Location) ?? Utils.MentionChannel(scheduledEvent.Channel.Id)));
mentions.Clear(); mentions.Clear();
} }
} }
@ -173,7 +178,7 @@ public class EventHandler {
var eventConfig = Boyfriend.GetGuildConfig(guild.Id); var eventConfig = Boyfriend.GetGuildConfig(guild.Id);
var channel = guild.GetTextChannel(Convert.ToUInt64(eventConfig["EventCompletedChannel"])); var channel = guild.GetTextChannel(Convert.ToUInt64(eventConfig["EventCompletedChannel"]));
if (channel != null) if (channel != null)
await channel.SendMessageAsync(string.Format(Messages.EventCompleted, Utils.WrapInline(scheduledEvent.Name), await channel.SendMessageAsync(string.Format(Messages.EventCompleted, Utils.Wrap(scheduledEvent.Name),
Utils.WrapInline(scheduledEvent.StartTime.Subtract(DateTimeOffset.Now).Negate().ToString()))); Utils.Wrap(scheduledEvent.StartTime.Subtract(DateTimeOffset.Now).Negate().ToString())));
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -297,4 +297,7 @@
<data name="CommandDescriptionUnmute" xml:space="preserve"> <data name="CommandDescriptionUnmute" xml:space="preserve">
<value>Unmutes a member</value> <value>Unmutes a member</value>
</data> </data>
<data name="ReasonRequired" xml:space="preserve">
<value>You must specify a reason!</value>
</data>
</root> </root>

View file

@ -288,4 +288,7 @@
<data name="CommandDescriptionUnmute" xml:space="preserve"> <data name="CommandDescriptionUnmute" xml:space="preserve">
<value>Разглушает участника</value> <value>Разглушает участника</value>
</data> </data>
<data name="ReasonRequired" xml:space="preserve">
<value>Требуется указать причину!</value>
</data>
</root> </root>

View file

@ -10,7 +10,6 @@ using Humanizer.Localisation;
namespace Boyfriend; namespace Boyfriend;
public static class Utils { public static class Utils {
private static readonly string[] Formats = { private static readonly string[] Formats = {
"%d'd'%h'h'%m'm'%s's'", "%d'd'%h'h'%m'm'", "%d'd'%h'h'%s's'", "%d'd'%h'h'", "%d'd'%m'm'%s's'", "%d'd'%m'm'", "%d'd'%h'h'%m'm'%s's'", "%d'd'%h'h'%m'm'", "%d'd'%h'h'%s's'", "%d'd'%h'h'", "%d'd'%m'm'%s's'", "%d'd'%m'm'",
"%d'd'%s's'", "%d'd'", "%h'h'%m'm'%s's'", "%h'h'%m'm'", "%h'h'%s's'", "%h'h'", "%m'm'%s's'", "%m'm'", "%s's'", "%d'd'%s's'", "%d'd'", "%h'h'%m'm'%s's'", "%h'h'%m'm'", "%h'h'%s's'", "%h'h'", "%m'm'%s's'", "%m'm'", "%s's'",
@ -21,10 +20,12 @@ public static class Utils {
public static readonly Random Random = new(); public static readonly Random Random = new();
private static readonly Dictionary<string, string> ReflectionMessageCache = new(); private static readonly Dictionary<string, string> ReflectionMessageCache = new();
private static readonly Dictionary<string, CultureInfo> CultureInfoCache = new() { private static readonly Dictionary<string, CultureInfo> CultureInfoCache = new() {
{"ru", new CultureInfo("ru-RU")}, { "ru", new CultureInfo("ru-RU") },
{"en", new CultureInfo("en-US")} { "en", new CultureInfo("en-US") }
}; };
private static readonly Dictionary<ulong, SocketRole> MuteRoleCache = new(); private static readonly Dictionary<ulong, SocketRole> MuteRoleCache = new();
private static readonly AllowedMentions AllowRoles = new() { private static readonly AllowedMentions AllowRoles = new() {
@ -40,19 +41,12 @@ public static class Utils {
.GetTextChannel(ParseMention(Boyfriend.GetGuildConfig(id)["AdminLogChannel"])); .GetTextChannel(ParseMention(Boyfriend.GetGuildConfig(id)["AdminLogChannel"]));
} }
public static string Wrap(string? original) { public static string? Wrap(string? original, bool limitedSpace = false) {
if (original == null) return "";
var toReturn = original.Replace("```", "ˋˋˋ");
return $"```{toReturn}{(toReturn.EndsWith("`") || toReturn.Trim().Equals("") ? " " : "")}```";
}
public static string? WrapInline(string? original) {
return original == null ? null : $"`{original.Replace("`", "ˋ")}`";
}
public static string? WrapAsNeeded(string? original) {
if (original == null) return null; if (original == null) return null;
return original.Contains('\n') ? Wrap(original) : WrapInline(original); var maxChars = limitedSpace ? 970 : 1940;
if (original.Length > maxChars) original = original[..maxChars];
var style = original.Contains('\n') ? "```" : "`";
return $"{style}{original}{(original.Equals("") ? " " : "")}{style}";
} }
public static string MentionChannel(ulong id) { public static string MentionChannel(ulong id) {
@ -73,9 +67,7 @@ public static class Utils {
} }
public static async Task SendDirectMessage(SocketUser user, string toSend) { public static async Task SendDirectMessage(SocketUser user, string toSend) {
try { try { await user.SendMessageAsync(toSend); } catch (HttpException e) {
await user.SendMessageAsync(toSend);
} catch (HttpException e) {
if (e.DiscordCode != DiscordErrorCode.CannotSendMessageToUser) if (e.DiscordCode != DiscordErrorCode.CannotSendMessageToUser)
throw; throw;
} }
@ -91,14 +83,21 @@ public static class Utils {
MuteRoleCache.Add(id, role); MuteRoleCache.Add(id, role);
break; break;
} }
return role; return role;
} }
public static void RemoveMuteRoleFromCache(ulong id) {
if (MuteRoleCache.ContainsKey(id)) MuteRoleCache.Remove(id);
}
public static async Task SilentSendAsync(SocketTextChannel? channel, string text, bool allowRoles = false) { public static async Task SilentSendAsync(SocketTextChannel? channel, string text, bool allowRoles = false) {
if (channel == null || text.Length is 0 or > 2000) return; if (channel == null || text.Length is 0 or > 2000)
throw new Exception($"Message length is out of range: {text.Length}");
await channel.SendMessageAsync(text, false, null, null, allowRoles ? AllowRoles : AllowedMentions.None); await channel.SendMessageAsync(text, false, null, null, allowRoles ? AllowRoles : AllowedMentions.None);
} }
public static TimeSpan? GetTimeSpan(ref string from) { public static TimeSpan? GetTimeSpan(ref string from) {
if (TimeSpan.TryParseExact(from.ToLowerInvariant(), Formats, CultureInfo.InvariantCulture, out var timeSpan)) if (TimeSpan.TryParseExact(from.ToLowerInvariant(), Formats, CultureInfo.InvariantCulture, out var timeSpan))
return timeSpan; return timeSpan;
@ -122,7 +121,7 @@ public static class Utils {
var toReturn = var toReturn =
typeof(Messages).GetProperty(propertyName, BindingFlags.NonPublic | BindingFlags.Static)?.GetValue(null) typeof(Messages).GetProperty(propertyName, BindingFlags.NonPublic | BindingFlags.Static)?.GetValue(null)
?.ToString()! ?? throw new Exception($"Could not find localized property: {name}"); ?.ToString()! ?? throw new Exception($"Could not find localized property: {propertyName}");
ReflectionMessageCache.Add(name, toReturn); ReflectionMessageCache.Add(name, toReturn);
return toReturn; return toReturn;
} }
@ -144,11 +143,12 @@ public static class Utils {
} }
public static string GetHumanizedTimeOffset(ref TimeSpan span) { public static string GetHumanizedTimeOffset(ref TimeSpan span) {
return span.TotalSeconds > 0 ? $" {span.Humanize(minUnit: TimeUnit.Second, culture: Messages.Culture)}" return span.TotalSeconds > 0
? $" {span.Humanize(minUnit: TimeUnit.Second, culture: Messages.Culture)}"
: Messages.Ever; : Messages.Ever;
} }
public static void SetCurrentLanguage(ulong guildId) { public static void SetCurrentLanguage(ulong guildId) {
Messages.Culture = CultureInfoCache[Boyfriend.GetGuildConfig(guildId)["Lang"]]; Messages.Culture = CultureInfoCache[Boyfriend.GetGuildConfig(guildId)["Lang"]];
} }
} }