Add !suggest, to get suggested searches from google
This commit is contained in:
parent
f54e25dddd
commit
8d946fb60b
2 changed files with 29 additions and 0 deletions
|
@ -1,15 +1,19 @@
|
||||||
#--require-config google-api-key
|
#--require-config google-api-key
|
||||||
#--require-config google-search-id
|
#--require-config google-search-id
|
||||||
|
|
||||||
|
import json
|
||||||
from src import Utils
|
from src import Utils
|
||||||
|
|
||||||
URL_GOOGLESEARCH = "https://www.googleapis.com/customsearch/v1"
|
URL_GOOGLESEARCH = "https://www.googleapis.com/customsearch/v1"
|
||||||
|
URL_GOOGLESUGGEST = "http://google.com/complete/search"
|
||||||
|
|
||||||
class Module(object):
|
class Module(object):
|
||||||
def __init__(self, bot, events, exports):
|
def __init__(self, bot, events, exports):
|
||||||
self.bot = bot
|
self.bot = bot
|
||||||
events.on("received.command").on("google", "g").hook(self.google,
|
events.on("received.command").on("google", "g").hook(self.google,
|
||||||
help="Google feeling lucky", usage="[search term]")
|
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):
|
def google(self, event):
|
||||||
phrase = event["args"] or event["buffer"].get()
|
phrase = event["args"] or event["buffer"].get()
|
||||||
|
@ -29,3 +33,25 @@ class Module(object):
|
||||||
event["stderr"].write("Failed to load results")
|
event["stderr"].write("Failed to load results")
|
||||||
else:
|
else:
|
||||||
event["stderr"].write("No phrase provided")
|
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")
|
||||||
|
|
|
@ -285,3 +285,6 @@ def hook(event, **kwargs):
|
||||||
{"event": event, "kwargs": kwargs})
|
{"event": event, "kwargs": kwargs})
|
||||||
return func
|
return func
|
||||||
return _hook_func
|
return _hook_func
|
||||||
|
|
||||||
|
def strip_html(s):
|
||||||
|
return bs4.BeautifulSoup(s, "lxml").get_text()
|
||||||
|
|
Loading…
Reference in a new issue