diff --git a/modules/google.py b/modules/google.py index 42acf954..1d7b6e8c 100644 --- a/modules/google.py +++ b/modules/google.py @@ -1,15 +1,19 @@ #--require-config google-api-key #--require-config google-search-id +import json from src import Utils URL_GOOGLESEARCH = "https://www.googleapis.com/customsearch/v1" +URL_GOOGLESUGGEST = "http://google.com/complete/search" class Module(object): def __init__(self, bot, events, exports): self.bot = bot events.on("received.command").on("google", "g").hook(self.google, help="Google feeling lucky", usage="[search term]") + events.on("received.command.suggest").hook(self.suggest, + help="Get suggested phrases from Google", usage="[phrase]") def google(self, event): phrase = event["args"] or event["buffer"].get() @@ -29,3 +33,25 @@ class Module(object): event["stderr"].write("Failed to load results") else: event["stderr"].write("No phrase provided") + + def suggest(self, event): + phrase = event["args"] or event["buffer"].get() + if phrase: + page = Utils.get_url(URL_GOOGLESUGGEST, get_params={ + "output": "json", "client": "hp", "q": phrase}) + if page: + # google gives us jsonp, so we need to unwrap it. + page = page.split("(", 1)[1][:-1] + page = json.loads(page) + suggestions = page[1] + suggestions = [Utils.strip_html(s[0]) for s in suggestions] + + if suggestions: + event["stdout"].write("%s: %s" % (phrase, + ", ".join(suggestions))) + else: + event["stderr"].write("No suggestions found") + else: + event["stderr"].write("Failed to load results") + else: + event["stderr"].write("No phrase provided") diff --git a/src/Utils.py b/src/Utils.py index cd0e0cfa..e78c08fc 100644 --- a/src/Utils.py +++ b/src/Utils.py @@ -285,3 +285,6 @@ def hook(event, **kwargs): {"event": event, "kwargs": kwargs}) return func return _hook_func + +def strip_html(s): + return bs4.BeautifulSoup(s, "lxml").get_text()