示例#1
0
        public async Task <WikiSummary> GetSummaryAsync(string title)
        {
            using HttpClient http = _http.CreateClient();
            string result = await http.GetStringAsync($"{ApiUrl}&list=&prop=extracts&explaintext&exsentences=3&exintro=&titles={title}&format=json").ConfigureAwait(false);

            var summary = new WikiSummary();

            using (JsonDocument json = JsonDocument.Parse(result))
            {
                JsonElement  element = json.RootElement.GetProperty("query").GetProperty("pages");
                JsonProperty page    = element.EnumerateObject().First();
                summary.Title   = page.Value.GetProperty("title").GetString();
                summary.Extract = page.Value.GetProperty("extract").GetString();
            }

            string imageResult = await http.GetStringAsync($"{ApiUrl}&titles={title}&prop=pageimages&pithumbsize=500&format=json").ConfigureAwait(false);

            using (JsonDocument json = JsonDocument.Parse(imageResult))
            {
                JsonElement  element = json.RootElement.GetProperty("query").GetProperty("pages");
                JsonProperty page    = element.EnumerateObject().First();
                if (page.Value.TryGetProperty("thumbnail", out JsonElement thumbnail))
                {
                    summary.ImageUrl = thumbnail.GetProperty("source").GetString();
                }
            }

            return(summary);
        }
示例#2
0
文件: Searches.cs 项目: snoww/roki
        public async Task Wikipedia([Leftover] string args)
        {
            string[] argsSplit    = args.Split(' ');
            var      queryBuilder = new StringBuilder();
            var      showResults  = false;

            foreach (string str in argsSplit)
            {
                if (!showResults && str.Equals("-q", StringComparison.OrdinalIgnoreCase))
                {
                    showResults = true;
                    continue;
                }

                queryBuilder.Append(str + " ");
            }

            string query = queryBuilder.ToString().Trim();

            using IDisposable typing = Context.Channel.EnterTypingState();
            // maybe in future only get 1 article if -q not provided
            List <WikiSearch> results = await Service.SearchAsync(query).ConfigureAwait(false);

            if (results == null || results.Count == 0)
            {
                await Context.Channel.SendErrorAsync($"Cannot find any results for: `{query}`").ConfigureAwait(false);

                return;
            }

            if (string.IsNullOrWhiteSpace(results[0].Snippet))
            {
                await Context.Channel.SendErrorAsync($"Cannot find any results for: `{query}`, did you mean `{results[0].Title}`?");

                return;
            }

            if (!showResults)
            {
                WikiSummary article = await Service.GetSummaryAsync(results[0].Title).ConfigureAwait(false);
                await SendArticleAsync(article).ConfigureAwait(false);

                return;
            }

            var          counter = 1;
            EmbedBuilder embed   = new EmbedBuilder().WithDynamicColor(Context)
                                   .WithAuthor("Wikipedia", WikipediaIconUrl)
                                   .WithTitle($"Search results for: `{query}`")
                                   .WithDescription(string.Join("\n", results
                                                                .Select(a => $"{counter++}. [{a.Title}]({WikipediaUrl}/{HttpUtility.UrlPathEncode(a.Title)})\n\t{a.Snippet}")));

            await Context.Channel.EmbedAsync(embed).ConfigureAwait(false);

            // for future allow selecting article and showing it
        }
示例#3
0
文件: Searches.cs 项目: snoww/roki
        private async Task SendArticleAsync(WikiSummary article)
        {
            EmbedBuilder embed = new EmbedBuilder().WithDynamicColor(Context)
                                 .WithAuthor("Wikipedia", WikipediaIconUrl)
                                 .WithTitle(article.Title)
                                 .WithUrl($"{WikipediaUrl}/{HttpUtility.UrlPathEncode(article.Title)}")
                                 .WithDescription(article.Extract);

            if (!string.IsNullOrWhiteSpace(article.ImageUrl))
            {
                embed.WithImageUrl(article.ImageUrl);
            }

            await Context.Channel.EmbedAsync(embed).ConfigureAwait(false);
        }