This repository has been archived on 2023-04-13. You can view files and clone it, but you cannot make any changes to it's state, such as pushing and creating new issues, pull requests or comments.
CloudBot/disabled_stuff/google.py

52 lines
1.6 KiB
Python
Raw Normal View History

2012-02-19 15:01:22 +13:00
import random
2014-02-14 16:36:57 +13:00
from util import hook, http, text
2012-02-19 15:01:22 +13:00
def api_get(kind, query):
2012-04-02 09:17:55 -07:00
"""Use the RESTful Google Search API"""
2012-02-19 15:01:22 +13:00
url = 'http://ajax.googleapis.com/ajax/services/search/%s?' \
2012-04-26 12:33:55 +12:00
'v=1.0&safe=moderate'
2012-02-19 15:01:22 +13:00
return http.get_json(url % kind, q=query)
2012-04-02 08:20:17 -07:00
@hook.command('image')
@hook.command('gis')
2012-02-19 15:01:22 +13:00
@hook.command
2012-04-02 08:20:17 -07:00
def googleimage(inp):
2013-09-04 18:30:04 +08:00
"""gis <query> -- Returns first Google Image result for <query>."""
2012-02-19 15:01:22 +13:00
parsed = api_get('images', inp)
if not 200 <= parsed['responseStatus'] < 300:
2013-09-05 09:46:49 +08:00
raise IOError('error searching for images: {}: {}'.format(parsed['responseStatus'], ''))
2012-02-19 15:01:22 +13:00
if not parsed['responseData']['results']:
return 'no images found'
2013-11-12 07:06:06 +01:00
return random.choice(parsed['responseData']['results'][:10])['unescapedUrl']
2012-04-02 09:17:55 -07:00
2012-02-19 15:01:22 +13:00
2012-03-22 21:59:55 +13:00
@hook.command('search')
2012-02-19 15:01:22 +13:00
@hook.command('g')
@hook.command
def google(inp):
2013-09-04 18:30:04 +08:00
"""google <query> -- Returns first google search result for <query>."""
2012-02-19 15:01:22 +13:00
parsed = api_get('web', inp)
if not 200 <= parsed['responseStatus'] < 300:
2013-09-05 09:46:49 +08:00
raise IOError('error searching for pages: {}: {}'.format(parsed['responseStatus'], ''))
2012-02-19 15:01:22 +13:00
if not parsed['responseData']['results']:
2012-02-20 10:50:02 +13:00
return 'No results found.'
2012-02-19 15:01:22 +13:00
result = parsed['responseData']['results'][0]
title = http.unescape(result['titleNoFormatting'])
title = text.truncate_str(title, 60)
2012-02-19 15:01:22 +13:00
content = http.unescape(result['content'])
2012-04-26 12:52:19 +12:00
if not content:
2012-02-19 15:01:22 +13:00
content = "No description available."
else:
content = http.html.fromstring(content).text_content()
content = text.truncate_str(content, 150)
2012-02-19 15:01:22 +13:00
2013-11-12 07:06:06 +01:00
return u'{} -- \x02{}\x02: "{}"'.format(result['unescapedUrl'], title, content)