This repository has been archived on 2023-04-13. You can view files and clone it, but cannot push or open issues or pull requests.
CloudBot/plugins/google.py

51 lines
1.6 KiB
Python
Raw Normal View History

2012-02-19 03:01:22 +01:00
import random
from util import hook, http, text
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?' \
2012-04-26 02:33:55 +02:00
'v=1.0&safe=moderate'
2012-02-19 03:01:22 +01:00
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):
2013-09-04 12:30:04 +02:00
"""gis <query> -- Returns first Google Image result for <query>."""
2012-02-19 03:01:22 +01:00
parsed = api_get('images', inp)
if not 200 <= parsed['responseStatus'] < 300:
2013-09-05 03:46:49 +02:00
raise IOError('error searching for images: {}: {}'.format(parsed['responseStatus'], ''))
2012-02-19 03:01:22 +01: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 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):
2013-09-04 12:30:04 +02: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:
2013-09-05 03:46:49 +02:00
raise IOError('error searching for pages: {}: {}'.format(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'])
title = text.truncate_str(title, 60)
2012-02-19 03:01:22 +01:00
content = http.unescape(result['content'])
2012-04-26 02:52:19 +02:00
if not content:
2012-02-19 03:01:22 +01:00
content = "No description available."
else:
content = http.html.fromstring(content).text_content()
content = text.truncate_str(content, 150)
2012-02-19 03:01:22 +01:00
2013-11-12 07:06:06 +01:00
return u'{} -- \x02{}\x02: "{}"'.format(result['unescapedUrl'], title, content)