2018-08-31 09:51:47 +00:00
|
|
|
#--require-config google-api-key
|
|
|
|
#--require-config google-search-id
|
2016-03-30 18:31:23 +00:00
|
|
|
|
2018-09-26 13:36:33 +00:00
|
|
|
import json
|
2018-09-27 10:46:10 +00:00
|
|
|
from src import ModuleManager, Utils
|
2016-03-29 11:56:58 +00:00
|
|
|
|
|
|
|
URL_GOOGLESEARCH = "https://www.googleapis.com/customsearch/v1"
|
2018-09-26 13:36:33 +00:00
|
|
|
URL_GOOGLESUGGEST = "http://google.com/complete/search"
|
2016-03-29 11:56:58 +00:00
|
|
|
|
2018-09-27 10:46:10 +00:00
|
|
|
class Module(ModuleManager.BaseModule):
|
2018-09-26 17:27:17 +00:00
|
|
|
@Utils.hook("received.command.google|g", usage="[search term]")
|
2016-03-29 11:56:58 +00:00
|
|
|
def google(self, event):
|
2018-09-26 17:27:17 +00:00
|
|
|
"""
|
|
|
|
Get first Google result for a given search term
|
|
|
|
"""
|
2018-09-30 10:43:34 +00:00
|
|
|
phrase = event["args"] or event["target"].buffer.get()
|
2016-03-29 11:56:58 +00:00
|
|
|
if phrase:
|
|
|
|
page = Utils.get_url(URL_GOOGLESEARCH, get_params={
|
|
|
|
"q": phrase, "key": self.bot.config[
|
2018-08-31 09:51:47 +00:00
|
|
|
"google-api-key"], "cx": self.bot.config[
|
|
|
|
"google-search-id"], "prettyPrint": "true",
|
2018-08-31 03:14:56 +00:00
|
|
|
"num": 1, "gl": "gb"}, json=True)
|
2016-03-29 11:56:58 +00:00
|
|
|
if page:
|
|
|
|
if "items" in page and len(page["items"]):
|
2018-09-08 21:53:31 +00:00
|
|
|
event["stdout"].write("(" + Utils.bold(phrase) + ") " \
|
|
|
|
+ page["items"][0]["link"])
|
2016-03-29 11:56:58 +00:00
|
|
|
else:
|
|
|
|
event["stderr"].write("No results found")
|
|
|
|
else:
|
|
|
|
event["stderr"].write("Failed to load results")
|
|
|
|
else:
|
|
|
|
event["stderr"].write("No phrase provided")
|
2018-09-26 13:36:33 +00:00
|
|
|
|
2018-09-26 17:27:17 +00:00
|
|
|
@Utils.hook("received.command.suggest", usage="[phrase]")
|
2018-09-26 13:36:33 +00:00
|
|
|
def suggest(self, event):
|
2018-09-26 17:27:17 +00:00
|
|
|
"""
|
|
|
|
Get suggested phrases from Google
|
|
|
|
"""
|
2018-09-30 10:43:34 +00:00
|
|
|
phrase = event["args"] or event["target"].buffer.get()
|
2018-09-26 13:36:33 +00:00
|
|
|
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")
|