public void ConstructorMessage_SetsValues()
        {
            const string message = "This is a message.";
            var          commandNotFoundException = new CommandNotFoundException(message);

            Assert.That(commandNotFoundException.Message, Is.EqualTo(message));
        }
Пример #2
0
        public static async Task OnError(CommandsNextExtension _, CommandErrorEventArgs e)
        {
            if (e.Context.User.IsBotSafeCheck())
            {
                return;
            }

            var ex = e.Exception;

            if (ex is InvalidOperationException && ex.Message.Contains("No matching subcommands were found"))
            {
                ex = new CommandNotFoundException(e.Command.Name);
            }

            if (ex is not CommandNotFoundException cnfe)
            {
                Config.Log.Error(e.Exception);
                return;
            }

            if (string.IsNullOrEmpty(cnfe.CommandName))
            {
                return;
            }

            if (e.Context.Prefix != Config.CommandPrefix &&
                e.Context.Prefix != Config.AutoRemoveCommandPrefix &&
                (e.Context.Message.Content?.EndsWith("?") ?? false) &&
                e.Context.CommandsNext.RegisteredCommands.TryGetValue("8ball", out var cmd))
            {
                var updatedContext = e.Context.CommandsNext.CreateContext(
                    e.Context.Message,
                    e.Context.Prefix,
                    cmd,
                    e.Context.Message.Content[e.Context.Prefix.Length..].Trim()
        private static void CheckErrors(this PowerShell ps, CancellationToken cancellationToken = default(CancellationToken))
        {
            PSDataCollection <ErrorRecord> errors = (ps.Streams == null) ? null : ps.Streams.Error;

            if (errors != null && errors.Count > 0)
            {
                if (errors.Count == 1)
                {
                    throw RestoreCommandNotFoundException(errors[0]);
                }
                else
                {
                    List <Exception>         innerExceptions   = errors.Select(e => RestoreCommandNotFoundException(e)).ToList();
                    CommandNotFoundException notFoundException = innerExceptions.OfType <CommandNotFoundException>().FirstOrDefault();

                    if (notFoundException != null)
                    {
                        throw notFoundException;
                    }
                    else
                    {
                        throw new AggregateException(string.Join(Environment.NewLine, errors.Select(e => e.Exception.Message)), innerExceptions);
                    }
                }
            }

            if (ps.HadErrors)
            {
                cancellationToken.ThrowIfCancellationRequested();                       //	PipelineStoppedException();
                throw new InvalidPowerShellStateException();
            }
        }
        public void ConstructorMessageInnerException_SetsValues()
        {
            const string message                  = "This is another message.";
            var          innerException           = new IOException();
            var          commandNotFoundException = new CommandNotFoundException(message, innerException);

            Assert.That(commandNotFoundException.Message, Is.EqualTo(message));
            Assert.That(commandNotFoundException.InnerException, Is.EqualTo(innerException));
        }
        public void ConstructorCommandNameCommandArgs_SetsValues()
        {
            const string commandName = "This is yet another message.";
            var          commandArgs = new[] { "Arg0", "Arg1" };
            var          commandNotFoundException = new CommandNotFoundException(commandName, commandArgs);

            Assert.That(commandNotFoundException.Message, Is.EqualTo("Invalid command name."));
            Assert.That(commandNotFoundException.CommandName, Is.EqualTo(commandName));
            Assert.That(commandNotFoundException.CommandArgs, Is.EqualTo(commandArgs));
        }
Пример #6
0
        internal IEnumerator <DSResource> InvokeCmdletAsync(System.Management.Automation.PowerShell powerShell, Expression expression, EventHandler <DataAddedEventArgs> dataAddedEventHandler, AsyncCallback executionCompletionCallback, bool noStreamingResponse)
        {
            Tracer tracer = new Tracer();

            this.dataStore = new AsyncDataStore <DSResource>(expression, noStreamingResponse);
            this.output    = new PSDataCollection <PSObject>();
            tracer.CommandInvocationStart(this.cmdletInfo.CmdletName);
            powerShell.Runspace = this.runspace.Item.Runspace;
            powerShell.AddCommand(this.cmdletInfo.CmdletName);
            foreach (string key in this.parameters.Keys)
            {
                if (!this.cmdletInfo.IsSwitch(key))
                {
                    powerShell.AddParameter(key, this.parameters[key]);
                }
                else
                {
                    powerShell.AddParameter(key);
                }
            }
            this.isExecutionCompleted = false;
            using (OperationTracer operationTracer = new OperationTracer(new Action <string>(TraceHelper.Current.CmdletExecutionStart), new Action <string>(TraceHelper.Current.CmdletExecutionEnd), powerShell.Commands.ToTraceMessage()))
            {
                try
                {
                    this.timer.Start();
                    powerShell.Invoke <PSObject>(null, this.output, Utils.GetPSInvocationSettings());
                }
                catch (CommandNotFoundException commandNotFoundException1)
                {
                    CommandNotFoundException commandNotFoundException = commandNotFoundException1;
                    throw new CommandInvocationFailedException(powerShell.Commands.Commands[0].CommandText, commandNotFoundException);
                }
                catch (ParameterBindingException parameterBindingException1)
                {
                    ParameterBindingException parameterBindingException = parameterBindingException1;
                    throw new CommandInvocationFailedException(powerShell.Commands.Commands[0].CommandText, parameterBindingException);
                }
                catch (CmdletInvocationException cmdletInvocationException1)
                {
                    CmdletInvocationException cmdletInvocationException = cmdletInvocationException1;
                    throw new CommandInvocationFailedException(powerShell.Commands.Commands[0].CommandText, cmdletInvocationException);
                }
            }
            return(new BlockingEnumerator <DSResource>(this.dataStore));
        }
Пример #7
0
        public Command Select(string commandName, List <Command> availableCommands)
        {
            var command = new MatchSelector <Command>().Match(commandName, availableCommands, c => c.Name);

            if (command != null)
            {
                return(command);
            }

            var exception = new CommandNotFoundException(commandName);

            exception.AvailableCommands.AddRange(availableCommands);

            var possibleCommands = new MatchSelector <Command>().PartialMatch(commandName, availableCommands, c => c.Name);

            exception.PossibleCommands.AddRange(possibleCommands);

            throw exception;
        }
        public void Serialization_Successful()
        {
            const string commandName    = "This is yet again another message!";
            var          commandArgs    = new[] { "Arg0", "Arg1", "Arg2", "Arg3" };
            var          innerException = new IOException();
            var          commandNotFoundExceptionOriginal =
                new CommandNotFoundException(commandName, commandArgs, innerException);
            CommandNotFoundException commandNotFoundException;

            using (var memoryStream = new MemoryStream())
            {
                var binaryFormatter = new BinaryFormatter();
                binaryFormatter.Serialize(memoryStream, commandNotFoundExceptionOriginal);
                memoryStream.Position    = 0;
                commandNotFoundException = (CommandNotFoundException)binaryFormatter
                                           .Deserialize(memoryStream);
            }

            Assert.That(commandNotFoundException.Message, Is.EqualTo("Invalid command name."));
            Assert.That(commandNotFoundException.CommandName, Is.EqualTo(commandName));
            Assert.That(commandNotFoundException.CommandArgs, Is.EqualTo(commandArgs));
            Assert.That(commandNotFoundException.InnerException, Is.TypeOf <IOException>());
        }
Пример #9
0
        public Wall_E()
        {
            Config = JsonConvert.DeserializeObject <Config>(File.ReadAllText(Directory.GetCurrentDirectory() + @"\Config.json"));

            Discord = new DiscordClient(new DiscordConfiguration {
                Token = Config.Token,
                UseInternalLogHandler   = true,
                TokenType               = Config.TokenType,
                AutoReconnect           = true,
                ReconnectIndefinitely   = true,
                GatewayCompressionLevel = GatewayCompressionLevel.Stream,
                LargeThreshold          = 250,
                LogLevel = LogLevel.Info,
                WebSocketClientFactory = WebSocket4NetCoreClient.CreateNew,
            });

            Lavalink = Discord.UseLavalink();

            CommandsNext = Discord.UseCommandsNext(new CommandsNextConfiguration {
                EnableDms           = Config.EnableDms,
                EnableMentionPrefix = true,
                EnableDefaultHelp   = false,
                StringPrefixes      = new[] { Config.Prefix },

                Services = new ServiceCollection()
                           .AddSingleton <CSPRNG>()
                           .AddSingleton(new MusicService(Discord))
                           .BuildServiceProvider(true)
            });

            DiscordChannel Log     = Discord.GetChannelAsync(valores.IdLogWall_E).Result;
            int            iterate = 0;

            CommandsNext.CommandErrored += async(args) => {
                var ctx = args.Context;

                CommandNotFoundException cntfe = (CommandNotFoundException)args.Exception;
                if (!String.IsNullOrEmpty(cntfe.CommandName))
                {
                    if (iterate == 1)
                    {
                        await args.Context.RespondAsync($"Nononononononono, esse comando: `{Config.Prefix}{cntfe.CommandName}` também non ecziste!");

                        iterate = 0;
                    }
                    else
                    {
                        await args.Context.RespondAsync($"Padre Quevedo te alerta, esse comando: `{Config.Prefix}{cntfe.CommandName}` non ecziste!");

                        iterate++;
                    }
                    Console.WriteLine(args.Exception.ToString());
                    await Log.SendMessageAsync($"O membro `{ctx.Member.DisplayName}` executou um comando inexistente: `{Config.Prefix}{cntfe.CommandName}`.\nChat: `{ctx.Channel}`\nDia e Hora: `{DateTime.Now}`\n-------------------------------------------------------\n");
                }
            };

            Discord.Ready += DiscordClient_Ready;

            async Task DiscordClient_Ready(ReadyEventArgs e)
            {
                await Discord.UpdateStatusAsync(new DiscordActivity("no Discord da UBGE!"));

                await Log.SendMessageAsync($"**Wall-E da Ética online!**\nLigado às: ``{DateTime.Now}``");

                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine($"[{DateTime.Now.Year}-{DateTime.Now.Month}-{DateTime.Now.Day} {DateTime.Now.Hour}:{DateTime.Now.Minute}:{DateTime.Now.Second} -03:00] [Wall-E] [DSharpPlus] Meu ping é: {Discord.Ping}ms!");
                Console.ResetColor();

                DiscordChannel Paulo = Discord.GetChannelAsync(valores.PauloCanal).Result;

                //await Paulo.SendMessageAsync($"Tenho: **{Discord.GetCommandsNext().RegisteredCommands.Count}** comandos!");
                Console.WriteLine($"[Wall-E] [DSharpPlus] Tenho: {Discord.GetCommandsNext().RegisteredCommands.Count} comandos!");

                IRC(Discord);
            }

            CommandsNext.RegisterCommands(Assembly.GetEntryAssembly());

            Interactivity = Discord.UseInteractivity(new InteractivityConfiguration {
                PaginationBehavior = TimeoutBehaviour.DeleteMessage,
                PaginationTimeout  = TimeSpan.FromMinutes(3),
                Timeout            = TimeSpan.FromMinutes(3)
            });
        }
Пример #10
0
 private static Task CommandNotFoundHandler(CommandNotFoundException ex, DiscordChannel logChannel)
 {
     return(Task.CompletedTask); // may add command suggestions to send the user based on what they typed
 }
Пример #11
0
        private void AccumulateMatchingCommands(IEnumerable <string> commandNames)
        {
            SearchResolutionOptions none = SearchResolutionOptions.None;

            if (this.All != false)
            {
                none = SearchResolutionOptions.SearchAllScopes;
            }
            if ((this.CommandType & CommandTypes.Alias) != 0)
            {
                none |= SearchResolutionOptions.ResolveAliasPatterns;
            }
            if ((this.CommandType & (CommandTypes.Workflow | CommandTypes.Filter | CommandTypes.Function)) != 0)
            {
                none |= SearchResolutionOptions.ResolveFunctionPatterns;
            }
            foreach (string str in commandNames)
            {
                try
                {
                    string str2    = null;
                    string pattern = str;
                    bool   flag    = false;
                    if ((str.IndexOf('\\') > 0) && (str.Split(new char[] { '\\' }).Length == 2))
                    {
                        string[] strArray = str.Split(new char[] { '\\' }, 2);
                        str2    = strArray[0];
                        pattern = strArray[1];
                        flag    = true;
                    }
                    if ((this.Module.Length == 1) && !WildcardPattern.ContainsWildcardCharacters(this.Module[0]))
                    {
                        str2 = this.Module[0];
                    }
                    bool isPattern = WildcardPattern.ContainsWildcardCharacters(pattern);
                    if (isPattern)
                    {
                        none |= SearchResolutionOptions.CommandNameIsPattern;
                    }
                    int  currentCount = 0;
                    bool flag3        = this.FindCommandForName(none, str, isPattern, true, ref currentCount);
                    if (!flag3 || isPattern)
                    {
                        if (!isPattern || !string.IsNullOrEmpty(str2))
                        {
                            string commandName = str;
                            if (!flag && !string.IsNullOrEmpty(str2))
                            {
                                commandName = str2 + @"\" + str;
                            }
                            try
                            {
                                CommandDiscovery.LookupCommandInfo(commandName, base.MyInvocation.CommandOrigin, base.Context);
                            }
                            catch (CommandNotFoundException)
                            {
                            }
                            flag3 = this.FindCommandForName(none, str, isPattern, false, ref currentCount);
                        }
                        else if ((this.ListImported == false) && ((this.TotalCount < 0) || (currentCount < this.TotalCount)))
                        {
                            foreach (CommandInfo info in ModuleUtils.GetMatchingCommands(pattern, base.Context, base.MyInvocation.CommandOrigin, true))
                            {
                                CommandInfo current = info;
                                if ((this.IsCommandMatch(ref current) && !this.IsCommandInResult(current)) && this.IsParameterMatch(current))
                                {
                                    this.accumulatedResults.Add(current);
                                    currentCount++;
                                    if ((this.TotalCount >= 0) && (currentCount >= this.TotalCount))
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    if (!flag3 && !isPattern)
                    {
                        CommandNotFoundException replaceParentContainsErrorRecordException = new CommandNotFoundException(str, null, "CommandNotFoundException", DiscoveryExceptions.CommandNotFoundException, new object[0]);
                        base.WriteError(new ErrorRecord(replaceParentContainsErrorRecordException.ErrorRecord, replaceParentContainsErrorRecordException));
                    }
                }
                catch (CommandNotFoundException exception2)
                {
                    base.WriteError(new ErrorRecord(exception2.ErrorRecord, exception2));
                }
            }
        }