Search code examples
c#discord.net

How to change discord bots game activity randomly after a interval


I am trying to get my bot to change its game status every so often.

Here is what I have tried: Making it a command this works but can not use it due to the fact that the command is always running because of the loop making other commands unable to be ran.

[Command("randomplaying")]
        [RequireUserPermission(GuildPermission.MentionEveryone)]
        private async Task randomPlaying()
        {
            const int delay = 3000;

            Random rand = new Random();

            string[] serverActivity = File.ReadAllLines(Server.GameActivity.servergameactivitypath);

            for (; ; )
            {
                int randomIndex = rand.Next(serverActivity.Length);
                string gameActityText = serverActivity[randomIndex];
                await Task.Delay(delay);
                await Context.Client.SetGameAsync(gameActityText, "", ActivityType.Playing);
            }
        }

Trying to do it inside of the Program.cs

private async Task randomPlaying()
        {
            const int delay = 3000;

            Random rand = new Random();

            string[] serverActivity = File.ReadAllLines(Commands.Server.GameActivity.servergameactivitypath);

            for (; ; )
            {
                int randomIndex = rand.Next(serverActivity.Length);
                string gameActityText = serverActivity[randomIndex];
                await Task.Delay(delay);
                await Context.Client.SetGameAsync(gameActityText, "", ActivityType.Playing);
            }
        }

And calling it with

await randomPlaying();

This method does nothing and doesn't even show its working.

servergameactivitypath code is

public static string servergameactivitypath = AppDomain.CurrentDomain.BaseDirectory + "/config/gameactivity.txt";


        public static void createGameActivityTXT()
        {
            File.WriteAllText(servergameactivitypath, "Hello There\nTest1\nTest2\nTest3");
        }

    }

Solution

  • Use:

    
        private async Task randomPlaying()
            {
                const int delay = 3000;
    
                Random rand = new Random();
    
                string[] serverActivity = File.ReadAllLines(Commands.Server.GameActivity.servergameactivitypath);
    
                for (; ; )
                {
                    int randomIndex = rand.Next(serverActivity.Length);
                    string gameActityText = serverActivity[randomIndex];
                    await Task.Delay(delay);
                    await _client.SetGameAsync(gameActityText, "", ActivityType.Playing);
                }
            } 
    

    Call in MainAsync() using above Task.Delay

    await randomPlaying()