From 92e451ad68d33919623a2dfaf4d306ae1fb30786 Mon Sep 17 00:00:00 2001 From: Ryan Hitchman Date: Thu, 14 May 2009 22:00:48 -0600 Subject: [PATCH] google search plugin (same module as google image search) --- plugins/gis.py | 23 ------------------- plugins/google.py | 56 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 23 deletions(-) delete mode 100644 plugins/gis.py create mode 100644 plugins/google.py diff --git a/plugins/gis.py b/plugins/gis.py deleted file mode 100644 index 3a1c0fc..0000000 --- a/plugins/gis.py +++ /dev/null @@ -1,23 +0,0 @@ -import yaml -import urllib - -import hook - - -@hook.command -def gis(inp): - '''.gis -- returns first google image result (safesearch off)''' - if not inp: - return gis.__doc__ - - req_url = 'http://ajax.googleapis.com/ajax/services/search/images?' \ - 'v=1.0&safe=off&q=' - url = req_url + urllib.quote(inp, safe='') - json = urllib.urlopen(url).read() - parsed = yaml.load(json) - if not 200 <= parsed['responseStatus'] < 300: - raise IOError('error searching for images: %d: %s' % ( - parsed['responseStatus'], '')) - if not parsed['responseData']['results']: - return 'no images found' - return parsed['responseData']['results'][0]['unescapedUrl'] diff --git a/plugins/google.py b/plugins/google.py new file mode 100644 index 0000000..37c03bb --- /dev/null +++ b/plugins/google.py @@ -0,0 +1,56 @@ +import yaml +import urllib +from lxml import html + +import hook + + +def api_get(kind, query): + req_url = 'http://ajax.googleapis.com/ajax/services/search/%s?' \ + 'v=1.0&safe=off&q=%s' + url = req_url % (kind, urllib.quote(query, safe='')) + json = urllib.urlopen(url).read() + return yaml.load(json) + + +@hook.command +def gis(inp): + '''.gis -- returns first google image result (safesearch off)''' + if not inp: + return gis.__doc__ + + parsed = api_get('images', inp) + if not 200 <= parsed['responseStatus'] < 300: + raise IOError('error searching for images: %d: %s' % ( + parsed['responseStatus'], '')) + if not parsed['responseData']['results']: + return 'no images found' + return parsed['responseData']['results'][0]['unescapedUrl'] + +@hook.command +@hook.command('g') +@hook.command('goog') +def google(inp): + '''.g/.goog/.google -- returns first google search result''' + if not inp: + return google.__doc__ + + parsed = api_get('web', inp) + if not 200 <= parsed['responseStatus'] < 300: + raise IOError('error searching for pages: %d: %s' % ( + parsed['responseStatus'], '')) + if not parsed['responseData']['results']: + return 'no results found' + + result = parsed['responseData']['results'][0] + + title, content = map(lambda x: html.fromstring(x).text_content(), + (result['titleNoFormatting'], result['content'])) + + out = '%s -- \x02%s\x02: "%s"' % (result['unescapedUrl'], title, content) + out = ' '.join(out.split()) + + if len(out) > 300: + out = out[:out.rfind(' ')] + '..."' + + return out