|
1
|
|
|
#!/usr/bin/python |
|
2
|
|
|
# -*- coding: utf-8 -*- |
|
3
|
|
|
from modules.logging import logging_decorator |
|
4
|
|
|
from google_images_download import google_images_download |
|
5
|
|
|
from telegram.ext.dispatcher import run_async |
|
6
|
|
|
from telegram.ext import CommandHandler |
|
7
|
|
|
from telegram import ChatAction |
|
8
|
|
|
from random import randint |
|
9
|
|
|
import logging |
|
10
|
|
|
import sys |
|
11
|
|
|
import re |
|
12
|
|
|
import io |
|
13
|
|
|
|
|
14
|
|
|
|
|
15
|
|
|
def module_init(gd): |
|
16
|
|
|
commands_image = gd.config["commands_image"] |
|
17
|
|
|
commands_gif = gd.config["commands_gif"] |
|
18
|
|
|
for command in commands_image: |
|
19
|
|
|
gd.dp.add_handler(CommandHandler(command, image_search, pass_args=True)) |
|
20
|
|
|
for command in commands_gif: |
|
21
|
|
|
gd.dp.add_handler(CommandHandler(command, gif_search, pass_args=True)) |
|
22
|
|
|
|
|
23
|
|
|
|
|
24
|
|
|
@run_async |
|
25
|
|
|
@logging_decorator("img") |
|
26
|
|
|
def image_search(bot, update, args): |
|
27
|
|
|
query = " ".join(args) |
|
28
|
|
|
google_args = {"keywords":query, "limit":30, "no_download":True} |
|
29
|
|
|
query = search(bot, update, args, google_args) |
|
30
|
|
|
return query |
|
31
|
|
|
|
|
32
|
|
|
|
|
33
|
|
|
@run_async |
|
34
|
|
|
@logging_decorator("gif") |
|
35
|
|
|
def gif_search(bot, update, args): |
|
36
|
|
|
query = " ".join(args) |
|
37
|
|
|
google_args = {"keywords":query, "limit":30, "no_download":True, "format":"gif"} |
|
38
|
|
|
query = search(bot, update, args, google_args) |
|
39
|
|
|
return query |
|
40
|
|
|
|
|
41
|
|
|
|
|
42
|
|
|
def search(bot, update, args, google_args): |
|
43
|
|
|
if len(args) == 0: |
|
44
|
|
|
update.message.reply_text("You need a query to search!") |
|
45
|
|
|
return |
|
46
|
|
|
update.message.chat.send_action(ChatAction.UPLOAD_PHOTO) |
|
47
|
|
|
query = " ".join(args) |
|
48
|
|
|
try: |
|
49
|
|
|
final_img = get_image(query, google_args) |
|
50
|
|
|
except: |
|
51
|
|
|
update.message.reply_text("Sorry, something gone wrong!") |
|
52
|
|
|
return |
|
53
|
|
|
if final_img is None: |
|
54
|
|
|
update.message.reply_text("Nothing found!") |
|
55
|
|
|
return |
|
56
|
|
|
msg_text = "[link](%s)" % final_img |
|
57
|
|
|
update.message.reply_text(msg_text, parse_mode="Markdown", disable_web_page_preview=False) |
|
58
|
|
|
return query |
|
59
|
|
|
|
|
60
|
|
|
|
|
61
|
|
|
def get_image(query, google_args): |
|
62
|
|
|
sys.stdout = io.StringIO() |
|
63
|
|
|
response = google_images_download.googleimagesdownload() |
|
64
|
|
|
|
|
65
|
|
|
response.download(google_args) |
|
66
|
|
|
result = sys.stdout.getvalue() |
|
67
|
|
|
sys.stdout.close() |
|
68
|
|
|
sys.stdout = sys.__stdout__ |
|
69
|
|
|
urls = re.findall(r'(https?://\S+)', result) |
|
70
|
|
|
image_to_send = urls[randint(0, 29)] |
|
71
|
|
|
return image_to_send |
|
72
|
|
|
|