private Task SlashCommandExecuted(SlashCommandInfo arg1, Discord.IInteractionContext arg2, IResult arg3) { if (!arg3.IsSuccess) { switch (arg3.Error) { case InteractionCommandError.UnmetPrecondition: // implement break; case InteractionCommandError.UnknownCommand: // implement break; case InteractionCommandError.BadArgs: // implement break; case InteractionCommandError.Exception: // implement break; case InteractionCommandError.Unsuccessful: // implement break; default: break; } } return(Task.CompletedTask); }
/// <summary> /// Creates an <see cref="EmbedBuilder"/> object for help for a particular command using reflection and attribute values. /// </summary> /// <param name="command">The command to describe.</param> /// <returns>An <see cref="EmbedBuilder"/> ready to be built.</returns> private EmbedBuilder GenerateEmbeddedSlashCommandHelp(string command) { string helpImageUrl = Configuration.GetSection("images").GetSection("help")["64"]; string commandTitle = Format.Code($"/{command}"); List <ModuleInfo> modules = InteractionService.Modules.Where(m => m.HasAttribute <HelpTitleAttribute>()) .OrderBy(m => m.GetAttribute <HelpOrderAttribute>()?.Order) .ToList(); SlashCommandInfo slashCommandInfo = InteractionService.SlashCommands.GetSlashCommand(command); EmbedBuilder embed = new EmbedBuilder().WithTitle($"Comando {commandTitle}") .WithColor(GlobalConfiguration.Colors.Help) .WithDescription(GlobalConfiguration.Constants.BLANK_SPACE) .WithThumbnailUrl(helpImageUrl) .AddField(Format.Bold("Descripción"), Format.Italics(slashCommandInfo.Description)); if (slashCommandInfo.Parameters.Count > 0) { StringBuilder parameterBuilder = new(); foreach (SlashCommandParameterInfo parameter in slashCommandInfo.Parameters) { parameterBuilder.AppendLine($"{Format.Code($"<{parameter.Name}>")}: {(parameter.IsRequired ? " " : $"{Format.Bold("[Opcional]")} ")}{Format.Italics(parameter.Description)}"); } embed.AddField(Format.Bold("Parámetros"), parameterBuilder.ToString()); } else { embed.AddField(Format.Bold("Parámetros"), Format.Italics("Ninguno.")); } return(embed); }
private Task SlashCommandExecuted(SlashCommandInfo commandInfo, IInteractionContext context, IResult result) { if (!result.IsSuccess) { switch (result.Error) { case InteractionCommandError.UnmetPrecondition: // implement break; case InteractionCommandError.UnknownCommand: // implement break; case InteractionCommandError.BadArgs: // implement break; case InteractionCommandError.Exception: // implement break; case InteractionCommandError.Unsuccessful: // implement break; default: break; } } return(Task.CompletedTask); }
private async Task SlashCommandExecutedAsync(SlashCommandInfo command, IInteractionContext context, Discord.Interactions.IResult result) { // the command was successful, we don't care about this result, unless we want to log that a command succeeded. if (result.IsSuccess) { return; } await context.Interaction.RespondAsync(result.ErrorReason, ephemeral : true); }
/// <summary> /// Callback for command execution. Reply with error if command fails execution. /// </summary> /// <param name="command"></param> /// <param name="context"></param> /// <param name="result"></param> /// <returns></returns> private async Task OnInteractionExecutedAsync( SlashCommandInfo command, IInteractionContext context, IResult result) { if (result.IsSuccess) { return; } // Command not successful, reply with error. _logger.LogError(result.ToString()); _logger.LogError($"{result.ErrorReason}: {result.Error.ToString()}"); await context.Channel.SendMessageAsync(result.ToString(), allowedMentions : AllowedMentions.None); }
private async Task CmdErroredHandler(SlashCommandInfo info, IInteractionContext context, Discord.Interactions.IResult result) { if (!result.IsSuccess) { if (result is ExecuteResult eResult) { if (eResult.Exception is BaseAPIException) { _logger.LogError($"Command '{info.Name}' invoked by '{context.User.Username}#{context.User.Discriminator}' failed: {(eResult.Exception as BaseAPIException).Error}"); using var scope = _serviceProvider.CreateScope(); Translator translator = scope.ServiceProvider.GetRequiredService <Translator>(); if (context.Guild != null) { await translator.SetContext(context.Guild.Id); } string errorCode = "#" + ((int)(eResult.Exception as BaseAPIException).Error).ToString("D4"); EmbedBuilder builder = new EmbedBuilder() .WithTitle(translator.T().SomethingWentWrong()) .WithColor(Color.Red) .WithDescription(translator.T().Enum((eResult.Exception as BaseAPIException).Error)) .WithCurrentTimestamp() .WithFooter($"{translator.T().Code()} {errorCode}"); try { await context.Interaction.RespondAsync(embed : builder.Build()); } catch (TimeoutException) { await context.Channel.SendMessageAsync(embed : builder.Build()); } } else { _logger.LogError($"Command '{info.Name}' invoked by '{context.User.Username}#{context.User.Discriminator}' failed: " + eResult.Exception.Message + "\n" + eResult.Exception.StackTrace); } } else { _logger.LogError($"Command '{info.Name}' invoked by '{context.User.Username}#{context.User.Discriminator}' failed due to {result.Error}."); } } }
private Task HelpCommand(string input) { //IEnumerable<object> cmds = CmdService.Commands.Where(cmdInfo => cmdInfo.Name == input || cmdInfo.Aliases.Contains(input)); //cmds = cmds.Concat(InteractionService.SlashCommands.Where(cmdInfo => cmdInfo.Name == input)); var cmds = _cmdHelpService.GetCmds(Context.User, input).ToArray(); if (cmds.Length == 0) { return(NoResultError("commands", input)); } var cmdStrings = cmds .Select(cmd => cmd switch { CommandInfo cmdInfo => $"{GuildConfig.Prefix}{cmdInfo.Name} {cmdInfo.Parameters.Select(param => $"<{param.Name}>").Join(' ')}\n{cmdInfo.Summary}", SlashCommandInfo slashCmdInfo => $"/{slashCmdInfo.Name} {slashCmdInfo.Parameters.Select(param => param.IsRequired ? $"<{param.Name}>" : $"<optional: {param.Name}>").Join(' ')}\n{slashCmdInfo.Description}", _ => "" }
async Task SlashCommandExecuted(SlashCommandInfo arg1, Discord.IInteractionContext arg2, Discord.Interactions.IResult arg3) { if (!arg3.IsSuccess) { switch (arg3.Error) { case InteractionCommandError.UnmetPrecondition: await arg2.Interaction.RespondAsync($"Unmet Precondition: {arg3.ErrorReason}", ephemeral : true); break; case InteractionCommandError.UnknownCommand: await arg2.Interaction.RespondAsync("Unknown command", ephemeral : true); break; case InteractionCommandError.BadArgs: await arg2.Interaction.RespondAsync("Invalid number or arguments", ephemeral : true); break; case InteractionCommandError.Exception: Console.WriteLine("Command Error:"); Console.WriteLine(arg3.ErrorReason); await arg2.Interaction.RespondAsync($"Command exception: {arg3.ErrorReason}. If this message persists, please let us know in the support server (https://discord.gg/xyzMyJH) !", ephemeral : true); break; case InteractionCommandError.Unsuccessful: await arg2.Interaction.RespondAsync("Command could not be executed", ephemeral : true); break; default: break; } } }
/// <summary> /// Retrieves the Slash Command result and acts accordingly in case of error. /// </summary> /// <param name="_">The received <see cref="SlashCommandInfo"/>.</param> /// <param name="arg2">The interaction context.</param> /// <param name="arg3">The interaction result.</param> /// <returns>A task that represents the asynchronous execution operation. The task contains the result of the command execution.</returns> public async Task HandleSlashCommandAsync(SlashCommandInfo _, IInteractionContext arg2, IResult arg3) => await HandleCommandAsync(arg2, arg3);
/// <summary> /// Handles success and failures from slash commands. /// </summary> /// <param name="arg1"></param> /// <param name="arg2"></param> /// <param name="arg3"></param> /// <returns></returns> private Task SlashCommandExecuted(SlashCommandInfo arg1, Discord.IInteractionContext arg2, Discord.Interactions.IResult arg3) { if (!arg3.IsSuccess) { // Defer if not already done: try { arg2.Interaction.DeferAsync(true).GetAwaiter().GetResult(); } catch { // ignore } // Write error to console: Console.WriteLine("Error: " + arg3.Error); switch (arg3.Error) { case InteractionCommandError.UnmetPrecondition: // Check for userperm error: if (arg3.ErrorReason.Contains("UserPerm")) { arg2.Interaction.FollowupAsync("You do not have permission to execute this command.", ephemeral: true); break; } arg2.Interaction.FollowupAsync("Command Failed\n" + arg3.ErrorReason, ephemeral: true); break; case InteractionCommandError.UnknownCommand: arg2.Interaction.FollowupAsync("Unknown command. It may have been recently removed or changed.", ephemeral: true); break; case InteractionCommandError.BadArgs: arg2.Interaction.FollowupAsync("The provided values are invalid. (BadArgs)", ephemeral: true); break; case InteractionCommandError.Exception: //notify owner if desired: if (arg3.ErrorReason.Contains("Invalid Form Body")) { arg2.Interaction.FollowupAsync("Invalid form body. Please check to ensure that all of your parameters are correct.", ephemeral: true); break; } if (notifyOwnerOnError && !string.IsNullOrEmpty(_config["OwnerID"])) { string error = Format.Bold("Error:") + "\n" + Format.Code(arg3.ErrorReason) + "\n\n" + Format.Bold("Command:") + "\n" + Format.BlockQuote(arg1.Name + " " + DiscordTools.SlashParamToString(arg2)); if (error.Length > 2000) { error = error.Substring(0, 2000); } UserExtensions.SendMessageAsync(_client.GetUser(ulong.Parse(_config["OwnerID"])), error); } arg2.Interaction.FollowupAsync("Sorry, Something went wrong...", ephemeral: true); break; case InteractionCommandError.Unsuccessful: //notify owner if desired: if (notifyOwnerOnError && !string.IsNullOrEmpty(_config["OwnerID"])) { string error = Format.Bold("Error:") + "\n" + Format.Code(arg3.ErrorReason) + "\n\n" + Format.Bold("Command:") + "\n" + Format.BlockQuote(arg1.Name + " " + DiscordTools.SlashParamToString(arg2)); if (error.Length > 2000) { error = error.Substring(0, 2000); } UserExtensions.SendMessageAsync(_client.GetUser(ulong.Parse(_config["OwnerID"])), error); } arg2.Interaction.FollowupAsync("Sorry, Something went wrong...", ephemeral: true); break; default: //notify owner if desired: if (notifyOwnerOnError && !string.IsNullOrEmpty(_config["OwnerID"])) { string error = Format.Bold("Error:") + "\n" + Format.Code(arg3.ErrorReason) + "\n\n" + Format.Bold("Command:") + "\n" + Format.BlockQuote(arg1.Name + " " + DiscordTools.SlashParamToString(arg2)); if (error.Length > 2000) { error = error.Substring(0, 2000); } UserExtensions.SendMessageAsync(_client.GetUser(ulong.Parse(_config["OwnerID"])), error); } arg2.Interaction.FollowupAsync("Sorry, Something went wrong..."); break; } } return(Task.CompletedTask); }