using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net.Http; using System.Xml; namespace GoogleRandomSuggestions { static class GoogleSuggestions { private const string url = "http://google.com/complete/search?q={0}&output=toolbar"; static HttpClient http; static GoogleSuggestions() { http = new HttpClient(); } public static IEnumerable GetSuggestions(string search) { string xml = http.GetAsync(String.Format(url, Uri.EscapeUriString(search))).Result.Content.ReadAsStringAsync().Result; XmlDocument xdoc = new XmlDocument(); bool stop = false; int attemptsLeft = 10; List suggestions = new List(); while (!stop) { try { xdoc.LoadXml(xml); foreach (XmlNode node in xdoc.DocumentElement.ChildNodes) { XmlNode suggestion = node.ChildNodes[0]; suggestions.Add(suggestion.Attributes["data"].Value); } stop = true; } catch (XmlException ex) { if (xml.Contains("automated")) { attemptsLeft--; if (attemptsLeft == 0) stop = true; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(String.Format("Automated query error - {0} attempts remaining", attemptsLeft)); Console.ForegroundColor = ConsoleColor.Gray; http.Dispose(); System.Threading.Thread.Sleep(500); http = new HttpClient(); } else { stop = true; throw ex; } } } return suggestions; } } } namespace GoogleRandomSuggestions { class Program { static Random rng; static Program() { rng = new Random(); } static bool StringBeginsWith(string str, string beginning) { if (str.Length < beginning.Length) return false; return str.Substring(0, beginning.Length).Equals(beginning); } static string RandomPhrase(string start) { string phrase = start; bool stop = false; while (!stop) { string[] suggestions = GoogleSuggestions.GetSuggestions(phrase).Where(s => StringBeginsWith(s, phrase) && !s.Equals(phrase)).ToArray(); if (suggestions.Length == 0) { stop = true; } else if (suggestions.Length == 1) { phrase = suggestions[0]; stop = true; } else { string choice = suggestions[rng.Next(suggestions.Length)]; if (phrase.Length + 1 > choice.Length) { phrase = choice; stop = true; } else { phrase = choice.Substring(0, phrase.Length + 1); Console.ForegroundColor = ConsoleColor.White; Console.Write(phrase); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine(choice.Substring(phrase.Length)); } } } return phrase; } static string RandomPhrase() { return RandomPhrase(Char.ConvertFromUtf32(rng.Next(65, 91))); } static void Main(string[] args) { string input = ""; while (true) { Console.Write("> "); string last = input; input = Console.ReadLine(); if (input.Length == 0) input = last; Console.WriteLine(); string phrase = RandomPhrase(input); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(phrase); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine(); } } } }