Example #1
0
        public async Task UnBan(InteractionContext ctx,
                                [Option("user", "User to unban")] DiscordUser user, [Option("reason", "reason for ban")] string reason)
        {
            await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource);

            var usr = await ctx.Guild.GetMemberAsync(ctx.User.Id);

            var perms = (usr.PermissionsIn(ctx.Channel) & Permissions.BanMembers) != 0;


            if (!perms || user.Id == ctx.User.Id)
            {
                await ctx.Client.SendMessageAsync(ctx.Guild.GetChannel(607392574235344928),
                                                  $"{ctx.User.Mention} tried to use the unban command on {user.Mention} for reason {reason} but was denied\n(►˛◄’!)");

                await ctx.DeleteResponseAsync();

                return;
            }

            try
            {
                await ctx.Guild.UnbanMemberAsync(user.Id, reason);
            }
            catch (Exception e)
            {
                await ctx.EditResponseAsync(
                    new DiscordWebhookBuilder().WithContent($"Failed to unban {user.Mention}."));

                return;
            }

            await ctx.EditResponseAsync(
                new DiscordWebhookBuilder().WithContent($"{user.Mention} has been unbanned."));
        }
Example #2
0
        public async Task tldr(InteractionContext ctx, [Option("package", "Search term to use to find tldr pages")]
                               string searchTerm)
        {
            //response may take a while so we need to do this first
            await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource);

            searchTerm = searchTerm.ToLower();
            var tldrUrl = $"https://raw.githubusercontent.com/tldr-pages/tldr/master/pages/common/{searchTerm}.md";
            var resp    = "";

            try
            {
                resp = await tldrUrl.GetStringAsync();
            }
            catch (FlurlHttpException ex)
            {
                await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("No tldr page found"));

                return;
            }

            var lines = resp.Replace("\n\n", "\n").Split("\n");
            var embed = new DiscordEmbedBuilder()
                        .WithTitle($"TLDR page: {lines.FirstOrDefault()?.Remove(0, 2)}")
                        .WithColor(new DiscordColor(0x478061))
                        .WithDescription(string.Join("\n", lines.Skip(1)))
                        .Build();
            await ctx.EditResponseAsync(new DiscordWebhookBuilder().AddEmbed(embed));
        }
Example #3
0
        public static async Task ResetLevel(InteractionContext ctx, DiscordUser user)
        {
            await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource);

            var usr = await ctx.Guild.GetMemberAsync(ctx.User.Id);

            var perms = (usr.PermissionsIn(ctx.Channel) & Permissions.BanMembers) != 0;

            if (!perms)
            {
                await ctx.DeleteResponseAsync();

                return;
            }

            using var db = new LiteDatabase(@$ "{ctx.Guild.Id}.db");
            var col = db.GetCollection <UserData>("users");

            var userData = col.FindOne(x => x.Id == user.Id);

            if (userData != null)
            {
                userData.MessageCount = 0;
                userData.Level        = 0;

                await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("Users level reset"));

                return;
            }

            await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("User not found in database"));
        }
Example #4
0
        public static async Task EditLevelRole(InteractionContext ctx, DiscordRole role, long level)
        {
            await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource);

            var usr = await ctx.Guild.GetMemberAsync(ctx.User.Id);

            var perms = (usr.PermissionsIn(ctx.Channel) & Permissions.BanMembers) != 0;

            if (!perms)
            {
                await ctx.DeleteResponseAsync();

                return;
            }

            using var db = new LiteDatabase(@$ "global.db");
            var col = db.GetCollection <ServerSettings>("servers");

            var server = col.FindOne(x => x.Id == ctx.Guild.Id);

            if (server == null)
            {
                server = new ServerSettings()
                {
                    Id = ctx.Guild.Id
                };
                col.Insert(server);
            }

            if (level == -1)
            {
                if (server.RoleLevels.ContainsKey(role.Id))
                {
                    await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("Role level removed"));
                }
                else
                {
                    await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("Role level does not exist"));
                }
            }
            else if (level > 0)
            {
                server.RoleLevels ??= new Dictionary <ulong, long>();
                if (server.RoleLevels.TryAdd(role.Id, level))
                {
                    await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("Role level added"));
                }
                else
                {
                    await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("Role level already exists"));
                }
            }
            else
            {
                await ctx.DeleteResponseAsync();
            }

            col.Update(server);
        }
Example #5
0
            public async Task Search(InteractionContext ctx, [Option("searchTerm", "locate files in all XBPS packages")]
                                     string searchTerm)
            {
                //response may take a while so we need to do this first
                await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource);

                var resp = "";

                if (!Directory.Exists("tmp/xlocate"))
                {
                    await ctx.EditResponseAsync(
                        new DiscordWebhookBuilder().WithContent("No database found please update"));

                    return;
                }

                var files = Directory.GetFiles("tmp/xlocate");

                foreach (var file in files)
                {
                    // if (file.Contains(".git"))
                    // {
                    //     continue;
                    // }

                    Console.WriteLine(file);
                    var pkg = Path.GetFileName(file);

                    foreach (var line in File.ReadLines(file))
                    {
                        if (!line.Contains(searchTerm))
                        {
                            continue;
                        }

                        if (resp.Length + line.Length + pkg.Length + 1 + Environment.NewLine.Length > 1994)
                        {
                            break;
                        }

                        resp += $"{pkg}:{line}{Environment.NewLine}";
                    }
                }

                if (!string.IsNullOrEmpty(resp))
                {
                    await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent(
                                                    $"```{resp}```"));

                    return;
                }

                await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("Could not find files"));
            }
Example #6
0
        public static async Task EditBlacklist(InteractionContext ctx, string option, DiscordChannel channel)
        {
            await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource);

            var usr = await ctx.Guild.GetMemberAsync(ctx.User.Id);

            var perms = (usr.PermissionsIn(ctx.Channel) & Permissions.BanMembers) != 0;

            if (!perms)
            {
                await ctx.DeleteResponseAsync();

                return;
            }

            using var db = new LiteDatabase(@$ "global.db");
            var col = db.GetCollection <ServerSettings>("servers");

            var server = col.FindOne(x => x.Id == ctx.Guild.Id);

            if (server == null)
            {
                server = new ServerSettings()
                {
                    Id = ctx.Guild.Id
                };
                col.Insert(server);
            }

            switch (option)
            {
            case "add":
                server.ExperienceBlacklistedChannels ??= new List <ulong>();
                server.ExperienceBlacklistedChannels.Add(channel.Id);
                await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent($"{channel.Mention} added"));

                break;

            case "remove":
                if (server.ExperienceBlacklistedChannels.Contains(channel.Id))
                {
                    server.ExperienceBlacklistedChannels.Remove(channel.Id);
                    await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent($"{channel.Mention} removed"));
                }
                else
                {
                    await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent($"{channel.Mention} not blacklisted"));
                }
                break;
            }
            col.Update(server);
        }
Example #7
0
        public static async Task GetLevel(InteractionContext ctx,
                                          DiscordUser user = null !)
        {
            await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource);

            using var db = new LiteDatabase(@$ "{ctx.Guild.Id}.db");
            var col = db.GetCollection <UserData>("users");

            if (user == null)
            {
                user = ctx.User;
            }
            var userData = col.FindOne(x => x.Id == user.Id);

            if (userData != null)
            {
                var embed = new DiscordEmbedBuilder();
                embed.AddField("Level", userData.Level.ToString());
                embed.AddField("Message Count", userData.MessageCount.ToString());

                await ctx.EditResponseAsync(new DiscordWebhookBuilder().AddEmbed(embed));

                return;
            }

            await ctx.DeleteResponseAsync();
        }
Example #8
0
            public async Task Update(InteractionContext ctx)
            {
                //response may take a while so we need to do this first
                await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource);

                if (!Directory.Exists("tmp/xlocate") && Directory.GetFiles("tmp/xlocate").Length > 0)
                {
                    var clone = Repository.Clone("https://alpha.de.repo.voidlinux.org/xlocate/xlocate.git",
                                                 "tmp/xlocate");
                    await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent(clone));
                }

                using var repo = new Repository("tmp/xlocate");
                // Credential information to fetch
                PullOptions options = new();

                options.FetchOptions = new FetchOptions();
                var signature = new Signature(
                    new Identity("VoidBot", "*****@*****.**"), DateTimeOffset.Now);

                try
                {
                    var pull = LibGit2Sharp.Commands.Pull(repo, signature, options);

                    switch (pull.Status)
                    {
                    case MergeStatus.UpToDate:
                        await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("Cache up to date"));

                        break;

                    case MergeStatus.FastForward:
                        await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("Cache updated"));

                        break;
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("Already up to date"));
                }
            }
Example #9
0
        public static async Task GetDebugLogAsync(InteractionContext ctx)
        {
            await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().WithContent("Trying to get log").AsEphemeral(false));

            DateTime now         = DateTime.Now;
            var      target_file = $"miku_log{now.ToString("yyyy/MM/dd").Replace("/","")}.txt";

            if (!File.Exists(target_file))
            {
                await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("Failed to get log"));

                return;
            }
            else
            {
                await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent($"Found log {Formatter.Bold(target_file)}"));
            }
            try
            {
                if (!File.Exists($"temp-{target_file}"))
                {
                    File.Copy(target_file, $"temp-{target_file}");
                }
                else
                {
                    File.Delete($"temp-{target_file}");
                    File.Copy(target_file, $"temp-{target_file}");
                }
                FileStream log = new(path : $"temp-{target_file}", FileMode.Open, FileAccess.Read);
                await ctx.FollowUpAsync(new DiscordFollowupMessageBuilder().AddFile(target_file, log, true).WithContent($"Log {Formatter.Bold(target_file)}").AsEphemeral(false));

                log.Close();
                log.Dispose();
                File.Delete($"temp-{target_file}");
            }
            catch (Exception ex)
            {
                await ctx.FollowUpAsync(new DiscordFollowupMessageBuilder().WithContent(ex.Message).AsEphemeral(false));

                await ctx.FollowUpAsync(new DiscordFollowupMessageBuilder().WithContent(ex.StackTrace).AsEphemeral(false));
            }
            await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("Done"));
        }
Example #10
0
                public async Task ServerIconSet(
                    InteractionContext ctx,
                    [Option("url", "Url of the icon")] string url
                    )
                {
                    if ((ctx.Member.PermissionsIn(ctx.Channel) & Permissions.ManageGuild) == 0)
                    {
                        await ctx.CreateResponseAsync(
                            InteractionResponseType.ChannelMessageWithSource,
                            new DiscordInteractionResponseBuilder()
                            .WithContent("You must have manage server permissions to run this command")
                            .AsEphemeral(true)
                            );

                        return;
                    }

                    await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource);

                    var request = WebRequest.Create(url);

                    using (var response = await request.GetResponseAsync())
                    {
                        using (var ms = new MemoryStream())
                        {
                            var respStream = response.GetResponseStream();
                            if (respStream is null)
                            {
                                await ctx.CreateResponseAsync(
                                    InteractionResponseType.ChannelMessageWithSource,
                                    new DiscordInteractionResponseBuilder()
                                    .WithContent("An error occured while setting that image")
                                    .AsEphemeral(true)
                                    );

                                return;
                            }

                            await respStream.CopyToAsync(ms);

                            ms.Position = 0;
                            await ctx.Guild.ModifyAsync(model => model.Icon = ms);
                        }
                    }


                    await ctx.EditResponseAsync(new DiscordWebhookBuilder()
                                                .AddEmbed(new DiscordEmbedBuilder()
                                                          .WithImageUrl(url)
                                                          .WithTitle("Icon set")));
                }
Example #11
0
        private async Task <bool> CheckCache(InteractionContext ctx)
        {
            if (Directory.Exists("tldr-cache") &&
                (Directory.GetLastWriteTimeUtc("tldr-cache") - DateTime.UtcNow) <= TimeSpan.FromDays(30))
            {
                return(true);
            }

            await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("Updating cache..."));

            try
            {
                await UpdateCache();

                await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("Cache updated"));
            }
            catch (Exception e)
            {
                return(false);
            }

            return(true);
        }
Example #12
0
        public static async Task ViewBlacklist(InteractionContext ctx)
        {
            await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource);

            var usr = await ctx.Guild.GetMemberAsync(ctx.User.Id);

            var perms = (usr.PermissionsIn(ctx.Channel) & Permissions.BanMembers) != 0;

            if (!perms)
            {
                await ctx.DeleteResponseAsync();

                return;
            }

            using var db = new LiteDatabase(@$ "global.db");
            var col = db.GetCollection <ServerSettings>("servers");

            var server = col.FindOne(x => x.Id == ctx.Guild.Id);

            if (server == null)
            {
                await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("Server not found"));

                return;
            }

            if (server.ExperienceBlacklistedChannels.Any())
            {
                await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent(string.Join(", ", server.ExperienceBlacklistedChannels.Select(x => $"<#{x}>"))));
            }
            else
            {
                await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("No channels blacklisted"));
            }
        }
Example #13
0
    public async Task WebShot(InteractionContext ctx, [Option("url", "The url to take a screenshot of")] string url,
                              [Choice("10s", 10)]
                              [Choice("7s", 7)]
                              [Choice("5s", 5)]
                              [Choice("Don't wait", 0)]
                              [Option("waittime", "How long to wait after it takes a screenshot")]
                              long waittime = 0)
    {
        await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource);

        var bob = new DiscordEmbedBuilder().WithImageUrl("attachment://html.png")
                  .WithFooter($"Requested by {ctx.User.Username}", ctx.User.GetAvatarUrl(ImageFormat.Png))
                  .WithColor(DiscordColor.Green);

        using var e = await Browser.RenderUrlAsync(url, (byte) waittime);

        await ctx.EditResponseAsync(new DiscordWebhookBuilder().AddFile("html.png", e).AddEmbed(bob.Build()));
    }
Example #14
0
        public async Task MessagesClear(
            InteractionContext ctx,
            [Option("num", "Number of messages to clear, defaults to 100")]
            long num = 100
            )
        {
            await ctx.CreateResponseAsync(
                InteractionResponseType.DeferredChannelMessageWithSource,
                new DiscordInteractionResponseBuilder().AsEphemeral(true)
                );

            var messagesToDelete =
                (await ctx.Channel.GetMessagesAsync((int)num)).Where(x => (DateTimeOffset.UtcNow - x.Timestamp).TotalDays <= 14);
            var messagesToDeleteAsAnArray = messagesToDelete as DiscordMessage[] ?? messagesToDelete.ToArray();

            await ctx.Channel.DeleteMessagesAsync(messagesToDeleteAsAnArray);

            await ctx.EditResponseAsync(
                new DiscordWebhookBuilder().WithContent($"Deleted {messagesToDeleteAsAnArray.Length} messages."));
        }
Example #15
0
        public async Task Faq(InteractionContext ctx,
                              [Choice("discordinstall", "discordinstall")]
                              [Option("option", "option")]
                              string option,
                              [Option("atuser", "user to mention")] DiscordUser user = null !)
        {
            await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource);

            switch (option)
            {
            case "discordinstall":
                var embed = new DiscordEmbedBuilder()
                {
                    Title       = Formatter.Underline(Formatter.Bold("Please do not run these commands as root")),
                    Description = "How to install discord using xbps-src \n" + Formatter.BlockCode(@"git clone https://github.com/void-linux/void-packages
cd void-packages
./xbps-src binary-bootstrap
echo XBPS_ALLOW_RESTRICTED=yes > etc/conf
./xbps-src pkg discord
sudo xbps-install --repository=hostdir/binpkgs/nonfree discord", "bash")
                };

                var build = new DiscordWebhookBuilder();

                if (user != null)
                {
                    embed.Description += $"\n{user.Mention}";
                }
                build.AddEmbed(embed);

                await ctx.EditResponseAsync(build);

                return;

                break;

            case "":
                break;
            }
            await ctx.DeleteResponseAsync();
        }
Example #16
0
        public async Task MassBan(InteractionContext ctx,
                                  [Option("users", "space separated list of ids to ban")]
                                  string users, [Option("reason", "reason for ban")] string reason)
        {
            await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource);

            var usr = await ctx.Guild.GetMemberAsync(ctx.User.Id);

            var perms = (usr.PermissionsIn(ctx.Channel) & Permissions.BanMembers) != 0;


            if (!perms || users.Contains(ctx.User.Id.ToString()))
            {
                await ctx.Client.SendMessageAsync(ctx.Guild.GetChannel(607392574235344928),
                                                  $"{ctx.User.Mention} tried to use the ban command on {users} for reason {reason} but was denied\n(►˛◄’!)");

                await ctx.DeleteResponseAsync();

                return;
            }

            var userList = users.Split(' ').Select(ulong.Parse);

            var failCount = 0;

            foreach (var user in userList)
            {
                try
                {
                    await ctx.Guild.BanMemberAsync(user, 7, reason);
                }
                catch (Exception e)
                {
                    failCount++;
                }
            }

            await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent(
                                            $"{userList.Count() - failCount} users have been banned. {(failCount > 0 ? $"Failed to ban {failCount} users" : "")} "));
        }
Example #17
0
        public async Task GetTLDR(InteractionContext ctx,
                                  [Option("page", "page to find")] string name,
                                  [Option("platform", "Specifies the platform to be used")]
                                  Platform platform = Platform.Linux,
                                  [Option("language", "Specifies the preferred language for the page returned")]
                                  string?language = null

                                  )
        {
            await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource);

            if (!await CheckCache(ctx))
            {
                await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("Cache update failed"));
            }


            name = name.ToLower();
            name = name.Replace(' ', '-');


            var index = await GetIndex();

            var page = index.Commands.FirstOrDefault(x => x.Name == name);

            //if page not found, redownload cache and try again
            if (page == null)
            {
                await CheckCache(ctx);

                index = await GetIndex();

                page = index.Commands.FirstOrDefault(x => x.Name == name);

                if (page == null)
                {
                    await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("page not found"));

                    return;
                }
            }


            var targets = page.Targets.Where(x => x.Os == platform).ToList();

            if (!targets.Any())
            {
                //fallback to common
                targets = page.Targets.Where(x => x.Os == Platform.Common).ToList();

                //fallback to random platform
                if (!targets.Any())
                {
                    targets = page.Targets.ToList();
                }
            }

            if (language != null)
            {
                var langTargets = targets.Where(x => x.Language == language)
                                  .ToList();
                if (!langTargets.Any())
                {
                    await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("page not found in chosen language"));

                    return;
                }

                targets = langTargets;
            }
            else
            {
                //default to english
                var langTargets = targets.Where(x => x.Language == "en")
                                  .ToList();

                if (langTargets.Any())
                {
                    targets = langTargets;
                }
            }

            var finalTarget = targets.FirstOrDefault();

            if (finalTarget == null)
            {
                await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("page not found"));

                return;
            }

            var lines = await GetPageFromTarget(name, finalTarget);


            var builder = new DiscordWebhookBuilder();

            var embed = new DiscordEmbedBuilder()
                        .WithTitle($"tldr page: {lines.FirstOrDefault()?.Remove(0, 2)} ({finalTarget.Os})")
                        .WithAuthor("tldr pages", "https://tldr.sh/", "https://tldr.sh/assets/img/icon.png")
                        .WithColor(new DiscordColor("#54B59A"))
                        .WithDescription(string.Join("\n", lines.Skip(1)).Replace("\n\n", "\n"))
                        .WithFooter("tldr - collaborative cheatsheets for console commands ",
                                    "https://github.githubassets.com/images/icons/emoji/unicode/1f4da.png")
                        .Build();

            builder.AddEmbed(embed);

            if (finalTarget.Os != Platform.Common && finalTarget.Os != platform)
            {
                var warningEmbed = new DiscordEmbedBuilder()
                                   .WithTitle($"Platform: {finalTarget.Os}")
                                   .WithColor(DiscordColor.Red)
                                   .Build();
                builder.AddEmbed(warningEmbed);
            }

            await ctx.EditResponseAsync(builder);
        }
        public async Task TimeSpanTest(InteractionContext ctx, [Option("timespan", "Time span")] TimeSpan?timespan)
        {
            await ctx.DeferAsync();

            await ctx.EditResponseAsync(new Entities.DiscordWebhookBuilder().WithContent(timespan == null ? "Invalid time span" : timespan.ToString()));
        }
Example #19
0
        public async Task Xbps(InteractionContext ctx,
                               [Option("searchTerm", "Search term to use to find package")]
                               string searchTerm,
                               [Choice("aarch64", "aarch64")]
                               [Choice("aarch64-musl", "aarch64-musl")]
                               [Choice("armv6l-musl", "armv6l-musl")]
                               [Choice("armv7l", "armv7l")]
                               [Choice("armv7l-musl", "armv7l-musl")]
                               [Choice("i686", "i686")]
                               [Choice("x86_64", "x86_64")]
                               [Choice("x86_64-musl", "x86_64-musl")]
                               [Option("arch", "arch filter")]
                               string arch = "x86_64")
        {
            var interactivity = ctx.Client.GetInteractivity();


            //response may take a while so we need to do this first
            await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource);

            searchTerm = searchTerm.Replace(' ', '+');

            var xqApiUrl = Config.AppSetting.GetSection("DiscordSettings")["xqApiUrl"];

            PackageListResponse resp;

            try
            {
                resp = await $"{xqApiUrl}query/{arch}?q={searchTerm}".GetJsonAsync <PackageListResponse>();
            }
            catch (FlurlHttpException ex)
            {
                //todo: make helper function for embeds
                var embed = new DiscordEmbedBuilder()
                            .WithTitle($"Void Repo Search: {searchTerm}")
                            .WithDescription(ex.Message + " report this error to @Epictek#6136")
                            .WithUrl(
                    $"https://github.com/void-linux/void-packages/search?q%5B%5D=filename%3Atemplate+path%3A%2Fsrcpkgs&q%5B%5D={searchTerm}&s=indexed")
                            .WithColor(new DiscordColor(0x478061))
                            .WithFooter(
                    "Search results xq-api",
                    "https://voidlinux.org/assets/img/void_bg.png"
                    ).Build();
                await ctx.EditResponseAsync(new DiscordWebhookBuilder().AddEmbed(embed));

                return;
            }

            if (resp.Data.Length == 0)
            {
                var embed = new DiscordEmbedBuilder()
                            .WithTitle($"Void Repo Search: {searchTerm}")
                            .WithDescription("No packages found")
                            .WithUrl(
                    $"https://github.com/void-linux/void-packages/search?q%5B%5D=filename%3Atemplate+path%3A%2Fsrcpkgs&q%5B%5D={searchTerm}&s=indexed")
                            .WithColor(new DiscordColor(0x478061))
                            .WithFooter(
                    "Search results xq-api",
                    "https://voidlinux.org/assets/img/void_bg.png"
                    ).Build();
                await ctx.EditResponseAsync(new DiscordWebhookBuilder().AddEmbed(embed));

                return;
            }

            string       links = "";
            IList <Page> pages = new List <Page>();

            Package last = resp.Data.Last();

            foreach (Package package in resp.Data)
            {
                var packageString =
                    $"[{package.Name} {package.Version}](https://github.com/void-linux/void-packages/tree/master/srcpkgs/{package.Name}) - {package.ShortDesc}";

                links += packageString + "\n";

                if (packageString.Length + links.Length > 2000 || package.Equals(last))
                {
                    var embed = new DiscordEmbedBuilder()
                                .WithTitle("Void Repo Search: " + searchTerm)
                                .WithDescription(links)
                                .WithUrl(
                        "https://github.com/void-linux/void-packages/search?q%5B%5D=filename%3Atemplate+path%3A%2Fsrcpkgs&q%5B%5D=" +
                        searchTerm + "&s=indexed")
                                .WithColor(new DiscordColor(0x478061))
                                .WithFooter(
                        "Search results from xq-api",
                        "https://voidlinux.org/assets/img/void_bg.png"
                        );

                    pages.Add(new Page
                    {
                        Embed = embed
                    });

                    links = "";
                }
            }

            if (pages.Count > 1)
            {
                await ctx.DeleteResponseAsync();

                await interactivity.SendPaginatedMessageAsync(ctx.Channel, ctx.Interaction.User, pages);
            }
            else
            {
                await ctx.EditResponseAsync(new DiscordWebhookBuilder().AddEmbed(pages.First().Embed));
            }
        }
Example #20
0
        public async Task Package(InteractionContext ctx, [Option("searchTerm", "Search term to use to find package")]
                                  string searchTerm,
                                  [Choice("aarch64", "aarch64")]
                                  [Choice("aarch64-musl", "aarch64-musl")]
                                  [Choice("armv6l-musl", "armv6l-musl")]
                                  [Choice("armv7l", "armv7l")]
                                  [Choice("armv7l-musl", "armv7l-musl")]
                                  [Choice("i686", "i686")]
                                  [Choice("x86_64", "x86_64")]
                                  [Choice("x86_64-musl", "x86_64-musl")]
                                  [Option("arch", "arch filter")]
                                  string arch = "x86_64")
        {
            //response may take a while so we need to do this first
            await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource);

            var xqApiUrl = Config.AppSetting.GetSection("DiscordSettings")["xqApiUrl"];

            PackageResponse resp;

            try
            {
                resp = await $"{xqApiUrl}/packages/{arch}/{searchTerm}".GetJsonAsync <PackageResponse>();
            }
            catch (FlurlHttpException ex)
            {
                if (ex.Call.HttpResponseMessage.StatusCode == HttpStatusCode.NotFound)
                {
                    var embed = new DiscordEmbedBuilder()
                                .WithTitle($"Void Repo package: {searchTerm}")
                                .WithDescription("Package not found")
                                .WithUrl(
                        $"https://github.com/void-linux/void-packages/search?q%5B%5D=filename%3Atemplate+path%3A%2Fsrcpkgs&q%5B%5D={searchTerm}&s=indexed")
                                .WithColor(new DiscordColor(0x478061))
                                .WithFooter(
                        "Search results xq-api",
                        "https://voidlinux.org/assets/img/void_bg.png"
                        ).Build();
                    await ctx.EditResponseAsync(new DiscordWebhookBuilder().AddEmbed(embed));

                    return;
                }
                else
                {
                    //todo: make helper function for embeds
                    var embed = new DiscordEmbedBuilder()
                                .WithTitle($"Void Repo Search: {searchTerm}")
                                .WithDescription(ex.Message + " report this error to @Epictek#6136")
                                .WithUrl(
                        $"https://github.com/void-linux/void-packages/search?q%5B%5D=filename%3Atemplate+path%3A%2Fsrcpkgs&q%5B%5D={searchTerm}&s=indexed")
                                .WithColor(new DiscordColor(0x478061))
                                .WithFooter(
                        "Search results xq-api",
                        "https://voidlinux.org/assets/img/void_bg.png"
                        ).Build();
                    await ctx.EditResponseAsync(new DiscordWebhookBuilder().AddEmbed(embed));

                    return;
                }
            }

            var em = new DiscordEmbedBuilder()
                     .WithTitle($"Void Repo Package: {resp.Data.Name}")
                     .WithUrl(
                $"https://github.com/void-linux/void-packages/search?q%5B%5D=filename%3Atemplate+path%3A%2Fsrcpkgs&q%5B%5D={resp.Data.Name}&s=indexed")
                     .WithColor(new DiscordColor(0x478061))
                     .WithFooter(
                "Search results xq-api",
                "https://voidlinux.org/assets/img/void_bg.png"
                );

            foreach (var val in resp.Data.ToKeyValuePairs())
            {
                if (val.Value is Array)
                {
                    //em.AddField(val.Key, string.Join(", ", (string[]) val.Value), false);
                }
                else if (val.Value is string value)
                {
                    em.AddField(val.Key, value, true);
                }
            }

            await ctx.EditResponseAsync(new DiscordWebhookBuilder().AddEmbed(em.Build()));
        }
 public override async Task CreateErrorResponse(string errorMessage)
 {
     await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent(errorMessage));
 }
Example #22
0
        public async Task GetTLDR(InteractionContext ctx,
                                  [Option("page", "page to find")] string page,
                                  [Choice("linux", "linux")]
                                  [Choice("osx", "osx")]
                                  [Choice("windows", "windows")]
                                  [Choice("android", "android")]
                                  [Choice("sunos", "sunos")]
                                  [Choice("common", "common")]
                                  [Option("platform", "Specifies the platform to be used")]
                                  string platform = "linux",

                                  // [Option("language", "Specifies the preferred language for the page returned")]
                                  // string? language = null,
                                  [Option("update", "Updates the offline cache of pages")]
                                  bool update = false
                                  )
        {
            await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource);

            if (update || !Directory.Exists("tldr-cache"))
            {
                await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("Updating cache..."));

                try
                {
                    await UpdateCache();

                    await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("Cache updated"));
                }
                catch (Exception e)
                {
                    await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("Cache update failed"));

                    return;
                }
            }

            //language ??= ctx.Guild.PreferredLocale;

            page = page.ToLower();
            page = page.Replace(' ', '-');
            var path = FindPage(page, platform);

            if (path == null)
            {
                await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("page not found"));

                return;
            }

            var lines = await File.ReadAllLinesAsync(path);

            var builder = new DiscordWebhookBuilder();

            var resultPlatform = path.Split('/')[2];

            var embed = new DiscordEmbedBuilder()
                        .WithTitle($"tldr page: {lines.FirstOrDefault()?.Remove(0, 2)} ({resultPlatform})")
                        .WithAuthor("tldr pages", "https://tldr.sh/", "https://tldr.sh/assets/img/icon.png")
                        .WithColor(new DiscordColor("#54B59A"))
                        .WithDescription(string.Join("\n", lines.Skip(1)).Replace("\n\n", "\n"))
                        .WithFooter("tldr - collaborative cheatsheets for console commands ",
                                    "https://github.githubassets.com/images/icons/emoji/unicode/1f4da.png")
                        .Build();

            builder.AddEmbed(embed);

            if (resultPlatform != "common" && resultPlatform != platform)
            {
                var warningEmbed = new DiscordEmbedBuilder()
                                   .WithTitle("Platform: " + resultPlatform)
                                   .WithColor(DiscordColor.Red)
                                   .Build();
                builder.AddEmbed(warningEmbed);
            }

            await ctx.EditResponseAsync(builder);
        }