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 App { /// /// The bot prefix /// public readonly string BotPrefix; /// /// The bot token /// public readonly string BotToken; /// /// The bot client /// public DiscordSocketClient Client; /// /// The bot command handler /// private CommandHandler _commandServiceHandler; /// /// The command service /// private CommandService _service; /// /// The main Boot constructor /// /// The bot token /// The bot prefix public App(string botToken, string botPrefix) { this.BotPrefix = botPrefix; this.BotToken = botToken; } /// /// Checks if the bot is ready /// /// true if the bot is ready, otherwise false public bool IsReady { get; private set; } /// /// The start method for the bot. This method is used to load the bot /// /// /// The discord socket config. If null then the default one will be applied (AlwaysDownloadUsers=true, /// UseInteractionSnowflakeDate=false, GatewayIntents=GatewayIntents.All) /// /// Task public async Task Awake(DiscordSocketConfig? config = null) { if (config is null) 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(); CommonTasks(); await Client.LoginAsync(TokenType.Bot, BotToken); await Client.StartAsync(); _commandServiceHandler = new CommandHandler(Client, _service, BotPrefix); await _commandServiceHandler.InstallCommandsAsync(); Application.CurrentApplication.DiscordBotClient = this; while (!IsReady) ; } private void CommonTasks() { if (Client == null) return; Client.Log += Log; Client.LoggedIn += LoggedIn; Client.Ready += Ready; Client.Disconnected += Client_Disconnected; } private async Task Client_Disconnected(Exception arg) { if (arg.Message.Contains("401")) { Application.CurrentApplication.ApplicationEnvironmentVariables.Remove("token"); Application.CurrentApplication.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.CurrentApplication.Logger.Log("Successfully Logged In", this); return Task.CompletedTask; } private Task Log(LogMessage message) { switch (message.Severity) { case LogSeverity.Error: case LogSeverity.Critical: Application.CurrentApplication.Logger.Log(message.Message, this, LogType.Error); break; case LogSeverity.Info: case LogSeverity.Debug: Application.CurrentApplication.Logger.Log(message.Message, this, LogType.Info); break; } return Task.CompletedTask; } }