Benn
Benn

Reputation: 1

Check for user input in the console while running other code?

Okay, I am new to c#, so I don't have a great understanding of how some stuff works, but I am running a discord bot and I am trying to take user input from the console without stopping the other tasks in the code. When I use something like console.Readline() it will wait for user input before running the rest of the code. Is there any way to have the rest of the code running while also checking for user input? I'm sorry if any of this doesn't make sense but feel free to ask me any questions I would appreciate any help.

Here is the working code:

class Program
{
    public static void Main(string[] args)
    => new Program().MainAsync().GetAwaiter().GetResult();


    private DiscordSocketClient _client;
    public async Task MainAsync()
    {
        _client = new DiscordSocketClient();
        _client.MessageReceived += CommandHandler;
        _client.Log += Log;

        
        var token = File.ReadAllText("token.txt");


        await _client.LoginAsync(TokenType.Bot, token);
        await _client.StartAsync();

        // Block this task until the program is closed.
        await Task.Delay(-1);
    }

    private Task Log(LogMessage msg)
    {
        Console.WriteLine(msg.ToString());
        return Task.CompletedTask;
    }


        public Task CommandHandler(SocketMessage message)
    {
        //variables
        string command = "";
        int lengthOfCommand = message.Content.Length;
        Random rnd = new Random();

        command = message.Content.Substring(0, lengthOfCommand).ToLower();

        string[] greetings = { "hello", "hey", "hi", "sup", };
        string[] greetingResponse = { $"Hello {message.Author.Mention}", $"Hey {message.Author.Mention}", $"Hi {message.Author.Mention}" };

        int greetingsIndex = rnd.Next(0, greetingResponse.Length);

        for (int i = 0; i < greetings.Length; i++) // greetings
        {
            if (command.Equals(greetings[i]))
            {
                message.Channel.SendMessageAsync($@"{greetingResponse[greetingsIndex]}");
            }
            else if (command.Contains($"{greetings[i]} "))
            {
                message.Channel.SendMessageAsync($@"{greetingResponse[greetingsIndex]}"); // goes through the string array and chooses a random response
            }
        }
}

Upvotes: 0

Views: 437

Answers (1)

what you're looking for is threading

read more here

read more here

try this:

new Thread(() => {
    // things you want to do async
}).Start();

Upvotes: 1

Related Questions