Search code examples
c#eventsdiscord.net

How would I implement a cooldown for Events or Commands in Discord.Net?


In my MessageRecieved event handler, I have code that processes text that a user sent into a Discord Text Channel for keywords. If certain keywords are in the text, it'll return a GIF link(s) that corresponds to the keyword(s) found in the message. For example, "The quick brown fox jumps over the lazy dog". If "fox" and "dog" are part of my list of keywords, the event would return a fox GIF and dog GIF in Discord.

Naturally, it'll be very obnoxious if the user spams keywords in Discord and fill the text channel with GIFs so I want to implement a cooldown feature to limit spam (and rate limits).

How would I do this?


Solution

  • In the #dotnet_discord_net channel in the Discord API server, I found this example from April 2023 that was used to answer a similar question.

    private static readonly ConcurrentDictionary<ulong, DateTimeOffset> CommandExecutionTimestamps = new();
    
            [SlashCommand("example", "?")]
            public async Task ExampleCommand()
            {
                if (CommandExecutionTimestamps.TryGetValue(Context.User.Id, out var lastExecution) &&
                    (DateTimeOffset.Now - lastExecution) < TimeSpan.FromSeconds(5))
                {
                    await RespondAsync("Timeout", ephemeral: true);
                    return;
                }
                
                await RespondAsync("Hello", ephemeral: true);
                CommandExecutionTimestamps[Context.User.Id] = DateTimeOffset.Now;
            }
    

    Although, the user was asking about cooldowns for commands, I used this same logic for cooldowns for events.