another two or three refactors

This commit is contained in:
l1ttleO 2022-05-14 18:12:24 +05:00
parent 868b6bcaa7
commit 790f77aa49
Signed by: Octol1ttle
GPG key ID: B77C34313AEE1FFF
21 changed files with 1447 additions and 944 deletions

View file

@ -1,73 +1,72 @@
using Discord;
using Discord.Commands;
// ReSharper disable UnusedType.Global
// ReSharper disable UnusedMember.Global
// ReSharper disable ClassNeverInstantiated.Global
using Discord.WebSocket;
namespace Boyfriend.Commands;
public class BanCommand : Command {
public override async Task Run(SocketCommandContext context, string[] args) {
var reason = Utils.JoinString(args, 1);
public override string[] Aliases { get; } = {"ban", "бан"};
public override int ArgsLengthRequired => 2;
TimeSpan duration;
try {
duration = Utils.GetTimeSpan(args[1]);
reason = Utils.JoinString(args, 2);
} catch (Exception e) when (e is ArgumentNullException or FormatException or OverflowException) {
await Warn(context.Channel as ITextChannel, Messages.DurationParseFailed);
duration = TimeSpan.FromMilliseconds(-1);
public override async Task Run(SocketCommandContext context, string[] args) {
var toBan = Utils.ParseUser(args[0]);
if (toBan == null) {
Error(Messages.UserDoesntExist, false);
return;
}
await BanUser(context.Guild, context.Channel as ITextChannel, context.Guild.GetUser(context.User.Id),
await Utils.ParseUser(args[0]), duration, reason);
var guild = context.Guild;
var author = (SocketGuildUser) context.User;
var permissionCheckResponse = CommandHandler.HasPermission(ref author, GuildPermission.BanMembers);
if (permissionCheckResponse != "") {
Error(permissionCheckResponse, true);
return;
}
var reason = Utils.JoinString(ref args, 2);
var memberToBan = Utils.ParseMember(guild, args[0]);
if (memberToBan != null) {
var interactionCheckResponse = CommandHandler.CanInteract(ref author, ref memberToBan);
if (interactionCheckResponse != "") {
Error(interactionCheckResponse, true);
return;
}
}
var duration = Utils.GetTimeSpan(ref args[1]) ?? TimeSpan.FromMilliseconds(-1);
if (duration.TotalSeconds < 0) {
Warn(Messages.DurationParseFailed);
reason = Utils.JoinString(ref args, 1);
}
await BanUser(guild, author, toBan, duration, reason);
}
public static async Task BanUser(IGuild guild, ITextChannel? channel, IGuildUser author, IUser toBan,
TimeSpan duration, string reason) {
var authorMention = author.Mention;
var guildBanMessage = $"({Utils.GetNameAndDiscrim(author)}) {reason}";
var memberToBan = await guild.GetUserAsync(toBan.Id);
var expiresIn = duration.TotalSeconds > 0 ? string.Format(Messages.PunishmentExpiresIn, Environment.NewLine,
DateTimeOffset.Now.ToUnixTimeSeconds() + duration.TotalSeconds) : "";
var notification = string.Format(Messages.UserBanned, authorMention, toBan.Mention, Utils.WrapInline(reason),
expiresIn);
await CommandHandler.CheckPermissions(author, GuildPermission.BanMembers);
if (memberToBan != null)
await CommandHandler.CheckInteractions(author, memberToBan);
public static async Task BanUser(SocketGuild guild, SocketGuildUser author, SocketUser toBan, TimeSpan duration,
string reason) {
var guildBanMessage = $"({author}) {reason}";
await Utils.SendDirectMessage(toBan,
string.Format(Messages.YouWereBanned, author.Mention, guild.Name, Utils.WrapInline(reason)));
await guild.AddBanAsync(toBan, 0, guildBanMessage);
await Utils.SilentSendAsync(channel,
string.Format(Messages.BanResponse, toBan.Mention, Utils.WrapInline(reason)));
await Utils.SilentSendAsync(await guild.GetSystemChannelAsync(), notification);
await Utils.SilentSendAsync(await Utils.GetAdminLogChannel(guild), notification);
var feedback = string.Format(Messages.FeedbackUserBanned, toBan.Mention,
Utils.GetHumanizedTimeOffset(ref duration), Utils.WrapInline(reason));
Success(feedback, author.Mention, false, false);
await Utils.SendFeedback(feedback, guild.Id, author.Mention, true);
if (duration.TotalSeconds > 0) {
await Task.Run(async () => {
async void DelayUnban() {
await Task.Delay(duration);
try {
await UnbanCommand.UnbanUser(guild, null, await guild.GetCurrentUserAsync(), toBan,
Messages.PunishmentExpired);
} catch (ApplicationException) {}
});
await UnbanCommand.UnbanUser(guild, guild.CurrentUser, toBan, Messages.PunishmentExpired);
}
var task = new Task(DelayUnban);
task.Start();
}
}
public override List<string> GetAliases() {
return new List<string> {"ban", "бан"};
}
public override int GetArgumentsAmountRequired() {
return 2;
}
public override string GetSummary() {
return "Банит пользователя";
}
}
}

View file

@ -1,54 +1,46 @@
using Discord;
using Discord.Commands;
// ReSharper disable UnusedType.Global
// ReSharper disable UnusedMember.Global
// ReSharper disable ClassNeverInstantiated.Global
using Discord.WebSocket;
namespace Boyfriend.Commands;
public class ClearCommand : Command {
public override async Task Run(SocketCommandContext context, string[] args) {
var user = context.User;
public override string[] Aliases { get; } = {"clear", "purge", "очистить", "стереть"};
public override int ArgsLengthRequired => 1;
int toDelete;
try {
toDelete = Convert.ToInt32(args[0]);
} catch (Exception e) when (e is FormatException or OverflowException) {
throw new ApplicationException(Messages.ClearInvalidAmountSpecified);
public override async Task Run(SocketCommandContext context, string[] args) {
var user = (SocketGuildUser) context.User;
if (context.Channel is not SocketTextChannel channel) throw new Exception();
var permissionCheckResponse = CommandHandler.HasPermission(ref user, GuildPermission.ManageMessages);
if (permissionCheckResponse != "") {
Error(permissionCheckResponse, true);
return;
}
if (context.Channel is not ITextChannel channel) return;
await CommandHandler.CheckPermissions(context.Guild.GetUser(user.Id), GuildPermission.ManageMessages);
if (!int.TryParse(args[0], out var toDelete)) {
Error(Messages.ClearInvalidAmountSpecified, false);
return;
}
switch (toDelete) {
case < 1:
throw new ApplicationException(Messages.ClearNegativeAmount);
Error(Messages.ClearNegativeAmount, false);
break;
case > 200:
throw new ApplicationException(Messages.ClearAmountTooLarge);
default: {
Error(Messages.ClearAmountTooLarge, false);
break;
default:
var messages = await channel.GetMessagesAsync(toDelete + 1).FlattenAsync();
await channel.DeleteMessagesAsync(messages, Utils.GetRequestOptions(Utils.GetNameAndDiscrim(user)));
await channel.DeleteMessagesAsync(messages, Utils.GetRequestOptions(user.ToString()!));
await Utils.SendFeedback(
string.Format(Messages.FeedbackMessagesCleared, (toDelete + 1).ToString(), channel.Mention),
context.Guild.Id, user.Mention);
await Utils.SilentSendAsync(await Utils.GetAdminLogChannel(context.Guild),
string.Format(Messages.MessagesDeleted, user.Mention, toDelete + 1,
Utils.MentionChannel(context.Channel.Id)));
break;
}
}
}
public override List<string> GetAliases() {
return new List<string> {"clear", "purge", "очистить", "стереть"};
}
public override int GetArgumentsAmountRequired() {
return 1;
}
public override string GetSummary() {
return "Очищает сообщения";
}
}
}

View file

@ -1,18 +1,32 @@
using Discord;
using System.Text;
using Discord.Commands;
namespace Boyfriend.Commands;
public abstract class Command {
public abstract string[] Aliases { get; }
public abstract int ArgsLengthRequired { get; }
public abstract Task Run(SocketCommandContext context, string[] args);
public abstract List<string> GetAliases();
protected static void Output(ref StringBuilder message) {
CommandHandler.StackedReplyMessage.Append(message).AppendLine();
}
public abstract int GetArgumentsAmountRequired();
protected static void Success(string message, string userMention, bool sendPublicFeedback = false,
bool sendPrivateFeedback = true) {
CommandHandler.StackedReplyMessage.Append(":white_check_mark: ").AppendLine(message);
if (sendPrivateFeedback)
Utils.StackFeedback(ref message, ref userMention, sendPublicFeedback);
}
public abstract string GetSummary();
protected static void Warn(string message) {
CommandHandler.StackedReplyMessage.Append(":warning: ").AppendLine(message);
}
protected static async Task Warn(ITextChannel? channel, string warning) {
await Utils.SilentSendAsync(channel, ":warning: " + warning);
protected static void Error(string message, bool accessDenied) {
var symbol = accessDenied ? ":no_entry_sign: " : ":x: ";
CommandHandler.StackedReplyMessage.Append(symbol).AppendLine(message);
}
}

View file

@ -1,30 +1,22 @@
using Discord.Commands;
// ReSharper disable UnusedType.Global
// ReSharper disable UnusedMember.Global
using Humanizer;
namespace Boyfriend.Commands;
public class HelpCommand : Command {
public override async Task Run(SocketCommandContext context, string[] args) {
var nl = Environment.NewLine;
var prefix = Boyfriend.GetGuildConfig(context.Guild).Prefix;
var toSend = string.Format(Messages.CommandHelp, nl);
public override string[] Aliases { get; } = {"help", "помощь", "справка"};
public override int ArgsLengthRequired => 0;
toSend = CommandHandler.Commands.Aggregate(toSend,
(current, command) => current + $"`{prefix}{command.GetAliases()[0]}`: {command.GetSummary()}{nl}");
await context.Channel.SendMessageAsync(toSend);
}
public override Task Run(SocketCommandContext context, string[] args) {
var prefix = Boyfriend.GetGuildConfig(context.Guild.Id)["Prefix"];
var toSend = Boyfriend.StringBuilder.Append(Messages.CommandHelp);
public override List<string> GetAliases() {
return new List<string> {"help", "помощь", "справка"};
}
foreach (var command in CommandHandler.Commands)
toSend.Append(
$"\n`{prefix}{command.Aliases[0]}`: {Utils.GetMessage($"CommandDescription{command.Aliases[0].Titleize()}")}");
Output(ref toSend);
toSend.Clear();
public override int GetArgumentsAmountRequired() {
return 0;
return Task.CompletedTask;
}
public override string GetSummary() {
return "Показывает эту справку";
}
}
}

View file

@ -1,50 +1,49 @@
using Discord;
using Discord.Commands;
// ReSharper disable UnusedType.Global
// ReSharper disable UnusedMember.Global
// ReSharper disable ClassNeverInstantiated.Global
using Discord.WebSocket;
namespace Boyfriend.Commands;
public class KickCommand : Command {
public override string[] Aliases { get; } = {"kick", "кик", "выгнать"};
public override int ArgsLengthRequired => 2;
public override async Task Run(SocketCommandContext context, string[] args) {
var author = context.Guild.GetUser(context.User.Id);
var toKick = await Utils.ParseMember(context.Guild, args[0]);
var author = (SocketGuildUser) context.User;
await CommandHandler.CheckPermissions(author, GuildPermission.KickMembers);
await CommandHandler.CheckInteractions(author, toKick);
var permissionCheckResponse = CommandHandler.HasPermission(ref author, GuildPermission.KickMembers);
if (permissionCheckResponse != "") {
Error(permissionCheckResponse, true);
return;
}
await KickMember(context.Guild, context.Channel as ITextChannel, author, toKick, Utils.JoinString(args, 1));
var toKick = Utils.ParseMember(context.Guild, args[0]);
if (toKick == null) {
Error(Messages.UserNotInGuild, false);
return;
}
var interactionCheckResponse = CommandHandler.CanInteract(ref author, ref toKick);
if (interactionCheckResponse != "") {
Error(interactionCheckResponse, true);
return;
}
await KickMember(context.Guild, author, toKick, Utils.JoinString(ref args, 1));
Success(
string.Format(Messages.FeedbackMemberKicked, toKick.Mention,
Utils.WrapInline(Utils.JoinString(ref args, 1))), author.Mention);
}
private static async Task KickMember(IGuild guild, ITextChannel? channel, IUser author, IGuildUser toKick,
string reason) {
private static async Task KickMember(IGuild guild, SocketUser author, SocketGuildUser toKick, string reason) {
var authorMention = author.Mention;
var guildKickMessage = $"({Utils.GetNameAndDiscrim(author)}) {reason}";
var notification = string.Format(Messages.MemberKicked, authorMention, toKick.Mention,
Utils.WrapInline(reason));
var guildKickMessage = $"({author}) {reason}";
await Utils.SendDirectMessage(toKick, string.Format(Messages.YouWereKicked, authorMention, guild.Name,
Utils.WrapInline(reason)));
await Utils.SendDirectMessage(toKick,
string.Format(Messages.YouWereKicked, authorMention, guild.Name, Utils.WrapInline(reason)));
await toKick.KickAsync(guildKickMessage);
await Utils.SilentSendAsync(channel, string.Format(Messages.KickResponse, toKick.Mention,
Utils.WrapInline(reason)));
await Utils.SilentSendAsync(await guild.GetSystemChannelAsync(), notification);
await Utils.SilentSendAsync(await Utils.GetAdminLogChannel(guild), notification);
}
public override List<string> GetAliases() {
return new List<string> {"kick", "кик"};
}
public override int GetArgumentsAmountRequired() {
return 2;
}
public override string GetSummary() {
return "Выгоняет участника";
}
}
}

View file

@ -1,117 +1,122 @@
using Discord;
using Discord.Commands;
using Discord.Net;
// ReSharper disable UnusedType.Global
// ReSharper disable UnusedMember.Global
// ReSharper disable ClassNeverInstantiated.Global
using Discord.WebSocket;
namespace Boyfriend.Commands;
public class MuteCommand : Command {
public override async Task Run(SocketCommandContext context, string[] args) {
var author = context.Guild.GetUser(context.User.Id);
var config = Boyfriend.GetGuildConfig(context.Guild);
var reason = Utils.JoinString(args, 1);
var role = Utils.GetMuteRole(context.Guild);
var rolesRemoved = config.RolesRemovedOnMute!;
var toMute = await Utils.ParseMember(context.Guild, args[0]);
public override string[] Aliases { get; } = {"mute", "timeout", "заглушить", "мут"};
public override int ArgsLengthRequired => 2;
TimeSpan duration;
try {
duration = Utils.GetTimeSpan(args[1]);
reason = Utils.JoinString(args, 2);
} catch (Exception e) when (e is ArgumentNullException or FormatException or OverflowException) {
await Warn(context.Channel as ITextChannel, Messages.DurationParseFailed);
duration = TimeSpan.FromMilliseconds(-1);
public override async Task Run(SocketCommandContext context, string[] args) {
var toMute = Utils.ParseMember(context.Guild, args[0]);
var reason = Utils.JoinString(ref args, 2);
var duration = Utils.GetTimeSpan(ref args[1]) ?? TimeSpan.FromMilliseconds(-1);
if (duration.TotalSeconds < 0) {
Warn(Messages.DurationParseFailed);
reason = Utils.JoinString(ref args, 1);
}
if (toMute == null)
throw new ApplicationException(Messages.UserNotInGuild);
if (toMute == null) {
Error(Messages.UserNotInGuild, false);
return;
}
if (role != null && toMute.RoleIds.Any(x => x == role.Id) || toMute.TimedOutUntil != null &&
toMute.TimedOutUntil.Value.ToUnixTimeMilliseconds() > DateTimeOffset.Now.ToUnixTimeMilliseconds())
throw new ApplicationException(Messages.MemberAlreadyMuted);
var guild = context.Guild;
var role = Utils.GetMuteRole(ref guild);
if (role != null) {
var hasMuteRole = false;
foreach (var x in toMute.Roles) {
if (x != role) continue;
hasMuteRole = true;
break;
}
if (hasMuteRole || (toMute.TimedOutUntil != null && toMute.TimedOutUntil.Value.ToUnixTimeMilliseconds() >
DateTimeOffset.Now.ToUnixTimeMilliseconds())) {
Error(Messages.MemberAlreadyMuted, false);
return;
}
}
var rolesRemoved = Boyfriend.GetRemovedRoles(context.Guild.Id);
if (rolesRemoved.ContainsKey(toMute.Id)) {
foreach (var roleId in rolesRemoved[toMute.Id]) await toMute.AddRoleAsync(roleId);
rolesRemoved.Remove(toMute.Id);
await config.Save();
throw new ApplicationException(Messages.RolesReturned);
CommandHandler.ConfigWriteScheduled = true;
Warn(Messages.RolesReturned);
}
await CommandHandler.CheckPermissions(author, GuildPermission.ModerateMembers, GuildPermission.ManageRoles);
await CommandHandler.CheckInteractions(author, toMute);
var author = (SocketGuildUser) context.User;
await MuteMember(context.Guild, context.Channel as ITextChannel, context.Guild.GetUser(context.User.Id), toMute,
duration, reason);
var permissionCheckResponse = CommandHandler.HasPermission(ref author, GuildPermission.ModerateMembers);
if (permissionCheckResponse != "") {
Error(permissionCheckResponse, true);
return;
}
var interactionCheckResponse = CommandHandler.CanInteract(ref author, ref toMute);
if (interactionCheckResponse != "") {
Error(interactionCheckResponse, true);
return;
}
await MuteMember(guild, author, toMute, duration, reason);
Success(
string.Format(Messages.FeedbackMemberMuted, toMute.Mention, Utils.GetHumanizedTimeOffset(ref duration),
Utils.WrapInline(reason)), author.Mention, true);
}
private static async Task MuteMember(IGuild guild, ITextChannel? channel, IGuildUser author, IGuildUser toMute,
private static async Task MuteMember(SocketGuild guild, SocketUser author, SocketGuildUser toMute,
TimeSpan duration, string reason) {
await CommandHandler.CheckPermissions(author, GuildPermission.ManageMessages, GuildPermission.ManageRoles);
var authorMention = author.Mention;
var config = Boyfriend.GetGuildConfig(guild);
var requestOptions = Utils.GetRequestOptions($"({Utils.GetNameAndDiscrim(author)}) {reason}");
var role = Utils.GetMuteRole(guild);
var config = Boyfriend.GetGuildConfig(guild.Id);
var requestOptions = Utils.GetRequestOptions($"({author}) {reason}");
var role = Utils.GetMuteRole(ref guild);
var hasDuration = duration.TotalSeconds > 0;
var expiresIn = hasDuration ? string.Format(Messages.PunishmentExpiresIn, Environment.NewLine,
DateTimeOffset.Now.ToUnixTimeSeconds() + duration.TotalSeconds) : "";
var notification = string.Format(Messages.MemberMuted, authorMention, toMute.Mention, Utils.WrapInline(reason),
expiresIn);
if (role != null) {
if (config.RemoveRolesOnMute.GetValueOrDefault(false)) {
if (config["RemoveRolesOnMute"] == "true") {
var rolesRemoved = new List<ulong>();
foreach (var roleId in toMute.RoleIds) {
foreach (var userRole in toMute.Roles)
try {
if (roleId == guild.Id) continue;
if (roleId == role.Id) continue;
await toMute.RemoveRoleAsync(roleId);
rolesRemoved.Add(roleId);
if (userRole == guild.EveryoneRole || userRole == role) continue;
await toMute.RemoveRoleAsync(role);
rolesRemoved.Add(userRole.Id);
} catch (HttpException e) {
await Warn(channel,
string.Format(Messages.RoleRemovalFailed, $"<@&{roleId}>", Utils.WrapInline(e.Reason)));
Warn(string.Format(Messages.RoleRemovalFailed, $"<@&{userRole}>", Utils.WrapInline(e.Reason)));
}
}
config.RolesRemovedOnMute!.Add(toMute.Id, rolesRemoved);
await config.Save();
Boyfriend.GetRemovedRoles(guild.Id).Add(toMute.Id, rolesRemoved.AsReadOnly());
CommandHandler.ConfigWriteScheduled = true;
if (hasDuration)
await Task.Run(async () => {
if (hasDuration) {
async void DelayUnmute() {
await Task.Delay(duration);
try {
await UnmuteCommand.UnmuteMember(guild, null, await guild.GetCurrentUserAsync(), toMute,
Messages.PunishmentExpired);
} catch (ApplicationException) {}
});
await UnmuteCommand.UnmuteMember(guild, guild.CurrentUser, toMute, Messages.PunishmentExpired);
}
var task = new Task(DelayUnmute);
task.Start();
}
}
await toMute.AddRoleAsync(role, requestOptions);
} else {
if (!hasDuration)
throw new ApplicationException(Messages.DurationRequiredForTimeOuts);
if (toMute.IsBot)
throw new ApplicationException(Messages.CannotTimeOutBot);
if (!hasDuration) {
Error(Messages.DurationRequiredForTimeOuts, false);
return;
}
if (toMute.IsBot) {
Error(Messages.CannotTimeOutBot, false);
return;
}
await toMute.SetTimeOutAsync(duration, requestOptions);
}
await Utils.SilentSendAsync(channel,
string.Format(Messages.MuteResponse, toMute.Mention, Utils.WrapInline(reason)));
await Utils.SilentSendAsync(await guild.GetSystemChannelAsync(), notification);
await Utils.SilentSendAsync(await Utils.GetAdminLogChannel(guild), notification);
}
public override List<string> GetAliases() {
return new List<string> {"mute", "мут", "мьют"};
}
public override int GetArgumentsAmountRequired() {
return 2;
}
public override string GetSummary() {
return "Глушит участника";
}
}

View file

@ -1,25 +1,19 @@
using Discord.Commands;
// ReSharper disable UnusedType.Global
// ReSharper disable UnusedMember.Global
namespace Boyfriend.Commands;
public class PingCommand : Command {
public override async Task Run(SocketCommandContext context, string[] args) {
await context.Channel.SendMessageAsync($"{Utils.GetBeep(Boyfriend.GetGuildConfig(context.Guild).Lang!)}" +
$"{Boyfriend.Client.Latency}{Messages.Milliseconds}");
}
public override string[] Aliases { get; } = {"ping", "latency", "pong", "пинг", "задержка", "понг"};
public override int ArgsLengthRequired => 0;
public override List<string> GetAliases() {
return new List<string> {"ping", "пинг", "задержка"};
}
public override Task Run(SocketCommandContext context, string[] args) {
var builder = Boyfriend.StringBuilder;
public override int GetArgumentsAmountRequired() {
return 0;
}
builder.Append(Utils.GetBeep()).Append(Boyfriend.Client.Latency).Append(Messages.Milliseconds);
public override string GetSummary() {
return "Измеряет время обработки REST-запроса";
Output(ref builder);
builder.Clear();
return Task.CompletedTask;
}
}
}

View file

@ -1,111 +1,156 @@
using System.Reflection;
using Discord;
using Discord;
using Discord.Commands;
// ReSharper disable UnusedType.Global
// ReSharper disable UnusedMember.Global
using Discord.WebSocket;
namespace Boyfriend.Commands;
public class SettingsCommand : Command {
public override async Task Run(SocketCommandContext context, string[] args) {
var config = Boyfriend.GetGuildConfig(context.Guild);
var guild = context.Guild;
public override string[] Aliases { get; } = {"settings", "config", "настройки", "конфиг"};
public override int ArgsLengthRequired => 0;
await CommandHandler.CheckPermissions(context.Guild.GetUser(context.User.Id), GuildPermission.ManageGuild);
public override Task Run(SocketCommandContext context, string[] args) {
var author = (SocketGuildUser) context.User;
var permissionCheckResponse = CommandHandler.HasPermission(ref author, GuildPermission.ManageGuild);
if (permissionCheckResponse != "") {
Error(permissionCheckResponse, true);
return Task.CompletedTask;
}
var guild = context.Guild;
var config = Boyfriend.GetGuildConfig(guild.Id);
if (args.Length == 0) {
var nl = Environment.NewLine;
dynamic forCheck;
var adminLogChannel = (forCheck = guild.GetTextChannel(config.AdminLogChannel.GetValueOrDefault(0))) == null
? Messages.ChannelNotSpecified : forCheck.Mention;
var botLogChannel = (forCheck = guild.GetTextChannel(config.BotLogChannel.GetValueOrDefault(0))) == null
? Messages.ChannelNotSpecified : forCheck.Mention;
var muteRole = (forCheck = guild.GetRole(config.MuteRole.GetValueOrDefault(0))) == null
? Messages.RoleNotSpecified : forCheck.Mention;
var defaultRole = (forCheck = guild.GetRole(config.DefaultRole.GetValueOrDefault(0))) == null
? Messages.RoleNotSpecified : forCheck.Mention;
var toSend = string.Format(Messages.CurrentSettings, nl) +
string.Format(Messages.CurrentSettingsLang, config.Lang, nl) +
string.Format(Messages.CurrentSettingsPrefix, config.Prefix, nl) +
string.Format(Messages.CurrentSettingsRemoveRoles,
YesOrNo(config.RemoveRolesOnMute.GetValueOrDefault(false)), nl) +
string.Format(Messages.CurrentSettingsUseSystemChannel,
YesOrNo(config.UseSystemChannel.GetValueOrDefault(true)), nl) +
string.Format(Messages.CurrentSettingsSendWelcomeMessages,
YesOrNo(config.SendWelcomeMessages.GetValueOrDefault(true)), nl) +
string.Format(Messages.CurrentSettingsReceiveStartupMessages,
YesOrNo(config.ReceiveStartupMessages.GetValueOrDefault(true)), nl) +
string.Format(Messages.CurrentSettingsWelcomeMessage, config.WelcomeMessage, nl) +
string.Format(Messages.CurrentSettingsDefaultRole, defaultRole, nl) +
string.Format(Messages.CurrentSettingsMuteRole, muteRole, nl) +
string.Format(Messages.CurrentSettingsAdminLogChannel, adminLogChannel, nl) +
string.Format(Messages.CurrentSettingsBotLogChannel, botLogChannel);
await Utils.SilentSendAsync(context.Channel as ITextChannel ?? throw new ApplicationException(), toSend);
return;
}
var currentSettings = Boyfriend.StringBuilder.AppendLine(Messages.CurrentSettings);
var setting = args[0].ToLower();
var value = "";
foreach (var setting in Boyfriend.DefaultConfig) {
var format = "{0}";
var currentValue = config[setting.Key];
if (args.Length >= 2)
try {
value = args[1].ToLower();
} catch (IndexOutOfRangeException) {
throw new ApplicationException(Messages.InvalidSettingValue);
if (setting.Key.EndsWith("Channel")) {
if (guild.GetTextChannel(Convert.ToUInt64(currentValue)) != null)
format = "<#{0}>";
else
currentValue = Messages.ChannelNotSpecified;
} else if (setting.Key.EndsWith("Role")) {
if (guild.GetRole(Convert.ToUInt64(currentValue)) != null)
format = "<@&{0}>";
else
currentValue = Messages.RoleNotSpecified;
} else {
if (IsBool(currentValue))
currentValue = YesOrNo(currentValue == "true");
else
format = Utils.WrapInline("{0}")!;
}
currentSettings.Append($"{Utils.GetMessage($"Settings{setting.Key}")} (`{setting.Key}`): ")
.AppendFormat(format, currentValue).AppendLine();
}
PropertyInfo? property = null;
foreach (var prop in typeof(GuildConfig).GetProperties())
if (setting == prop.Name.ToLower())
property = prop;
if (property == null || !property.CanWrite)
throw new ApplicationException(Messages.SettingDoesntExist);
var type = property.PropertyType;
Output(ref currentSettings);
currentSettings.Clear();
return Task.CompletedTask;
}
var selectedSetting = args[0].ToLower();
var exists = false;
foreach (var setting in Boyfriend.DefaultConfig) {
if (selectedSetting != setting.Key.ToLower()) continue;
selectedSetting = setting.Key;
exists = true;
break;
}
if (!exists) {
Error(Messages.SettingDoesntExist, false);
return Task.CompletedTask;
}
string value;
if (args.Length >= 2) {
value = Utils.JoinString(ref args, 1);
if (selectedSetting != "WelcomeMessage")
value = value.Replace(" ", "").ToLower();
if (value.StartsWith(",") || value.Count(x => x == ',') > 1) {
Error(Messages.InvalidSettingValue, false);
return Task.CompletedTask;
}
} else {
value = "reset";
}
if (IsBool(Boyfriend.DefaultConfig[selectedSetting]) && !IsBool(value)) {
value = value switch {
"y" or "yes" => "true",
"n" or "no" => "false",
_ => value
};
if (!IsBool(value)) {
Error(Messages.InvalidSettingValue, false);
return Task.CompletedTask;
}
}
var localizedSelectedSetting = Utils.GetMessage($"Settings{selectedSetting}");
var mention = Utils.ParseMention(value);
if (mention != 0) value = mention.ToString();
var formatting = Utils.WrapInline("{0}")!;
if (selectedSetting.EndsWith("Channel"))
formatting = "<#{0}>";
if (selectedSetting.EndsWith("Role"))
formatting = "<@&{0}>";
if (value is "0" or "reset" or "default")
formatting = Messages.SettingNotDefined;
var formattedValue = IsBool(value) ? YesOrNo(value == "true") : string.Format(formatting, value);
if (value is "reset" or "default") {
property.SetValue(config, null);
} else if (type == typeof(string)) {
if (setting == "lang" && value is not ("ru" or "en"))
throw new ApplicationException(Messages.LanguageNotSupported);
property.SetValue(config, value);
config[selectedSetting] = Boyfriend.DefaultConfig[selectedSetting];
} else {
try {
if (type == typeof(bool?))
property.SetValue(config, Convert.ToBoolean(value));
if (type == typeof(ulong?)) {
var id = Convert.ToUInt64(value);
if (property.Name.EndsWith("Channel") && guild.GetTextChannel(id) == null)
throw new ApplicationException(Messages.InvalidChannel);
if (property.Name.EndsWith("Role") && guild.GetRole(id) == null)
throw new ApplicationException(Messages.InvalidRole);
property.SetValue(config, id);
}
} catch (Exception e) when (e is FormatException or OverflowException) {
throw new ApplicationException(Messages.InvalidSettingValue);
if (value == config[selectedSetting]) {
Error(string.Format(Messages.SettingsNothingChanged, localizedSelectedSetting, formattedValue), false);
return Task.CompletedTask;
}
}
config.Validate();
await config.Save();
await context.Channel.SendMessageAsync(Messages.SettingsUpdated);
if (selectedSetting == "Lang" && value is not "ru" and not "en") {
Error(Messages.LanguageNotSupported, false);
return Task.CompletedTask;
}
if (selectedSetting.EndsWith("Channel") && guild.GetTextChannel(mention) == null) {
Error(Messages.InvalidChannel, false);
return Task.CompletedTask;
}
if (selectedSetting.EndsWith("Role") && guild.GetRole(mention) == null) {
Error(Messages.InvalidRole, false);
return Task.CompletedTask;
}
config[selectedSetting] = value;
}
if (selectedSetting == "Lang") {
Utils.SetCurrentLanguage(guild.Id);
localizedSelectedSetting = Utils.GetMessage($"Settings{selectedSetting}");
}
CommandHandler.ConfigWriteScheduled = true;
Success(string.Format(Messages.FeedbackSettingsUpdated, localizedSelectedSetting, formattedValue),
author.Mention);
return Task.CompletedTask;
}
private static string YesOrNo(bool isYes) {
return isYes ? Messages.Yes : Messages.No;
}
public override List<string> GetAliases() {
return new List<string> {"settings", "настройки", "config", "конфиг "};
private static bool IsBool(string value) {
return value is "true" or "false";
}
public override int GetArgumentsAmountRequired() {
return 0;
}
public override string GetSummary() {
return "Настраивает бота отдельно для этого сервера";
}
}
}

View file

@ -1,48 +1,45 @@
using Discord;
using Discord.Commands;
// ReSharper disable UnusedType.Global
// ReSharper disable UnusedMember.Global
// ReSharper disable ClassNeverInstantiated.Global
using Discord.WebSocket;
namespace Boyfriend.Commands;
public class UnbanCommand : Command {
public override string[] Aliases { get; } = {"unban", "разбан"};
public override int ArgsLengthRequired => 2;
public override async Task Run(SocketCommandContext context, string[] args) {
await UnbanUser(context.Guild, context.Channel as ITextChannel, context.Guild.GetUser(context.User.Id),
await Utils.ParseUser(args[0]), Utils.JoinString(args, 1));
var author = (SocketGuildUser) context.User;
var permissionCheckResponse = CommandHandler.HasPermission(ref author, GuildPermission.BanMembers);
if (permissionCheckResponse != "") {
Error(permissionCheckResponse, true);
return;
}
var toUnban = Utils.ParseUser(args[0]);
if (toUnban == null) {
Error(Messages.UserDoesntExist, false);
return;
}
var reason = Utils.JoinString(ref args, 1);
await UnbanUser(context.Guild, author, toUnban, reason);
}
public static async Task UnbanUser(IGuild guild, ITextChannel? channel, IGuildUser author, IUser toUnban,
string reason) {
var authorMention = author.Mention;
var notification = string.Format(Messages.UserUnbanned, authorMention, toUnban.Mention,
Utils.WrapInline(reason));
var requestOptions = Utils.GetRequestOptions($"({Utils.GetNameAndDiscrim(author)}) {reason}");
await CommandHandler.CheckPermissions(author, GuildPermission.BanMembers);
if (guild.GetBanAsync(toUnban.Id) == null)
throw new ApplicationException(Messages.UserNotBanned);
public static async Task UnbanUser(SocketGuild guild, SocketGuildUser author, SocketUser toUnban, string reason) {
if (guild.GetBanAsync(toUnban.Id) == null) {
Error(Messages.UserNotBanned, false);
return;
}
var requestOptions = Utils.GetRequestOptions($"({author}) {reason}");
await guild.RemoveBanAsync(toUnban, requestOptions);
await Utils.SilentSendAsync(channel, string.Format(Messages.UnbanResponse, toUnban.Mention,
Utils.WrapInline(reason)));
await Utils.SilentSendAsync(await guild.GetSystemChannelAsync(), notification);
await Utils.SilentSendAsync(await Utils.GetAdminLogChannel(guild), notification);
}
public override List<string> GetAliases() {
return new List<string> {"unban", "разбан"};
}
public override int GetArgumentsAmountRequired() {
return 2;
}
public override string GetSummary() {
return "Возвращает пользователя из бана";
var feedback = string.Format(Messages.FeedbackUserUnbanned, toUnban.Mention, Utils.WrapInline(reason));
Success(feedback, author.Mention, false, false);
await Utils.SendFeedback(feedback, guild.Id, author.Mention, true);
}
}

View file

@ -1,71 +1,78 @@
using Discord;
using Discord.Commands;
// ReSharper disable UnusedType.Global
// ReSharper disable UnusedMember.Global
// ReSharper disable ClassNeverInstantiated.Global
using Discord.WebSocket;
namespace Boyfriend.Commands;
public class UnmuteCommand : Command {
public override string[] Aliases { get; } = {"unmute", "размут"};
public override int ArgsLengthRequired => 2;
public override async Task Run(SocketCommandContext context, string[] args) {
await UnmuteMember(context.Guild, context.Channel as ITextChannel, context.Guild.GetUser(context.User.Id),
await Utils.ParseMember(context.Guild, args[0]), Utils.JoinString(args, 1));
var author = (SocketGuildUser) context.User;
var permissionCheckResponse = CommandHandler.HasPermission(ref author, GuildPermission.ModerateMembers);
if (permissionCheckResponse != "") {
Error(permissionCheckResponse, true);
return;
}
var toUnmute = Utils.ParseMember(context.Guild, args[0]);
if (toUnmute == null) {
Error(Messages.UserDoesntExist, false);
return;
}
var interactionCheckResponse = CommandHandler.CanInteract(ref author, ref toUnmute);
if (interactionCheckResponse != "") {
Error(interactionCheckResponse, true);
return;
}
var reason = Utils.JoinString(ref args, 1);
await UnmuteMember(context.Guild, author, toUnmute, reason);
}
public static async Task UnmuteMember(IGuild guild, ITextChannel? channel, IGuildUser author, IGuildUser toUnmute,
public static async Task UnmuteMember(SocketGuild guild, SocketGuildUser author, SocketGuildUser toUnmute,
string reason) {
await CommandHandler.CheckPermissions(author, GuildPermission.ModerateMembers, GuildPermission.ManageRoles);
await CommandHandler.CheckInteractions(author, toUnmute);
var authorMention = author.Mention;
var config = Boyfriend.GetGuildConfig(guild);
var notification = string.Format(Messages.MemberUnmuted, authorMention, toUnmute.Mention,
Utils.WrapInline(reason));
var requestOptions = Utils.GetRequestOptions($"({Utils.GetNameAndDiscrim(author)}) {reason}");
var role = Utils.GetMuteRole(guild);
var requestOptions = Utils.GetRequestOptions($"({author}) {reason}");
var role = Utils.GetMuteRole(ref guild);
if (role != null) {
if (toUnmute.RoleIds.All(x => x != role.Id)) {
var rolesRemoved = config.RolesRemovedOnMute;
await toUnmute.AddRolesAsync(rolesRemoved![toUnmute.Id]);
rolesRemoved.Remove(toUnmute.Id);
await config.Save();
throw new ApplicationException(Messages.RolesReturned);
var muted = false;
foreach (var x in toUnmute.Roles) {
if (x != role) continue;
muted = true;
break;
}
if (toUnmute.RoleIds.All(x => x != role.Id))
throw new ApplicationException(Messages.MemberNotMuted);
var rolesRemoved = Boyfriend.GetRemovedRoles(guild.Id);
await toUnmute.RemoveRoleAsync(role, requestOptions);
if (config.RolesRemovedOnMute!.ContainsKey(toUnmute.Id)) {
await toUnmute.AddRolesAsync(config.RolesRemovedOnMute[toUnmute.Id]);
config.RolesRemovedOnMute.Remove(toUnmute.Id);
await config.Save();
if (rolesRemoved.ContainsKey(toUnmute.Id)) {
await toUnmute.AddRolesAsync(rolesRemoved[toUnmute.Id]);
rolesRemoved.Remove(toUnmute.Id);
CommandHandler.ConfigWriteScheduled = true;
}
if (muted) {
await toUnmute.RemoveRoleAsync(role, requestOptions);
} else {
Error(Messages.MemberNotMuted, false);
return;
}
} else {
if (toUnmute.TimedOutUntil == null || toUnmute.TimedOutUntil.Value.ToUnixTimeMilliseconds()
< DateTimeOffset.Now.ToUnixTimeMilliseconds())
throw new ApplicationException(Messages.MemberNotMuted);
if (toUnmute.TimedOutUntil == null || toUnmute.TimedOutUntil.Value.ToUnixTimeMilliseconds() <
DateTimeOffset.Now.ToUnixTimeMilliseconds()) {
Error(Messages.MemberNotMuted, false);
return;
}
await toUnmute.RemoveTimeOutAsync();
}
await Utils.SilentSendAsync(channel, string.Format(Messages.UnmuteResponse, toUnmute.Mention,
Utils.WrapInline(reason)));
await Utils.SilentSendAsync(await guild.GetSystemChannelAsync(), notification);
await Utils.SilentSendAsync(await Utils.GetAdminLogChannel(guild), notification);
}
public override List<string> GetAliases() {
return new List<string> {"unmute", "размут"};
}
public override int GetArgumentsAmountRequired() {
return 2;
}
public override string GetSummary() {
return "Снимает мут с участника";
var feedback = string.Format(Messages.FeedbackMemberUnmuted, toUnmute.Mention, Utils.WrapInline(reason));
Success(feedback, author.Mention, false, false);
await Utils.SendFeedback(feedback, guild.Id, author.Mention, true);
}
}