From 8644f70b14592d8ffd50235f6f172cfc964ee1b9 Mon Sep 17 00:00:00 2001 From: l1ttleO Date: Tue, 7 Dec 2021 23:27:27 +0500 Subject: [PATCH] tired --- Boyfriend/Boyfriend.cs | 17 ++++--- Boyfriend/CommandHandler.cs | 29 ------------ Boyfriend/Commands/BanModule.cs | 26 +++++++++++ Boyfriend/Commands/PingModule.cs | 2 + Boyfriend/Commands/Unban.cs | 23 ++++++++++ Boyfriend/EventHandler.cs | 79 ++++++++++++++++++++++++++++++++ Boyfriend/Utils.cs | 19 +++++++- 7 files changed, 158 insertions(+), 37 deletions(-) delete mode 100644 Boyfriend/CommandHandler.cs create mode 100644 Boyfriend/Commands/BanModule.cs create mode 100644 Boyfriend/Commands/Unban.cs create mode 100644 Boyfriend/EventHandler.cs diff --git a/Boyfriend/Boyfriend.cs b/Boyfriend/Boyfriend.cs index 89853d8..cea4da0 100644 --- a/Boyfriend/Boyfriend.cs +++ b/Boyfriend/Boyfriend.cs @@ -2,21 +2,24 @@ using Discord.WebSocket; namespace Boyfriend; - public class Boyfriend { + public static class Boyfriend { - public static void Main(string[] args) - => new Boyfriend().MainAsync().GetAwaiter().GetResult(); + public static void Main() + => Init().GetAwaiter().GetResult(); - public static readonly DiscordSocketClient Client = new(); + private static readonly DiscordSocketConfig Config = new() { + MessageCacheSize = 250 + }; + public static readonly DiscordSocketClient Client = new(Config); - private async Task MainAsync() { + private static async Task Init() { Client.Log += Log; - var token = File.ReadAllText("token.txt").Trim(); + var token = (await File.ReadAllTextAsync("token.txt")).Trim(); await Client.LoginAsync(TokenType.Bot, token); await Client.StartAsync(); - await new CommandHandler().InstallCommandsAsync(); + await new EventHandler().InitEvents(); await Task.Delay(-1); } diff --git a/Boyfriend/CommandHandler.cs b/Boyfriend/CommandHandler.cs deleted file mode 100644 index 5f000ba..0000000 --- a/Boyfriend/CommandHandler.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System.Reflection; -using Discord.Commands; -using Discord.WebSocket; - -namespace Boyfriend; - -public class CommandHandler { - private readonly DiscordSocketClient _client = Boyfriend.Client; - private readonly CommandService _commands = new CommandService(); - - public async Task InstallCommandsAsync() { - _client.MessageReceived += HandleCommandAsync; - await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), null); - } - - private async Task HandleCommandAsync(SocketMessage messageParam) { - if (messageParam is not SocketUserMessage message) return; - var argPos = 0; - - if (!(message.HasCharPrefix('!', ref argPos) || - message.HasMentionPrefix(_client.CurrentUser, ref argPos)) || - message.Author.IsBot) - return; - - var context = new SocketCommandContext(_client, message); - - await _commands.ExecuteAsync(context, argPos, null); - } -} \ No newline at end of file diff --git a/Boyfriend/Commands/BanModule.cs b/Boyfriend/Commands/BanModule.cs new file mode 100644 index 0000000..973059f --- /dev/null +++ b/Boyfriend/Commands/BanModule.cs @@ -0,0 +1,26 @@ +using Discord; +using Discord.Commands; +// ReSharper disable UnusedType.Global +// ReSharper disable UnusedMember.Global + +namespace Boyfriend.Commands; + +public class BanModule : ModuleBase { + + [Command("ban")] + [Summary("Банит пользователя")] + [Alias("бан")] + public async Task Run(IUser toBan, TimeSpan duration, [Remainder]string reason) + => await BanUser(Context.Guild, Context.User, toBan, duration, reason); + + public async void BanUser(IGuild guild, IUser author, IUser toBan, TimeSpan duration, string reason = "") { + var authorMention = author.Mention; + await toBan.SendMessageAsync("Тебя забанил " + authorMention + " за " + reason); + await guild.AddBanAsync(toBan, 0, reason); + await guild.GetSystemChannelAsync().Result.SendMessageAsync(authorMention + " банит " + toBan.Mention + " за " + + reason); + var banTimer = new System.Timers.Timer(duration.Milliseconds); + banTimer.Elapsed += UnbanModule.UnbanUser(guild, author, toBan, "Время наказания истекло").; + banTimer.Start(); + } +} \ No newline at end of file diff --git a/Boyfriend/Commands/PingModule.cs b/Boyfriend/Commands/PingModule.cs index c818ee2..39d0ad7 100644 --- a/Boyfriend/Commands/PingModule.cs +++ b/Boyfriend/Commands/PingModule.cs @@ -1,4 +1,6 @@ using Discord.Commands; +// ReSharper disable UnusedType.Global +// ReSharper disable UnusedMember.Global namespace Boyfriend.Commands; diff --git a/Boyfriend/Commands/Unban.cs b/Boyfriend/Commands/Unban.cs new file mode 100644 index 0000000..0ef4361 --- /dev/null +++ b/Boyfriend/Commands/Unban.cs @@ -0,0 +1,23 @@ +using Discord; +using Discord.Commands; +// ReSharper disable UnusedType.Global +// ReSharper disable UnusedMember.Global + +namespace Boyfriend.Commands; + +public class UnbanModule : ModuleBase { + + [Command("unban")] + [Summary("Возвращает пользователя из бана")] + [Alias("разбан")] + public async Task Run(IUser toBan, TimeSpan duration, [Remainder]string reason) + => await UnbanUser(Context.Guild, Context.User, toBan, reason); + + public async Task UnbanUser(IGuild guild, IUser author, IUser toBan, string reason = "") { + var authorMention = author.Mention; + await toBan.SendMessageAsync("Тебя разбанил " + authorMention + " за " + reason); + await guild.RemoveBanAsync(toBan); + await guild.GetSystemChannelAsync().Result.SendMessageAsync(authorMention + " возвращает из бана " + + toBan.Mention + " за " + reason); + } +} \ No newline at end of file diff --git a/Boyfriend/EventHandler.cs b/Boyfriend/EventHandler.cs new file mode 100644 index 0000000..95d970b --- /dev/null +++ b/Boyfriend/EventHandler.cs @@ -0,0 +1,79 @@ +using System.Reflection; +using Boyfriend.Commands; +using Discord; +using Discord.Commands; +using Discord.WebSocket; + +namespace Boyfriend; + +public class EventHandler { + private readonly DiscordSocketClient _client = Boyfriend.Client; + private readonly CommandService _commands = new(); + + public async Task InitEvents() { + _client.Ready += ReadyEvent; + _client.MessageDeleted += MessageDeletedEvent; + _client.MessageReceived += MessageReceivedEvent; + _client.MessageUpdated += MessageUpdatedEvent; + _client.UserJoined += UserJoinedEvent; + await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), null); + } + + [Obsolete("Stop hard-coding things!")] + private async Task ReadyEvent() { + if (_client.GetChannel(618044439939645444) is not IMessageChannel botLogChannel) + throw new ArgumentException("Invalid bot log channel"); + await botLogChannel.SendMessageAsync(Utils.GetBeep() + + "Я запустился! (C#)"); + } + + private static async Task MessageDeletedEvent(Cacheable message, ISocketMessageChannel channel) { + var msg = message.Value; + string toSend; + if (msg == null) + toSend = "Удалено сообщение в канале " + Utils.MentionChannel(channel.Id) + ", но я забыл что там было"; + else + toSend = "Удалено сообщение от " + msg.Author.Mention + " в канале " + Utils.MentionChannel(channel.Id) + + ": " + Utils.Wrap(msg.Content); + await Utils.GetAdminLogChannel().SendMessageAsync(toSend); + } + + private async Task MessageReceivedEvent(SocketMessage messageParam) { + if (messageParam is not SocketUserMessage {Author: IGuildUser user} message) return; + var argPos = 0; + var guild = user.Guild; + + if ((message.MentionedUsers.Count > 3 || message.MentionedRoles.Count > 2) + && !user.GuildPermissions.MentionEveryone) + await new BanModule().BanUser(guild, guild.GetCurrentUserAsync().Result, user, TimeSpan.Zero, + "Более 3-ёх упоминаний в одном сообщении"); + + if (!(message.HasCharPrefix('!', ref argPos) || message.HasMentionPrefix(_client.CurrentUser, ref argPos)) || + message.Author.IsBot) + return; + + var context = new SocketCommandContext(_client, message); + + await _commands.ExecuteAsync(context, argPos, null); + } + + private static async Task MessageUpdatedEvent(Cacheable messageCached, SocketMessage messageSocket, + ISocketMessageChannel channel) { + var msg = messageCached.Value; + string toSend; + if (msg == null) + toSend = "Отредактировано сообщение в канале " + + Utils.MentionChannel(channel.Id) + ", но я забыл что там было до редактирования: " + + Utils.Wrap(messageSocket.Content); + else + toSend = "Отредактировано сообщение от " + msg.Author.Mention + " в канале " + + Utils.MentionChannel(channel.Id) + ": " + Utils.Wrap(msg.Content) + + Utils.Wrap(messageSocket.Content); + await Utils.GetAdminLogChannel().SendMessageAsync(toSend); + } + + private static async Task UserJoinedEvent(SocketGuildUser user) { + await user.Guild.SystemChannel.SendMessageAsync(user.Mention + ", добро пожаловать на сервер " + + user.Guild.Name); + } +} \ No newline at end of file diff --git a/Boyfriend/Utils.cs b/Boyfriend/Utils.cs index 6b6524b..29dec57 100644 --- a/Boyfriend/Utils.cs +++ b/Boyfriend/Utils.cs @@ -1,8 +1,25 @@ -namespace Boyfriend; +using Discord; + +namespace Boyfriend; public static class Utils { public static string GetBeep() { var letters = new[] { "а", "о", "и"}; return "Б" + letters[new Random().Next(3)] + "п! "; } + + [Obsolete("Stop hard-coding things!")] + public static IMessageChannel GetAdminLogChannel() { + if (Boyfriend.Client.GetChannel(870929165141032971) is not IMessageChannel adminLogChannel) + throw new ArgumentException("Invalid admin log channel"); + return adminLogChannel; + } + + public static string Wrap(string original) { + return original.Trim().Equals("") ? "" : "```" + original.Replace("```", "​`​`​`​") + "```"; + } + + public static string MentionChannel(ulong id) { + return "<#" + id + ">"; + } } \ No newline at end of file