Guild blacklist implementation

This commit is contained in:
Octol1ttle 2022-10-18 22:55:16 +05:00
parent e767205c1a
commit c0ae850fb8
Signed by: Octol1ttle
GPG key ID: B77C34313AEE1FFF
9 changed files with 843 additions and 789 deletions

View file

@ -60,7 +60,7 @@ public static class Boyfriend {
await Client.StartAsync(); await Client.StartAsync();
await Client.SetActivityAsync(Activity); await Client.SetActivityAsync(Activity);
new EventHandler().InitEvents(); EventHandler.InitEvents();
await Task.Delay(-1); await Task.Delay(-1);
} }
@ -128,10 +128,13 @@ 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) {
if (guild.Channels.All(x => x.Id != channel)) continue; // ReSharper disable once LoopCanBeConvertedToQuery
foreach (var x in guild.Channels)
if (x.Id == channel) {
GuildCache.Add(channel, guild); GuildCache.Add(channel, guild);
return guild; return guild;
} }
}
throw new Exception("Could not find guild by channel!"); throw new Exception("Could not find guild by channel!");
} }

View file

@ -24,7 +24,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Discord.Net" Version="3.8.0"/> <PackageReference Include="Discord.Net" Version="3.8.1"/>
<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"/>
</ItemGroup> </ItemGroup>

View file

@ -29,6 +29,7 @@ public sealed class CommandProcessor {
private readonly List<Task> _tasks = new(); private readonly List<Task> _tasks = new();
public readonly SocketCommandContext Context; public readonly SocketCommandContext Context;
private bool _serverBlacklisted;
public bool ConfigWriteScheduled = false; public bool ConfigWriteScheduled = false;
@ -56,6 +57,11 @@ public sealed class CommandProcessor {
var cleanList = Context.Message.CleanContent.Split("\n"); var cleanList = Context.Message.CleanContent.Split("\n");
for (var i = 0; i < list.Length; i++) { for (var i = 0; i < list.Length; i++) {
RunCommandOnLine(list[i], cleanList[i], regex); RunCommandOnLine(list[i], cleanList[i], regex);
if (_serverBlacklisted) {
await Context.Message.ReplyAsync(Messages.ServerBlacklisted);
return;
}
if (_stackedReplyMessage.Length > 0) _ = Context.Channel.TriggerTypingAsync(); if (_stackedReplyMessage.Length > 0) _ = Context.Channel.TriggerTypingAsync();
var member = Boyfriend.Client.GetGuild(Context.Guild.Id) var member = Boyfriend.Client.GetGuild(Context.Guild.Id)
.GetUser(Context.User.Id); // Getting an up-to-date copy .GetUser(Context.User.Id); // Getting an up-to-date copy
@ -79,6 +85,10 @@ public sealed class CommandProcessor {
if (lineNoMention == line if (lineNoMention == line
|| !command.Aliases.Contains(lineNoMention.Trim().ToLower().Split()[0])) || !command.Aliases.Contains(lineNoMention.Trim().ToLower().Split()[0]))
continue; continue;
if (Utils.IsServerBlacklisted(Context.Guild)) {
_serverBlacklisted = true;
return;
}
var args = line.Split().Skip(lineNoMention.StartsWith(" ") ? 2 : 1).ToArray(); var args = line.Split().Skip(lineNoMention.StartsWith(" ") ? 2 : 1).ToArray();
var cleanArgs = cleanLine.Split().Skip(lineNoMention.StartsWith(" ") ? 2 : 1).ToArray(); var cleanArgs = cleanLine.Split().Skip(lineNoMention.StartsWith(" ") ? 2 : 1).ToArray();

View file

@ -1,7 +1,7 @@
namespace Boyfriend.Commands; namespace Boyfriend.Commands;
public sealed class SelfBanCommand : ICommand { public sealed class SelfBanCommand : ICommand {
public string[] Aliases { get; } = { "grantoverseer", "grant", "overseer", "voooo", "overseergrant", "special" }; public string[] Aliases { get; } = { "cavepleaselisten" };
public async Task RunAsync(CommandProcessor cmd, string[] args, string[] cleanArgs) { public async Task RunAsync(CommandProcessor cmd, string[] args, string[] cleanArgs) {
await BanCommand.BanUser(cmd, cmd.Context.User, TimeSpan.FromMilliseconds(-1), ""); await BanCommand.BanUser(cmd, cmd.Context.User, TimeSpan.FromMilliseconds(-1), "");

View file

@ -1,36 +1,42 @@
using Boyfriend.Commands; using Discord;
using Discord;
using Discord.Rest; using Discord.Rest;
using Discord.WebSocket; using Discord.WebSocket;
using Humanizer;
namespace Boyfriend; namespace Boyfriend;
public sealed class EventHandler { public static class EventHandler {
private readonly DiscordSocketClient _client = Boyfriend.Client; private static readonly DiscordSocketClient Client = Boyfriend.Client;
private static bool _sendReadyMessages = true;
public void InitEvents() { public static void InitEvents() {
_client.Ready += ReadyEvent; Client.Ready += ReadyEvent;
_client.MessageDeleted += MessageDeletedEvent; Client.MessageDeleted += MessageDeletedEvent;
_client.MessageReceived += MessageReceivedEvent; Client.MessageReceived += MessageReceivedEvent;
_client.MessageUpdated += MessageUpdatedEvent; Client.MessageUpdated += MessageUpdatedEvent;
_client.UserJoined += UserJoinedEvent; Client.UserJoined += UserJoinedEvent;
_client.GuildScheduledEventCreated += ScheduledEventCreatedEvent; Client.GuildScheduledEventCreated += ScheduledEventCreatedEvent;
_client.GuildScheduledEventCancelled += ScheduledEventCancelledEvent; Client.GuildScheduledEventCancelled += ScheduledEventCancelledEvent;
_client.GuildScheduledEventStarted += ScheduledEventStartedEvent; Client.GuildScheduledEventStarted += ScheduledEventStartedEvent;
_client.GuildScheduledEventCompleted += ScheduledEventCompletedEvent; Client.GuildScheduledEventCompleted += ScheduledEventCompletedEvent;
} }
private static async Task ReadyEvent() { private static Task ReadyEvent() {
if (!_sendReadyMessages) return Task.CompletedTask;
var i = Utils.Random.Next(3); var i = Utils.Random.Next(3);
foreach (var guild in Boyfriend.Client.Guilds) { foreach (var guild in Client.Guilds) {
var config = Boyfriend.GetGuildConfig(guild.Id); var config = Boyfriend.GetGuildConfig(guild.Id);
var channel = guild.GetTextChannel(Convert.ToUInt64(config["BotLogChannel"])); var channel = guild.GetTextChannel(Convert.ToUInt64(config["BotLogChannel"]));
Utils.SetCurrentLanguage(guild.Id); Utils.SetCurrentLanguage(guild.Id);
if (config["ReceiveStartupMessages"] is not "true" || channel == null) continue; if (config["ReceiveStartupMessages"] is not "true" || channel == null ||
await channel.SendMessageAsync(string.Format(Messages.Ready, Utils.GetBeep(i))); Utils.IsServerBlacklisted(guild)) continue;
_ = channel.SendMessageAsync(string.Format(Messages.Ready, Utils.GetBeep(i)));
} }
_sendReadyMessages = false;
return Task.CompletedTask;
} }
private static async Task MessageDeletedEvent(Cacheable<IMessage, ulong> message, private static async Task MessageDeletedEvent(Cacheable<IMessage, ulong> message,
@ -39,6 +45,7 @@ public sealed class EventHandler {
if (msg is null or ISystemMessage || msg.Author.IsBot) return; if (msg is null or ISystemMessage || msg.Author.IsBot) return;
var guild = Boyfriend.FindGuild(channel.Value.Id); var guild = Boyfriend.FindGuild(channel.Value.Id);
if (Utils.IsServerBlacklisted(guild)) return;
Utils.SetCurrentLanguage(guild.Id); Utils.SetCurrentLanguage(guild.Id);
@ -62,13 +69,6 @@ public sealed class EventHandler {
Utils.SetCurrentLanguage(guild.Id); Utils.SetCurrentLanguage(guild.Id);
if ((message.MentionedUsers.Count > 3 || message.MentionedRoles.Count > 2) &&
!user.GuildPermissions.MentionEveryone) {
await BanCommand.BanUser(new CommandProcessor(message), user, TimeSpan.FromMilliseconds(-1),
Messages.AutobanReason);
return;
}
var prev = ""; var prev = "";
var prevFailsafe = ""; var prevFailsafe = "";
var prevs = await message.Channel.GetMessagesAsync(3).FlattenAsync(); var prevs = await message.Channel.GetMessagesAsync(3).FlattenAsync();
@ -92,20 +92,22 @@ public sealed class EventHandler {
if (msg is null or ISystemMessage || msg.CleanContent == messageSocket.CleanContent || msg.Author.IsBot) return; if (msg is null or ISystemMessage || msg.CleanContent == messageSocket.CleanContent || msg.Author.IsBot) return;
var guildId = Boyfriend.FindGuild(channel.Id).Id; var guild = Boyfriend.FindGuild(channel.Id);
if (Utils.IsServerBlacklisted(guild)) return;
Utils.SetCurrentLanguage(guildId); Utils.SetCurrentLanguage(guild.Id);
var isLimitedSpace = msg.CleanContent.Length + messageSocket.CleanContent.Length < 1940; var isLimitedSpace = msg.CleanContent.Length + messageSocket.CleanContent.Length < 1940;
await Utils.SendFeedbackAsync( await Utils.SendFeedbackAsync(
string.Format(Messages.CachedMessageEdited, Utils.MentionChannel(channel.Id), string.Format(Messages.CachedMessageEdited, Utils.MentionChannel(channel.Id),
Utils.Wrap(msg.CleanContent, isLimitedSpace), Utils.Wrap(messageSocket.CleanContent, isLimitedSpace)), Utils.Wrap(msg.CleanContent, isLimitedSpace), Utils.Wrap(messageSocket.CleanContent, isLimitedSpace)),
guildId, msg.Author.Mention); guild.Id, msg.Author.Mention);
} }
private static async Task UserJoinedEvent(SocketGuildUser user) { private static async Task UserJoinedEvent(SocketGuildUser user) {
var guild = user.Guild; var guild = user.Guild;
if (Utils.IsServerBlacklisted(guild)) return;
var config = Boyfriend.GetGuildConfig(guild.Id); var config = Boyfriend.GetGuildConfig(guild.Id);
if (config["SendWelcomeMessages"] is "true") if (config["SendWelcomeMessages"] is "true")
@ -118,6 +120,7 @@ public sealed class EventHandler {
private static async Task ScheduledEventCreatedEvent(SocketGuildEvent scheduledEvent) { private static async Task ScheduledEventCreatedEvent(SocketGuildEvent scheduledEvent) {
var guild = scheduledEvent.Guild; var guild = scheduledEvent.Guild;
if (Utils.IsServerBlacklisted(guild)) return;
var eventConfig = Boyfriend.GetGuildConfig(guild.Id); var eventConfig = Boyfriend.GetGuildConfig(guild.Id);
var channel = guild.GetTextChannel(Convert.ToUInt64(eventConfig["EventCreatedChannel"])); var channel = guild.GetTextChannel(Convert.ToUInt64(eventConfig["EventCreatedChannel"]));
@ -139,6 +142,7 @@ public sealed class EventHandler {
private static async Task ScheduledEventCancelledEvent(SocketGuildEvent scheduledEvent) { private static async Task ScheduledEventCancelledEvent(SocketGuildEvent scheduledEvent) {
var guild = scheduledEvent.Guild; var guild = scheduledEvent.Guild;
if (Utils.IsServerBlacklisted(guild)) return;
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)
@ -148,6 +152,7 @@ public sealed class EventHandler {
private static async Task ScheduledEventStartedEvent(SocketGuildEvent scheduledEvent) { private static async Task ScheduledEventStartedEvent(SocketGuildEvent scheduledEvent) {
var guild = scheduledEvent.Guild; var guild = scheduledEvent.Guild;
if (Utils.IsServerBlacklisted(guild)) return;
var eventConfig = Boyfriend.GetGuildConfig(guild.Id); var eventConfig = Boyfriend.GetGuildConfig(guild.Id);
var channel = guild.GetTextChannel(Convert.ToUInt64(eventConfig["EventStartedChannel"])); var channel = guild.GetTextChannel(Convert.ToUInt64(eventConfig["EventStartedChannel"]));
@ -170,10 +175,11 @@ public sealed class EventHandler {
private static async Task ScheduledEventCompletedEvent(SocketGuildEvent scheduledEvent) { private static async Task ScheduledEventCompletedEvent(SocketGuildEvent scheduledEvent) {
var guild = scheduledEvent.Guild; var guild = scheduledEvent.Guild;
if (Utils.IsServerBlacklisted(guild)) return;
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.Wrap(scheduledEvent.Name), await channel.SendMessageAsync(string.Format(Messages.EventCompleted, Utils.Wrap(scheduledEvent.Name),
Utils.Wrap(scheduledEvent.StartTime.Subtract(DateTimeOffset.Now).Negate().ToString()))); Utils.Wrap(scheduledEvent.StartTime.Subtract(DateTimeOffset.Now).Negate().Humanize())));
} }
} }

View file

@ -248,6 +248,15 @@ namespace Boyfriend {
} }
} }
/// <summary>
/// Looks up a localized string similar to We do not support hate towards our fellow members. And sometimes, we are not able to ban the offender..
/// </summary>
internal static string CommandDescriptionCavepleaselisten {
get {
return ResourceManager.GetString("CommandDescriptionCavepleaselisten", resourceCulture);
}
}
/// <summary> /// <summary>
/// Looks up a localized string similar to Deletes a specified amount of messages in this channel. /// Looks up a localized string similar to Deletes a specified amount of messages in this channel.
/// </summary> /// </summary>
@ -285,7 +294,7 @@ namespace Boyfriend {
} }
/// <summary> /// <summary>
/// Looks up a localized string similar to Shows latency to Discord servers (not counting local processing time). /// Looks up a localized string similar to Shows (inaccurate) latency.
/// </summary> /// </summary>
internal static string CommandDescriptionPing { internal static string CommandDescriptionPing {
get { get {
@ -707,6 +716,15 @@ namespace Boyfriend {
} }
} }
/// <summary>
/// Looks up a localized string similar to This feature is unavailable because this guild is currently blacklisted..
/// </summary>
internal static string ServerBlacklisted {
get {
return ResourceManager.GetString("ServerBlacklisted", resourceCulture);
}
}
/// <summary> /// <summary>
/// Looks up a localized string similar to That setting doesn&apos;t exist!. /// Looks up a localized string similar to That setting doesn&apos;t exist!.
/// </summary> /// </summary>

View file

@ -244,7 +244,7 @@
<value>Mutes a member</value> <value>Mutes a member</value>
</data> </data>
<data name="CommandDescriptionPing" xml:space="preserve"> <data name="CommandDescriptionPing" xml:space="preserve">
<value>Shows latency to Discord servers (not counting local processing time)</value> <value>Shows (inaccurate) latency</value>
</data> </data>
<data name="CommandDescriptionSettings" xml:space="preserve"> <data name="CommandDescriptionSettings" xml:space="preserve">
<value>Allows you to change certain preferences for this guild</value> <value>Allows you to change certain preferences for this guild</value>
@ -378,4 +378,10 @@
<data name="UserCannotUnmuteTarget" xml:space="preserve"> <data name="UserCannotUnmuteTarget" xml:space="preserve">
<value>You cannot unmute this user!</value> <value>You cannot unmute this user!</value>
</data> </data>
<data name="CommandDescriptionCavepleaselisten" xml:space="preserve">
<value>We do not support hate towards our fellow members. And sometimes, we are not able to ban the offender.</value>
</data>
<data name="ServerBlacklisted" xml:space="preserve">
<value>This feature is unavailable because this guild is currently blacklisted.</value>
</data>
</root> </root>

View file

@ -235,7 +235,7 @@
<value>Глушит участника</value> <value>Глушит участника</value>
</data> </data>
<data name="CommandDescriptionPing" xml:space="preserve"> <data name="CommandDescriptionPing" xml:space="preserve">
<value>Показывает задержку до серверов Discord (не считая времени на локальные вычисления)</value> <value>Показывает (неточную) задержку</value>
</data> </data>
<data name="CommandDescriptionSettings" xml:space="preserve"> <data name="CommandDescriptionSettings" xml:space="preserve">
<value>Позволяет менять некоторые настройки под этот сервер</value> <value>Позволяет менять некоторые настройки под этот сервер</value>
@ -369,4 +369,10 @@
<data name="BotCannotUnmuteTarget" xml:space="preserve"> <data name="BotCannotUnmuteTarget" xml:space="preserve">
<value>Я не могу вернуть из мута этого пользователя!</value> <value>Я не могу вернуть из мута этого пользователя!</value>
</data> </data>
<data name="CommandDescriptionCavepleaselisten" xml:space="preserve">
<value>Мы не поддерживаем ненависть против участников. И иногда, мы не способны забанить нарушителя.</value>
</data>
<data name="ServerBlacklisted" xml:space="preserve">
<value>Эта функция недоступна потому что этот сервер находится в чёрном списке.</value>
</data>
</root> </root>

View file

@ -162,4 +162,9 @@ public static class Utils {
await Task.Delay(duration); await Task.Delay(duration);
await UnmuteCommand.UnmuteMemberAsync(cmd, muted, reason); await UnmuteCommand.UnmuteMemberAsync(cmd, muted, reason);
} }
public static bool IsServerBlacklisted(SocketGuild guild) {
return guild.GetUser(196160375593369600) != null && guild.OwnerId != 326642240229474304 &&
guild.OwnerId != 504343489664909322;
}
} }