public List<String> Search(String query, int pages=1) { BaseClientService.Initializer init = new Google.Apis.Services.BaseClientService.Initializer(); init.ApiKey = key; CustomsearchService svc = new CustomsearchService(init); List<String> imageUrls = new List<String>(); for (int p = 1; p <= pages; p++) { CseResource.ListRequest listRequest = svc.Cse.List(query); listRequest.Cx = customEngine; listRequest.SearchType = CseResource.SearchType.Image; listRequest.Start = p*10; listRequest.ImgColorType = CseResource.ImgColorType.Color; Search search = listRequest.Fetch(); //Let's just get the thumbnail images if (search.Items != null) { foreach (Result result in search.Items) { imageUrls.Add(result.Image.ThumbnailLink); } } } return imageUrls; }
public List <SOPage> GoogleStackoverflowSearch(string query) { const string apiKey = "AIzaSyA04T2CMJSaGS9AWl66v43rzZTi7z4iKJw"; const string searchEngineId = "015600743573451307836:fzhqm3defkg"; CustomsearchService customSearchService = new CustomsearchService(new Google.Apis.Services.BaseClientService.Initializer() { ApiKey = apiKey }); Google.Apis.Customsearch.v1.CseResource.ListRequest listRequest = customSearchService.Cse.List(query); listRequest.Cx = searchEngineId; Search search = listRequest.Execute(); List <SOPage> results = new List <SOPage>(); if (search?.Items?.Count > 0) { foreach (var item in search.Items) { results.Add(new SOPage { Title = item.Title, URL = item.Link }); } } return(results); }
// // GET: /GoogleSearch/ public ActionResult SearchPost() { var apiKey = "AIzaSyAeyUzivp1tuMpDp_6cnVXb8DWVb1i9rJQ"; var searchEngineId = "000444561497760690246:j6o8r-ulmmm"; var query = "testing"; var customSearchService = new CustomsearchService(new BaseClientService.Initializer { ApiKey = apiKey }); var listRequest = customSearchService.Cse.List(query); listRequest.Cx = searchEngineId; IList <Result> paging = new List <Result>(); var count = 0; while (paging != null) { listRequest.Start = count * 10 + 1; paging = listRequest.Execute().Items; if (paging != null) { foreach (var item in paging) { Console.WriteLine("Title : " + item.Title + Environment.NewLine + "Link : " + item.Link + Environment.NewLine + Environment.NewLine); } } count++; } return(View(paging)); }
public async Task ProcessMessage(Message message) { if (_chatSettingsBotData.ActiveCommand != ActiveCommand.YouTubeSearch) { var inlineKeyboard = new InlineKeyboardMarkup(new[] { new[] { InlineKeyboardButton.WithCallbackData("Dancing!", "Dancing"), InlineKeyboardButton.WithCallbackData("Cats in space", "Cats in space"), InlineKeyboardButton.WithCallbackData("Tame Impala", "Tame Impala") } }); _chatSettingsBotData.ActiveCommand = ActiveCommand.YouTubeSearch; await _botService.Client.SendTextMessageAsync(message.Chat.Id, "Choose from list ot try to search something funny: ", replyMarkup : inlineKeyboard); return; } var svc = new CustomsearchService(new BaseClientService.Initializer { ApiKey = BotConstants.YouTubeSearch.ApiKey }); var listRequest = svc.Cse.List(); listRequest.Q = message.Text; listRequest.Cx = BotConstants.YouTubeSearch.CxKey; var search = await listRequest.ExecuteAsync(); var keyboard = KeyboardBuilder.CreateExitButton(); if (search.Items == null || search.Items.Count == 0) { await _botService.Client.SendTextMessageAsync(message.Chat.Id, "No videos:( Try again: ", replyMarkup : keyboard); return; } var numberOfVideos = 3; for (var i = 0; i < Math.Min(search.Items.Count, numberOfVideos); i++) { if (i == Math.Min(search.Items.Count, numberOfVideos) - 1) { await _botService.Client.SendTextMessageAsync(message.Chat.Id, search.Items[i].Link, replyMarkup : keyboard); break; } await _botService.Client.SendTextMessageAsync(message.Chat.Id, search.Items[i].Link); } _chatSettingsBotData.ActiveCommand = ActiveCommand.Default; }
private void Search_Button_Click(object sender, RoutedEventArgs e) { // Set up the custom search service then execute the query string apiKey = "AIzaSyC9XZlQmVl7c5N-lGnm9YlTlFZkxTjKiRI"; string context = "47c96d1ee9214d539"; var customSearchService = new CustomsearchService(new BaseClientService.Initializer { ApiKey = apiKey }); string query = ComposeQuery(); var listRequest = customSearchService.Cse.List(); listRequest.Cx = context; listRequest.Q = query; listRequest.Num = 10; listRequest.SearchType = CseResource.ListRequest.SearchTypeEnum.Image; listRequest.Safe = CseResource.ListRequest.SafeEnum.Active; var result = listRequest.Execute().Items?.ToList(); //Add the image URLs to a list foreach (var item in result) { this.urls.Add(item.Link.ToString()); } // Fire off a search results window. Made this choice to make searching more deliberate, the Google CSE API is pretty restrictive, about 100 requests/day // Making a box that would autoupdate as the user typed would use that rate up pretty quickly. SearchResultsWindow searchResultsWindow = new SearchResultsWindow(this.urls, ref currentSlideInfo); searchResultsWindow.Show(); }
public IList <string> Do(string term) { var customSearchService = new CustomsearchService(new BaseClientService.Initializer { ApiKey = apiKey }); var listRequest = customSearchService.Cse.List(term); listRequest.Cx = searchEngineId; var result = new List <string>(); IList <Result> paging = new List <Result>(); var count = 0; while (paging != null) { listRequest.Start = count * 10 + 1; paging = listRequest.Execute().Items; if (paging != null) { foreach (var item in paging) { result.Add(item.FormattedUrl); } } count++; } return(result); }
//-----Search engine for getting images (This is not implemented yet but is working and pulling images)-----// public static void SearchForRecipeImages() { MainViewModel mainView = new MainViewModel(); const string apiKey = "AIzaSyDaIJFcnkDTl2IXy-jxazUmtWFjxMGiwzA"; const string searchEngineId = "003934496790675996198:prnegsihbvm"; Query += "Meals with "; foreach (var item in MainViewModel.IngredientslList) { Query += $"{item.IngredientsEntered},"; } var customSearchService = new CustomsearchService(new BaseClientService.Initializer { ApiKey = apiKey }); var listRequest = customSearchService.Cse.List(Query); listRequest.Cx = searchEngineId; //-----This line makes the search and image search-----// listRequest.SearchType = CseResource.ListRequest.SearchTypeEnum.Image; RecipePageViewModel.PagingImages = listRequest.Execute().Items; Query = ""; }
public async Task FetchImagesFromGoogle(Post post) { using (var searchService = new CustomsearchService(new Google.Apis.Services.BaseClientService.Initializer { ApiKey = _apiKey })) { var listRequest = searchService.Cse.List(post.Keyword); listRequest.Cx = _searchEngineId; listRequest.SearchType = (int)SearchTypeEnum.Image; listRequest.Num = 5; listRequest.ImgSize = CseResource.ListRequest.ImgSizeEnum.Xxlarge; var search = listRequest.Execute(); foreach (var image in search.Items.Take(post.MaxNumberImages).ToList()) { if (image.Mime == "image/jpeg") { post.Images.Add(new Image() { Width = (int)image.Image.Width, Height = (int)image.Image.Height, URI = image.Link }); } } } }
private static string GetRandomCatPicture() { var queryParams = new Dictionary <string, string> { ["key"] = GoogleApiKey, ["cx"] = GoogleSearchEngineId, ["q"] = "kittens", ["searchType"] = "image" }; var service = new CustomsearchService(new BaseClientService.Initializer { ApiKey = GoogleApiKey, ApplicationName = "SelfCareBot" }); CseResource.ListRequest listRequest = service.Cse.List("kittens"); listRequest.Cx = GoogleSearchEngineId; listRequest.SearchType = CseResource.ListRequest.SearchTypeEnum.Image; var search = listRequest.Execute(); var randomIndex = Rng.Next(0, search.Items.Count - 1); var randomItem = search.Items[randomIndex]; return(randomItem.Link); }
public ActionResult Search(string q) { const string apiKey = "AIzaSyClPcof_cL9nwRWDCgbCntJA5t1PPEwWzY"; const string cx = "012086554440813063826:svstp_wt1ea"; var model = new SearchModel { Query = q }; if (!String.IsNullOrWhiteSpace(q)) { try { var svc = new CustomsearchService(new BaseClientService.Initializer { ApiKey = apiKey }); var listRequest = svc.Cse.List(q); listRequest.Cx = cx; model.Results = listRequest.Execute(); } catch (Exception ex) { Global.Logger.Error("Error in custom search for q='" + q + "'", ex); } } return(View(model)); }
/// <summary> /// Returns metadata about the search performed, metadata about the custom search engine used for the search, and the search results. /// Documentation https://developers.google.com/customsearch/v1/reference/cse/list /// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong. /// </summary> /// <param name="service">Authenticated Customsearch service.</param> /// <param name="q">Query</param> /// <param name="optional">Optional paramaters.</param> /// <returns>SearchResponse</returns> public static Search List(CustomsearchService service, string q, CseListOptionalParms optional = null) { try { // Initial validation. if (service == null) { throw new ArgumentNullException("service"); } if (q == null) { throw new ArgumentNullException(q); } // Building the initial request. var request = service.Cse.List(q); // Applying optional parameters to the request. request = (CseResource.ListRequest)SampleHelpers.ApplyOptionalParms(request, optional); // Requesting data. return(request.Execute()); } catch (Exception ex) { throw new Exception("Request Cse.List failed.", ex); } }
public List <String> Search(String query, int pages = 1) { BaseClientService.Initializer init = new Google.Apis.Services.BaseClientService.Initializer(); init.ApiKey = key; CustomsearchService svc = new CustomsearchService(init); List <String> imageUrls = new List <String>(); for (int p = 1; p <= pages; p++) { CseResource.ListRequest listRequest = svc.Cse.List(query); listRequest.Cx = customEngine; listRequest.SearchType = CseResource.SearchType.Image; listRequest.Start = p * 10; listRequest.ImgColorType = CseResource.ImgColorType.Color; Search search = listRequest.Fetch(); //Let's just get the thumbnail images if (search.Items != null) { foreach (Result result in search.Items) { imageUrls.Add(result.Image.ThumbnailLink); } } } return(imageUrls); }
/// <summary> /// Searches Google /// </summary> /// <param name="search"></param> /// <param name="appName"></param> /// <returns></returns> public static Search Search(string search, string appName) { try { if (string.IsNullOrWhiteSpace(Config.bot.Apis.ApiGoogleSearchKey) || string.IsNullOrWhiteSpace(Config.bot.Apis.GoogleSearchEngineId)) { return(null); } Search googleSearch; using (CustomsearchService google = new CustomsearchService(new BaseClientService.Initializer { ApiKey = Config.bot.Apis.ApiGoogleSearchKey, ApplicationName = appName })) { CseResource.ListRequest searchListRequest = google.Cse.List(); searchListRequest.Q = search; searchListRequest.Cx = Config.bot.Apis.GoogleSearchEngineId; googleSearch = searchListRequest.Execute(); } return(googleSearch); } catch { return(null); } }
public async Task google(params string[] str) { string query = string.Join(" ", str.Skip(0)); string apiKey = "AIzaSyAi4_XbS4euGFf7LJYH9jLdERF92PRELE0"; string cx = "006365420480420697386:a5kksrll-pc"; var search = new CustomsearchService(new BaseClientService.Initializer { ApiKey = apiKey }); var listRequest = search.Cse.List(); listRequest.Q = query; listRequest.Cx = cx; var results = listRequest.Execute(); string result = ""; foreach (var res in results.Items) { string title = string.Format("`{0}`", res.Title); string link = string.Format("<{0}>", res.Link); result += (title + " " + link + "\n"); } var embed = new EmbedBuilder() .WithAuthor(a => a .WithName("Google") .WithIconUrl("https://maxcdn.icons8.com/Share/icon/Logos//google_logo1600.png")) .WithTitle($"Search Results for: {query}") .WithUrl($"https://www.google.com/search?q={WebUtility.UrlEncode(query)}") .WithTimestamp(DateTimeOffset.UtcNow) .WithDescription($"Showing top 10 Google results for **{query}**\n" + result) .WithColor(new Discord.Color(90, 218, 85)); await ReplyAsync("Fetching results ", false, embed.Build()); await ReplyAsync(string.Format($"First result: `{results.Items.First().Title}` {results.Items.First().Link}")); }
public bool Init() { svc = new CustomsearchService(new BaseClientService.Initializer { ApiKey = apikey }); return(true); }
/// <summary> /// This returns a URL for an image. /// This uses Google and will return the first image result from a search term. /// </summary> /// <param name="searchTerms"></param> /// <returns></returns> public static string DownloadImage(string searchTerms) { // This is my private API key string apiKey = "AIzaSyAD5OsjTu6d-8xwOEkewvgA0JtNecMfoNo"; // Google Images Engine ID string searchEngineId = "008801159646905401147:nqod7kqw_kc"; // C# Library provided by Google to handle search commands CustomsearchService customSearchService = new CustomsearchService(new Google.Apis.Services.BaseClientService.Initializer { ApiKey = apiKey }); // Request a list of search results Google.Apis.Customsearch.v1.CseResource.ListRequest listRequest = customSearchService.Cse.List(searchTerms); // Assign vars for the search listRequest.Cx = searchEngineId; listRequest.SearchType = CseResource.ListRequest.SearchTypeEnum.Image; listRequest.Num = 1; listRequest.Start = 1; // Execute the search Search search = listRequest.Execute(); // Validate quantity of search results if (search.Items.Count == 0) { return(string.Empty); } // Return the very first image found (URL to) return(search.Items[0].Link); }
public List <SearchResult> getResults(String query, int itemsPerPage, int page) { const string apiKey = "AIzaSyCbwi1U_KFwou26QLz1 - K8P5y0pJRwQm30"; const string searchEngineId = "006347468050510818806:bdoeuah7j4m"; CustomsearchService service = new CustomsearchService(new BaseClientService.Initializer { ApiKey = apiKey }); ListRequest request = service.Cse.List(query); request.Cx = searchEngineId; request.Num = itemsPerPage; request.Start = itemsPerPage * page; List <SearchResult> results = new List <SearchResult>(); foreach (var item in request.Execute().Items) { results.Add( new SearchResult { Title = item.Title, Link = item.Link } ); } return(results); }
public CustomSearchService(IOptions <CustomSearchOptions> options) { _options = options.Value; _innerService = new CustomsearchService(new BaseClientService.Initializer { ApiKey = _options.ApiKey }); }
// TODO: Move apiKey to database public virtual async Task SetupAsync(string apiKey) { try { _baseClientService = new BaseClientService.Initializer() { ApplicationName = "Ditto", ApiKey = apiKey }; _urlShortenerService = new UrlshortenerService(_baseClientService); _customSearchService = new CustomsearchService(_baseClientService); await Youtube.SetupAsync(_baseClientService); // Test method var test = await Youtube.GetPlaylistNameAsync("0"); } catch (Exception ex) { if (ex is GoogleApiException) { throw ex; } } }
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); } }
//Get Google Results public object GetGoogleResults(string Keyword) { var customSearchGet = new CustomsearchService(new Google.Apis.Services.BaseClientService.Initializer { ApiKey = _api }); string query = Keyword; var listRequest = customSearchGet.Cse.List(query); listRequest.Cx = _searchEngineId; IList <Google.Apis.Customsearch.v1.Data.Result> Results = new List <Google.Apis.Customsearch.v1.Data.Result>(); byte count = 0; try { while (Results != null) { listRequest.Start = count * 10 + 1; Results = listRequest.Execute().Items; if (Results != null) { foreach (var item in Results) { _urls.Add(item.Link); } } count++; } return(_urls); } catch (Exception ex) { return(ex); } }
public CustomSearch(string key, string cx) { _cx = cx; _cse = new CustomsearchService { Key = key }; }
public Search getFirstMovie(string movieTitle) { try { keys(); query = movieTitle; CustomsearchService customSearchService = new CustomsearchService(new Google.Apis.Services.BaseClientService.Initializer() { ApiKey = apiKey }); Google.Apis.Customsearch.v1.CseResource.ListRequest listRequest = customSearchService.Cse.List(query); listRequest.Cx = searchEngineId; Search search = listRequest.Execute(); foreach (var item in search.Items) { Console.WriteLine("Title : " + item.Title + Environment.NewLine + "Link : " + item.Link + Environment.NewLine + Environment.NewLine); } Console.ReadLine(); return(search); } catch (Exception er) { Console.WriteLine("Error message: " + er.ToString()); throw; } }
public SearchBE Search(string query) { SearchBE r = new SearchBE(); try { string apiKey = AppSettingsHelper.GetValue("GoogleAPIKey"); string searchEngineID = AppSettingsHelper.GetValue("GoogleSearchEngineID"); CustomsearchService service = new CustomsearchService(new BaseClientService.Initializer { ApiKey = apiKey }); CseResource.ListRequest rq = service.Cse.List(query); rq.Cx = searchEngineID; Search search = rq.Execute(); if (search != null) { r.SearchEngine = "Google"; r.Query = query; r.TotalResult = search.SearchInformation.TotalResults; r.FormatTotalResult = search.SearchInformation.FormattedTotalResults; r.Time = search.SearchInformation.SearchTime; } } catch (Exception e) { r.SearchEngine = "Google"; r.Query = query + e.Message; r.TotalResult = 0; r.Time = 0; } return(r); }
private void Search(CustomsearchService searchservice, string term, int n_searches, /*out*/ List <Double_Links> imageUrls) { ListRequest listRequest = searchservice.Cse.List(); // listRequest.CreateRequest(); listRequest.Cx = "ca0ca9bbd59600922"; listRequest.SearchType = ListRequest.SearchTypeEnum.Image; listRequest.ImgColorType = ListRequest.ImgColorTypeEnum.ImgColorTypeUndefined; if (term == "") { return; } listRequest.Q = term; listRequest.Num = n_searches; var search = listRequest.Execute(); if (search.Items == null) { return; } foreach (Result result in search.Items) { imageUrls.Add(new Double_Links { thumbnail = result.Image.ThumbnailLink, picture = result.Link }); } }
public void Initialize(string apiKey) { _customsearch = new CustomsearchService(new BaseClientService.Initializer { ApiKey = apiKey }); }
public async Task SearchImgAsync([Remainder] string search) { var customSearchService = new CustomsearchService(new BaseClientService.Initializer { ApiKey = SerenityCredentials.GoogleAPIKey() }); var listRequest = customSearchService.Cse.List(search); Random rnd = new Random(); listRequest.Cx = SerenityCredentials.CustomSearchEngineKey(); //Restricting the search to only images listRequest.SearchType = CseResource.ListRequest.SearchTypeEnum.Image; //The results will be put inside this list IList <Result> paging = new List <Result>(); //Begins the search paging = listRequest.Execute().Items; int index = 0; var embedImg = new EmbedBuilder() .WithColor(new Color(240, 230, 231)) .WithAuthor(eab => eab.WithName(search)) .WithDescription(paging.ElementAt(index).Link) .WithImageUrl(paging.ElementAt(index).Link); await Context.Channel.SendMessageAsync("", false, embedImg); }
public ThingsToDo(string c) { customSearchService = new CustomsearchService(new BaseClientService.Initializer { ApiKey = APIKey }); ciudad = c; locationsToVisit = Enumerable.Empty <HtmlNode>(); }
public GoogleEngineApi(string apiKey, string searchEngineId) { _apiKey = apiKey; _searchEngineId = searchEngineId; _customSearchService = new CustomsearchService(new BaseClientService.Initializer { ApiKey = apiKey }); }
public GoogleWebSearch(string apiKey, string cx) { _cx = cx; _customsearchService = new CustomsearchService(new BaseClientService.Initializer() { ApiKey = apiKey }); }
public Grabber(string apiKey, string searchEngineId) { customSearchService = new CustomsearchService(new Google.Apis.Services.BaseClientService.Initializer() { ApiKey = apiKey }); this.searchEngineId = searchEngineId; }
// // GET: /Main/ public MainController() { this.googleApiKey = "AIzaSyC66KeMa7sfsdwC6mJWcHT4yiWNHzLdzOc"; this.googleSearchEngineId = "004492732884117081044:th2qqajcg0c"; this.rssApi = "https://news.google.com/news/feeds?q="; this.googleService = new Google.Apis.Customsearch.v1.CustomsearchService( new BaseClientService.Initializer { ApiKey = this.googleApiKey }); this.flickr = new Flickr("1a5ca7d9ee95091bd1249fabd254b5ae", "f7e6199868b71ffa"); }
public Search googleImageSearch(string apiKey, string searchEngineId, string query, uint start) { CustomsearchService customSearchService = new CustomsearchService(new BaseClientService.Initializer() { ApiKey = apiKey }); CseResource.ListRequest listRequest = customSearchService.Cse.List(query); listRequest.Cx = searchEngineId; listRequest.FileType = "jpg"; listRequest.Start = start; listRequest.ImgSize = CseResource.ListRequest.ImgSizeEnum.Xlarge; listRequest.SearchType = CseResource.ListRequest.SearchTypeEnum.Image; listRequest.Filter = CseResource.ListRequest.FilterEnum.Value1; Search search = listRequest.Execute(); return search; }
private static async Task<string> SearchGoogle(string query) { string apiKey = ConfigurationManager.AppSettings["GOOGLE_SEARCH_API_KEY"]; string searchEngineId = ConfigurationManager.AppSettings["GOOGLE_SEARCH_ENGINE_ID"]; using (var searchService = new CustomsearchService(new Google.Apis.Services.BaseClientService.Initializer { ApiKey = apiKey })) { var listRequest = searchService.Cse.List(query); listRequest.Cx = searchEngineId; var search = await listRequest.ExecuteAsync(); return search.Items?.First().Link; } }
private static void Main(string[] args) { //// Search 32 results of keyword : "Google APIs for .NET" //GwebSearchClient client = new GwebSearchClient(/* Enter the URL of your site here */); //IList<IWebResult> results = client.Search("Google API for .NET", 32); //foreach (IWebResult result in results) //{ // Console.WriteLine("[{0}] {1} => {2}", result.Title, result.Content, result.Url); //} //WebQuery query = new WebQuery("Insert query here"); //query.StartIndex.Value = 2; //query.HostLangauge.Value = Languages.English; //IGoogleResultSet<GoogleWebResult> resultSet = GoogleService.Instance.Search<GoogleWebResult>(query); //const string apiKey = "YOUR_API_KEY"; //const string searchEngineId = "010297209645085268115:tvi4k-bftis"; //const string query = "'sky is blue'"; //CustomsearchService customSearchService = // new CustomsearchService(new Google.Apis.Services.BaseClientService.Initializer() { ApiKey = apiKey }); //Google.Apis.Customsearch.v1.CseResource.ListRequest listRequest = customSearchService.Cse.List(query); //listRequest.Cx = searchEngineId; //Search search = listRequest.Execute(); //foreach (var item in search.Items) //{ // Console.WriteLine("Title : " + item.Title + Environment.NewLine + "Link : " + item.Link + // Environment.NewLine + "Description: " + item.Snippet + Environment.NewLine); //} //Console.ReadLine(); const string apiKey = "YOUR_API_KEY"; const string searchEngineId = "003470263288780838160:ty47piyybua"; const string query = "sky is blue"; CustomsearchService customSearchService = new CustomsearchService(new Google.Apis.Services.BaseClientService.Initializer() { ApiKey = apiKey }); Google.Apis.Customsearch.v1.CseResource.ListRequest listRequest = customSearchService.Cse.List(query); listRequest.Cx = searchEngineId; Search search = listRequest.Execute(); foreach (var item in search.Items) { Console.WriteLine("Title : " + item.Title + Environment.NewLine + "Link : " + item.Link + Environment.NewLine + item.Snippet + Environment.NewLine); } Console.ReadLine(); }
public static void GoogleString(Message triggerMessage) { var searchTerms = CommandFactory.GetParameters(triggerMessage.RawText); var searchString = string.Join(" ", searchTerms); const string apiKey = "AIzaSyC1KAPCB759-e4nMRS2dOxm0keFUdGWyY8"; const string searchEngineId = "008509564598163386467:l2hjjt0senw"; string query = searchString; CustomsearchService customSearchService = new CustomsearchService(new Google.Apis.Services.BaseClientService.Initializer() { ApiKey = apiKey }); CseResource.ListRequest listRequest = customSearchService.Cse.List(query); listRequest.Cx = searchEngineId; Search search = listRequest.Execute(); triggerMessage.Channel.SendMessage($"Here's what I found about \"{searchString}\": \n\n*{search.Items.First().Snippet}* \n\nFor more see: {search.Items.First().Link}"); triggerMessage.Channel.SendMessage($"Not what you were looking for? https://www.google.com/search?q={string.Join("+", searchTerms)}"); }
private IEnumerable<string> GetUrls(string topicOrHtml) { #if _USE_GOOGLE_API var cs = new CustomsearchService(new BaseClientService.Initializer() {ApiKey = api_key, ApplicationName = "SelfBeautifyingPainting" }); var listRequest = cs.Cse.List(topicOrHtml); listRequest.Cx = cx; //listRequest.SearchType = CseResource.ListRequest.SearchTypeEnum.Image; //listRequest.ExactTerms = topic; listRequest.Key = api_key; listRequest.Googlehost = "https://www.google.com"; listRequest.ImgColorType=CseResource.ListRequest.ImgColorTypeEnum.Color; listRequest.FileType = "jpg"; var search = listRequest.Execute(); foreach (var result in search.Items) { yield return result.Image.ContextLink; } #else var urls = new List<string>(); var ndx = topicOrHtml.IndexOf("class=\"images_table\"", StringComparison.Ordinal); ndx = topicOrHtml.IndexOf("<img", ndx, StringComparison.Ordinal); while (ndx >= 0) { ndx = topicOrHtml.IndexOf("src=\"", ndx, StringComparison.Ordinal); ndx = ndx + 5; var ndx2 = topicOrHtml.IndexOf("\"", ndx, StringComparison.Ordinal); var url = topicOrHtml.Substring(ndx, ndx2 - ndx); urls.Add(url); ndx = topicOrHtml.IndexOf("<img", ndx, StringComparison.Ordinal); } return urls; #endif }
/* This service method calls the google API to discover WSDL services */ public string[] DiscoverWsdlServices(string keywords) { int i = 0; /* The keyword WSDL is appended to the provided search query */ /* to ensure that returned results are more in-line with */ /* the requirement, i.e. WSDL services. */ string query = keywords + " WSDL"; /* Create an array of URLs to be returned */ string[] urls = new string[MAX_SEARCH_COUNT * MAX_PAGES_PER_SEARCH]; /* Create a custom search service object and set the API key */ CustomsearchService customSearchService = new CustomsearchService( new Google.Apis.Services.BaseClientService.Initializer() { ApiKey = GOOGLE_API_KEY }); /* Create a list request object to perform the search */ CseResource.ListRequest listRequest = customSearchService.Cse.List(query); /* Set the search engine ID */ listRequest.Cx = GOOGLE_SEARCH_ENGINE_ID; /* This loop varies the start index and repeatedly performs the search */ for (int k = 1; k < (MAX_SEARCH_COUNT * MAX_PAGES_PER_SEARCH); k += MAX_PAGES_PER_SEARCH) { /* Setting the start index */ listRequest.Start = k; /* Perform the search. Along with the query to search for, the WSDL search */ /* would need certain URL patterns to look for. These URL patterns such as */ /* "*.wsdl", "*.svc?wsdl", "*.asmx?wsdl" and "*.php?wsdl" are programmed */ /* into the search engine while creating it using the google's custom */ /* search engine control panel. The search engine ID helps recognize the */ /* custom search engine that has been created. */ Search search = listRequest.Execute(); /* If the search returns no results, break. There's no */ /* point in searching more. */ if (search.Items == null) continue; /* Traverse the search result list and copy links that match WSDL type URLs */ /* into an array of strings to be returned */ foreach (var item in search.Items) { #if FILTER if (item.Link.EndsWith(".wsdl") || item.Link.EndsWith(".svc?wsdl") || item.Link.EndsWith(".asmx?wsdl") || item.Link.EndsWith(".php?wsdl")) #endif { urls[i++] = item.Title + URL_TITLE_LINK_SEPARATOR + item.Link; } } } return urls; }
private void performSearch() { //Clears the content of each existing PictureBox this.Clear(); //Temporarily disable the search button pbSearch.Enabled = false; //Storing the search text entered by the user searchText = txtSearchTerm.Text; //Displaying the current page number lblPage.Text = "Page " + Convert.ToInt32(pageNumber + 1); //Initialising both lists thumbnailImages = new List<string>(); fullImages = new List<string>(); //Defining a new Google Custom Search service using the specific API Key CustomsearchService customSearchService = new CustomsearchService(new Google.Apis.Services.BaseClientService.Initializer() { ApiKey = apiKey }); //Providing the search text to the custom search service CseResource.ListRequest listRequest = customSearchService.Cse.List(txtSearchTerm.Text); //Associating the list request to the Google Custom Search Engine ID listRequest.Cx = searchEngineId; //Specifying that the search will be an image search listRequest.SearchType = CseResource.ListRequest.SearchTypeEnum.Image; //Determining the start position of the search listRequest.Start = (pageNumber * 10) + 1; //Each search will return a maximum of 10 images (Google Custom Search API limit) listRequest.Num = 10; try { //Attempt to perform the search Search search = listRequest.Execute(); //If any search results are returned if (search.Items != null) { lblNoImages.Visible = false; //Adding the image URLs for both thumbnail and full versions of the image foreach (var item in search.Items) { thumbnailImages.Add(item.Image.ThumbnailLink); fullImages.Add(item.Link); } //Calculating the number of selected images (all images are already selected by default) selectedImages = thumbnailImages.Count; if (thumbnailImages.Count > 0) { //The starting x and y coordinates to draw the first PictureBox int xPos = 50; int yPos = 90; pbSave.Enabled = true; //Initialising the thumbnail PictureBox array thumbImgArray = new PictureBox[thumbnailImages.Count]; //Initialising the Boolean array imageSelected = new Boolean[thumbnailImages.Count]; for (int i = 0; i < thumbnailImages.Count; i++) { imageSelected[i] = true; thumbImgArray[i] = new PictureBox(); //Load the PictureBox with the image having the specified thumbnail image URL thumbImgArray[i].Load(thumbnailImages[i]); //Set the starting position to draw the current PictureBox if (xPos > 1000) { xPos = 50; yPos = yPos + 208; } //Set the properties of the current PictureBox, including width, height, background colour and mouse click events thumbImgArray[i].Left = xPos; thumbImgArray[i].Top = yPos; thumbImgArray[i].Width = 200; thumbImgArray[i].Height = 200; thumbImgArray[i].Visible = true; thumbImgArray[i].BorderStyle = BorderStyle.None; thumbImgArray[i].BackColor = System.Drawing.Color.Green; thumbImgArray[i].Padding = new System.Windows.Forms.Padding(3); thumbImgArray[i].SizeMode = PictureBoxSizeMode.StretchImage; thumbImgArray[i].Tag = i; thumbImgArray[i].MouseDown += new MouseEventHandler(thumbnail_MouseDown); thumbImgArray[i].DoubleClick += new EventHandler(thumbnail_DoubleClick); //Add the PictureBox to the Form controls this.Controls.Add(thumbImgArray[i]); //Sets the x-coordinate for the next PictureBox xPos = xPos + 208; //Processes all Windows messages currently in the message queue. Application.DoEvents(); } pbPrevious.Visible = false; lblPage.Visible = true; pbSave.Visible = true; pbNext.Visible = true; //Re-enable the search button pbSearch.Enabled = true; //Checks the number of thumbnail images to determine whether the 'Next' PictureBox button should show or not if (10 % thumbnailImages.Count != 0) pbNext.Visible = false; else pbNext.Visible = true; } } //No results found - the user is informed accordingly and the main PictureBox buttons are hidden else { lblNoImages.Visible = true; pbPrevious.Visible = false; pbNext.Visible = false; lblPage.Visible = false; pbSave.Visible = false; } } catch (Google.GoogleApiException) { //The user is informed accordingly if a Google API exception is thrown lblNoImages.Text = "Google Custom Search API Issue"; lblNoImages.Visible = true; } }