Skip to content

Commit

Permalink
Now supports Sharding!
Browse files Browse the repository at this point in the history
  • Loading branch information
CloudTheWolf committed Oct 22, 2022
1 parent 8cde667 commit 81fb4af
Show file tree
Hide file tree
Showing 8 changed files with 215 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,13 @@
<BaseOutputPath>bin\</BaseOutputPath>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<OutputPath>C:\Users\MichaelHoward\Documents\GitHub\CloudTheWolf.DSharpPlus.Scaffolding\CloudTheWolf.DSharpPlus.Scaffolding.Worker\bin\Debug\Plugins</OutputPath>
<PlatformTarget>AnyCPU</PlatformTarget>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="CloudTheWolf.DSharpPlus.Scaffolding.Data" Version="2.0.0.1" />
<PackageReference Include="CloudTheWolf.DSharpPlus.Scaffolding.Shared" Version="2.1.0.6" />
<PackageReference Include="CloudTheWolf.DSharpPlus.Scaffolding.Shared" Version="2.1.0.16" />
</ItemGroup>
</Project>
9 changes: 5 additions & 4 deletions CloudTheWolf.DSharpPlus.Scaffolding.Example.Module/Example.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@
using Microsoft.Extensions.Logging;
using System;
using CloudTheWolf.DSharpPlus.Scaffolding.Example.Module.ApplicationCommands;
using DSharpPlus.CommandsNext;
using DSharpPlus.SlashCommands;

namespace CloudTheWolf.DSharpPlus.Scaffolding.Example.Module
{
public class Example : IPlugin
public class Example : IShardPlugin
{
public string Name => "Example Plugin";

Expand All @@ -19,7 +21,7 @@ public class Example : IPlugin

public static ILogger<Logger> Logger;

public void InitPlugin(IBot bot, ILogger<Logger> logger, DiscordConfiguration discordConfiguration, IConfigurationRoot applicationConfig)
public void InitPlugin(IShardBot bot, ILogger<Logger> logger, DiscordConfiguration discordConfiguration, IConfigurationRoot applicationConfig)
{
Logger = logger;
LoadConfig(applicationConfig);
Expand All @@ -28,12 +30,11 @@ public void InitPlugin(IBot bot, ILogger<Logger> logger, DiscordConfiguration di

}

private void RegisterCommands(IBot bot)
private void RegisterCommands(IShardBot bot)
{
bot.SlashCommandsExt.RegisterCommands<ExampleSlashCommands>();
bot.Commands.RegisterCommands<ExampleCommands>();
Logger.LogInformation($"{Name}: Registered {nameof(ExampleCommands)}!");

}

private void LoadConfig(IConfigurationRoot applicationConfig)
Expand Down
3 changes: 1 addition & 2 deletions CloudTheWolf.DSharpPlus.Scaffolding.Worker/Bot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,11 @@
using System.Threading;
using System.Threading.Tasks;
using DSharpPlus.SlashCommands;
using Emzi0767.Utilities;
using Microsoft.Extensions.Configuration;

namespace CloudTheWolf.DSharpPlus.Scaffolding.Worker
{
class Bot : IBot
internal class Bot : IBot
{
public DiscordClient Client { get; set; }
public VoiceNextExtension Voice { get; set; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

<ItemGroup>
<PackageReference Include="CloudTheWolf.DSharpPlus.Scaffolding.Data" Version="2.0.0.1" />
<PackageReference Include="CloudTheWolf.DSharpPlus.Scaffolding.Shared" Version="2.1.0.6" />
<PackageReference Include="CloudTheWolf.DSharpPlus.Scaffolding.Shared" Version="2.1.0.16" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" />
<PackageReference Include="Microsoft.Extensions.Hosting.Systemd" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="6.0.1" />
Expand Down
5 changes: 5 additions & 0 deletions CloudTheWolf.DSharpPlus.Scaffolding.Worker/Options.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ namespace CloudTheWolf.DSharpPlus.Scaffolding.Worker
{
public class Options
{
/// <summary>
/// Set if the bot uses Sharding
/// </summary>
public static bool ShardMode { get; set; }

/// <summary>
/// Prefix for commands
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ namespace CloudTheWolf.DSharpPlus.Scaffolding.Worker.Services
public class PluginLoader
{
public List<IPlugin> Plugins { get; set; }
public List<IShardPlugin> ShardPlugins { get; set; }

public void LoadPlugins()
{
Expand All @@ -20,11 +21,15 @@ public void LoadPlugins()
//Load the DLLs from the Plugins directory
if (Directory.Exists(Constants.PluginsFolder))
{
var files = Directory.GetFiles(Constants.PluginsFolder);
foreach (var file in files)
var dirs = Directory.GetDirectories(Constants.PluginsFolder);
foreach (var dir in dirs)
{
if (file.EndsWith("dll"))
Assembly.LoadFrom(Path.GetFullPath(file));
var files = Directory.GetFiles(dir);
foreach (var file in files)
{
if (file.EndsWith("dll"))
Assembly.LoadFrom(Path.GetFullPath(file));
}
}
}

Expand Down Expand Up @@ -66,5 +71,60 @@ public void LoadPlugins()
}
}

public void LoadShardPlugins()
{
try
{
ShardPlugins = new List<IShardPlugin>();

//Load the DLLs from the Plugins directory
if (Directory.Exists(Constants.PluginsFolder))
{
var files = Directory.GetFiles(Constants.PluginsFolder);
foreach (var file in files)
{
if (file.EndsWith("dll"))
Assembly.LoadFrom(Path.GetFullPath(file));
}
}

var interfaceType = typeof(IShardPlugin);
//Fetch all types that implement the interface IPlugin and are a class
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
var ts = new List<Type>();
var tsLikePlugin = new List<Type>();

foreach (var assembly in assemblies)
{
var item = assembly.GetTypes();
ts.Add(item.FirstOrDefault());
}

foreach (var type in ts)
{
if (interfaceType.IsAssignableFrom(type))
{
if (type.IsClass)
{
tsLikePlugin.Add(type);
}
}
}

var types = tsLikePlugin.ToArray();

//Create a new instance of all found types
foreach (var type in types)
{
ShardPlugins.Add((IShardPlugin)Activator.CreateInstance(type));
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}

}
}
120 changes: 120 additions & 0 deletions CloudTheWolf.DSharpPlus.Scaffolding.Worker/ShardBot.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
using CloudTheWolf.DSharpPlus.Scaffolding.Logging;
using CloudTheWolf.DSharpPlus.Scaffolding.Shared.Interfaces;
using CloudTheWolf.DSharpPlus.Scaffolding.Worker.Services;
using DSharpPlus;
using DSharpPlus.CommandsNext;
using DSharpPlus.EventArgs;
using DSharpPlus.Interactivity;
using DSharpPlus.Interactivity.Extensions;
using DSharpPlus.Lavalink;
using DSharpPlus.VoiceNext;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using DSharpPlus.SlashCommands;
using Emzi0767.Utilities;
using Microsoft.Extensions.Configuration;

namespace CloudTheWolf.DSharpPlus.Scaffolding.Worker
{
internal class ShardBot : IShardBot
{
public DiscordShardedClient Client { get; set; }
public IReadOnlyDictionary<int, VoiceNextExtension> Voice { get; set; }
public DiscordRestClient Rest { get; set; }
public IReadOnlyDictionary<int,CommandsNextExtension> Commands { get; set; }
public IReadOnlyDictionary<int, InteractivityExtension> Interactivity { get; set; }
public IReadOnlyDictionary<int, LavalinkConfiguration> LavalinkConfig { get; set; }
public IReadOnlyDictionary<int, SlashCommandsExtension> SlashCommandsExt { get; set; }


private static DiscordConfiguration _config;
private static dynamic _myConfig;
private static readonly PluginLoader PluginLoader = new PluginLoader();

public static ILogger<Logger> Logger;

public async Task RunAsync(CancellationToken stoppingToken, ILogger<Logger> logger)
{
Logger = logger;
Logger.LogInformation("Bot Starting!");
LoadConfig();
SetDiscordConfig();
CreateDiscordClient();
CreateClientCommandConfiguration();
InitPlugins();
await Client.StartAsync();
await Task.Delay(-1, stoppingToken);
}

private void InitPlugins()
{
PluginLoader.LoadShardPlugins();

foreach (var plugin in PluginLoader.ShardPlugins)
{
plugin.InitPlugin(this, Logger, _config, Program.configuration);
}
}

private static void LoadConfig()
{
Options.Token = Program.configuration.GetValue<string>("Discord:token");
Options.Prefix = new string[] { Program.configuration.GetValue<string>("Discord:prefix") };
Options.EnableDms = Program.configuration.GetValue<bool>("Discord:enableDms");
Options.EnableMentionPrefix = Program.configuration.GetValue<bool>("Discord:enableMentionPrefix");
Options.DmHelp = Program.configuration.GetValue<bool>("Discord:dmHelp");
Options.DefaultHelp = Program.configuration.GetValue<bool>("Discord:enableDefaultHelp");

}


private void CreateClientCommandConfiguration()
{
var commandsConfig = new CommandsNextConfiguration
{
StringPrefixes = Options.Prefix,
EnableDms = Options.EnableDms,
EnableMentionPrefix = Options.EnableMentionPrefix,
DmHelp = Options.DmHelp,
EnableDefaultHelp = Options.DefaultHelp
};


Commands = Client.UseCommandsNextAsync(commandsConfig).Result;
}

private void CreateDiscordClient()
{
Client = new DiscordShardedClient(_config);
Interactivity = Client.GetInteractivityAsync().Result;
Client.Ready += OnClientReady;
SlashCommandsExt = Client.UseSlashCommandsAsync().Result;

}

private static void SetDiscordConfig()
{
_config = new DiscordConfiguration
{
Token = Options.Token,
TokenType = TokenType.Bot,
AutoReconnect = true,
Intents = DiscordIntents.All,
LoggerFactory = Logging.Logger.LoggerFactory,

};
}

private static Task OnClientReady(DiscordClient sender, ReadyEventArgs readyEventArgs)
{
Logger.LogInformation($"Bot Ready!");

return Task.CompletedTask;
}
}
}
16 changes: 13 additions & 3 deletions CloudTheWolf.DSharpPlus.Scaffolding.Worker/Worker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Threading;
using System.Threading.Tasks;
using System;
using Microsoft.Extensions.Configuration;

namespace CloudTheWolf.DSharpPlus.Scaffolding.Worker
{
Expand All @@ -21,9 +22,18 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
var bot = new Bot();
await bot.RunAsync(stoppingToken, _logger);
await Task.Delay(-1, stoppingToken);
if(Program.configuration.GetValue<bool>("ShardMode"))
{
var bot = new ShardBot();
await bot.RunAsync(stoppingToken, _logger);
await Task.Delay(-1, stoppingToken);
}
else
{
var bot = new Bot();
await bot.RunAsync(stoppingToken, _logger);
await Task.Delay(-1, stoppingToken);
}
}
}
}
Expand Down

0 comments on commit 81fb4af

Please sign in to comment.