|
1
|
|
|
#!/usr/bin/python |
|
2
|
|
|
# -*- coding: utf-8 -*- |
|
3
|
|
|
from telegram.ext.dispatcher import run_async |
|
4
|
|
|
from googleapiclient.errors import HttpError |
|
5
|
|
|
from googleapiclient.discovery import build |
|
6
|
|
|
from telegram.ext import CommandHandler |
|
7
|
|
|
from modules.logging import log_command |
|
8
|
|
|
from datetime import datetime |
|
9
|
|
|
from telegram import ChatAction |
|
10
|
|
|
from random import randint |
|
11
|
|
|
import logging |
|
12
|
|
|
|
|
13
|
|
|
|
|
14
|
|
|
def module_init(gd): |
|
15
|
|
|
global dev_key, cse_id |
|
16
|
|
|
dev_key = gd.config["google_dev_key"] |
|
17
|
|
|
cse_id = gd.config["google_cse_id"] |
|
18
|
|
|
commands = gd.config["commands_image"] |
|
19
|
|
|
for command in commands: |
|
20
|
|
|
gd.dp.add_handler(CommandHandler(command, g_search, pass_args=True)) |
|
21
|
|
|
logging.getLogger('googleapiclient.discovery').setLevel(logging.ERROR) |
|
22
|
|
|
|
|
23
|
|
|
|
|
24
|
|
|
@run_async |
|
25
|
|
|
def g_search(bot, update, args): |
|
26
|
|
|
current_time = datetime.strftime(datetime.now(), "%d.%m.%Y %H:%M:%S") |
|
27
|
|
|
if len(args) == 0: |
|
28
|
|
|
update.message.reply_text("You need a query to search!") |
|
29
|
|
|
return |
|
30
|
|
|
update.message.chat.send_action(ChatAction.UPLOAD_PHOTO) |
|
31
|
|
|
query = " ".join(args) |
|
32
|
|
|
try: |
|
33
|
|
|
final_img = get_image(query) |
|
34
|
|
|
except HttpError: |
|
35
|
|
|
update.message.reply_text("Sorry, my daily limit for search exceeded. Check back tomorrow!") |
|
36
|
|
|
return |
|
37
|
|
|
if final_img is None: |
|
38
|
|
|
update.message.reply_text("Nothing found!") |
|
39
|
|
|
return |
|
40
|
|
|
msg_text = "[link](%s)" % final_img |
|
41
|
|
|
update.message.reply_text(msg_text, parse_mode="Markdown") |
|
42
|
|
|
print (current_time, ">", "/img", query, ">", update.message.from_user.username) |
|
43
|
|
|
log_command(bot, update, current_time, "img") |
|
44
|
|
|
|
|
45
|
|
|
|
|
46
|
|
|
def get_image(query): |
|
47
|
|
|
service = build("customsearch", "v1", developerKey=dev_key, cache_discovery=False) |
|
|
|
|
|
|
48
|
|
|
result = service.cse().list(q=query, cx=cse_id, searchType="image").execute() |
|
|
|
|
|
|
49
|
|
|
total_results = int(result["queries"]["request"][0]["totalResults"]) |
|
50
|
|
|
if total_results < 1: |
|
51
|
|
|
return None |
|
52
|
|
|
random_item = randint(0, len(result["items"])-1) |
|
53
|
|
|
final_img = result["items"][random_item]["link"] |
|
54
|
|
|
return final_img |
|
55
|
|
|
|