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

55 lines
1.6 KiB
Python
Raw Normal View History

2012-02-19 03:01:22 +01:00
import random
2012-04-21 18:26:24 +02:00
from util import hook, http
2012-04-23 22:51:54 +02:00
from util.text 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?' \
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):
2012-05-16 05:07:27 +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:
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]) \
['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-05-16 05:07:27 +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:
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'])
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()
out = '%s -- \x02%s\x02: "%s"' % (result['unescapedUrl'], title, content)
2012-02-19 03:01:22 +01:00
2012-04-26 02:52:19 +02:00
return truncate_words(out, 300)