Search code examples
c#.netdiscord.net

Discord.NET run multiple bots from one console app project


I've seen many examples how to run Discord.NET Bot but all those examples show how to run 1 bot per 1 console app project or one bot sharded with servers so is this library designed only for 1<-->1 approach because I saw also singleton is used for connecting part? Is it possible to run multiple bots from one codebase? I need this to keep track bots/connectons and see statuses in webapplication but it might be bad decision if I go with multiple console applications approach.


Solution

  • You should probably use object and class for each discord bot though but I wanted to give you idea of how can you achieve such an effect. I would probably also use better logging system (maybe some logging library?). But if I were you I would think maybe about using docker and docker-compose?

    Cheers

    using System.Threading;
    using System.Threading.Tasks;
    using Discord;
    using Discord.WebSocket;
    
    namespace temp
    {
        public class Program
        {
            public static async Task Bot1(Func<LogMessage, Task> log, CancellationToken cancellationToken)
            {
                var client = new DiscordSocketClient();
                client.Log += log;
                await client.LoginAsync(TokenType.Bot, "token1");
                await client.StartAsync();
                await Task.Delay(-1, cancellationToken);
            }
            public static async Task Bot2(Func<LogMessage, Task> log, CancellationToken cancellationToken)
            {
                var client = new DiscordSocketClient();
                client.Log += log;
                await client.LoginAsync(TokenType.Bot, "token2");
                await client.StartAsync();
                await Task.Delay(-1, cancellationToken);
            }
            public static void Main()
            {
                var cancellationToken = new CancellationTokenSource();
                Console.CancelKeyPress += (sender, args) =>
                {
                    cancellationToken.Cancel();
                    args.Cancel = true;
                };
                Task.WhenAll(new Task[]
                {
                    Bot1(Log, cancellationToken.Token),
                    Bot2(Log, cancellationToken.Token)
                });
            }
    
            private static async Task Log(LogMessage message)
            {
                Console.WriteLine(message);
            }
        }
    }