using System; using System.Diagnostics; using System.Threading.Tasks; using Discord; using Discord.Commands; using Discord.WebSocket; using DiscordBotCore.Others; namespace DiscordBotCore.Bot; public class DiscordBotApplication { /// /// The bot prefix /// private readonly string _BotPrefix; /// /// The bot token /// private readonly string _BotToken; /// /// The bot client /// public DiscordSocketClient Client; /// /// The bot command handler /// private CommandHandler _CommandServiceHandler; /// /// The command service /// private CommandService _Service; /// /// Checks if the bot is ready /// /// true if the bot is ready, otherwise false private bool IsReady { get; set; } /// /// The main Boot constructor /// /// The bot token /// The bot prefix public DiscordBotApplication(string botToken, string botPrefix) { this._BotPrefix = botPrefix; this._BotToken = botToken; } /// /// The start method for the bot. This method is used to load the bot /// public async Task StartAsync() { var config = new DiscordSocketConfig { AlwaysDownloadUsers = true, //Disable system clock checkup (for responses at slash commands) UseInteractionSnowflakeDate = false, GatewayIntents = GatewayIntents.All }; Client = new DiscordSocketClient(config); _Service = new CommandService(); Client.Log += Log; Client.LoggedIn += LoggedIn; Client.Ready += Ready; Client.Disconnected += Client_Disconnected; await Client.LoginAsync(TokenType.Bot, _BotToken); await Client.StartAsync(); _CommandServiceHandler = new CommandHandler(Client, _Service, _BotPrefix); await _CommandServiceHandler.InstallCommandsAsync(); Application.CurrentApplication.DiscordBotClient = this; // wait for the bot to be ready while (!IsReady) { await Task.Delay(100); } } private async Task Client_Disconnected(Exception arg) { if (arg.Message.Contains("401")) { Application.CurrentApplication.ApplicationEnvironmentVariables.Remove("token"); Application.Logger.Log("The token is invalid.", this, LogType.Critical); await Application.CurrentApplication.ApplicationEnvironmentVariables.SaveToFile(); await Task.Delay(3000); Process.Start(Environment.ProcessPath); Environment.Exit(0); } } private Task Ready() { IsReady = true; return Task.CompletedTask; } private Task LoggedIn() { Application.Logger.Log("Successfully Logged In", this); return Task.CompletedTask; } private Task Log(LogMessage message) { switch (message.Severity) { case LogSeverity.Error: case LogSeverity.Critical: Application.Logger.Log(message.Message, this, LogType.Error); break; case LogSeverity.Info: case LogSeverity.Debug: Application.Logger.Log(message.Message, this, LogType.Info); break; } return Task.CompletedTask; } }