From 592fef3aa84fefb485af90f86e5926bacb911f08 Mon Sep 17 00:00:00 2001 From: Larry Date: Fri, 18 Oct 2024 21:29:55 -0600 Subject: [PATCH] Create players slash command --- DiscordPlayerCountBot/Bot/Bot.cs | 49 ++++++++++++++++++++++++++++++-- 1 file changed, 46 insertions(+), 3 deletions(-) diff --git a/DiscordPlayerCountBot/Bot/Bot.cs b/DiscordPlayerCountBot/Bot/Bot.cs index 145ed23..f200a1d 100644 --- a/DiscordPlayerCountBot/Bot/Bot.cs +++ b/DiscordPlayerCountBot/Bot/Bot.cs @@ -11,6 +11,7 @@ public class Bot : LoggableClass public readonly BotInformation Information; public readonly Dictionary DataProviders = new(); public readonly Dictionary ApplicationTokens = new(); + public string LastKnownStatus = string.Empty; public Bot(BotInformation info, Dictionary applicationTokens, IServiceProvider services) { @@ -25,10 +26,52 @@ public Bot(BotInformation info, Dictionary applicationTokens, IS HandlerTimeout = null }); + DiscordClient.Ready += DiscordClient_Ready; + DiscordClient.SlashCommandExecuted += DiscordClient_SlashCommandExecuted; + + DataProviders = services.GetServices() .ToDictionary(value => value.GetRequiredProviderType()); } + private async Task DiscordClient_SlashCommandExecuted(SocketSlashCommand command) + { + // NOTE: I only have logic for one slash command, if I am going to add more functionality. + // I will want to create a way to register commands, so people can expand it. + + if (string.IsNullOrEmpty(LastKnownStatus)) + { + await command.RespondAsync("Bot does not have a status to display."); + return; + } + + var embed = new EmbedBuilder + { + Title = $"Server: {Information.Name}", + Fields = new() + { + new() + { + Name = "Players", + Value = LastKnownStatus + } + } + }; + + await command.RespondAsync(embeds: new[] { embed.Build() }, ephemeral: true); + } + + private async Task DiscordClient_Ready() + { + var globalCommand = new SlashCommandBuilder() + { + Name = "players", + Description = $"This will show the player count for the server: {Information.Name}" + }; + + await DiscordClient.CreateGlobalApplicationCommandAsync(globalCommand.Build()); + } + public async Task StartAsync(bool shouldStart) { if (Information!.Address.Contains("hostname") || Information.Address.Contains("localhost")) @@ -74,10 +117,10 @@ public async Task UpdateAsync() return; } - var gameStatus = serverInformation.ReplaceTagsWithValues(Information.StatusFormat, Information.UseNameAsLabel, Information.Name); + LastKnownStatus = serverInformation.ReplaceTagsWithValues(Information.StatusFormat, Information.UseNameAsLabel, Information.Name); - await DiscordClient.SetGameAsync(gameStatus, null, (ActivityType)activityInteger); - await DiscordClient.SetChannelName(Information.ChannelID, gameStatus); + await DiscordClient.SetGameAsync(LastKnownStatus, null, (ActivityType)activityInteger); + await DiscordClient.SetChannelName(Information.ChannelID, LastKnownStatus); } } } \ No newline at end of file