2012-02-19 03:01:22 +01:00
|
|
|
import random
|
2012-04-21 18:26:24 +02:00
|
|
|
from util import hook, http
|
|
|
|
|
|
|
|
from util.formatting import truncate_words
|
2012-02-19 03:01:22 +01:00
|
|
|
|
|
|
|
|
|
|
|
def api_get(kind, query):
|
2012-04-02 18:17:55 +02:00
|
|
|
"""Use the RESTful Google Search API"""
|
2012-02-19 03:01:22 +01:00
|
|
|
url = 'http://ajax.googleapis.com/ajax/services/search/%s?' \
|
|
|
|
'v=1.0&safe=off'
|
|
|
|
return http.get_json(url % kind, q=query)
|
|
|
|
|
|
|
|
|
2012-04-02 17:20:17 +02:00
|
|
|
@hook.command('image')
|
|
|
|
@hook.command('gis')
|
2012-02-19 03:01:22 +01:00
|
|
|
@hook.command
|
2012-04-02 17:20:17 +02:00
|
|
|
def googleimage(inp):
|
2012-02-28 03:03:43 +01:00
|
|
|
".gis <term> -- Returns first Google Image result (Safesearch off)."
|
2012-02-19 03:01:22 +01:00
|
|
|
|
|
|
|
parsed = api_get('images', inp)
|
|
|
|
if not 200 <= parsed['responseStatus'] < 300:
|
2012-03-12 19:13:32 +01:00
|
|
|
raise IOError('error searching for images: %d: %s' % ( \
|
|
|
|
parsed['responseStatus'], ''))
|
2012-02-19 03:01:22 +01:00
|
|
|
if not parsed['responseData']['results']:
|
|
|
|
return 'no images found'
|
2012-04-21 18:26:24 +02:00
|
|
|
return random.choice(parsed['responseData']['results'][:10]) \
|
2012-04-20 17:10:48 +02:00
|
|
|
['unescapedUrl']
|
2012-04-02 18:17:55 +02:00
|
|
|
|
2012-02-19 03:01:22 +01:00
|
|
|
|
2012-03-22 09:59:55 +01:00
|
|
|
@hook.command('search')
|
2012-02-19 03:01:22 +01:00
|
|
|
@hook.command('g')
|
|
|
|
@hook.command
|
|
|
|
def google(inp):
|
2012-02-28 03:03:43 +01:00
|
|
|
".google <query> -- Returns first google search result for <query>."
|
2012-02-19 03:01:22 +01:00
|
|
|
|
|
|
|
parsed = api_get('web', inp)
|
|
|
|
if not 200 <= parsed['responseStatus'] < 300:
|
|
|
|
raise IOError('error searching for pages: %d: %s' % (
|
2012-03-12 19:13:32 +01:00
|
|
|
parsed['responseStatus'], ''))
|
2012-02-19 03:01:22 +01:00
|
|
|
if not parsed['responseData']['results']:
|
2012-02-19 22:50:02 +01:00
|
|
|
return 'No results found.'
|
2012-02-19 03:01:22 +01:00
|
|
|
|
|
|
|
result = parsed['responseData']['results'][0]
|
|
|
|
|
|
|
|
title = http.unescape(result['titleNoFormatting'])
|
|
|
|
content = http.unescape(result['content'])
|
|
|
|
|
|
|
|
if len(content) == 0:
|
|
|
|
content = "No description available."
|
|
|
|
else:
|
|
|
|
content = http.html.fromstring(content).text_content()
|
|
|
|
|
2012-02-22 02:18:33 +01:00
|
|
|
out = '%s -- \x02%s\x02: "%s"' % (result['unescapedUrl'], title, content)
|
2012-02-19 03:01:22 +01:00
|
|
|
|
|
|
|
out = ' '.join(out.split())
|
|
|
|
|
2012-04-21 18:26:24 +02:00
|
|
|
out = truncate_words(out, 300)
|
2012-02-19 03:01:22 +01:00
|
|
|
|
|
|
|
return out
|