Beispiel #1
0
        public static async Task <bool> CommandIsEnabledAsync(ICommandContext context, string commandName)
        {
            CommandInfo commandInfo = OurFoodChainBot.Instance.GetInstalledCommandByName(commandName);

            if (commandInfo is null)
            {
                return(false);
            }

            if (!HasPrivilege(context.User, GetPrivilegeLevel(commandInfo)))
            {
                return(false);
            }

            if (!OurFoodChainBot.Instance.Config.AdvancedCommandsEnabled && GetDifficultyLevel(commandInfo) >= DifficultyLevel.Advanced)
            {
                return(false);
            }

            if (!(await commandInfo.CheckPreconditionsAsync(context, OurFoodChainBot.Instance.ServiceProvider)).IsSuccess)
            {
                return(false);
            }

            return(true);
        }
Beispiel #2
0
        public async Task <List <CommandGroup> > GetUsableCommandGroups(
            SocketCommandContext context, Func <CommandInfo, bool> shouldKeep = null)
        {
            List <CommandGroup> groups = GetAllCommandGroups();

            foreach (CommandGroup group in groups)
            {
                for (int i = 0; i < group.Count; i++)
                {
                    CommandInfo cmd    = group[i];
                    var         result = await cmd.CheckPreconditionsAsync(context);

                    if (!result.IsSuccess)
                    {
                        group.RemoveAt(i);
                        i--;
                    }
                }
            }
            if (shouldKeep != null)
            {
                FilterCommandGroups(groups, shouldKeep);
            }
            return(groups);
        }
Beispiel #3
0
        private async Task <bool> CheckPreCon(SocketCommandContext y, CommandInfo x)
        {
            var z = await(x.CheckPreconditionsAsync(y));

            if (z.IsSuccess)
            {
                return(true);
            }
            return(false);
        }
Beispiel #4
0
        public async Task<Embed> HandleCommandUnmetPrecondition(ICommandContext context, CommandInfo commandInfo)
        {
            var preconditonMessage = await commandInfo.CheckPreconditionsAsync(context); /*await GeneratePreconditionList(context, commandInfo);*/

            var embed = _embedFactory.Generate(
                requestedType: EmbedType.Error,
                title: "⚠ Unmet Preconditons",
                description: preconditonMessage.ErrorReason);

            return embed.Build();
        }
        private async Task HelpAsync(CommandInfo commandInfo)
        {
            if (commandInfo == null)
            {
                await ReplyEmbedAsync($"The command `{commandInfo.Name}` is not a command that exists.");

                return;
            }

            var usageAttribute = commandInfo.Attributes.FirstOrDefault(x => x is UsageAttribute) as UsageAttribute;
            var prefix         = GetPrefix(Context) ?? $"@{Context.Client.CurrentUser.Username} ";
            var embed          = new EmbedBuilder().WithInfoColor();
            var result         = await commandInfo.CheckPreconditionsAsync(Context, _provider);

            if (result.IsSuccess)
            {
                var sbuilder = new StringBuilder()
                               .Append(prefix + commandInfo.Aliases.First());
                var fields = new List <EmbedFieldBuilder>();
                foreach (var parameter in commandInfo.Parameters)
                {
                    var p = parameter.Name;
                    p = p.FirstCharToUpper();
                    if (parameter.Summary != null)
                    {
                        fields.Add(new EmbedFieldBuilder().WithName(p).WithValue(parameter.Summary));
                    }
                    if (parameter.IsRemainder)
                    {
                        p += "...";
                    }
                    p = parameter.IsOptional ? $"[{p}]" : $"<{p}>";
                    sbuilder.Append(" " + p);
                }

                embed.AddField(sbuilder.ToString(), commandInfo.Remarks ?? commandInfo.Summary);
                foreach (var field in fields)
                {
                    embed.AddField(field);
                }

                if (usageAttribute != null)
                {
                    embed.AddField("Usage", $"`{prefix}{usageAttribute.Text}`");
                }
            }

            embed.WithFooter(x => x.Text = $"Aliases: {string.Join(", ", commandInfo.Aliases)}");

            await ReplyEmbedAsync(embed : embed);
        }
Beispiel #6
0
        public async Task <bool> IsCommandAvailableAsync(ICommandContext context, string commandName)
        {
            CommandInfo commandInfo = _commandService.Commands
                                      .Where(i => i.Name.Equals(commandName, StringComparison.OrdinalIgnoreCase) || i.Aliases.Any(a => a.Equals(commandName, StringComparison.OrdinalIgnoreCase)))
                                      .FirstOrDefault();

            if (commandInfo is null)
            {
                return(false);
            }

            if (!(await commandInfo.CheckPreconditionsAsync(context, _serviceProvider)).IsSuccess)
            {
                return(false);
            }

            return(true);
        }
Beispiel #7
0
        public async Task <List <CommandInfo> > GetUsableCommands(
            SocketCommandContext context, Func <CommandInfo, bool> shouldKeep = null)
        {
            List <CommandInfo> commands = GetAllCommands();

            for (int i = 0; i < commands.Count; i++)
            {
                CommandInfo cmd    = commands[i];
                var         result = await cmd.CheckPreconditionsAsync(context);

                if (!result.IsSuccess)
                {
                    commands.RemoveAt(i);
                    i--;
                }
            }
            if (shouldKeep != null)
            {
                FilterCommands(commands, shouldKeep);
            }
            return(commands);
        }
Beispiel #8
0
        bool shouldDisplay(CommandInfo cmd)
        {
            PreconditionResult result = cmd.CheckPreconditionsAsync(Context).Result;

            return(result.IsSuccess && (cmd.Summary == null | !cmd.Summary.Contains("(Easter Egg)")));
        }
Beispiel #9
0
        public async Task HelpCommand([Optional][Remainder] string Command)
        {
            if (string.IsNullOrEmpty(Command))
            {
                List <EmbedBuilder> EmbedBuilders = new();

                int PageNumber = 2;

                EmbedBuilders.Add(
                    BuildEmbed(EmojiEnum.Love)
                    .WithTitle($"{DiscordSocketClient.CurrentUser.Username} Help")
                    .WithDescription($"{BotConfiguration.Help}")
                    );

                List <string> Pages = new();

                foreach (ModuleInfo Module in CommandService.Modules)
                {
                    string ModuleName = Regex.Replace(Module.Name, "[a-z][A-Z]", m => m.Value[0] + " " + m.Value[1]);

                    List <string> Description = new();

                    ServiceCollection ServiceCollection = new();

                    HelpAbstraction HelpAbstraction = new() {
                        BotConfiguration    = BotConfiguration,
                        DiscordSocketClient = DiscordSocketClient
                    };

                    ServiceCollection.AddSingleton(HelpAbstraction);

                    foreach (CommandInfo CommandInfo in Module.Commands)
                    {
                        PreconditionResult Result = await CommandInfo.CheckPreconditionsAsync(Context, ServiceCollection.BuildServiceProvider());

                        if (Result.IsSuccess)
                        {
                            Description.Add($"**~{string.Join("/", CommandInfo.Aliases.ToArray())}:** {CommandInfo.Summary}");
                        }
                    }

                    if (Description.Count > 0)
                    {
                        Pages.Add($"**Page {PageNumber++}:** {ModuleName}");
                        EmbedBuilders.Add(
                            BuildEmbed(EmojiEnum.Love)
                            .WithTitle($"{ModuleName}")
                            .WithDescription(string.Join("\n\n", Description.ToArray()))
                            );
                    }
                }

                EmbedBuilders[0].AddField("Help Pages",
                                          string.Join('\n', Pages.ToArray())
                                          );

                await CreateReactionMenu(EmbedBuilders.ToArray(), Context.Channel);
            }
            else
            {
                SearchResult Result = CommandService.Search(Context, Command);

                if (!Result.IsSuccess)
                {
                    await BuildEmbed(EmojiEnum.Annoyed)
                    .WithTitle("Unknown Command")
                    .WithDescription($"Sorry, I couldn't find a command like **{Command}**.")
                    .SendEmbed(Context.Channel);
                }
                else
                {
                    EmbedBuilder EmbedBuilder = BuildEmbed(EmojiEnum.Love)
                                                .WithTitle($"Here are some commands like **{Command}**!");

                    foreach (CommandMatch CommandMatch in Result.Commands)
                    {
                        EmbedBuilder.GetParametersForCommand(CommandMatch.Command, BotConfiguration);
                    }

                    await EmbedBuilder.SendEmbed(Context.Channel);
                }
            }
        }
        public async Task Help(string text = "")
        {
            if (text == string.Empty)
            {
                Image image = null;

                if (HttpHelper.UrlExists("https://play.pokemonshowdown.com/sprites/xyani/dewott.gif"))
                {
                    byte[] imageBytes = await Program.Instance.HttpClient.GetByteArrayAsync("https://play.pokemonshowdown.com/sprites/xyani/dewott.gif");

                    using (MemoryStream ms = new MemoryStream(imageBytes))
                    {
                        image = Image.FromStream(ms);
                    }
                }

                if (image != null)
                {
                    if (File.Exists(Path.Combine(this.AppPath, "pokemon.gif")))
                    {
                        File.Delete(Path.Combine(this.AppPath, "pokemon.gif"));
                    }

                    image.Save(Path.Combine(this.AppPath, "pokemon.gif"));

                    await(await this.Context.User.GetOrCreateDMChannelAsync()).SendFileAsync(Path.Combine(this.AppPath, "pokemon.gif"));
                }

                EmbedBuilder builder = new EmbedBuilder();
                builder.WithColor(Color.FromArgb(163, 214, 227));
                builder.Title = "List of commands:";

                string commands = string.Empty;

                foreach (CommandInfo commandServiceCommand in Globals.CommandService.Commands)
                {
                    if (!(await commandServiceCommand.CheckPreconditionsAsync(this.Context)).IsSuccess)
                    {
                        continue;
                    }

                    commands += $"{commandServiceCommand.Name}\n";
                }

                builder.Description = commands;

                await(await this.Context.User.GetOrCreateDMChannelAsync()).SendMessageAsync(string.Empty, false, builder.Build());
            }
            else if (Globals.CommandService.Commands.ToList().Find(e => e.Name == text) != null)
            {
                EmbedBuilder builder = new EmbedBuilder();

                CommandInfo requestedInfo = Globals.CommandService.Commands.ToList().Find(e => e.Name == text);

                if (!(await requestedInfo.CheckPreconditionsAsync(this.Context)).IsSuccess)
                {
                    await this.ReplyAsync((await requestedInfo.CheckPreconditionsAsync(this.Context)).ErrorReason);

                    return;
                }

                builder.Title       = text;
                builder.Description = string.Empty;

                if (requestedInfo.Parameters.Count > 0)
                {
                    foreach (ParameterInfo parameter in requestedInfo.Parameters)
                    {
                        builder.Title += $" [{parameter.Name}{(parameter.IsOptional ? $" = {Convert.ToString(parameter.DefaultValue)}" : string.Empty)}] ";
                    }
                }

                if (requestedInfo.Aliases.Count > 0)
                {
                    builder.Description += "\nAliases: ";
                    builder.Description  = requestedInfo.Aliases.Aggregate(builder.Description, (current, alias) => current + $"{alias} ");
                }

                if (!string.IsNullOrWhiteSpace(requestedInfo.Summary))
                {
                    builder.Description += $"\n{requestedInfo.Summary}\n";
                }

                if (requestedInfo.Parameters.Count > 0)
                {
                    builder.Description = requestedInfo.Parameters.Where(parameter => !string.IsNullOrWhiteSpace(parameter.Summary)).Aggregate(builder.Description, (current, parameter) => current + $"\n{parameter.Name}: {parameter.Summary}");
                }

                await this.ReplyAsync(string.Empty, false, builder.Build());
            }
            else
            {
                Dictionary <string, string> allAliasDict = new Dictionary <string, string>();

                EmbedBuilder builder = new EmbedBuilder
                {
                    Title       = string.Empty,
                    Description = string.Empty
                };

                foreach (CommandInfo cmdInfo in Globals.CommandService.Commands)
                {
                    foreach (string cmdInfoAlias in cmdInfo.Aliases)
                    {
                        allAliasDict.Add(cmdInfoAlias, cmdInfo.Name);
                    }
                }

                if (allAliasDict.TryGetValue(text, out string result))
                {
                    CommandInfo requestedInfo = Globals.CommandService.Commands.ToList().Find(e => e.Name == result);

                    builder.Title = result;

                    if (requestedInfo.Parameters.Count > 0)
                    {
                        foreach (ParameterInfo parameter in requestedInfo.Parameters)
                        {
                            builder.Title += $" [{parameter.Name}{(parameter.IsOptional ? $" = {Convert.ToString(parameter.DefaultValue)}" : string.Empty)}] ";
                        }
                    }

                    if (requestedInfo.Aliases.Count > 0)
                    {
                        builder.Description += "Aliases: ";
                        builder.Description  = requestedInfo.Aliases.Aggregate(builder.Description, (current, alias) => current + $"{alias} ");
                    }

                    if (!string.IsNullOrWhiteSpace(requestedInfo.Summary))
                    {
                        builder.Description += $"\n{requestedInfo.Summary}\n";
                    }

                    if (requestedInfo.Parameters.Count > 0)
                    {
                        foreach (ParameterInfo parameter in requestedInfo.Parameters)
                        {
                            if (!string.IsNullOrWhiteSpace(parameter.Summary))
                            {
                                builder.Description += $"\n{parameter.Name}: {parameter.Summary}";
                            }
                        }
                    }

                    await this.ReplyAsync(string.Empty, false, builder.Build());
                }
                else
                {
                    await this.ReplyAsync("Command not found!");
                }
            }
        }
Beispiel #11
0
        /// <summary>
        ///     Checks if user imported command which should not be accessible to him.
        /// </summary>
        /// <param name="commandInfo"></param>
        /// <returns>False if user didn't meet command preconditions</returns>
        public async Task <bool> UserCanUseCommand(CommandInfo commandInfo)
        {
            var preconditions = await commandInfo.CheckPreconditionsAsync(Context, ServiceProvider);

            return(preconditions.IsSuccess);
        }
Beispiel #12
0
 public bool CheckPrecond(CommandInfo command)
 => command.CheckPreconditionsAsync(Context).GetAwaiter().GetResult().IsSuccess;
Beispiel #13
0
        public async Task HelpCommand([Optional][Remainder] string Command)
        {
            if (string.IsNullOrEmpty(Command))
            {
                List <EmbedBuilder> Embeds = new();

                Embeds.Add(
                    BuildEmbed(EmojiEnum.Love)
                    .WithTitle($"{DiscordSocketClient.CurrentUser.Username} Help")
                    .WithDescription($"{BotConfiguration.Help}")
                    );

                ServiceCollection ServiceCollection = new();

                HelpAbstraction HelpAbstraction = new() {
                    BotConfiguration    = BotConfiguration,
                    DiscordSocketClient = DiscordSocketClient
                };

                ServiceCollection.AddSingleton(HelpAbstraction);

                foreach (ModuleInfo Module in CommandService.Modules)
                {
                    string ModuleName = Regex.Replace(Module.Name, "[a-z][A-Z]", m => m.Value[0] + " " + m.Value[1]);

                    EmbedBuilder CurrentBuilder = BuildEmbed(EmojiEnum.Love).WithTitle(ModuleName);

                    string Description = string.Empty;

                    foreach (CommandInfo CommandInfo in Module.Commands)
                    {
                        PreconditionResult Result = await CommandInfo.CheckPreconditionsAsync(Context, ServiceCollection.BuildServiceProvider());

                        if (Result.IsSuccess)
                        {
                            string Field = $"**{BotConfiguration.Prefix}{string.Join("/", CommandInfo.Aliases.ToArray())}:** {CommandInfo.Summary}\n\n";

                            try {
                                CurrentBuilder.WithDescription(Description += Field);
                            } catch (Exception) {
                                Embeds.Add(CurrentBuilder);
                                Description    = string.Empty;
                                CurrentBuilder = new EmbedBuilder().WithTitle(ModuleName).WithDescription(Description += Field).WithColor(Color.Green);
                            }
                        }
                    }

                    if (!string.IsNullOrEmpty(CurrentBuilder.Description))
                    {
                        Embeds.Add(CurrentBuilder);
                    }
                }

                List <string> Pages        = new ();
                string        PreviousPage = $"{DiscordSocketClient.CurrentUser.Username} Help";
                int           PageNumber   = 0;

                foreach (EmbedBuilder Embed in Embeds)
                {
                    PageNumber++;
                    if (PreviousPage != Embed.Title)
                    {
                        Pages.Add($"**Page {PageNumber}:** {Embed.Title}");
                        PreviousPage = Embed.Title;
                    }
                }

                Embeds[0].AddField("Help Pages",
                                   string.Join('\n', Pages.ToArray())
                                   );

                await CreateReactionMenu(Embeds.ToArray(), Context.Channel);
            }
            else
            {
                SearchResult Result = CommandService.Search(Context, Command);

                if (!Result.IsSuccess)
                {
                    await BuildEmbed(EmojiEnum.Annoyed)
                    .WithTitle("Unknown Command")
                    .WithDescription($"Sorry, I couldn't find a command like **{Command}**.")
                    .SendEmbed(Context.Channel);
                }
                else
                {
                    EmbedBuilder EmbedBuilder = BuildEmbed(EmojiEnum.Love)
                                                .WithTitle($"{BotConfiguration.Prefix}{Command} Command Help");

                    foreach (CommandMatch CommandMatch in Result.Commands)
                    {
                        EmbedBuilder.GetParametersForCommand(CommandMatch.Command, BotConfiguration);
                    }

                    await EmbedBuilder.SendEmbed(Context.Channel);
                }
            }
        }