From 5891cdfe036d4c8e0cb0a2c2f754f11206a9c803 Mon Sep 17 00:00:00 2001 From: Noi Date: Tue, 9 Aug 2022 18:45:57 -0700 Subject: [PATCH] Add warning for deprecated commands --- CommandsText.cs | 1 + TextCommandRemovalWarning.cs | 41 ++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 TextCommandRemovalWarning.cs diff --git a/CommandsText.cs b/CommandsText.cs index 8fa5e67..bcf2c4f 100644 --- a/CommandsText.cs +++ b/CommandsText.cs @@ -67,6 +67,7 @@ internal class CommandsText { if (msgsplit[0].StartsWith(CommandPrefix, StringComparison.OrdinalIgnoreCase)) { var cmdBase = msgsplit[0][3..]; if (_commands.ContainsKey(cmdBase)) { + NoiTheCat.TextCommandRemovalWarning.Intercept(message, channel.Guild.Id); Program.Log("Command invoked", $"{channel.Guild.Name}/{message.Author} {message.Content}"); try { await _commands[cmdBase](channel, (SocketGuildUser)message.Author, message).ConfigureAwait(false); diff --git a/TextCommandRemovalWarning.cs b/TextCommandRemovalWarning.cs new file mode 100644 index 0000000..db5ca06 --- /dev/null +++ b/TextCommandRemovalWarning.cs @@ -0,0 +1,41 @@ +namespace NoiTheCat; +static class TextCommandRemovalWarning { + public const string StopUsingTextCommands = ":warning: **Reminder**: Text-based commands will be phased out by the end of August. " + + "Please switch to using slash commands. For details on their usage, use this bot's `/help` command."; + private static readonly RateLimit _warnedList = new(8 * 60 * 60); // 8 hours + + public static void Intercept(SocketMessage msg, ulong gid) { + lock (_warnedList) { + if (!_warnedList.IsPermitted(gid)) return; + try { + msg.Channel.SendMessageAsync(StopUsingTextCommands).GetAwaiter().GetResult(); + } catch (Exception e) { + _warnedList.Reset(gid); + Console.WriteLine(e.ToString()); + } + } + } + private class RateLimit where T : notnull { + private const int DefaultTimeout = 20; + public int Timeout { get; } + private Dictionary Entries { get; } = new Dictionary(); + public RateLimit() : this(DefaultTimeout) { } + public RateLimit(int timeout) { + if (timeout < 0) throw new ArgumentOutOfRangeException(nameof(timeout), "Timeout valie cannot be negative."); + Timeout = timeout; + } + public bool IsPermitted(T value) { + if (Timeout == 0) return true; + var now = DateTime.Now; + var expired = Entries.Where(x => x.Value.AddSeconds(Timeout) <= now).Select(x => x.Key).ToList(); + foreach (var item in expired) Entries.Remove(item); + if (Entries.ContainsKey(value)) return false; + else { + Entries.Add(value, DateTime.Now); + return true; + } + } + public bool Reset(T value) => Entries.Remove(value); + } + +} \ No newline at end of file