John Landon John Landon - 1 month ago 13
C# Question

How to add a 3 second delay in C#?

I just started in coding c#, and I am making a Bot for my discord server. I recently added a command !meme, where it would randomly pull from around 100 different pictures to send in the chat. The second I implemented this command, everyone just totally abused it, and it was at the point where there was like 15 pictures popping up in chat every 2 seconds because of the !meme spam.

I want to be able to add a 3 second delay before the command itself can be used again. I tried using

Thread.Sleep(3000);
and that did not work. Same for
await
Task.Delay(3000);
which I used inside of the async.

private void RegisterMemeCommand()
{
commands.CreateCommand("Meme")
.Do(async (e) =>
{
int RandomMeme = rng.Next(MemeList.Length);
string memetopost = MemeList[RandomMeme];
await e.Channel.SendFile(memetopost);
});
}

Answer

As I don't have complete code, from what you have up in the question, try this:

var lastSentOn=DateTime.MinValue;
commands.CreateCommand("Meme")
.Do(async (e) =>
{
    if((DateTime.Now - lastSentOn).TotalSeconds > 3)
    { 
        int RandomMeme = rng.Next(MemeList.Length);
        string memetopost = MemeList[RandomMeme];
        lastSentOn = DateTime.Now;
        await e.Channel.SendFile(memetopost);
    }
});

You may need to associate lastSentOn with some user id etc. A dictionary will be helpful in this scenario.