首页 > 解决方案 > C#。我将如何获取随机 ID,然后获取 largeImgURL

问题描述

我已经尝试了很多事情,但我的大脑现在无法正常工作,我不知道该怎么办了。我已经搜索了互联网,但我没有找到任何可以帮助我的东西。

如果您想要 JSON API 链接,我正在尝试使用 Hits.ID 获取随机搜索结果并从 Hit 获取大图像 URL,以便您可以更好地了解我正在尝试做什么。

搜索命令

[Command("search")]
        public async Task Search(CommandContext ctx, string args)
        {
            WebClient n = new WebClient();

            var json = n.DownloadString("https://pixabay.com/api/?key=###################&q=" + args + "&image_type=photo&pretty=true");
            var root = JsonConvert.DeserializeObject<Root>(json);

            var builder = new DiscordEmbedBuilder
            {
                Color = DiscordColor.Rose,
                Description = "Search Result",
            };

            foreach (Hit hit in root.hits)
            {
                builder.WithImageUrl(hit.largeImageURL);
            }
            await ctx.RespondAsync(embed: builder.Build());
        }

获取设置

        public class Hit
        {
            public string largeImageURL { get; set; }
            public int webformatHeight { get; set; }
            public int webformatWidth { get; set; }
            public int likes { get; set; }
            public int imageWidth { get; set; }
            public int id { get; set; }
            public int user_id { get; set; }
            public int views { get; set; }
            public int comments { get; set; }
            public string pageURL { get; set; }
            public int imageHeight { get; set; }
            public string webformatURL { get; set; }
            public string type { get; set; }
            public int previewHeight { get; set; }
            public string tags { get; set; }
            public int downloads { get; set; }
            public string user { get; set; }
            public int favorites { get; set; }
            public int imageSize { get; set; }
            public int previewWidth { get; set; }
            public string userImageURL { get; set; }
            public string previewURL { get; set; }
        }

        public class Root
        {
            public int totalHits { get; set; }
            public List<Hit> hits { get; set; }
            public int total { get; set; }
        }

标签: c#jsondiscord

解决方案


要从命中列表中获得随机命中,您可以使用 Linq 来获得这样的结果。

Hit randomHit = root.hits.ElementAt(new Random().Next(x.Count));
var randomUrl = randomHit.largeImageURL;

ElementAt为您提供特定索引处的元素。使用 0 和该列表中的总命中数之间的随机数,您可以获得随机命中。一旦你有了它,你就可以得到那个对象的 userImageUrl。


推荐阅读