1
0
Fork 1
mirror of https://github.com/TeamOctolings/Octobot.git synced 2025-05-04 21:16:29 +03:00

now fully configurable :D

This commit is contained in:
l1ttleO 2021-12-16 00:07:04 +05:00
parent 270fba5c3c
commit 1c9caf6d75
Signed by: Octol1ttle
GPG key ID: B77C34313AEE1FFF
11 changed files with 221 additions and 71 deletions

View file

@ -12,13 +12,14 @@ public class BanModule : ModuleBase<SocketCommandContext> {
[Command("ban")]
[Summary("Банит пользователя")]
[Alias("бан")]
public async Task Run(string user, string durationString, [Remainder]string reason) {
public async Task Run(string user, [Remainder]string reason) {
TimeSpan duration;
try {
duration = TimeSpan.Parse(durationString);
var reasonArray = reason.Split();
duration = Utils.GetTimeSpan(reasonArray[0]);
reason = string.Join(" ", reasonArray.Skip(1));
} catch (Exception e) when (e is ArgumentNullException or FormatException or OverflowException) {
duration = TimeSpan.FromMilliseconds(-1);
reason = durationString + reason;
}
var author = Context.Guild.GetUser(Context.User.Id);
var toBan = await Utils.ParseUser(user);
@ -35,8 +36,8 @@ public class BanModule : ModuleBase<SocketCommandContext> {
var guildBanMessage = $"({author.Username}#{author.Discriminator}) {reason}";
await guild.AddBanAsync(toBan, 0, guildBanMessage);
var notification = $"{authorMention} банит {toBan.Mention} за {Utils.WrapInline(reason)}";
await Utils.SilentSendAsync(guild.GetSystemChannelAsync().Result, notification);
await Utils.SilentSendAsync(Utils.GetAdminLogChannel(), notification);
await Utils.SilentSendAsync(await guild.GetSystemChannelAsync(), notification);
await Utils.SilentSendAsync(await Utils.GetAdminLogChannel(guild), notification);
var task = new Task(() => UnbanModule.UnbanUser(guild, guild.GetCurrentUserAsync().Result, toBan,
"Время наказания истекло"));
await Utils.StartDelayed(task, duration, () => guild.GetBanAsync(toBan).Result != null);

View file

@ -23,7 +23,7 @@ public class ClearModule : ModuleBase<SocketCommandContext> {
default: {
var messages = await channel.GetMessagesAsync(toDelete + 1).FlattenAsync();
await channel.DeleteMessagesAsync(messages);
await Utils.GetAdminLogChannel().SendMessageAsync(
await Utils.SilentSendAsync(await Utils.GetAdminLogChannel(Context.Guild),
$"{Context.User.Mention} удаляет {toDelete + 1} сообщений в канале " +
$"{Utils.MentionChannel(Context.Channel.Id)}");
break;

View file

@ -14,13 +14,13 @@ public class KickModule : ModuleBase<SocketCommandContext> {
[Alias("кик")]
public async Task Run(string user, [Remainder]string reason) {
var author = Context.Guild.GetUser(Context.User.Id);
var toKick = Utils.ParseMember(Context.Guild, user).Result;
var toKick = await Utils.ParseMember(Context.Guild, user);
await CommandHandler.CheckPermissions(author, GuildPermission.KickMembers);
await CommandHandler.CheckInteractions(author, toKick);
KickMember(Context.Guild, Context.Guild.GetUser(Context.User.Id), toKick, reason);
}
private static async void KickMember(IGuild guild, IGuildUser author, IGuildUser toKick, string reason) {
private static async void KickMember(IGuild guild, IUser author, IGuildUser toKick, string reason) {
var authorMention = author.Mention;
await Utils.SendDirectMessage(toKick, $"Тебя кикнул {authorMention} на сервере {guild.Name} за " +
$"{Utils.WrapInline(reason)}");
@ -28,7 +28,7 @@ public class KickModule : ModuleBase<SocketCommandContext> {
var guildKickMessage = $"({author.Username}#{author.Discriminator}) {reason}";
await toKick.KickAsync(guildKickMessage);
var notification = $"{authorMention} выгоняет {toKick.Mention} за {Utils.WrapInline(reason)}";
await Utils.SilentSendAsync(guild.GetSystemChannelAsync().Result, notification);
await Utils.SilentSendAsync(Utils.GetAdminLogChannel(), notification);
await Utils.SilentSendAsync(await guild.GetSystemChannelAsync(), notification);
await Utils.SilentSendAsync(await Utils.GetAdminLogChannel(guild), notification);
}
}

View file

@ -12,16 +12,21 @@ public class MuteModule : ModuleBase<SocketCommandContext> {
[Command("mute")]
[Summary("Глушит пользователя")]
[Alias("мут")]
public async Task Run(string user, string durationString, [Remainder]string reason) {
public async Task Run(string user, [Remainder]string reason) {
TimeSpan duration;
try {
duration = TimeSpan.Parse(durationString);
var reasonArray = reason.Split();
duration = Utils.GetTimeSpan(reasonArray[0]);
reason = string.Join(" ", reasonArray.Skip(1));
} catch (Exception e) when (e is ArgumentNullException or FormatException or OverflowException) {
duration = TimeSpan.FromMilliseconds(-1);
reason = durationString + reason;
}
var author = Context.Guild.GetUser(Context.User.Id);
var toMute = await Utils.ParseMember(Context.Guild, user);
if (toMute.RoleIds.Any(x => x == Utils.GetMuteRole(Context.Guild).Id))
throw new Exception("Участник уже заглушен!");
if (Boyfriend.GetGuildConfig(Context.Guild).RolesRemovedOnMute.ContainsKey(toMute.Id))
throw new Exception("Кто-то убрал роль мута самостоятельно!");
await CommandHandler.CheckPermissions(author, GuildPermission.ManageMessages, GuildPermission.ManageRoles);
await CommandHandler.CheckInteractions(author, toMute);
MuteMember(Context.Guild, Context.Guild.GetUser(Context.User.Id), toMute, duration, reason);
@ -32,17 +37,25 @@ public class MuteModule : ModuleBase<SocketCommandContext> {
await CommandHandler.CheckPermissions(author, GuildPermission.ManageMessages, GuildPermission.ManageRoles);
var authorMention = author.Mention;
var role = Utils.GetMuteRole(guild);
if (Boyfriend.GetGuildConfig(guild).RemoveRolesOnMute) {
foreach (var roleId in toMute.RoleIds) {
await toMute.RemoveRoleAsync(roleId);
var config = Boyfriend.GetGuildConfig(guild);
}
if (config.RemoveRolesOnMute) {
var rolesRemoved = new List<ulong>();
try {
foreach (var roleId in toMute.RoleIds) {
if (roleId == guild.Id) continue;
await toMute.RemoveRoleAsync(roleId);
rolesRemoved.Add(roleId);
}
} catch (NullReferenceException) {}
config.RolesRemovedOnMute.Add(toMute.Id, rolesRemoved);
config.Save();
}
await toMute.AddRoleAsync(role);
var notification = $"{authorMention} глушит {toMute.Mention} за {Utils.WrapInline(reason)}";
await Utils.SilentSendAsync(guild.GetSystemChannelAsync().Result, notification);
await Utils.SilentSendAsync(Utils.GetAdminLogChannel(), notification);
await Utils.SilentSendAsync(await guild.GetSystemChannelAsync(), notification);
await Utils.SilentSendAsync(await Utils.GetAdminLogChannel(guild), notification);
var task = new Task(() => UnmuteModule.UnmuteMember(guild, guild.GetCurrentUserAsync().Result, toMute,
"Время наказания истекло"));
await Utils.StartDelayed(task, duration, () => toMute.RoleIds.Any(x => x == role.Id));

View file

@ -1,4 +1,5 @@
using Discord.Commands;
using Discord;
using Discord.Commands;
// ReSharper disable UnusedType.Global
// ReSharper disable UnusedMember.Global
@ -10,37 +11,105 @@ public class SettingsModule : ModuleBase<SocketCommandContext> {
[Summary("Настраивает бота")]
[Alias("config", "настройки", "конфиг")]
public async Task Run([Remainder] string s = "") {
await CommandHandler.CheckPermissions(Context.Guild.GetUser(Context.User.Id), GuildPermission.ManageGuild);
var config = Boyfriend.GetGuildConfig(Context.Guild);
var sArray = s.Split(" ");
var guild = Context.Guild;
if (s == "") {
var nl = Environment.NewLine;
await Context.Channel.SendMessageAsync($"Текущие настройки:{nl}Язык: `{config.Lang}`" +
$"{nl}Префикс: `{config.Prefix}`" +
$"{nl}Удалять роли при муте: " +
$"{(config.RemoveRolesOnMute ? "Да" : "Нет")}");
var adminLogChannel = guild.GetTextChannel(config.AdminLogChannel);
var admin = adminLogChannel == null ? "Не указан" : adminLogChannel.Mention;
var botLogChannel = guild.GetTextChannel(config.BotLogChannel);
var bot = botLogChannel == null ? "Не указан" : botLogChannel.Mention;
var muteRole = guild.GetRole(config.MuteRole);
var mute = muteRole == null ? "Не указана" : muteRole.Mention;
var toSend = $"Текущие настройки:{nl}" +
$"Язык (`lang`): `{config.Lang}`{nl}" +
$"Префикс (`prefix`): `{config.Prefix}`{nl}" +
$"Удалять роли при муте (`removeRolesOnMute`): {YesOrNo(config.RemoveRolesOnMute)}{nl}" +
"Использовать канал системных сообщений для уведомлений (`useSystemChannel`): " +
$"{YesOrNo(config.UseSystemChannel)}{nl}" +
$"Отправлять приветствия (`sendWelcomeMessages`): {YesOrNo(config.UseSystemChannel)}{nl}" +
$"Роль мута (`muteRole`): {mute}{nl}" +
$"Канал админ-уведомлений (`adminLogChannel`): " +
$"{admin}{nl}" +
$"Канал бот-уведомлений (`botLogChannel`): " +
$"{bot}";
await Utils.SilentSendAsync(Context.Channel as ITextChannel ?? throw new Exception(), toSend);
return;
}
if (sArray[0].ToLower() == "lang") {
if (sArray[1].ToLower() != "ru") throw new Exception("Язык не поддерживается!");
config.Lang = sArray[1].ToLower();
var setting = sArray[0].ToLower();
var value = sArray[1].ToLower();
ITextChannel? channel;
try {
channel = await Utils.ParseChannel(value) as ITextChannel;
} catch (FormatException) {
channel = null;
}
IRole? role;
try {
role = Utils.ParseRole(guild, value);
}
catch (FormatException) {
role = null;
}
if (sArray[0].ToLower() == "prefix")
config.Prefix = sArray[1];
var boolValue = ParseBool(sArray[1]);
if (sArray[0].ToLower() == "removerolesonmute") {
try {
config.RemoveRolesOnMute = bool.Parse(sArray[1].ToLower());
} catch (FormatException) {
await Context.Channel.SendMessageAsync("Неверный параметр! Требуется `true` или `false`");
return;
}
switch (setting) {
case "lang" when sArray[1].ToLower() != "ru":
throw new Exception("Язык не поддерживается!");
case "lang":
config.Lang = value;
break;
case "prefix":
config.Prefix = value;
break;
case "removerolesonmute":
config.RemoveRolesOnMute = boolValue ??
throw new Exception("Неверный параметр! Требуется `true` или `false");
break;
case "usesystemchannel":
config.UseSystemChannel = boolValue ??
throw new Exception("Неверный параметр! Требуется `true` или `false");
break;
case "sendwelcomemessages":
config.SendWelcomeMessages = boolValue ??
throw new Exception("Неверный параметр! Требуется `true` или `false");
break;
case "adminlogchannel":
config.AdminLogChannel = Convert.ToUInt64((channel ??
throw new Exception("Указан недействительный канал!"))
.Id);
break;
case "botlogchannel":
config.BotLogChannel = Convert.ToUInt64((channel ??
throw new Exception("Указан недействительный канал!"))
.Id);
break;
case "muterole":
config.MuteRole = Convert.ToUInt64((role ?? throw new Exception("Указана недействительная роль!"))
.Id);
break;
}
config.Save();
await Context.Channel.SendMessageAsync("Настройки успешно обновлены!");
}
private static bool? ParseBool(string toParse) {
try {
return bool.Parse(toParse.ToLower());
} catch (FormatException) {
return null;
}
}
private static string YesOrNo(bool isYes) {
return isYes ? "Да" : "Нет";
}
}

View file

@ -11,12 +11,11 @@ public class UnbanModule : ModuleBase<SocketCommandContext> {
[Command("unban")]
[Summary("Возвращает пользователя из бана")]
[Alias("разбан")]
public Task Run(string user, [Remainder] string reason) {
var toUnban = Utils.ParseUser(user).Result;
public async Task Run(string user, [Remainder] string reason) {
var toUnban = await Utils.ParseUser(user);
if (Context.Guild.GetBanAsync(toUnban.Id) == null)
throw new Exception("Пользователь не забанен!");
UnbanUser(Context.Guild, Context.Guild.GetUser(Context.User.Id), toUnban, reason);
return Task.CompletedTask;
}
public static async void UnbanUser(IGuild guild, IGuildUser author, IUser toUnban, string reason) {
@ -24,7 +23,7 @@ public class UnbanModule : ModuleBase<SocketCommandContext> {
var authorMention = author.Mention;
var notification = $"{authorMention} возвращает из бана {toUnban.Mention} за {Utils.WrapInline(reason)}";
await guild.RemoveBanAsync(toUnban);
await Utils.SilentSendAsync(guild.GetSystemChannelAsync().Result, notification);
await Utils.SilentSendAsync(Utils.GetAdminLogChannel(), notification);
await Utils.SilentSendAsync(await guild.GetSystemChannelAsync(), notification);
await Utils.SilentSendAsync(await Utils.GetAdminLogChannel(guild), notification);
}
}

View file

@ -12,12 +12,17 @@ public class UnmuteModule : ModuleBase<SocketCommandContext> {
[Summary("Возвращает пользователя из мута")]
[Alias("размут")]
public async Task Run(string user, [Remainder] string reason) {
var toUnmute = Utils.ParseMember(Context.Guild, user).Result;
var toUnmute = await Utils.ParseMember(Context.Guild, user);
var author = Context.Guild.GetUser(Context.User.Id);
await CommandHandler.CheckPermissions(author, GuildPermission.ManageMessages, GuildPermission.ManageRoles);
await CommandHandler.CheckInteractions(author, toUnmute);
if (toUnmute.RoleIds.All(x => x != Utils.GetMuteRole(Context.Guild).Id))
throw new Exception("Пользователь не в муте!");
if (toUnmute.RoleIds.All(x => x != Utils.GetMuteRole(Context.Guild).Id)) {
var rolesRemoved = Boyfriend.GetGuildConfig(Context.Guild).RolesRemovedOnMute;
if (!rolesRemoved.ContainsKey(toUnmute.Id)) throw new Exception("Пользователь не в муте!");
rolesRemoved.Remove(toUnmute.Id);
throw new Exception("Пользователь не в муте, но я нашёл и удалил запись о его удалённых ролях!");
}
UnmuteMember(Context.Guild, Context.Guild.GetUser(Context.User.Id), toUnmute, reason);
}
@ -26,7 +31,16 @@ public class UnmuteModule : ModuleBase<SocketCommandContext> {
var authorMention = author.Mention;
var notification = $"{authorMention} возвращает из мута {toUnmute.Mention} за {Utils.WrapInline(reason)}";
await toUnmute.RemoveRoleAsync(Utils.GetMuteRole(guild));
await Utils.SilentSendAsync(guild.GetSystemChannelAsync().Result, notification);
await Utils.SilentSendAsync(Utils.GetAdminLogChannel(), notification);
var config = Boyfriend.GetGuildConfig(guild);
if (config.RolesRemovedOnMute.ContainsKey(toUnmute.Id)) {
foreach (var roleId in config.RolesRemovedOnMute[toUnmute.Id]) {
await toUnmute.AddRoleAsync(roleId);
}
config.RolesRemovedOnMute.Remove(toUnmute.Id);
}
await Utils.SilentSendAsync(await guild.GetSystemChannelAsync(), notification);
await Utils.SilentSendAsync(await Utils.GetAdminLogChannel(guild), notification);
}
}