public async ValueTask <AdminCommandResult> GetCommandsAsync(Module module)
        {
            var commands = CommandUtilities.EnumerateAllCommands(module);
            var groups   = commands.GroupBy(x => x.FullAliases[0]).ToList();

            var pages = DefaultPaginator.GeneratePages(groups, 1024, group => new StringBuilder()
                                                       .Append(Markdown.Bold(FormatCommands(group)))
                                                       .AppendNewline(Localize($"info_command_{group.Key.Replace(' ', '_')}")).ToString(),
                                                       builderFunc: () => new LocalEmbedBuilder().WithSuccessColor()
                                                       .WithTitle(Localize("info_module_commands", Markdown.Code(module.Name))));

            /*
             * var pages = DefaultPaginator.GeneratePages(groups, 15, group => new EmbedFieldBuilder()
             *  //    .WithName(new StringBuilder(Config.DefaultPrefix)
             *  //        .AppendJoin($"\n{Config.DefaultPrefix}", group.First().FullAliases).Tag)
             *  .WithName(FormatCommands(group))
             *  .WithValue(Localize($"info_command_{group.Key.Replace(' ', '_')}")),
             *  embedFunc: builder => builder.WithSuccessColor()
             *      .WithTitle(Localize("info_module_commands", Format.Code(module.Name))));
             */

            if (pages.Count > 1)
            {
                await Pagination.SendPaginatorAsync(Context.Channel, new DefaultPaginator(pages, 0), pages[0]);

                return(CommandSuccess());
            }

            return(CommandSuccess(embed: pages[0].Embed));
        }
Exemple #2
0
        public async ValueTask <AdminCommandResult> ListAsync()
        {
            var selfRoles = await Context.Database.SelfRoles.Where(x => x.GuildId == Context.Guild.Id)
                            .ToListAsync();

            if (selfRoles.Count == 0)
            {
                return(CommandErrorLocalized("selfrole_list_none"));
            }

            var pages = DefaultPaginator.GeneratePages(selfRoles, 10, role => new LocalizedFieldBuilder(this)
                                                       .WithName(Context.Guild.GetRole(role.RoleId).Format(false))
                                                       .WithLocalizedValue("selfrole_list_groups",
                                                                           role.Groups.Length > 0 ? string.Join(", ", role.Groups) : Localize("info_none")), builderFunc: () =>
                                                       new LocalizedEmbedBuilder(this)
                                                       .WithSuccessColor()
                                                       .WithLocalizedTitle("selfrole_list_title", Context.Guild.Name.Sanitize()));

            if (pages.Count > 1)
            {
                await Pagination.SendPaginatorAsync(Context.Channel, new DefaultPaginator(pages, 0), pages[0]);

                return(CommandSuccess());
            }

            return(CommandSuccess(embed: pages[0].Embed));
        }
        public async ValueTask <AdminCommandResult> ListReactionRolesAsync()
        {
            var reactionRoles = await Context.Database.ReactionRoles.Where(x => x.GuildId == Context.Guild.Id)
                                .OrderByDescending(x => x.Id)
                                .ToListAsync();

            if (reactionRoles.Count == 0)
            {
                return(CommandErrorLocalized("reactionrole_list_none"));
            }

            var dict = new Dictionary <ulong, ITextChannel>();

            foreach (var role in reactionRoles.DistinctBy(x => x.MessageId))
            {
                dict.Add(role.ChannelId, Context.Guild.GetTextChannel(role.ChannelId));
            }

            var pages = DefaultPaginator.GeneratePages(reactionRoles, 10, role => new LocalEmbedFieldBuilder()
                                                       .WithName($"{role.Emoji} => {Context.Guild.GetRole(role.RoleId).Name.Sanitize()}")
                                                       .WithValue($"{role.Id} - #{dict[role.ChannelId].Name} ({role.MessageId})"), builderFunc: () => new LocalEmbedBuilder()
                                                       .WithSuccessColor()
                                                       .WithTitle(Localize("reactionrole_list", Context.Guild.Name.Sanitize())));

            if (pages.Count > 1)
            {
                await Pagination.SendPaginatorAsync(Context.Channel, new DefaultPaginator(pages, 0), pages[0]);

                return(CommandSuccess());
            }

            return(CommandSuccess(embed: pages[0].Embed));
        }
        public async ValueTask <AdminCommandResult> ListHighlightsAsync()
        {
            var highlights = await(Context.IsPrivate
                ? Context.Database.Highlights.Where(x => x.UserId == Context.User.Id && !x.GuildId.HasValue)
                : Context.Database.Highlights.Where(x => x.UserId == Context.User.Id && x.GuildId == Context.Guild.Id)).ToListAsync();

            /*
             * var highlights = await Context.Database.Highlights
             *  .Where(x => x.UserId == Context.User.Id &&
             *  (Context.IsPrivate && !x.GuildId.HasValue || x.GuildId == Context.Guild.Id))
             *  .ToListAsync();
             */

            if (highlights.Count == 0)
            {
                return(Context.IsPrivate
                    ? CommandErrorLocalized("highlight_list_none_global")
                    : CommandErrorLocalized("highlight_list_none_server", args: Context.Guild.Name.Sanitize()));
            }

            var pages = DefaultPaginator.GeneratePages(highlights, lineFunc: highlight => $"{highlight.Id} - \"{highlight.Text}\"",
                                                       builderFunc: () => new LocalEmbedBuilder().WithSuccessColor().WithTitle(Context.IsPrivate
                    ? Localize("highlight_list_global")
                    : Localize("highlight_list_guild", Context.Guild.Name.Sanitize())));

            if (pages.Count > 1)
            {
                await Pagination.SendPaginatorAsync(Context.Channel, new DefaultPaginator(pages, 0), pages[0]);

                return(CommandSuccess());
            }

            return(CommandSuccess(embed: pages[0].Embed));
        }
Exemple #5
0
                public async ValueTask <AdminCommandResult> ListLevelRewardsAsync()
                {
                    var rewards = await Context.Database.LevelRewards
                                  .Where(x => x.GuildId == Context.Guild.Id)
                                  .OrderBy(x => x.Tier)
                                  .ThenBy(x => x.Level)
                                  .ToListAsync();

                    if (rewards.Count == 0)
                    {
                        return(CommandErrorLocalized("guild_levelrewards_list_none"));
                    }

                    var pages = DefaultPaginator.GeneratePages(rewards, 5, FormatReward,
                                                               builderFunc: () => new LocalEmbedBuilder().WithSuccessColor().WithTitle(
                                                                   Localize("guild_levelrewards_list", Markdown.Bold(Context.Guild.Name.Sanitize()))));

                    if (pages.Count > 1)
                    {
                        await Pagination.SendPaginatorAsync(Context.Channel, new DefaultPaginator(pages, 0), pages[0]);

                        return(CommandSuccess());
                    }

                    return(CommandSuccess(embed: pages[0].Embed));

                    LocalEmbedFieldBuilder FormatReward(LevelReward reward)
                    {
                        var builder = new LocalEmbedFieldBuilder()
                                      .WithName(Localize("levelreward_title", reward.Tier, reward.Level));

                        switch (reward)
                        {
                        case RoleLevelReward roleReward:
                            var addedRoles = string.Join(", ",
                                                         roleReward.AddedRoleIds.Select(x => Context.Guild.GetRole(x).Format()));
                            var removedRoles = string.Join(", ",
                                                           roleReward.RemovedRoleIds.Select(x => Context.Guild.GetRole(x).Format()));
                            return(builder.WithValue(new StringBuilder(Localize("levelreward_role_addedroles"))
                                                     .Append(" ")
                                                     .AppendNewline(string.IsNullOrWhiteSpace(addedRoles)
                                        ? Localize("info_none")
                                        : addedRoles)
                                                     .Append(Localize("levelreward_role_removedroles"))
                                                     .Append(" ")
                                                     .AppendNewline(string.IsNullOrWhiteSpace(removedRoles)
                                        ? Localize("info_none")
                                        : removedRoles).ToString()
                                                     .TrimTo(LocalEmbedBuilder.MAX_DESCRIPTION_LENGTH / 2)));

                        default:
                            throw new ArgumentOutOfRangeException(nameof(reward));
                        }
                    }
                }
            public async ValueTask <AdminCommandResult> ViewHighlightBlacklistAsync()
            {
                var user = await Context.Database.GetOrCreateGlobalUserAsync(Context.User.Id);

                var blacklist = new List <string>();
                var updated   = false;

                foreach (var id in user.HighlightBlacklist)
                {
                    var target = await Context.Client.GetOrDownloadUserAsync(id);

                    if (target is null)
                    {
                        if (Context.Client.GetChannel(id) is CachedTextChannel channel)
                        {
                            blacklist.Add(channel.Format());
                        }
                        else
                        {
                            user.HighlightBlacklist.Remove(id);
                            updated = true;
                        }
                    }
                    else
                    {
                        blacklist.Add(target.Format());
                    }
                }

                if (updated)
                {
                    Context.Database.GlobalUsers.Update(user);
                    await Context.Database.SaveChangesAsync();
                }

                if (user.HighlightBlacklist.Count == 0)
                {
                    return(CommandErrorLocalized("highlight_blacklist_empty"));
                }

                var pages = DefaultPaginator.GeneratePages(blacklist,
                                                           lineFunc: target => target,
                                                           builderFunc: () => new LocalEmbedBuilder().WithSuccessColor().WithTitle(Localize("highlight_blacklist")));

                if (pages.Count > 1)
                {
                    await Pagination.SendPaginatorAsync(Context.Channel, new DefaultPaginator(pages, 0), pages[0]);

                    return(CommandSuccess());
                }

                return(CommandSuccess(embed: pages[0].Embed));
            }
Exemple #7
0
            public async ValueTask <AdminCommandResult> RegexSearchUsersAsync([Remainder] Regex regex)
            {
                var matches = new List <CachedMember>();
                var delay   = Task.Delay(TimeSpan.FromSeconds(5));
                var task    = Task.Run(() =>
                {
                    matches = Context.Guild.Members.Values.Where(MatchesRegex)
                              .OrderByDescending(x => x.JoinedAt)
                              .ToList();
                });

                using var _ = Context.Channel.Typing();
                var timeoutTask = await Task.WhenAny(delay, task);

                if (timeoutTask == delay)
                {
                    return(CommandErrorLocalized("user_searchregex_timeout"));
                }

                if (matches.Count == 0)
                {
                    return(CommandErrorLocalized("user_searchregex_no_results", args: regex.ToString()));
                }

                var pages = DefaultPaginator.GeneratePages(matches, 1024, FormatUser, builderFunc: () => new LocalEmbedBuilder()
                                                           .WithSuccessColor().WithTitle(Localize("user_searchregex_results")));

                if (pages.Count > 1)
                {
                    await Pagination.SendPaginatorAsync(Context.Channel, new DefaultPaginator(pages, 0), pages[0]);

                    return(CommandSuccess());
                }

                return(CommandSuccess(embed: pages[0].Embed));

                bool MatchesRegex(CachedMember target)
                {
                    if (string.IsNullOrWhiteSpace(target.Name))
                    {
                        return(false);
                    }

                    if (string.IsNullOrWhiteSpace(target.Nick))
                    {
                        return(regex.IsMatch(target.Name));
                    }

                    return(regex.IsMatch(target.Nick) || regex.IsMatch(target.Name));
                }
            }
Exemple #8
0
            public async ValueTask <AdminCommandResult> SearchUsersAsync(
                [Remainder, MustBe(StringLength.ShorterThan, 33)] string input)
            {
                // input = input.ToLower();
                var matches = new List <ValueTuple <int, CachedMember> >();

                foreach (var user in Context.Guild.Members.Values.Where(x => !string.IsNullOrWhiteSpace(x.Name)))
                {
                    var nickDistance = int.MaxValue;
                    if (!string.IsNullOrWhiteSpace(user.Nick))
                    {
                        nickDistance = input.GetLevenshteinDistanceTo(user.Nick.ToLower());
                        if (user.Nick.Contains(input, StringComparison.OrdinalIgnoreCase))
                        {
                            nickDistance -= 6;
                        }
                    }

                    var nameDistance = input.GetLevenshteinDistanceTo(user.Name.ToLower());
                    if (user.Name.Contains(input, StringComparison.OrdinalIgnoreCase))
                    {
                        nameDistance -= 8; // higher weighting for usernames
                    }
                    var distance = Math.Min(nameDistance, nickDistance);
                    if (distance <= 2)
                    {
                        matches.Add((distance, user));
                    }
                }

                if (matches.Count == 0)
                {
                    return(CommandErrorLocalized("user_search_no_results", args: input));
                }

                matches = matches.OrderBy(x => x.Item1).ToList();

                var pages = DefaultPaginator.GeneratePages(matches, 1024, x => FormatUser(x.Item2),
                                                           builderFunc: () => new LocalEmbedBuilder().WithSuccessColor().WithTitle(Localize("user_search_results", input)));

                if (pages.Count > 1)
                {
                    await Pagination.SendPaginatorAsync(Context.Channel, new DefaultPaginator(pages, 0), pages[0]);

                    return(CommandSuccess());
                }

                return(CommandSuccess(embed: pages[0].Embed));
            }
Exemple #9
0
        public async ValueTask <AdminCommandResult> ListPermissionAsync([MustBe(Operator.GreaterThan, 0)] int page = 1)
        {
            var permissions = await Context.Database.Permissions.Where(x => x.GuildId == Context.Guild.Id)
                              .OrderByDescending(x => x.Id)
                              .ToListAsync();

            if (permissions.Count == 0)
            {
                return(CommandErrorLocalized("permissions_none"));
            }

            var pages = DefaultPaginator.GeneratePages(permissions, lineFunc: Format,
                                                       builderFunc: () => new LocalEmbedBuilder()
                                                       .WithSuccessColor()
                                                       .WithTitle(Context.Localize("permissions_list", Context.Guild?.Name)));

            page = Math.Min(page, pages.Count) - 1;

            if (pages.Count > 1)
            {
                await Pagination.SendPaginatorAsync(Context.Channel, new DefaultPaginator(pages, page), pages[page]);

                return(CommandSuccess());
            }

            return(CommandSuccess(embed: pages[0].Embed));

            string Format(Permission permission)
            {
                var builder = new StringBuilder($"{permission.Id}. ")
                              .Append('`')
                              .Append(Context.Prefix)
                              .Append($"{Context.Path[0]} ")
                              .Append(permission.IsEnabled ? "enable " : "disable ")
                              .Append(permission.Type == PermissionType.Command ? "command " : "module ")
                              .Append($"{permission.Name ?? "all"} ")
                              .Append(permission.Filter switch
                {
                    PermissionFilter.Role => Context.Guild.GetRole(permission.TargetId.Value)?.Name.Sanitize() ?? "???",
                    PermissionFilter.Channel => Context.Guild.GetTextChannel(permission.TargetId.Value)?.Mention ?? "???",
                    PermissionFilter.User => Context.Guild.GetMember(permission.TargetId.Value)?.Tag.Sanitize() ?? "???",
                    _ => string.Empty
                })
                              .Append('`');

                return(builder.ToString());
            }
        public async ValueTask <AdminCommandResult> GetModulesAsync()
        {
            var pages = DefaultPaginator.GeneratePages(Commands.TopLevelModules.OrderBy(x => x.Name).ToList(), 7, module =>
                                                       new LocalizedFieldBuilder(this)
                                                       .WithName(module.Name)
                                                       .WithLocalizedValue($"info_modules_{module.Name.ToLowerInvariant()}"),
                                                       builderFunc: () => new LocalizedEmbedBuilder(this).WithSuccessColor().WithLocalizedTitle("info_modules_title"));

            if (pages.Count > 1)
            {
                await Pagination.SendPaginatorAsync(Context.Channel, new DefaultPaginator(pages, 0), pages[0]);

                return(CommandSuccess());
            }

            return(CommandSuccess(embed: pages[0].Embed));
        }
            public async ValueTask <AdminCommandResult> ViewBlacklistAsync()
            {
                var guild = await Context.Database.GetOrCreateGuildAsync(Context.Guild.Id);

                if (guild.BlacklistedStarboardIds.Count == 0)
                {
                    return(CommandErrorLocalized("starboard_blacklist_none"));
                }

                var list = new List <string>();

                foreach (var id in guild.BlacklistedStarboardIds)
                {
                    if (Context.Guild.GetTextChannel(id) is { } channel)
                    {
                        list.Add(channel.Format(false));
                        continue;
                    }

                    var user = await Context.Client.GetOrDownloadUserAsync(id);

                    list.Add(user?.Format(false) ?? $"??? `{id}`");
                }

                var pages = DefaultPaginator.GeneratePages(list, lineFunc: str => str,
                                                           builderFunc: () => new LocalizedEmbedBuilder(this)
                                                           .WithSuccessColor()
                                                           .WithLocalizedTitle("starboard_blacklist_title",
                                                                               Context.Guild.Name.Sanitize()));

                if (pages.Count > 1)
                {
                    await Pagination.SendPaginatorAsync(Context.Channel, new DefaultPaginator(pages, 0), pages[0]);

                    return(CommandSuccess());
                }

                return(CommandSuccess(embed: pages[0].Embed));
            }
Exemple #12
0
        public async ValueTask <AdminCommandResult> ListRemindersAsync()
        {
            var reminders = await Context.Database.Reminders.Where(x => x.AuthorId == Context.User.Id)
                            .OrderByDescending(x => x.Id)
                            .ToListAsync();

            if (!Context.IsPrivate)
            {
                reminders = reminders.Where(x => x.GuildId == Context.Guild.Id).ToList();
            }

            if (reminders.Count == 0)
            {
                return(CommandErrorLocalized("reminder_list_none"));
            }

            var pages = DefaultPaginator.GeneratePages(reminders, 10, reminder => new LocalEmbedFieldBuilder()
                                                       .WithName(Localize("", reminder.Id,
                                                                          (reminder.Ending - DateTimeOffset.UtcNow).HumanizeFormatted(Localization, Context.Language,
                                                                                                                                      TimeUnit.Second)))
                                                       .WithValue(reminder.Text ??
                                                                  Markdown.Link(Localize("info_jumpmessage"),
                                                                                $"https://discordapp.com/channels/{reminder.GuildId?.ToString() ?? "@me"}/{reminder.ChannelId}/{reminder.MessageId}")),
                                                       builderFunc: () => new LocalEmbedBuilder()
                                                       .WithTitle(Localize("reminder_list_title"))
                                                       .WithSuccessColor());

            if (pages.Count > 1)
            {
                await Pagination.SendPaginatorAsync(Context.Channel, new DefaultPaginator(pages, 0), pages[0]);

                return(CommandSuccess());
            }

            return(CommandSuccess(embed: pages[0].Embed));
        }
        public async ValueTask <AdminCommandResult> ListPersonalTagsAsync()
        {
            var tags = await Context.Database.Tags.Where(x =>
                                                         x.GuildId == Context.Guild.Id && x.AuthorId == Context.User.Id)
                       .ToListAsync();

            if (tags.Count == 0)
            {
                return(CommandErrorLocalized("tag_list_none"));
            }

            var pages = DefaultPaginator.GeneratePages(tags, lineFunc: tag => tag.Name,
                                                       builderFunc: () => new LocalEmbedBuilder().WithSuccessColor()
                                                       .WithTitle(Localize("tag_list_title", Context.Guild.Name.Sanitize())));

            if (pages.Count > 1)
            {
                await Pagination.SendPaginatorAsync(Context.Channel, new DefaultPaginator(pages, 0), pages[0]);

                return(CommandSuccess());
            }

            return(CommandSuccess(embed: pages[0].Embed));
        }