Passed
Push — master ( 7eca6c...2058e5 )
by Anas
02:09
created

modules.google_search.search()   A

Complexity

Conditions 4

Size

Total Lines 16
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 16
nop 3
dl 0
loc 16
rs 9.6
c 0
b 0
f 0
1
#!/usr/bin/python
2
# -*- coding: utf-8 -*-
3
from modules.logging import logging_decorator
4
from telegram.ext.dispatcher import run_async
5
from telegram.ext import PrefixHandler
6
from urllib.parse import quote_plus
7
from collections import Iterable
8
from telegram import ChatAction
9
from random import randint
10
import requests
11
import json
12
import re
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(PrefixHandler("/", command, image_search))
20
    for command in commands_gif:
21
        gd.dp.add_handler(PrefixHandler("/", command, gif_search))
22
23
24
@run_async
25
@logging_decorator("img")
26
def image_search(update, context):
27
    query = google_search(update, context)
28
    return query
29
30
31
@run_async
32
@logging_decorator("gif")
33
def gif_search(update, context):
34
    query = google_search(update, context, gif=True)
35
    return query
36
    
37
38
def google_search(update, context, gif=False):
39
    query = quote_plus(" ".join(context.args))
40
    if len(query) == 0:
41
        update.message.reply_text("You need a query to search!")
42
        return
43
    update.message.chat.send_action(ChatAction.UPLOAD_PHOTO)
44
    try:
45
        final_img = single_result(get_image(query, gif))
46
    except:
47
        update.message.reply_text("Sorry, something gone wrong!")
48
        return
49
    if final_img is None:
50
        update.message.reply_text("Nothing found!")
51
        return
52
    msg_text = "[link](%s)" % final_img
53
    update.message.reply_text(msg_text, parse_mode="Markdown", disable_web_page_preview=False)
54
55
56
def get_image(query, gif=False):
57
    if gif:
58
        link = "https://www.google.ru/search?q={}&tbm=isch&tbs=itp%3Aanimated".format(query)
59
    else:
60
        link = "https://www.google.ru/search?q={}&tbm=isch".format(query)
61
    req = requests.get(link, headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.142 Safari/537.36"})
62
    html_output = req.text
63
    googleregex = "AF_initDataCallback\({key: 'ds:1', isError:  false , hash: '2', data:(.*)}\);<\/script><script"
64
    html_links = re.search(googleregex, html_output, re.M | re.I | re.S).group(1)
65
    full_json = json.loads(html_links)
66
    for a in full_json:
67
        if isinstance(a, Iterable):
68
            for b in a:
69
                if isinstance(b, Iterable):
70
                    for c in b:
71
                        if isinstance(c, Iterable):
72
                            for d in c:
73
                                if d == "GRID_STATE0":
74
                                    links_json = c[2]
75
                                    break
76
    imgs_list = []
77
    for i in links_json:
0 ignored issues
show
introduced by
The variable links_json does not seem to be defined for all execution paths.
Loading history...
78
        try:
79
            imgs_list.append(i[1][3][0])
80
        except TypeError:
81
            pass
82
    return imgs_list
83
84
85
def single_result(links_list):
86
    if len(links_list) < 1:
87
        return None
88
    else:
89
        return links_list[randint(0, len(links_list)-1)]
90