cs-codex-dist-tests/Tools/BiblioTech/CommandHandler.cs

74 lines
2.3 KiB
C#
Raw Normal View History

2023-10-20 07:49:23 +00:00
using Discord.Net;
using Discord.WebSocket;
using Discord;
using Newtonsoft.Json;
2023-12-20 14:56:03 +00:00
using BiblioTech.Rewards;
2023-10-20 07:49:23 +00:00
namespace BiblioTech
{
public class CommandHandler
{
private readonly DiscordSocketClient client;
private readonly BaseCommand[] commands;
public CommandHandler(DiscordSocketClient client, params BaseCommand[] commands)
{
this.client = client;
this.commands = commands;
client.Ready += Client_Ready;
client.SlashCommandExecuted += SlashCommandHandler;
}
private async Task Client_Ready()
{
var guild = client.Guilds.Single(g => g.Id == Program.Config.ServerId);
2023-10-22 08:38:46 +00:00
Program.AdminChecker.SetGuild(guild);
2023-12-18 10:27:28 +00:00
Program.Log.Log($"Initializing for guild: '{guild.Name}'");
var adminChannels = guild.TextChannels.Where(Program.AdminChecker.IsAdminChannel).ToArray();
if (adminChannels == null || !adminChannels.Any()) throw new Exception("No admin message channel");
Program.AdminChecker.SetAdminChannel(adminChannels.First());
2024-02-19 13:56:49 +00:00
Program.RoleDriver = new RoleDriver(client);
2023-10-20 07:49:23 +00:00
var builders = commands.Select(c =>
{
2023-12-18 10:27:28 +00:00
var msg = $"Building command '{c.Name}' with options: ";
2023-10-20 07:49:23 +00:00
var builder = new SlashCommandBuilder()
.WithName(c.Name)
.WithDescription(c.Description);
foreach (var option in c.Options)
{
2023-12-18 10:27:28 +00:00
msg += option.Name + " ";
2023-10-24 12:07:15 +00:00
builder.AddOption(option.Build());
2023-10-20 07:49:23 +00:00
}
2023-12-18 10:27:28 +00:00
Program.Log.Log(msg);
2023-10-20 07:49:23 +00:00
return builder;
});
try
{
foreach (var builder in builders)
{
await guild.CreateApplicationCommandAsync(builder.Build());
}
}
catch (HttpException exception)
{
var json = JsonConvert.SerializeObject(exception.Errors, Formatting.Indented);
2023-12-18 10:27:28 +00:00
Program.Log.Error(json);
2023-10-20 07:49:23 +00:00
}
}
private async Task SlashCommandHandler(SocketSlashCommand command)
{
foreach (var cmd in commands)
{
await cmd.SlashCommandHandler(command);
}
}
}
}