-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgoogle.py
248 lines (223 loc) · 8.35 KB
/
google.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
import asyncio
import os
from shutil import rmtree
import datetime
import wikipedia
import requests
from justwatch import JustWatch
from bs4 import BeautifulSoup
from search_engine_parser import GoogleSearch
from search_engine_parser.core.exceptions import NoResultsOrTrafficError as GoglError
from geopy.geocoders import Nominatim
from telethon.tl import types
from . import *
def progress(current, total):
logger.info(
"Downloaded {} of {}\nCompleted {}".format(
current, total, (current / total) * 100
)
)
@bot.on(d3vil_cmd(pattern="wikipedia (.*)"))
@bot.on(sudo_cmd(pattern="wikipedia (.*)", allow_sudo=True))
async def _(event):
if event.fwd_from:
return
await edit_or_reply(event, "Processing ...")
input_str = event.pattern_match.group(1)
result = ""
results = wikipedia.search(input_str)
for s in results:
page = wikipedia.page(s)
url = page.url
result += f"> [{s}]({url}) \n"
await edit_or_reply(event, "WikiPedia **Search**: {} \n\n **Result**: \n\n{}".format(input_str, result)
)
@bot.on(d3vil_cmd(pattern="watch (.*)"))
@bot.on(sudo_cmd(pattern="watch (.*)", allow_sudo=True))
async def _(event):
if event.fwd_from:
return
query = event.pattern_match.group(1)
d3vil = await eor(event, "Finding Sites...")
streams = get_stream_data(query)
title = streams["title"]
thumb_link = streams["movie_thumb"]
release_year = streams["release_year"]
release_date = streams["release_date"]
scores = streams["score"]
try:
imdb_score = scores["imdb"]
except KeyError:
imdb_score = None
try:
tmdb_score = scores["tmdb"]
except KeyError:
tmdb_score = None
stream_providers = streams["providers"]
if release_date is None:
release_date = release_year
output_ = f"**Movie:**\n`{title}`\n**Release Date:**\n`{release_date}`"
if imdb_score:
output_ = output_ + f"\n**IMDB: **{imdb_score}"
if tmdb_score:
output_ = output_ + f"\n**TMDB: **{tmdb_score}"
output_ = output_ + "\n\n**Available on:**\n"
for provider, link in stream_providers.items():
if "sonyliv" in link:
link = link.replace(" ", "%20")
output_ += f"[{pretty(provider)}]({link})\n"
await bot.send_file(
event.chat_id,
caption=output_,
file=thumb_link,
force_document=False,
allow_cache=False,
silent=True,
)
await event.delete()
@bot.on(d3vil_cmd(pattern="google (.*)", outgoing=True))
@bot.on(sudo_cmd(pattern="google (.*)", allow_sudo=True))
async def google(event):
input_str = event.pattern_match.group(1)
if not input_str:
return await eod(event, "`Give something to search..`")
d3vil = await eor(event, "Searching...")
gos = GoogleSearch()
try:
got = await gos.async_search(f"{input_str}", cache=False)
except GoglError as e:
return await eod(event, str(e), 10)
output = ""
for i in range(len(got["links"])):
text = got["titles"][i]
url = got["links"][i]
des = got["descriptions"][i]
output += f" 👉🏻 [{text}]({url})\n`{des}`\n\n"
res = f"**Google Search Query:**\n`{input_str}`\n\n**Results:**\n{output}"
see = []
for i in range(0, len(res), 4095):
see.append(res[i : i + 4095])
for j in see:
await bot.send_message(event.chat_id, j, link_preview=False)
await d3vil.delete()
see.clear()
@bot.on(d3vil_cmd(pattern="img (.*)", outgoing=True))
@bot.on(sudo_cmd(pattern="img (.*)", allow_sudo=True))
async def img(event):
sim = event.pattern_match.group(1)
if not sim:
return await eod(event, "`Give something to search...`")
d3vil = await eor(event, f"Searching for `{sim}`...")
if "-" in sim:
try:
lim = int(sim.split(";")[1])
sim = sim.split(";")[0]
except BaseExceptaion:
lim = 5
else:
lim = 5
imgs = googleimagesdownload()
args = {
"keywords": sim,
"limit": lim,
"format": "jpg",
"output_directory": "./DOWNLOADS/",
}
letsgo = imgs.download(args)
gotit = letsgo[0][sim]
await event.client.send_file(event.chat_id, gotit, caption=sim, album=True)
rmtree(f"./DOWNLOADS/{sim}/")
await d3vil.delete()
@bot.on(d3vil_cmd(pattern="reverse"))
@bot.on(sudo_cmd(pattern="reverse", allow_sudo=True))
async def _(event):
if event.fwd_from:
return
start = datetime.datetime.now()
BASE_URL = "http://www.google.com"
OUTPUT_STR = "Reply to an image to do Google Reverse Search"
if event.reply_to_msg_id:
d3vil = await eor(event, "Pre Processing Media")
previous_message = await event.get_reply_message()
previous_message_text = previous_message.message
if previous_message.media:
downloaded_file_name = await bot.download_media(
previous_message, Config.TMP_DOWNLOAD_DIRECTORY
)
SEARCH_URL = "{}/searchbyimage/upload".format(BASE_URL)
multipart = {
"encoded_image": (
downloaded_file_name,
open(downloaded_file_name, "rb"),
),
"image_content": "",
}
# https://stackoverflow.com/a/28792943/4723940
google_rs_response = requests.post(
SEARCH_URL, files=multipart, allow_redirects=False
)
the_location = google_rs_response.headers.get("Location")
os.remove(downloaded_file_name)
else:
previous_message_text = previous_message.message
SEARCH_URL = "{}/searchbyimage?image_url={}"
request_url = SEARCH_URL.format(BASE_URL, previous_message_text)
google_rs_response = requests.get(request_url, allow_redirects=False)
the_location = google_rs_response.headers.get("Location")
await d3vil.edit("Found Google Result. Processing results...")
headers = {
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:58.0) Gecko/20100101 Firefox/58.0"
}
response = requests.get(the_location, headers=headers)
soup = BeautifulSoup(response.text, "html.parser")
# document.getElementsByClassName("r5a77d"): PRS
prs_div = soup.find_all("div", {"class": "r5a77d"})[0]
prs_anchor_element = prs_div.find("a")
prs_url = BASE_URL + prs_anchor_element.get("href")
prs_text = prs_anchor_element.text
# document.getElementById("jHnbRc")
img_size_div = soup.find(id="jHnbRc")
img_size = img_size_div.find_all("div")
end = datetime.datetime.now()
ms = (end - start).seconds
OUTPUT_STR = """Possible Related Search : <a href="{prs_url}">{prs_text}</a>
More Info: Open this <a href="{the_location}">Link</a> in {ms} seconds""".format(
**locals()
)
await d3vil.edit(OUTPUT_STR, parse_mode="HTML", link_preview=False)
@bot.on(d3vil_cmd(pattern="gps ?(.*)"))
@bot.on(sudo_cmd(pattern="gps ?(.*)", allow_sudo=True))
async def gps(event):
if event.fwd_from:
return
reply_to_id = event.message
if event.reply_to_msg_id:
reply_to_id = await event.get_reply_message()
input_str = event.pattern_match.group(1)
if not input_str:
return await eod(event, "What should i find? Give me location.🤨")
await edit_or_reply(event, "Finding😁")
geolocator = Nominatim(user_agent="d3vilbot")
geoloc = geolocator.geocode(input_str)
if geoloc:
lon = geoloc.longitude
lat = geoloc.latitude
await reply_to_id.reply(
input_str, file=types.InputMediaGeoPoint(types.InputGeoPoint(lat, lon))
)
await event.delete()
else:
await eod(event, "I coudn't find it😫")
CmdHelp("google").add_command(
"google", "<query>", "Does a google search for the query provided"
).add_command(
"img", "<query>", "Does a image search for the query provided"
).add_command(
"reverse", "<reply to a sticker/pic>", "Does a reverse image search on google and provides the similar images"
).add_command(
"gps", "<place>", "Gives the location of the given place/city/state."
).add_command(
"wikipedia", "<query>", "Searches for the query on Wikipedia."
).add_command(
"watch", "<query>", "Searches for all the available sites for watching that movie or series."
).add()