public static SearchResults FromGoogleCustomSearch(global::Google.Apis.Customsearch.v1.Data.Search gcsResults)
        {
            var request = gcsResults.Queries["request"][0];
            var results = new SearchResults(
                request.ExactTerms,
                gcsResults.Items.Count,
                int.Parse(gcsResults.SearchInformation.TotalResults),
                Convert.ToInt32(request.StartIndex.Value));

            var batchOrdinal = 0;
            var queryOrdinal = results.QueryStart;

            foreach (var gcsResult in gcsResults.Items)
            {
                var result = new SearchResult
                {
                    BatchOrdinal = batchOrdinal++,
                    QueryOrdinal = queryOrdinal++,
                    Url          = gcsResult.Link,
                    HtmlUrl      = gcsResult.HtmlFormattedUrl,
                    CacheUrl     = string.Format("http://webcache.googleusercontent.com/search?q=cache:{0}:{1}",
                                                 gcsResult.CacheId, gcsResult.Link),
                    Title       = gcsResult.Title,
                    HtmlTitle   = gcsResult.HtmlTitle,
                    Snippet     = gcsResult.Snippet,
                    HtmlSnippet = gcsResult.HtmlSnippet
                };

                results.Add(result);
            }

            return(results);
        }
示例#2
0
        public async Task <List <GoogleSearch> > SearchGoogle(string search)
        {
            try
            {
                using CustomsearchService googleService = new CustomsearchService(new BaseClientService.Initializer
                {
                    ApiKey          = Config.bot.Apis.ApiGoogleSearchKey,
                    ApplicationName = GetType().ToString()
                });

                CseResource.ListRequest searchRequest = googleService.Cse.List();
                searchRequest.Q  = search;
                searchRequest.Cx = Config.bot.Apis.GoogleSearchEngineId;

                global::Google.Apis.Customsearch.v1.Data.Search googleSearch = await searchRequest.ExecuteAsync();

                List <GoogleSearch> searches = googleSearch.Items
                                               .Select(result => new GoogleSearch(result.Title, result.Snippet, result.Link)).ToList();
                return(searches);
            }
            catch (Exception ex)
            {
                Logger.Error("An error occured while searching Google! {@Exception}", ex);
                return(null);
            }
        }