/
image.py
61 lines (51 loc) · 1.78 KB
/
image.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# coding: utf-8
from __future__ import absolute_import, unicode_literals
import requests
import anyjson
import random
from thebot import Plugin, on_command
class Plugin(Plugin):
"""Retrives images from the web."""
@on_command('(image|img)( me)? (?P<query>.+)')
def image(self, request, query):
"""Google random image on given topic."""
url = self._find_image(query)
if url is None:
request.respond('No image was found for query "{0}"'.format(query))
else:
request.respond(url)
@on_command('moustache( for)? (?P<query>.+)')
@on_command('усы( для)? (?P<query>.+)')
def mustache(self, request, query):
"""Apply moustache on image URL or random image on given topic."""
type = int(random.randint(0, 2))
if query.startswith('http'):
url = query
else:
url = self._find_image(query)
if url is None:
request.respond('No image was found for query "{0}"'.format(query))
return
request.respond(
'http://mustachify.me/{type}?src={url}'.format(
type=type,
url=url,
)
)
def _find_image(self, query):
response = requests.get(
'http://ajax.googleapis.com/ajax/services/search/images',
params=dict(
v="1.0",
rsz='8',
q=query,
safe='active',
)
)
if response.status_code == 200:
content = response.content
data = anyjson.deserialize(content)
images = data['responseData']['results']
if len(images) > 0:
image = random.choice(images[:5])
return image['unescapedUrl']