2009-05-15 04:00:48 +00:00
|
|
|
import urllib
|
2009-07-14 02:43:13 +00:00
|
|
|
import random
|
2009-05-15 04:00:48 +00:00
|
|
|
from lxml import html
|
2009-11-20 23:55:39 +00:00
|
|
|
import json
|
2009-05-15 04:00:48 +00:00
|
|
|
|
2009-11-20 23:55:39 +00:00
|
|
|
from util import hook
|
2009-05-15 04:00:48 +00:00
|
|
|
|
|
|
|
|
|
|
|
def api_get(kind, query):
|
|
|
|
req_url = 'http://ajax.googleapis.com/ajax/services/search/%s?' \
|
|
|
|
'v=1.0&safe=off&q=%s'
|
2009-12-22 22:54:30 +00:00
|
|
|
query = query.encode('utf8')
|
2009-05-15 04:00:48 +00:00
|
|
|
url = req_url % (kind, urllib.quote(query, safe=''))
|
2009-11-20 23:55:39 +00:00
|
|
|
page = urllib.urlopen(url).read()
|
|
|
|
return json.loads(page)
|
2009-05-15 04:00:48 +00:00
|
|
|
|
|
|
|
|
|
|
|
@hook.command
|
|
|
|
def gis(inp):
|
|
|
|
'''.gis <term> -- 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'
|
2009-07-14 02:43:13 +00:00
|
|
|
return random.choice(parsed['responseData']['results'][:10]
|
|
|
|
)['unescapedUrl'] # squares is dumb
|
2009-05-15 04:00:48 +00:00
|
|
|
|
2009-07-08 17:28:15 +00:00
|
|
|
|
2009-05-15 04:00:48 +00:00
|
|
|
@hook.command
|
|
|
|
@hook.command('g')
|
|
|
|
def google(inp):
|
2009-11-07 18:44:16 +00:00
|
|
|
'''.g/.google <query> -- returns first google search result'''
|
2009-05-15 04:00:48 +00:00
|
|
|
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']))
|
2009-07-08 17:28:15 +00:00
|
|
|
|
2009-05-15 04:00:48 +00:00
|
|
|
out = '%s -- \x02%s\x02: "%s"' % (result['unescapedUrl'], title, content)
|
|
|
|
out = ' '.join(out.split())
|
|
|
|
|
|
|
|
if len(out) > 300:
|
|
|
|
out = out[:out.rfind(' ')] + '..."'
|
|
|
|
|
|
|
|
return out
|