protected void HandleResult(IResult result) { if (result == null) { this.LastResponse = "Null Response\n"; LogView.AddLog(this.LastResponse); return; } this.LastResponseTexture = null; // Some platforms return the empty string instead of null. if (!string.IsNullOrEmpty(result.Error)) { this.Status = "Error - Check log for details"; this.LastResponse = "Error Response:\n" + result.Error; } else if (result.Cancelled) { this.Status = "Cancelled - Check log for details"; this.LastResponse = "Cancelled Response:\n" + result.RawResult; } else if (!string.IsNullOrEmpty(result.RawResult)) { this.Status = "Success - Check log for details"; this.LastResponse = "Success Response:\n" + result.RawResult; } else { this.LastResponse = "Empty Response\n"; } LogView.AddLog(result.ToString()); }
public async Task CommandExecutedAsync(Optional <CommandInfo> command, ICommandContext context, IResult result) { // command is unspecified when there was a search failure (command not found); we don't care about these errors if (!command.IsSpecified) { return; } // the command was successful, we don't care about this result, unless we want to log that a command succeeded. if (result.IsSuccess) { return; } Log.Fatal($"{context.User.Username} tried to call {command.Value.Name}"); Log.Fatal(result.ToString()); // the command failed, let's notify the user that something happened. await context.Channel.SendMessageAsync($"Maybe next time"); }
//IEnumerator<WWW> getImage(AccessToken CurToken) //{ // WWW www = new WWW("https://graph.facebook.com/" + CurToken.UserId + "/picture?type=large"); // yield return www; // headMesh.GetComponent<Image>().material.mainTexture = www.texture; //} private void loginName(IResult result) { if (result.Error != null) { Debug.Log("ERROR:" + result.Error); } else if (!FB.IsLoggedIn) { Debug.Log("User not login"); } else { IDictionary <string, string> dict; dict = Json.Deserialize(result.ToString()) as IDictionary <string, string>; database.name = dict["name"].ToString(); Debug.Log(database.name); } }
public async Task CommandExecutedAsync(Optional <CommandInfo> command, ICommandContext context, IResult result) { if (!command.IsSpecified) { return; } if (result.IsSuccess) { return; } // the command failed, let's notify the user that something happened. // commented out while live await context.Channel.SendMessageAsync($"error: {result.ToString()}"); //await context.Channel.SendMessageAsync($"Sowwy, der's an error. :c"); }
public async Task CommandExecutedAsync(Optional <CommandInfo> command, ICommandContext context, IResult result) { // command is unspecified when there was a search failure (command not found); we don't care about these errors if (!command.IsSpecified) { await context.Channel.SendMessageAsync("🔪"); } return; // the command was succesful, we don't care about this result, unless we want to log that a command succeeded. if (result.IsSuccess) { return; } // the command failed, let's notify the user that something happened. await context.Channel.SendMessageAsync($"error: {result.ToString()}"); }
private async Task HandleCommandAsync(SocketMessage socketMsg) { if (!(socketMsg is SocketUserMessage msg)) { return; } var context = new SocketCommandContext(discordClient, msg); SocketGuild guild = (msg.Channel as SocketTextChannel)?.Guild; string prefix = await GetPrefixAsync(guild?.Id).ConfigureAwait(false); int argPos = 0; if (msg.HasStringPrefix(prefix, ref argPos)) { string commandText = msg.Content.Substring(argPos).ToLowerInvariant().Trim(); if (!commandText.IsEmpty()) { IResult result = await commandService.ExecuteAsync(context, argPos, serviceProvider).ConfigureAwait(false); if (!result.IsSuccess) { if (result.Error.HasValue) { CommandError error = result.Error.Value; string errorMessage = GetCommandErrorMessage(error, prefix, commandText); _ = await context.Channel.SendMessageAsync(errorMessage).ConfigureAwait(false); if (error == CommandError.Exception || error == CommandError.ParseFailed || error == CommandError.Unsuccessful) { if (discordClient is MonkeyClient monkeyClient) { await monkeyClient.NotifyAdminAsync(errorMessage).ConfigureAwait(false); } } } else { _ = await context.Channel.SendMessageAsync(result.ToString()).ConfigureAwait(false); } } } } }
public async Task HandleCommand(SocketMessage s) { bool notrunning = !Globals.SelfbotRunning; if (notrunning) { Thread.CurrentThread.Abort(); } SocketUserMessage msg = s as SocketUserMessage; bool msgnull = msg == null; if (!msgnull) { SocketCommandContext context = new SocketCommandContext(this._client, msg); int argPos = 0; string prefix = Globals.Prefix; Globals.RecentGuildID = context.Channel.Id; bool haspref = msg.HasStringPrefix(prefix, ref argPos, StringComparison.Ordinal) && msg.Author.Id == this._client.CurrentUser.Id; if (haspref) { if (Configuration._Config.CustomCommands.TryGetValue(context.Message.Content.ToLower(), out string value)) { await context.Message.DeleteAsync(); ConsoleLog.Log(string.Format("[Console] Executed Custom CMD: {0}", value)); await context.Channel.SendMessageAsync(value); } else { var result2 = await this._cmds.ExecuteAsync(context, argPos, null, MultiMatchHandling.Exception); IResult result = result2; result2 = null; ConsoleLog.Log(string.Format("[Console] Executed CMD: {0}", context)); if (!result.IsSuccess) { ConsoleLog.Log(result.ToString()); } } } } }
private DocumentReader ParseInclude(string filePath) { Log.Info("Parsing included document at path '{0}'", filePath); using (new CompositeDisposable( new Log.ScopedIndent(), new Log.ScopedTimer(Log.Level.Debug, "Parse Include File", filePath))) { string configText = File.ReadAllText(filePath); IResult <ConfigDocument> result = DocumentParser.Document.TryParse(configText); if (!result.WasSuccessful) { throw new DocumentParseException(filePath, result.ToString()); } ConfigDocument configDoc = result.Value; var reader = new DocumentReader(configDoc, Solution.SolutionConfigDir); Log.Info("Finished parsing included document at path '{0}'", filePath); return(reader); } }
private async Task OnMessageReceivedAsync(SocketMessage socketMessage) { if (socketMessage is not SocketUserMessage userMessage || userMessage.Author.Id == _DiscordClient.CurrentUser.Id) { return; } SocketCommandContext commandContext = new(_DiscordClient, userMessage); int prefixIndex = 0; if (userMessage.HasStringPrefix(_Configuration.CurrentValue.Prefix, ref prefixIndex) || userMessage.HasMentionPrefix(_DiscordClient.CurrentUser, ref prefixIndex)) { IResult commandResult = await _CommandService.ExecuteAsync(commandContext, prefixIndex, _Services); if (!commandResult.IsSuccess) { await commandContext.Channel.SendMessageAsync(commandResult.ToString()); } } }
/// <summary> /// Parses the specified input string. /// </summary> /// <typeparam name="T">The type of the result.</typeparam> /// <param name="parser">The parser instance.</param> /// <param name="input">The input string to parse.</param> /// <exception cref="ParseException">An error has occured while parsing the specified input string.</exception> /// <exception cref="ArgumentNullException">One or more parameters is `null` (`Nothing` in Visual Basic).</exception> /// <returns> /// The result returned by the parser after parsing the source <paramref name="input"/>. /// </returns> public static T Parse <T>(this Parser <T> parser, string input) { if (parser == null) { throw new ArgumentNullException(nameof(parser)); } if (input == null) { throw new ArgumentNullException(nameof(input)); } IResult <T> result = parser.TryParse(input); if (result.WasSuccessful) { return(result.Value); } throw new ParseException(result.ToString()); }
protected void HandleResult(IResult result) { if (result == null) { return; } Debug.Log("open home"); SceneManager.LoadScene("Home"); Debug.Log(result.ToString()); /** * * {"access_token":"...","user_id":"...","callback_id":"...","key_hash":"...","permissions":"...","expiration_timestamp":"...","last_refresh":"...","opened":...,"declined_permissions":"..."} */ Debug.Log(result.RawResult.ToString()); JsonData data = JsonMapper.ToObject(result.RawResult.ToString()); Debug.Log(data["access_token"]); }
public async Task CommandExecutedAsync(ICommandContext context, IResult result) { /*if (!command.IsSpecified) * return;*/ //await Log.Logger(Log.Logs.INFO, result.IsSuccess.ToString()); if (result.Error == null) { //Console.WriteLine("Result Error Null"); return; } if (result.Error.Value == CommandError.UnknownCommand) { //Console.WriteLine("Unknown Command"); return; } if (result.Error.Value == CommandError.UnmetPrecondition) { await context.Channel.SendMessageAsync($"The following condition has failed: {result.ErrorReason}"); //Console.WriteLine("Unmet Precondition"); return; } if (result.Error.Value == CommandError.BadArgCount) { await context.Channel.SendMessageAsync($"Not enough arguments for the command!"); //Console.WriteLine("Not enough arguments"); return; } if (result.IsSuccess) { //Console.WriteLine("Success!"); return; } await context.Channel.SendMessageAsync($"There was an error running the command, please try it again and if the problem persists contact towergame#9726. {result.ErrorReason}"); await Log.Logger(Log.Logs.ERROR, $"A problem occured running a command: {result.ToString()}."); }
protected void GetAppLinkCallBack(IResult result) { string LastResponse = string.Empty; string Status = string.Empty; if (result == null) { LastResponse = "Null Response\n"; if (debug) { Debug.Log(LastResponse); } return; } if (!string.IsNullOrEmpty(result.Error)) { Status = "Error - Check log for details"; LastResponse = "Error Response:\n" + result.Error; } else if (result.Cancelled) { Status = "Cancelled - Check log for details"; LastResponse = "Cancelled Response:\n" + result.RawResult; } else if (!string.IsNullOrEmpty(result.RawResult)) { Status = "Success - Check log for details"; LastResponse = "Success Response:\n" + result.RawResult; } else { LastResponse = "Empty Response\n"; } if (debug) { Debug.Log(result.ToString()); } }
public async Task MessageReceivedAsync(SocketMessage rawMessage) { SocketUserMessage message = rawMessage as SocketUserMessage; // Ignore message if null or if message is from a Bot. if (message is null || message.Author.IsBot) { return; } // Holds the starting position of the command, after the prefix. int argPos = 0; // If the Prefix is wrong, don't process this message. if (!PrefixChecker(message, ref argPos)) { return; } // Get the Context of the message and broadcast the "typing" status until we're done. SocketCommandContext context = new SocketCommandContext(_client, message); using (IDisposable x = context.Channel.EnterTypingState()) { // Run the command. IResult result = await _commands.ExecuteAsync(context, argPos, _services); // Log any and all failures. if (!result.IsSuccess) { await ProgramLogger.Log(result.ErrorReason); } // Send back Error Message if there is one, but do not send "Unknown Command" Error Messages. if (result.Error.HasValue && result.Error.Value != CommandError.UnknownCommand) { await context.Channel.SendMessageAsync(result.ToString()); } } }
public async Task CommandExecutedAsync(Optional <CommandInfo> command, ICommandContext commandContext, IResult result) { // If the command is in a Guild Channel, delete the command. if (commandContext.Channel is IGuildChannel) { await commandContext.Channel.DeleteMessageAsync(commandContext.Message); } // If the command is not found, tell the user no such command exists, and return. if (!command.IsSpecified) { await commandContext.User.SendMessageAsync($"error: the command \"{commandContext.Message.Content}\" was not found"); return; } // If the command failed, let's notify the user that something happened. if (!result.IsSuccess) { await commandContext.User.SendMessageAsync($"error: {result.ToString()}"); } }
public async Task LogCommand(ICommandContext context, IResult result) { if (_client.GetChannel(LogChannel) is SocketTextChannel channel) { var embedBuilder = new EmbedBuilder { Color = result.IsSuccess ? new Color(10, 200, 10) : new Color(200, 10, 10), }; embedBuilder.AddField(f => { f.Name = "Guild:"; f.Value = $"**Name:** {context.Guild.Name} \n" + $"**Id:** {context.Guild.Id}"; f.IsInline = true; }); embedBuilder.AddField(f => { f.Name = "Channel:"; f.Value = $"**Name:** {context.Channel.Name} \n" + $"**Id:** {context.Channel.Id}"; f.IsInline = true; }); embedBuilder.AddField(f => { f.Name = "Content:"; f.Value = context.Message.Content; }); embedBuilder.AddField(f => { f.Name = "Result:"; f.Value = result.ToString(); }); embedBuilder.WithCurrentTimestamp(); await channel.SendMessageAsync("A command has been called!", false, embedBuilder.Build()); } }
protected void HandleResult(IResult result) { Debug.Log("HandleResult : " + result.ToString()); /* * if (result == null) * { * this.LastResponse = "Null Response\n"; * LogView.AddLog(this.LastResponse); * return; * } * * this.LastResponseTexture = null; * * // Some platforms return the empty string instead of null. * if (!string.IsNullOrEmpty(result.Error)) * { * this.Status = "Error - Check log for details"; * this.LastResponse = "Error Response:\n" + result.Error; * } * else if (result.Cancelled) * { * this.Status = "Cancelled - Check log for details"; * this.LastResponse = "Cancelled Response:\n" + result.RawResult; * } * else if (!string.IsNullOrEmpty(result.RawResult)) * { * this.Status = "Success - Check log for details"; * this.LastResponse = "Success Response:\n" + result.RawResult; * } * else * { * this.LastResponse = "Empty Response\n"; * } * * LogView.AddLog(result.ToString()); */ }
private async Task OnCommandExecutedAsync(CommandInfo command, ICommandContext context, IResult result) { if (result is PreconditionResult preResult) { await context.Channel.SendMessageAsync(preResult.ErrorReason); } else if (!string.IsNullOrEmpty(result?.ErrorReason)) { if (result.Error.Value.ToString().Equals("ObjectNotFound") || result.Error.Value.ToString().Equals("BadArgCount")) { await context.Channel.SendMessageAsync(string.Format(Messages.ERR_CMD_USAGE, context.User.Mention)); } else if (result.Error.Value.ToString().Equals("UnknownCommand")) { await context.Channel.SendMessageAsync(string.Format(Messages.ERR_CMD_NOT_EXIST, context.User.Mention)); } else { await context.Channel.SendMessageAsync(result.ToString()); } } }
public async Task CommandExceutedAsync(Optional <CommandInfo> command, ICommandContext context, IResult result) { if (!command.IsSpecified) { return; } if (result.IsSuccess) { return; } var embed = new EmbedBuilder { Title = "Command Failed", Description = result.ToString(), Color = Color.Red }; embed.WithCurrentTimestamp(); await context.Channel.SendMessageAsync(embed : embed.Build()); }
public async Task CommandExecutedAsync(Optional <CommandInfo> command, ICommandContext context, IResult result) { // command is unspecified when there was a search failure (command not found); we don't care about these errors if (!command.IsSpecified) { //await context.Channel.SendMessageAsync($"error: {result.ToString()}"); return; } // the command was succesful, we don't care about this result, unless we want to log that a command succeeded. if (result.IsSuccess) { await LogAsync(new LogMessage(LogSeverity.Info, context.User.Username, context.Message.ToString())); return; } // self handle some errors if (!result.Error.Equals("BadArgCount")) { var eb = new EmbedBuilder(); var embed = eb.AddField("Fehler", "Die Parameter sind nicht richtig eingegeben.\n" + "**!help " + command.Value.Name + "** für weitere Informationen verwenden.") .WithColor(Color.Red) .Build(); await context.Channel.SendMessageAsync(null, false, embed); return; } // the command failed, let's notify the user that something happened. if (!command.Value.Name.Equals("cheat")) { await context.Channel.SendMessageAsync($"error: {result.ToString()}"); } }
public string Item() { try { @prefix@name entity = new @prefix@name(); entity.SetData(Request.Form); entity.TrimEmptyProperty(); string id = Request.Form["__id"]; @defaultValue @additionalParams IResult result = @nameService.Instance.Save(id, entity); if (result.Status) { result.SetSuccessMessage("保存成功"); } return(result.ToString()); } catch (Exception e) { return(new Result(false, e.Message).ToString()); } }
public static async Task HandleCommand(SocketMessage Raw) { SocketUserMessage Message = Raw as SocketUserMessage; String Prefix = Rem.RemConfig["Command_Prefix"].ToString(); // Series of checks to make sure we've got a command if (Message == null) { return; } if (Message.Content == Prefix) { return; } if (Message.Content.Contains(Prefix + Prefix)) { return; } if (Message.Author.IsBot && ((bool)Rem.RemConfig["AcceptBotCommands"])) { return; } if (Message.Author == null) { return; } // Arguments int ArgPos = 0; if (!(Message.HasMentionPrefix(RemClient.CurrentUser, ref ArgPos) || Message.HasStringPrefix(Prefix, ref ArgPos))) { return; } // Preparing for control handover to command CommandContext Context = new CommandContext(RemClient, Message); SearchResult Search = RemService.Search(Context, ArgPos); CommandInfo Command = null; if (Search.IsSuccess) { Command = Search.Commands.FirstOrDefault().Command; } // Handover await Task.Run(async() => { IResult Result = await RemService.ExecuteAsync(Context, ArgPos, RemDeps, MultiMatchHandling.Best); Logging.LogMessage(LogLevel.Info, LogEvent.Command, $"{Command?.Name ?? Message.Content.Substring(ArgPos).Split(' ').First()} => {(Result.IsSuccess ? Result.ToString() : Result.Error.ToString())} | Server: [{(Context.IsPrivate ? "Private." : Context.Guild.Name)}] | {(Context.IsPrivate ? "Private." : $"Channel: #{Context.Channel.Name} ")} | Author: ({Context.User})"); if (!Result.IsSuccess) { await OnCommandError(Result, Context); } }); }
/// <summary> /// 判断一个返回结果是否成功。如果失败,将会弹出异常信息。 /// </summary> /// <param name="owner">控件拥有者。</param> /// <param name="result">返回结果。</param> /// <returns>返回结果的状态。</returns> public static bool IsSuccess(this Control owner, IResult result) { if (result != null) { if (result.IsSucceed) return true; Msg.ShowError(result.ToString()); } return false; }
/// <summary> /// 判断一个返回结果是否成功。如果失败,将会弹出异常信息。 /// </summary> /// <param name="owner">控件拥有者。</param> /// <param name="result">返回结果。</param> /// <param name="prefix">前缀内容。</param> /// <param name="suffix">后缀内容。</param> /// <returns>返回结果的状态。</returns> public static bool IsSuccess(this Control owner, IResult result, string prefix, string suffix = null) { if (result != null) { if (result.IsSucceed) return true; Msg.ShowError(owner, prefix + result.ToString() + suffix); } return false; }
public async Task CommandExecutedAsync(Optional <CommandInfo> command, ICommandContext context, IResult result) { // if a command isn't found, log that info to console and exit this method if (!command.IsSpecified) { _logger.LogError($"Command failed to execute for [" + context.User.Username + "] <-> [" + result.ErrorReason + "]!"); return; } // log success to the console and exit this method if (result.IsSuccess) { _logger.LogInformation($"Command [" + command.Value.Name + "] executed for -> [" + context.User.Username + "]"); return; } // failure scenario, let's let the user know await context.Channel.SendMessageAsync($"Sorry, " + context.User.Username + " something went wrong -> [" + result.ToString() + "]!"); }
public OwnApiHttpResponse(IResult apiResult) { StringContent content = new StringContent(apiResult.ToString(), Encoding.GetEncoding("UTF-8"), "application/json"); this.Content = content; }
private async Task HandleCommandAsync(SocketMessage messageParam) { var message = messageParam as SocketUserMessage; if (message == null) { return; } int argPos = 0; foreach (Message msg in Program.config.Messages) { if (message.Content.ToLower().Contains(msg.Question.ToLower()) && message.HasMentionPrefix(_client.CurrentUser, ref argPos)) { await message.Channel.SendMessageAsync(msg.Answer.Replace("%g", "<").Replace("%s", ">")); } } if ((message.HasStringPrefix(Program.config.CommandPrefix, ref argPos) && !message.Author.IsBot)) { var context = new SocketCommandContext(_client, message); await Program.Log(new LogMessage(LogSeverity.Info, "CommandHandler", "User " + messageParam.Author.Username + " in #" + messageParam.Channel.Name + " sent command: " + message)); // Execute the command with the command context we just // created, along with the service provider for precondition checks. if (Shared.commandsEnabled) { IResult result = await _commands.ExecuteAsync(context : context, argPos : argPos, services : null); if (!result.IsSuccess) { if (result.ErrorReason == "Unknown command.") { Random r = new Random(); int index = r.Next(0, 5); int index2 = r.Next(0, 5); if (index == index2) { await context.Channel.SendMessageAsync("I'm sorry, but i'm now watching to Pornhub and i don't know that command."); } else { await context.Channel.SendMessageAsync("I'm sorry, but i don't know that command."); } } else { await context.Channel.SendMessageAsync(result.ToString()); } } } else { await context.Channel.SendMessageAsync("I'm sorry, but commands are disabled by Administrator."); } } else { if (Program.config.AntiBWEnabled) { foreach (string badword in Program.config.BadWords) { if (message.Content.ToLower().Contains(badword.ToLower())) { await message.DeleteAsync(); await message.Channel.SendMessageAsync("That bad behaviour? Just be calm! <:fuckyou:545662379560796214>"); return; } } } } }
private void HandleResult(IResult result) { Debug.Log("[FacebookAuth] Result: " + result); if (result == null) { ex = new System.Exception("Error at login!"); tres = ProcessResult.Failure; return; } // Some platforms return the empty string instead of null. if (!string.IsNullOrEmpty(result.Error)) { ex = new System.Exception(result.Error); tres = ProcessResult.Failure; } else if (result.Cancelled) { ex = new System.Exception("LogIn cancelled"); tres = ProcessResult.Failure; } else if (!string.IsNullOrEmpty(result.RawResult)) { Debug.Log("[Facebook Auth] login OK!... Access token:: " + AccessToken.CurrentAccessToken.TokenString); Credential fbcredential = FacebookAuthProvider.GetCredential(AccessToken.CurrentAccessToken.TokenString); if (AuthManager.Instance.IsAuthenticated) { if (AuthManager.Instance.auth.CurrentUser.IsAnonymous) { AuthManager.Instance.auth.CurrentUser.LinkWithCredentialAsync(fbcredential).ContinueWith(task => { if (task.IsCanceled || task.IsFaulted) { QEventExecutor.ExecuteInUpdate(() => { ex = AuthManager.GetFirebaseException(task.Exception); Debug.LogError("[Facebok auth] An Error ocurred " + ex); tres = ProcessResult.Failure; }); return; } if (task.IsCompleted) { QEventExecutor.ExecuteInUpdate(() => { Debug.Log("[Facebook Auth] Auth completed!"); uid = task.Result.UserId; tres = ProcessResult.Completed; }); } }); } else { ex = new System.ArgumentException("User is not anonymous"); Debug.LogError("[FacebookAuth] User is not Anonymous!"); tres = ProcessResult.Failure; } } else { AuthManager.Instance.auth.SignInWithCredentialAsync(fbcredential).ContinueWith(task => { if (task.IsCanceled || task.IsFaulted) { QEventExecutor.ExecuteInUpdate(() => { ex = AuthManager.GetFirebaseException(task.Exception); Debug.LogError("[Facebok auth] An Error ocurred " + ex); tres = ProcessResult.Failure; }); return; } if (task.IsCompleted) { QEventExecutor.ExecuteInUpdate(() => { Debug.Log("[Facebook Auth] Register completed!"); uid = task.Result.UserId; tres = ProcessResult.Completed; }); } }); } } else { ex = new System.Exception("Empty Response"); tres = ProcessResult.Failure; } Debug.Log("[Facebook AUth] result: " + result.ToString()); }
public MathWorkspaceItem(string strExp, IResult result) { this.strExp = strExp; this.result = result; this.answer = result.ToString(); }
private void showResults(IResult results) { textBoxForFibonachiMethod.Text = results.ToString(); }
public string Delete(string id) { IResult result = OperateLogService.Instance.Delete(id); return(result.ToString()); }
private Task CommandLog(Optional <CommandInfo> info, ICommandContext context, IResult result) { if (result.IsSuccess) { return(Task.CompletedTask); } switch (result.Error.Value) { case CommandError.UnknownCommand: { return(Task.CompletedTask); } case CommandError.ParseFailed: { Console.WriteLine(context.Guild.Name + " | " + result.ToString()); break; } case CommandError.BadArgCount: { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(context.Guild.Name + " | " + result.ToString()); Console.ForegroundColor = ConsoleColor.Green; break; } case CommandError.ObjectNotFound: { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(context.Guild.Name + " | " + result.ToString()); Console.ForegroundColor = ConsoleColor.Green; break; } case CommandError.MultipleMatches: { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(context.Guild.Name + " | " + result.ToString()); Console.ForegroundColor = ConsoleColor.Green; break; } case CommandError.UnmetPrecondition: { Console.WriteLine(context.Guild.Name + " | " + result.ToString()); break; } case CommandError.Exception: { Console.WriteLine(context.Guild.Name + " | " + result.ToString()); break; } case CommandError.Unsuccessful: { Console.WriteLine(context.Guild.Name + " | " + result.ToString()); break; } default: { break; } } return(Task.CompletedTask); }
public string Delete(string id) { IResult result = DailyAccountSnapshotService.Instance.Delete(id); return(result.ToString()); }
/// <inheritdoc /> public async Task <EmbedBuilder> HandleErrorsAsync(IResult iResult, SocketCommandContext context) { var message = context.Message.Content.ToLower(); var prefix = Constants.Prefix; var result = iResult.ToString(); if (result.Contains("UnmetPrecondition: Bot requires guild permission EmbedLinks")) { await context.Channel.SendMessageAsync("I need the EmbedLinks permission for that command!").ConfigureAwait(false); return(null); } // User permission errors. if (result.Contains("UnmetPrecondition: User requires guild permission Administrator")) { return(EmbedError("Permission error", ":no_entry_sign: You need admin permissions for this command.")); } if (result.Contains("UnmetPrecondition: User requires guild permission ManageRoles")) { return(EmbedError("Permission error", ":no_entry_sign: You need Manage Roles permissions for this command.")); } // Sending the user a DM if the bot cant send a message in that channel. if (result.Contains("UnmetPrecondition: Bot requires guild permission SendMessages")) { await context.User.SendMessageAsync("", false, EmbedError("Permission error", "I need don't have the right permissions to talk in that channel!\n" + "Pls give me the SendMessages permission!").Build()).ConfigureAwait(false); return(null); } if (result.Contains("A quoted parameter is incomplete")) { return(EmbedError("Incorrect input", "If your are using quotes pls remember to close them <3")); } // If error is a Missing permissions error, send embedded error message. if (result.Contains("The server responded with error 50013: Missing Permissions") || result.Contains("UnmetPrecondition: Bot requires guild permission")) { if (context is SocketCommandContext commandContext) { var guildPermissions = commandContext.Guild.CurrentUser.Roles.Select(x => x.Permissions).ToList(); var description = "Im missing the following permissions:"; if (!guildPermissions.Any(x => x.SendMessages)) { description += " **SendMessages**"; } if (!guildPermissions.Any(x => x.EmbedLinks)) { description += " **EmbedLinks**"; } if (!guildPermissions.Any(x => x.AddReactions)) { description += " **AddReactions**"; } await commandContext.Channel.SendMessageAsync(description).ConfigureAwait(false); return(null); } } // Checking what command what used to embed the correct error. var defaultPrefixErrorMessage = CheckForCommand(message, result, prefix); if (defaultPrefixErrorMessage != null) { return(defaultPrefixErrorMessage); } var customPrefix = _prefixService.GetPrefix(context.Guild.Id); if (customPrefix != null) { var customPrefixErrorMessage = CheckForCommand(message, result, customPrefix); if (customPrefixErrorMessage != null) { return(customPrefixErrorMessage); } } // To many or to few parameters error messages. if (result.Contains("BadArgCount: The input text has too many parameters.")) { return(EmbedError("Incorrect input", "The input has to many parameters")); } if (result.Contains("BadArgCount: The input text has too few parameters.")) { return(EmbedError("Incorrect input", "The input text has too few parameters.")); } return(GetDefaultError(result)); }