public async Task <RuntimeResult> SeeMessageHistory(ulong messageId)
        {
            var db = Program.Services.GetRequiredService <MsgService>();

            using var DB = Program.Services.GetRequiredService <LogContext>();
            var dbMsg = DB.Messages.FirstOrDefault(x => x.MessageId == db.cast(messageId));

            if (dbMsg == null)
            {
                return(new BotResult("Message is not in database."));
            }
            var contents = db.GetContents(messageId).OrderBy(x => x.Timestamp);

            var url       = $"https://discord.com/channels/{dbMsg.Guild}/{dbMsg.Channel}/{dbMsg.Message}";
            var paginator = new StaticPaginatorBuilder()
                            .WithDefaultEmotes()
                            .WithFooter(PaginatorFooter.PageNumber);

            foreach (var content in contents)
            {
                var page = new PageBuilder()
                           .WithTitle($"Message at {content.Timestamp:dd/MM/yyyy HH:mm:ss}")
                           .WithText(url)
                           .WithDescription(content.Content);
                paginator.AddPage(page);
            }

            await PagedReplyAsync(paginator);

            return(new BotResult());
        }
Beispiel #2
0
        async Task printActualFor(BotUser u)
        {
            var paginator = new StaticPaginatorBuilder();
            var cPage     = new PageBuilder();

            cPage.Title = $"Permissions of {u.Name}";
            cPage.Text  = "These are the effective permissions of the user, taking into account wildcards, denials and allowals.";
            foreach (var perm in Service.AllNodes.Values)
            {
                if (!PermChecker.UserHasPerm(u, perm, out var inherit))
                {
                    continue;
                }
                string sep = inherit ? "**" : "";
                var    s   = $"`{perm.Node}` {sep}{perm.Description}{sep}\r\n";
                if ((cPage.Description.Length + s.Length) > 1024)
                {
                    paginator.AddPage(cPage);
                    cPage       = new PageBuilder();
                    cPage.Title = $"Permissions of {u.Name}";
                    cPage.Text  = "These are the effective permissions of the user, taking into account wildcards, denials and allowals.";
                }
                cPage.Description += s;
            }
            if (cPage.Description == "")
            {
                cPage.Description = "None.";
            }
            paginator.AddPage(cPage);
            await PagedReplyAsync(paginator);
        }
Beispiel #3
0
        public async Task ListAllPermissions(string prefix = null)
        {
            var         paginator = new StaticPaginatorBuilder();
            PageBuilder cPage     = new PageBuilder();

            foreach (var node in Service.AllNodes.Values)
            {
                if (prefix != null && !node.Node.StartsWith(prefix))
                {
                    continue;
                }
                var s = $"`{node.Node}` {node.Description}\r\n";
                if ((cPage.Text.Length + s.Length) > 1024)
                {
                    paginator.AddPage(cPage);
                    cPage = new PageBuilder();
                }
                cPage.Text += s;
            }
            if (cPage.Text == "")
            {
                cPage.Text = "No permissions nodes are known.";
            }
            paginator.AddPage(cPage);
            await PagedReplyAsync(paginator);
        }
Beispiel #4
0
        public async Task Help(ModuleInfo module)
        {
            var pages      = new List <PageBuilder>();
            var pageFields = new List <EmbedFieldBuilder>();

            foreach (CommandInfo command in module.Commands)
            {
                EmbedFieldBuilder embedField = new EmbedFieldBuilder();
                embedField.WithName(HelpUtilities.GetCommandUsage(command));
                embedField.WithValue(command.Summary ?? "no information given");
                pageFields.Add(embedField);
            }

            if (pageFields.Count <= 25)
            {
                PageBuilder page = new PageBuilder();
                page.WithTitle(module.Name);
                page.WithFields(pageFields);
                pages.Add(page);

                var builder = new EmbedBuilder();
                builder.WithTitle(module.Name);
                builder.WithFields(pageFields);
                await ReplyAsync("", false, builder.Build());
            }
            else
            {
                while (pageFields.Count > 0)
                {
                    PageBuilder page = new PageBuilder();
                    page.WithTitle(module.Name);
                    page.WithFields(pageFields.Take(25));
                    pages.Add(page);
                    if (pageFields.Count > 25)
                    {
                        pageFields.RemoveRange(0, 24);
                    }
                    else
                    {
                        pageFields.Clear();
                    }
                }

                var paginator = new StaticPaginatorBuilder()
                                .WithUsers(Context.User)
                                .WithPages(pages)
                                .WithFooter(PaginatorFooter.PageNumber | PaginatorFooter.Users)
                                .WithDefaultEmotes()
                                .Build();

                await _interactivity.SendPaginatorAsync(paginator, Context.Channel, TimeSpan.FromMinutes(2));
            }
        }
Beispiel #5
0
        public async Task TeamMembersAsync([Name("TeamName")][Remainder] string name)
        {
            SendConstructionMessage();

            var team = await ScrapClient.GetTeamByNameAsync(name);

            await DeleteConstructionMessageAsync();

            if (team != null)
            {
                var pages = new List <PageBuilder>();

                var allMembers = await team.GetMembersAsync();

                var groups = allMembers.GroupBy(x => x.Rank);

                var leader = groups.Where(x => x.Key == Rank.Leader).First().First();
                pages.Add(PageUtils.LeaderPage(team, leader));

                if (groups.Where(x => x.Key == Rank.Coleader).Any())
                {
                    var coLeaders = groups.Where(x => x.Key == Rank.Coleader).First().OrderByDescending(x => x.Trophies).ToArray();
                    pages.AddRange(coLeaders.Chunk(10).Select(x => PageUtils.CoLeaderPage(team, x.ToArray())));
                }
                if (groups.Where(x => x.Key == Rank.Elder).Any())
                {
                    var elders = groups.Where(x => x.Key == Rank.Elder).First().OrderByDescending(x => x.Trophies).ToArray();
                    pages.AddRange(elders.Chunk(10).Select(x => PageUtils.ElderPage(team, x.ToArray())));
                }
                if (groups.Where(x => x.Key == Rank.Member).Any())
                {
                    var members = groups.Where(x => x.Key == Rank.Member).First().OrderByDescending(x => x.Trophies).ToArray();
                    pages.AddRange(members.Chunk(10).Select(x => PageUtils.MemberPage(team, x.ToArray())));
                }

                var paginator = new StaticPaginatorBuilder()
                                .WithDefaultEmotes()
                                .WithDeletion(DeletionOptions.AfterCapturedContext | DeletionOptions.Valid)
                                .WithUsers(Context.User)
                                .WithPages(pages)
                                .Build();

                await Interactivity.SendPaginatorAsync(paginator, Context.Channel);
            }
            else
            {
                await ReplyAsync(embed : EmbedUtils.NotFoundEmbed("Team", name));
            }
        }
Beispiel #6
0
        /// <summary>
        /// Sends a deferred paginated message.
        /// </summary>
        /// <param name="embeds">The embed pages.</param>
        protected async Task SendDeferredPaginatedEmbedAsync(Embed[] embeds)
        {
            List <PageBuilder> pages = new();

            foreach (Embed embed in embeds)
            {
                PageBuilder pageBuilder = new PageBuilder().WithTitle(embed.Title)
                                          .WithDescription(embed.Description);
                foreach (EmbedField field in embed.Fields)
                {
                    pageBuilder.AddField(new EmbedFieldBuilder()
                    {
                        Name     = field.Name,
                        Value    = field.Value,
                        IsInline = field.Inline,
                    });
                }
                if (embed.Color.HasValue)
                {
                    pageBuilder.WithColor(embed.Color.Value);
                }
                if (embed.Thumbnail.HasValue)
                {
                    pageBuilder.WithThumbnailUrl(embed.Thumbnail.Value.Url);
                }
                if (embed.Footer.HasValue)
                {
                    pageBuilder.WithFooter(new EmbedFooterBuilder()
                    {
                        Text    = embed.Footer.Value.Text,
                        IconUrl = embed.Footer.HasValue ? embed.Footer.Value.IconUrl : null,
                    });
                }
                pages.Add(pageBuilder);
            }

            int             paginatorTimeout = Convert.ToInt32(Configuration["paginatorTimeout"]);
            StaticPaginator paginator        = new StaticPaginatorBuilder()
                                               .WithPages(pages)
                                               .WithDefaultButtons(Configuration)
                                               .WithJumpInputPrompt("Navegación de páginas")
                                               .WithJumpInputTextLabel($"Navegar a la página (1-{pages.Count}):")
                                               .WithExpiredJumpInputMessage("La interacción expiró. Por favor, ejecutá el comando nuevamente para volver a interactuar.")
                                               .WithInvalidJumpInputMessage($"La página a ingresar debe ser un número entre {Format.Bold("1")} y {Format.Bold(pages.Count.ToString())}.")
                                               .WithJumpInputInUseMessage("La función para saltar de página se encuentra actualmente en uso por otro usuario")
                                               .Build();
            await InteractiveService.SendPaginatorAsync(paginator, Context.Interaction as SocketInteraction, responseType : InteractionResponseType.DeferredChannelMessageWithSource, resetTimeoutOnInput : true, timeout : TimeSpan.FromSeconds(paginatorTimeout));
        }
Beispiel #7
0
        public async Task CardAsync([Remainder] string name)
        {
            var result = await _cardService.Where(x => x.Name, name).AllAsync();

            var cards = result.Value.DistinctBy(x => x.Name).ToArray();
            var pages = cards.OrderBy(x => string.Compare(x.Name, name, StringComparison.OrdinalIgnoreCase)).Select((x, i) => MagicHelper.BuildPage(x, i, cards.Length));

            var paginator = new StaticPaginatorBuilder()
            {
                Pages = pages.ToList()
            }.WithTimoutedEmbed(null).Build();

            if (result.IsSuccess && result.Value.Count > 0)
            {
                await _interactivityService.SendPaginatorAsync(paginator, Context.Channel);
            }
        }
        /// <summary>
        /// Configures the paginator with the default buttons.
        /// </summary>
        /// <param name="builder">The paginator builder.</param>
        /// <param name="configuration">The <see cref="IConfiguration"/>.</param>
        public static StaticPaginatorBuilder WithDefaultButtons(this StaticPaginatorBuilder builder, IConfiguration configuration)
        {
            var    emojis        = configuration.GetSection("customEmojis");
            IEmote firstEmoji    = Emote.Parse(emojis["firstPage"]);
            IEmote forwardEmoji  = Emote.Parse(emojis["nextPage"]);
            IEmote jumpEmoji     = Emote.Parse(emojis["jumpPage"]);
            IEmote backwardEmoji = Emote.Parse(emojis["previousPage"]);
            IEmote lastEmoji     = Emote.Parse(emojis["lastPage"]);

            Dictionary <IEmote, PaginatorAction> actions = new();

            actions.Add(firstEmoji, PaginatorAction.SkipToStart);
            actions.Add(backwardEmoji, PaginatorAction.Backward);
            actions.Add(jumpEmoji, PaginatorAction.Jump);
            actions.Add(forwardEmoji, PaginatorAction.Forward);
            actions.Add(lastEmoji, PaginatorAction.SkipToEnd);

            return(builder.WithOptions(actions));
        }
Beispiel #9
0
        public Task StaticPaginatorAsync()
        {
            var pages = new PageBuilder[] {
                new PageBuilder().WithTitle("I"),
                new PageBuilder().WithTitle("am"),
                new PageBuilder().WithTitle("cool"),
                new PageBuilder().WithTitle(":sunglasses:"),
                new PageBuilder().WithText("I am cool :crown:").WithAuthor(Context.User)
            };

            var paginator = new StaticPaginatorBuilder()
                            .WithUsers(Context.User)
                            .WithPages(pages)
                            .WithFooter(PaginatorFooter.PageNumber | PaginatorFooter.Users)
                            .WithDefaultEmotes()
                            .Build();

            return(Interactivity.SendPaginatorAsync(paginator, Context.Channel, TimeSpan.FromMinutes(2)));
        }
        public async Task ViewAll()
        {
            User  User  = Utils.GetUser(Context.User.Id);
            Actor Actor = User.Active;

            if (Actor == null)
            {
                await ReplyAsync("You have no active characters. Set one using the `Character` command or create one using the `Create` command");

                return;
            }

            if (Actor.Merits.Count == 0)
            {
                await ReplyAsync(Context.User.Mention + ", " + Actor.Name + " has no Items.");

                return;
            }

            var pages = new List <PageBuilder>();

            foreach (var item in Actor.Inventory.OrderBy(x => x.Name))
            {
                var page = new PageBuilder()
                           .WithTitle(item.Name)
                           .WithThumbnailUrl(Actor.Avatar);
                foreach (var segment in item.Description)
                {
                    page.AddField("Description", segment);
                }
                pages.Add(page);
            }

            var paginator = new StaticPaginatorBuilder()
                            .WithUsers(Context.User)
                            .WithPages(pages)
                            .WithDefaultEmotes()
                            .WithFooter(PaginatorFooter.PageNumber)
                            .Build();

            await Interactivity.SendPaginatorAsync(paginator, Context.Channel, TimeSpan.FromMinutes(5));
        }
Beispiel #11
0
        private async Task LeaderboardAsync <T>(T[] values, Func <T, string> nameSelector, Func <T, string> valueSelector,
                                                string entityName, string valueName, Color color)
        {
            var pages = new List <PageBuilder>();
            int index = 0;

            foreach (var chunk in values.Chunk(PageSize))
            {
                pages.Add(PageUtils.LeaderBoardPage(chunk, index, nameSelector, valueSelector, entityName, valueName, color));
                index += PageSize;
            }

            var paginator = new StaticPaginatorBuilder()
                            .WithDefaultEmotes()
                            .WithDeletion(DeletionOptions.Valid)
                            .WithUsers(Context.User)
                            .WithPages(pages.ToArray())
                            .Build();

            await Interactivity.SendPaginatorAsync(paginator, Context.Channel);
        }
Beispiel #12
0
        public async Task ListAll()
        {
            string content   = $"";
            var    paginator = new StaticPaginatorBuilder();

            foreach (var module in cmdService.Modules)
            {
                var page = new PageBuilder();
                var text = new StringBuilder();
                text.Append($"**{module.Name}**");
                if (!string.IsNullOrWhiteSpace(module.Summary))
                {
                    text.Append(": " + module.Summary);
                }
                page.WithText(text.ToString());
                List <string> cmds = new List <string>();
                foreach (var cmd in module.Commands)
                {
                    string s = $"{Program.Prefix}**{cmd.Aliases.First()}**";
                    foreach (var arg in cmd.Parameters)
                    {
                        var br = arg.IsOptional ? brackets[0] : brackets[1];
                        s += $" {br[0]}{arg.Type.Name} {arg.Name}{br[1]}";
                    }
                    s += " - " + cmd.Summary;
                    var result = await cmd.CheckPreconditionsAsync(Context, services);

                    if (result.IsSuccess)
                    {
                        cmds.Add(s);
                    }
                }

                page.WithDescription(string.Join("\r\n", cmds));
                paginator.AddPage(page);
            }

            await PagedReplyAsync(paginator);
        }
        public async Task View()
        {
            User  User  = Utils.GetUser(Context.User.Id);
            Actor Actor = User.Active;

            if (Actor == null)
            {
                await ReplyAsync("You have no active characters. Set one using the `Character` command or create one using the `Create` command");

                return;
            }
            var controls = new Dictionary <IEmote, PaginatorAction>()
            {
                { new Emoji("◀️"), PaginatorAction.Backward }, { new Emoji("▶️"), PaginatorAction.Forward }
            };
            var paginator = new StaticPaginatorBuilder()
                            .WithUsers(Context.User)
                            .WithPages(Actor.GetSheet())
                            .WithEmotes(controls)
                            .Build();

            await Interactivity.SendPaginatorAsync(paginator, Context.Channel, TimeSpan.FromMinutes(5));
        }
Beispiel #14
0
        async Task printListFor(BotUser u)
        {
            var paginator = new StaticPaginatorBuilder();
            var cPage     = new PageBuilder();

            foreach (var perm in u.Permissions)
            {
                string sep = perm.Type == PermType.Allow ? "**" : perm.Type == PermType.Deny ? "~~" : "";
                var    s   = $"`{perm.RawNode}` {sep}{perm.Description}{sep}\r\n";
                if ((cPage.Text.Length + s.Length) > 1024)
                {
                    paginator.AddPage(cPage);
                    cPage = new PageBuilder();
                }
                cPage.Text += s;
            }
            if (cPage.Text == "")
            {
                cPage.Text = "No permissions nodes are known.";
            }
            paginator.AddPage(cPage);
            await PagedReplyAsync(paginator);
        }
Beispiel #15
0
        /// <summary>Searches youtube for specified searchString and returns a paginator with the result.
        /// </summary>
        public async Task SearchAsync(string searchString, SocketCommandContext context)
        {
            var searchResults = await _lavaNode.SearchYouTubeAsync(searchString);

            if (searchResults.Tracks.Count == 0)
            {
                await context.Channel.SendMessageAsync(
                    embed : CustomFormats.CreateErrorEmbed($"No results found for {searchString}."));

                return;
            }

            var resultsCount = searchResults.Tracks.Count;

            /* We calculate the maximum items per page we want
             *     this will return the minimum number, either 10 or resultsCount*/
            var maxItemsPerPage = Math.Min(10, resultsCount);

            var maxPages = resultsCount / maxItemsPerPage;

            var pages = new PageBuilder[maxPages];

            var trackNum = 0;

            //We itterate through all the pages we need
            for (int i = 0; i < maxPages; i++)
            {
                var descriptionBuilder = new StringBuilder();

                //We take X items, equal to the number of maxItemsPerPage, so we don't overflow the embed max description length
                var results = searchResults.Tracks.Skip(i).Take(maxItemsPerPage);

                //We itterate through the results taken on the previous instruction
                foreach (var result in results)
                {
                    //We create the description for each page
                    descriptionBuilder.Append($"**{trackNum + 1}) {result.Title}** - {result.Duration}\n");
                    trackNum++;
                }

                //We create the page, with the description created on the previous loop
                pages[i] = new PageBuilder().WithDescription($"{descriptionBuilder}").WithColor(Color.Purple);
            }

            //We create the paginator to send
            var paginator = new StaticPaginatorBuilder()
                            .WithUsers(context.User)
                            .WithFooter(PaginatorFooter.PageNumber)
                            .WithEmotes(new Dictionary <IEmote, PaginatorAction>()
            {
                { new Emoji("⏮️"), PaginatorAction.SkipToStart },
                { new Emoji("⬅️"), PaginatorAction.Backward },
                { new Emoji("➡️"), PaginatorAction.Forward },
                { new Emoji("⏭️"), PaginatorAction.SkipToEnd }
            })
                            .WithPages(pages)
                            .WithTimoutedEmbed(pages[0].Build().Embed.ToEmbedBuilder())
                            .Build();

            //Send paginator to text channel
            await _interactivityService.SendPaginatorAsync(paginator, context.Channel, TimeSpan.FromSeconds(90));
        }
Beispiel #16
0
        /// <summary>Returns an embed containing the player queue.
        /// </summary>
        public async Task QueueAsync(SocketCommandContext context)
        {
            var guild = context.Guild;

            //Checks if bot is connected to a voice channel
            if (!_lavaNode.HasPlayer(guild))
            {
                await context.Channel.SendMessageAsync(embed : CustomFormats.CreateErrorEmbed("Could not acquire player."));

                return;
            }

            //Bot is connected to voice channel, so we get the player associated with the guild
            var player = _lavaNode.GetPlayer(guild);

            //If player isn't playing, then we return
            if (!(player.PlayerState is PlayerState.Playing))
            {
                await context.Channel.SendMessageAsync(embed : CustomFormats.CreateErrorEmbed("I'm not playing anything right now."));

                return;
            }

            //If there are no more songs in queue except for the current playing song, we return with a reply
            //saying the currently playing song and that no more songs are queued
            if (player.Queue.Count < 1 && player.Track != null)
            {
                await context.Channel.SendMessageAsync(embed : CustomFormats.CreateBasicEmbed("",
                                                                                              $"**Now playing: {player.Track.Title}**\nNo more songs queued.", Color.Blue));

                return;
            }

            try
            {
                //After checking if we have tracks in the queue

                //We save the count of tracks in queue to tracksCount variable
                var tracksCount = player.Queue.Count;

                /* We calculate the maximum items per page we want
                 * this will return the minimum number, either 10 or tracksCount*/
                var maxItemsPerPage = Math.Min(10, tracksCount);

                //We calculate how many pages we'll have (used to initialize array)
                var maxPages = tracksCount / maxItemsPerPage;

                //We initialize an array with size of maxPages
                var pages = new PageBuilder[maxPages];

                var trackNum = 2; //trackNum == 2 because we're not including the first track

                //We itterate through all the pages we need
                for (int i = 0; i < maxPages; i++)
                {
                    var descriptionBuilder = new StringBuilder();

                    //We take X items, equal to the number of maxItemsPerPage, so we don't overflow the embed max description length
                    var tracks = player.Queue.Skip(i).Take(maxItemsPerPage);

                    //We itterate through the tracks taken on the previous instruction
                    foreach (var track in tracks)
                    {
                        //We create the description for each page
                        descriptionBuilder.Append($"{trackNum}: [{track.Title}]({track.Url})\n");
                        trackNum++;
                    }

                    //We create the page, with the description created on the previous loop
                    pages[i] = new PageBuilder().WithTitle($"Now playing: {player.Track?.Title}")
                               .WithDescription($"{descriptionBuilder}").WithColor(Color.Blue);
                }

                //We create the paginator to send
                var paginator = new StaticPaginatorBuilder()
                                .WithUsers(context.User)
                                .WithFooter(PaginatorFooter.PageNumber)
                                .WithEmotes(new Dictionary <IEmote, PaginatorAction>()
                {
                    { new Emoji("⏮️"), PaginatorAction.SkipToStart },
                    { new Emoji("⬅️"), PaginatorAction.Backward },
                    { new Emoji("➡️"), PaginatorAction.Forward },
                    { new Emoji("⏭️"), PaginatorAction.SkipToEnd }
                })
                                .WithPages(pages)
                                .WithTimoutedEmbed(pages[0].Build().Embed.ToEmbedBuilder())
                                .Build();

                //Send the paginator to the text channel
                await _interactivityService.SendPaginatorAsync(paginator, context.Channel, TimeSpan.FromSeconds(150));
            }
            catch (Exception ex)
            {
                await context.Channel.SendMessageAsync(embed : CustomFormats.CreateErrorEmbed(ex.Message));
            }
        }