-
Is there some mechanism that would allow me to register multiple discord clients with different tokens within one single application? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Unfortunately not, I built the library around the most common scenario that treats a client as a global singleton. I believe it'd be possible to implement, but is not something I have time for in the near term. |
Beta Was this translation helpful? Give feedback.
-
Hi, y'all. I'm maybe a bit late, but it is possible to have multiple bots with multiple tokens in the same application. It is actually very easy to implement.
I've encapsulated the generation of the bot builder in one static method: BotGenerator.cs public static class BotGenerator
{
public static IHost Generate(string tokenKey)
{
var builder = Host
.CreateDefaultBuilder()
.ConfigureAppConfiguration(app =>
{
// Some config
})
.ConfigureLogging(logging =>
{
// Logger stuff
})
.ConfigureDiscordShardedHost((HostBuilderContext context, DiscordHostConfiguration config) =>
{
config.SocketConfig = new DiscordSocketConfig
{
LogLevel = LogSeverity.Verbose,
AlwaysDownloadUsers = false,
MessageCacheSize = 200,
TotalShards = 4
};
// Set the token here!
config.Token = context.Configuration[tokenKey];
config.ShardIds = new[] { 1 };
})
.ConfigureServices((HostBuilderContext context, IServiceCollection services) =>
{
// Some config
})
.Build();
return builder;
}
} Then, in the main Program.cs file you can use it: // Previous app configuration.
// Create a cancellation token in case you want to stop a bot.
CancellationTokenSource tokenSource = new();
// Generate a bot using one token.
// + run the bot asyncronously.
BotGenerator.Generate("token_basil").RunAsync(tokenSource.Token);
// Generate another one using another token.
// + run the bot asyncronously.
BotGenerator.Generate("token_bemus").RunAsync();
// Stop the first bot after 10 seconds.
Task.Factory.StartNew(() =>
{
Thread.Sleep(10000);
tokenSource.Cancel();
});
// Run the app.
app.Run(); In this example I've configured the same commands in both bots: |
Beta Was this translation helpful? Give feedback.
Unfortunately not, I built the library around the most common scenario that treats a client as a global singleton.
I believe it'd be possible to implement, but is not something I have time for in the near term.