1
0
Fork 1
mirror of https://github.com/TeamOctolings/Octobot.git synced 2025-01-31 09:09:00 +03:00

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

View file

@ -15,10 +15,10 @@
</PropertyGroup>
<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.ru" Version="2.14.1"/>
<PackageReference Include="Newtonsoft.Json" Version="13.0.1"/>
<PackageReference Include="Newtonsoft.Json" Version="13.0.2-beta1"/>
</ItemGroup>
<ItemGroup>

View file

@ -8,7 +8,6 @@ using Discord.WebSocket;
namespace Boyfriend;
public static class CommandHandler {
public static readonly Command[] Commands = {
new BanCommand(), new ClearCommand(), new HelpCommand(),
new KickCommand(), new MuteCommand(), new PingCommand(),
@ -34,9 +33,7 @@ public static class CommandHandler {
var config = Boyfriend.GetGuildConfig(guild.Id);
Regex regex;
if (RegexCache.ContainsKey(config["Prefix"])) {
regex = RegexCache[config["Prefix"]];
} else {
if (RegexCache.ContainsKey(config["Prefix"])) { regex = RegexCache[config["Prefix"]]; } else {
regex = new Regex(Regex.Escape(config["Prefix"]));
RegexCache.Add(config["Prefix"], regex);
}
@ -61,13 +58,14 @@ public static class CommandHandler {
if (currentLine != list.Length) continue;
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 systemChannel = guild.SystemChannel;
if (adminChannel != null)
if (StackedPrivateFeedback.Length > 0 && adminChannel != null && adminChannel.Id != message.Channel.Id)
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());
}
}

View file

@ -5,7 +5,7 @@ using Discord.WebSocket;
namespace Boyfriend.Commands;
public class BanCommand : Command {
public override string[] Aliases { get; } = {"ban", "бан"};
public override string[] Aliases { get; } = { "ban", "бан" };
public override int ArgsLengthRequired => 2;
public override async Task Run(SocketCommandContext context, string[] args) {
@ -17,7 +17,7 @@ public class BanCommand : Command {
}
var guild = context.Guild;
var author = (SocketGuildUser) context.User;
var author = (SocketGuildUser)context.User;
var permissionCheckResponse = CommandHandler.HasPermission(ref author, GuildPermission.BanMembers);
if (permissionCheckResponse != "") {
@ -40,6 +40,11 @@ public class BanCommand : Command {
if (duration.TotalSeconds < 0) {
Warn(Messages.DurationParseFailed);
reason = Utils.JoinString(ref args, 1);
if (reason == "") {
Error(Messages.ReasonRequired, false);
return;
}
}
await BanUser(guild, author, toBan, duration, reason);
@ -50,12 +55,12 @@ public class BanCommand : Command {
var guildBanMessage = $"({author}) {reason}";
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);
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);
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);
}
var task = new Task(DelayUnban);
task.Start();
new Task(DelayUnban).Start();
}
}
}

View file

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

View file

@ -5,11 +5,11 @@ using Discord.WebSocket;
namespace Boyfriend.Commands;
public class KickCommand : Command {
public override string[] Aliases { get; } = {"kick", "кик", "выгнать"};
public override string[] Aliases { get; } = { "kick", "кик", "выгнать" };
public override int ArgsLengthRequired => 2;
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);
if (permissionCheckResponse != "") {
@ -34,7 +34,7 @@ public class KickCommand : Command {
Success(
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) {
@ -42,7 +42,7 @@ public class KickCommand : Command {
var guildKickMessage = $"({author}) {reason}";
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);
}

View file

@ -6,7 +6,7 @@ using Discord.WebSocket;
namespace Boyfriend.Commands;
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 async Task Run(SocketCommandContext context, string[] args) {
@ -17,6 +17,11 @@ public class MuteCommand : Command {
if (duration.TotalSeconds < 0) {
Warn(Messages.DurationParseFailed);
reason = Utils.JoinString(ref args, 1);
if (reason == "") {
Error(Messages.ReasonRequired, false);
return;
}
}
if (toMute == null) {
@ -28,15 +33,9 @@ public class MuteCommand : Command {
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())) {
if (toMute.Roles.Contains(role) || (toMute.TimedOutUntil != null &&
toMute.TimedOutUntil.Value.ToUnixTimeMilliseconds() >
DateTimeOffset.Now.ToUnixTimeMilliseconds())) {
Error(Messages.MemberAlreadyMuted, false);
return;
}
@ -51,7 +50,7 @@ public class MuteCommand : Command {
Warn(Messages.RolesReturned);
}
var author = (SocketGuildUser) context.User;
var author = (SocketGuildUser)context.User;
var permissionCheckResponse = CommandHandler.HasPermission(ref author, GuildPermission.ModerateMembers);
if (permissionCheckResponse != "") {
@ -69,7 +68,7 @@ public class MuteCommand : Command {
Success(
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,
@ -88,7 +87,7 @@ public class MuteCommand : Command {
await toMute.RemoveRoleAsync(role);
rolesRemoved.Add(userRole.Id);
} 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());
@ -100,8 +99,7 @@ public class MuteCommand : Command {
await UnmuteCommand.UnmuteMember(guild, guild.CurrentUser, toMute, Messages.PunishmentExpired);
}
var task = new Task(DelayUnmute);
task.Start();
new Task(DelayUnmute).Start();
}
}
@ -111,6 +109,7 @@ public class MuteCommand : Command {
Error(Messages.DurationRequiredForTimeOuts, false);
return;
}
if (toMute.IsBot) {
Error(Messages.CannotTimeOutBot, false);
return;

View file

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

View file

@ -5,11 +5,11 @@ using Discord.WebSocket;
namespace Boyfriend.Commands;
public class UnbanCommand : Command {
public override string[] Aliases { get; } = {"unban", "разбан"};
public override string[] Aliases { get; } = { "unban", "разбан" };
public override int ArgsLengthRequired => 2;
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);
if (permissionCheckResponse != "") {
@ -38,7 +38,7 @@ public class UnbanCommand : Command {
var requestOptions = Utils.GetRequestOptions($"({author}) {reason}");
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);
await Utils.SendFeedback(feedback, guild.Id, author.Mention, true);
}

View file

@ -5,11 +5,11 @@ using Discord.WebSocket;
namespace Boyfriend.Commands;
public class UnmuteCommand : Command {
public override string[] Aliases { get; } = {"unmute", "размут"};
public override string[] Aliases { get; } = { "unmute", "размут" };
public override int ArgsLengthRequired => 2;
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);
if (permissionCheckResponse != "") {
@ -40,13 +40,6 @@ public class UnmuteCommand : Command {
var role = Utils.GetMuteRole(ref guild);
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);
if (rolesRemoved.ContainsKey(toUnmute.Id)) {
@ -55,9 +48,7 @@ public class UnmuteCommand : Command {
CommandHandler.ConfigWriteScheduled = true;
}
if (muted) {
await toUnmute.RemoveRoleAsync(role, requestOptions);
} else {
if (toUnmute.Roles.Contains(role)) { await toUnmute.RemoveRoleAsync(role, requestOptions); } else {
Error(Messages.MemberNotMuted, false);
return;
}
@ -71,7 +62,7 @@ public class UnmuteCommand : Command {
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);
await Utils.SendFeedback(feedback, guild.Id, author.Mention, true);
}

View file

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

View file

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

View file

@ -10,7 +10,6 @@ using Humanizer.Localisation;
namespace Boyfriend;
public static class Utils {
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'%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();
private static readonly Dictionary<string, string> ReflectionMessageCache = new();
private static readonly Dictionary<string, CultureInfo> CultureInfoCache = new() {
{"ru", new CultureInfo("ru-RU")},
{"en", new CultureInfo("en-US")}
{ "ru", new CultureInfo("ru-RU") },
{ "en", new CultureInfo("en-US") }
};
private static readonly Dictionary<ulong, SocketRole> MuteRoleCache = new();
private static readonly AllowedMentions AllowRoles = new() {
@ -40,19 +41,12 @@ public static class Utils {
.GetTextChannel(ParseMention(Boyfriend.GetGuildConfig(id)["AdminLogChannel"]));
}
public static string Wrap(string? original) {
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) {
public static string? Wrap(string? original, bool limitedSpace = false) {
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) {
@ -73,9 +67,7 @@ public static class Utils {
}
public static async Task SendDirectMessage(SocketUser user, string toSend) {
try {
await user.SendMessageAsync(toSend);
} catch (HttpException e) {
try { await user.SendMessageAsync(toSend); } catch (HttpException e) {
if (e.DiscordCode != DiscordErrorCode.CannotSendMessageToUser)
throw;
}
@ -91,14 +83,21 @@ public static class Utils {
MuteRoleCache.Add(id, role);
break;
}
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) {
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);
}
public static TimeSpan? GetTimeSpan(ref string from) {
if (TimeSpan.TryParseExact(from.ToLowerInvariant(), Formats, CultureInfo.InvariantCulture, out var timeSpan))
return timeSpan;
@ -122,7 +121,7 @@ public static class Utils {
var toReturn =
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);
return toReturn;
}
@ -144,7 +143,8 @@ public static class Utils {
}
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;
}