public async Task Start() { try { ShowJoinAndPartMessages = bool.Parse(_configuration.GetSection("ShowBotJoinMessages").Value); } catch (Exception ex) { _logger.LogWarning(ex, "Failed to parse ShowBotJoinMessages. Using false."); ShowJoinAndPartMessages = false; } var settings = await _discordBotSettingsRepository.Get(); if (settings == null) { settings = GetTokenFromConsole(); } try { await _client.LoginAsync(TokenType.Bot, settings.Token); } catch (Discord.Net.HttpException ex) { if (ex.Reason == "401: Unauthorized") { _logger.LogCritical("Token is not correct!"); Console.WriteLine("\nToken is incorrect."); Console.Write("Enter Token: "); settings.Token = Console.ReadLine(); await _discordBotSettingsRepository.EditAsync(settings); Start(); } else { _logger.LogCritical(ex, "An unhandeled HttpException has occured!"); Console.WriteLine("An unhandeled HttpException has occured!"); Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); Console.WriteLine("Discord Bot is quiting!"); if (LavaLinkHelper.isLavaLinkRunning()) { LavaLinkHelper.StopLavaLink(); } Environment.Exit(0); } } await _client.StartAsync(); await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _serviceProvider); }
private bool CheckIfLavaLinkIsEnabled() { if (!LavaLinkHelper.isLavaLinkRunning()) { ReplyAsync("Lavalink is not running :("); return(false); } return(true); }
/// <summary> /// Attempt to kill the bot cleanly. /// </summary> /// <param name="exitCode">Exit code to pass to the OS</param> public static void ExitCleanly(int exitCode = 0) { Console.WriteLine("Discord Bot is quiting!"); _cts.Cancel(); if (LavaLinkHelper.isLavaLinkRunning()) { LavaLinkHelper.StopLavaLink(); } Environment.Exit(exitCode); }
public async Task Quit([Summary("The image to display when the bot quits")] string imageUrl = null) { await Context.Channel.TriggerTypingAsync(); _logger.LogInformation("{username}#{discriminator} invoked quit on {server}/{channel}", Context.User.Username, Context.User.Discriminator, Context.Guild?.Name ?? "DM", Context.Channel.Name); if (Context.User.Username != _settings.OwnerName || Context.User.Discriminator != _settings.OwnerDiscriminator) { await ReplyAsync("Sorry, only the bot's owner can make the bot quit!"); return; } else { if (LavaLinkHelper.isLavaLinkRunning()) { await _lavaNode.DisconnectAsync(); } IUserMessage message; await ReplyAsync("Please, no! I want to live! Noooo....."); if (imageUrl != null) { // Delete the quit command so the image isn't shown twice await Context.Message.DeleteAsync(); } var memoryStream = await ImageHelper.FetchImage(imageUrl ?? ImageLookupUtility.GetImageUrl("QUIT_IMAGES")); if (memoryStream == null) { await ReplyAsync("Quit Image could not be fetched! Bye anyway!"); ShowQuitMessageIfEnabled(); Program.ExitCleanly(); } memoryStream.Seek(0, System.IO.SeekOrigin.Begin); message = await Context.Channel.SendFileAsync(memoryStream, "quitimage.png"); await Task.Delay(3000); await message.DeleteAsync(); ShowQuitMessageIfEnabled(); await _servers.SendLogsAsync(Context.Guild, "Bot quitting", $"{Context.User.Mention} has requested the bot to terminate."); await _client.StopAsync(); // Allow the client to cleanup Program.ExitCleanly(); } }
public async Task LavaLink([Summary("start or stop lavalink")] string enable = null) { await Context.Channel.TriggerTypingAsync(); _logger.LogInformation("{username}#{discriminator} executed lavalink ({option}) on {server}/{channel}", Context.User.Username, Context.User.Discriminator, enable, Context.Guild?.Name ?? "DM", Context.Channel.Name); if (enable == null) { await ReplyAsync("LavaLink is " + (LavaLinkHelper.isLavaLinkRunning() ? "" : "not") + " running."); return; } if (enable.ToLowerInvariant() == "start") { LavaLinkHelper.StartLavaLink(); await Task.Delay(5000); if (!_lavaNode.IsConnected) { await _lavaNode.ConnectAsync(); } } else if (enable.ToLowerInvariant() == "stop") { if (_lavaNode.IsConnected) { await _lavaNode.DisconnectAsync(); } LavaLinkHelper.StopLavaLink(); } else { await ReplyAsync("Would you like to `start` or `stop` lavalink?"); return; } await Context.Channel.SendEmbedAsync("Lava Link", $"Lavalink was {(enable.ToLowerInvariant() == "start" ? "started" : "stopped")}!", ColorHelper.GetColor(await _servers.GetServer(Context.Guild))); await _servers.SendLogsAsync(Context.Guild, "Lavalink", $"Lavalink was {(enable.ToLowerInvariant() == "start" ? "started": "stopped")} by {Context.User.Mention}!"); }
static async Task Main(string[] args) { // Initial Logging for before the Dependency Injection is setup Bootstrap.SetupLogging(); // Set up Dependency Injection var serviceProvider = Bootstrap.Initialize(args); var chatService = serviceProvider.GetRequiredService <IChatService>(); var settings = serviceProvider.GetRequiredService <ISettings>(); ConsoleHelper.ColorWriteLine(ConsoleColor.Red, $"{settings.BotName}"); ConsoleHelper.ColorWriteLine(ConsoleColor.Blue, @$ "MIT License Copyright(c) 2021 Kyle Givler (JoyfulReaper) {settings.BotWebsite}" + "\n\n"); if (settings.EnableLavaLink) { _logger.Warning("Unable to parse StartLavaLink, using {value}", _startLavaLink); } if (chatService != null) { try { if (_startLavaLink) { LavaLinkHelper.StartLavaLink(); } // Start the DiscordBot _logger.Information("DiscordBot Starting"); await Task.Run(chatService.Start, _cts.Token); } catch (Exception e) { // Catch all exceptions if they aren't handeled anywhere else, log and exit. _logger.Error(e, "Unhandeled Exception Caught!"); Console.WriteLine("Unhandeled Exception Caught!"); Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); while (e.InnerException != null) { e = e.InnerException; Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); } ExitCleanly(); } } else { _logger.Fatal("Failed to retrieve ChatService!"); Console.WriteLine("Failed to start DiscordBot!"); ExitCleanly(); } while (true) { // If the "Q" key is pressed quit the bot! Console.WriteLine("Press 'Q' to quit!"); var key = Console.ReadKey(true).KeyChar; if (char.ToLowerInvariant(key) == 'q') { break; } } ExitCleanly(); }