Spaces:
Runtime error
Runtime error
File size: 18,860 Bytes
78b07ad |
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 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 |
import io
import os
import time
import urllib.request
from shutil import rmtree
import emoji
import requests
from bs4 import BeautifulSoup
from edge_tts import Communicate
from geopy.geocoders import Nominatim
from geopy.location import Location
from googlesearch import search
from googletrans import LANGCODES, LANGUAGES, Translator
from imdb import Cinemagoer, Movie
from pyrogram import Client
from pyrogram.types import InputMediaPhoto, Message
from wikipedia import exceptions, summary
from Hellbot.functions.driver import Driver
from Hellbot.functions.images import download_images
from Hellbot.functions.paste import post_to_telegraph
from Hellbot.functions.scraping import is_valid_url
from . import Config, HelpMenu, Symbols, db, handler, hellbot, on_message
imdb = Cinemagoer()
mov_titles = [
"localized title",
"canonical title",
"smart canonical title",
"smart long imdb canonical title",
"long imdb canonical title",
"long imdb title",
]
final_msg = """
<b>โฆ ๐ณ๐ฌ๐ด{}00๐ฑ๐ซ ๐จ๐๐ฟ๐ ๐ฆ๐พ๐๐๐พ๐ ๐ฑ๐บ๐๐๐๐ ๐ฃ๐๏ฟฝ๐พ๐ผ๏ฟฝ๐๏ฟฝ๏ฟฝ:</b> <code></code>
<b>โฆ ๐จ๐ฌ๐ฃ๐ป ๐ด๐ฑ๐ซ:</b> <a href='https://www.imdb.com/title/tt{1}'>Click here.</a>
<b>โฆ ๐ ๐๐๐ฝ๐บ๐๐พ:</b> <code>{2}</code>
<b>โฆ ๐ฆ๐พ๐๐๐พ๐:</b> <code>{3}</code>
<b>โฆ ๐ฑ๐บ๐๐๐๐:</b> <code>{4}</code>
<b>โฆ ๐ฑ๐๐๐๐๐๐พ:</b> <code>{5}</code>
<b>โฆ ๐ฃ๐๐๐พ๐ผ๐๐๐:</b> <code>{6}</code>
<b><a href='{7}'>๐ซ ๐ฌ๐๐๐พ ๐ฝ๐พ๐๐บ๐๐
๐ ๐๐พ๐๐พ!</a></b>
"""
telegraph_msg = """
<img src='{0}'/>
<b>โฆ ๐ณ๐๐๐
๐พ:</b> <code>{1}</code>
<b>โฆ ๐จ๐ฌ๐ฃ๐ป ๐ด๐ฑ๐ซ:</b> <a href='https://www.imdb.com/title/tt{2}'>Click here.</a>
<b>โฆ ๐ ๐๐๐ฝ๐บ๐๐พ:</b> <code>{3}</code>
<b>โฆ ๐ฆ๐พ๐๐๐พ๐:</b> <code>{4}</code>
<b>โฆ ๐ฑ๐บ๐๐๐๐:</b> <code>{5}</code>
<b>โฆ ๐ฑ๐๐๐๐๐๐พ:</b> <code>{6}</code>
<b>โฆ ๐ฃ๐๐๐พ๐ผ๐๐๐:</b> <code>{7}</code>
<b>โฆ ๐ถ๐๐๐๐พ๐:</b> <code>{8}</code>
<b>โฆ ๐ข๐๐๐๐๐๐พ๐๐:</b> <code>{9}</code>
<b>โฆ ๐ข๐บ๐๐:</b> <code>{10}</code>
<b>โฆ ๐ข๐๐๐๐๐๐:</b> <code>{11}</code>
<b>โฆ ๐ซ๐บ๐๐๐๐บ๐๐พ:</b> <code>{12}</code>
<b>โฆ ๐ก๐๐ ๐ฎ๐ฟ๐ฟ๐๐ผ๐พ:</b> <code>{13}</code>
<b>โฆ ๐ฏ๐
๐๐๐๐14๐ก๐๐ ๐ฎ๐ฟ๐ฟ๐๐ผ๐พ:</b> <
<b>๐ @HellBot_Networks</b>
"""
@on_message("wikipedia", allow_stan=True)
async def google_search(client: Client, message: Message):
if len(message.command) < 2:
return await hellbot.edit(message, "Give some text to search on wikipedia.")
search_query = await hellbot.input(message)
hell = await hellbot.edit(
message, f"Searching for `{search_query}` on wikipedia..."
)
try:
data = summary(search_query, auto_suggest=False)
except exceptions.DisambiguationError as error:
error = str(error).split("\n")
result = "".join(
f"`{i}`\n" if lineno > 1 else f"**{i}**\n"
for lineno, i in enumerate(error, start=1)
)
return await hell.edit(f"**DisambiguationError:**\n\n{result}")
except exceptions.PageError:
return await hellbot.delete(hell, "**Page not found.**")
await hell.edit(
f"**๐ฒ๐พ๐บ๐๐ผ๐:** `{search_query}`\n**๐ฑ๐พ๐๐๐
๐:**\n{data}",
disable_web_page_preview=True,
)
@on_message("google", allow_stan=True)
async def googleSearch(_, message: Message):
if len(message.command) < 2:
return await hellbot.edit(message, "Give some text to search on google.")
search_query = await hellbot.input(message)
hell = await hellbot.edit(message, f"Searching for `{search_query}` on google...")
try:
results = search(search_query, 7, advanced=True)
except Exception as error:
return await hellbot.error(hell, f"`{str(error)}`")
outStr = f"**๐ ๐ฒ๐พ๐บ๐๐ผ๐:** `{search_query}`\n\n"
for result in results:
outStr += f"**๐ ๐ฑ๐พ๐๐๐
๐:** [{result.title}]({result.url})\n"
outStr += f"**๐ ๐ฃ๐พ๐๐ผ:** {str(result.description)[:50]}...\n\n"
await hell.edit(outStr, disable_web_page_preview=True)
@on_message("reverse", allow_stan=True)
async def reverseSearch(_, message: Message):
if not message.reply_to_message:
return await hellbot.edit(
message, "Reply to an image/sticker to reverse search it."
)
hell = await hellbot.edit(message, "Processing...")
if message.reply_to_message.sticker or message.reply_to_message.photo:
dl_path = await message.reply_to_message.download(
Config.DWL_DIR + "reverse.jpg"
)
file = {"encoded_image": (dl_path, open(dl_path, "rb"))}
else:
return await hellbot.error(
hell, "Reply to an image/sticker to reverse search it."
)
await hell.edit("Searching on google...")
resp = requests.post(
"https://www.google.com/searchbyimage/upload", files=file, allow_redirects=False
)
webresp = requests.get(
resp.headers.get("Location"),
headers={
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:58.0) Gecko/20100101 Firefox/58.0",
},
)
os.remove(dl_path)
soup = BeautifulSoup(webresp.text, "html.parser")
div = soup.find("div", {"class": "r5a77d"})
if div:
alls = div.find("a")
link = alls["href"]
text = alls.text
await hell.edit(
f"**๐ฏ๐๐๐๐๐ป๐
๐พ ๐ฑ๐พ๐๐๐
๐:** [{text}]({link})", disable_web_page_preview=True
)
else:
return await hell.edit("No results found.")
try:
to_send = []
images = await download_images(text, 3)
for image in images:
to_send.append(InputMediaPhoto(image))
if to_send:
await hell.reply_media_group(to_send)
try:
rmtree("./images")
except:
pass
except:
pass
@on_message("gps", allow_stan=True)
async def gpsLocation(_, message: Message):
if len(message.command) < 2:
return await hellbot.edit(message, "Give some place name to search.")
search_query = await hellbot.input(message)
hell = await hellbot.edit(
message, f"Searching for `{search_query}` on google maps..."
)
geolocator = Nominatim(user_agent="Hellbot")
location: Location = geolocator.geocode(search_query)
if not location:
return await hellbot.delete(hell, "Location not found.")
latitiude = location.latitude
longitude = location.longitude
address = location.address
await hell.reply_location(latitiude, longitude)
await hellbot.delete(hell, f"**๐ ๐ฏ๐
๐บ๐ผ๐พ:** {address}")
@on_message("webshot", allow_stan=True)
async def webScreenshot(_, message: Message):
if len(message.command) < 2:
return await hellbot.edit(message, "Give some url to take screenshot.")
search_query = await hellbot.input(message)
if not is_valid_url(search_query):
return await hellbot.edit(message, "Invalid url.")
hell = await hellbot.edit(message, f"Taking screenshot of `{search_query}`...")
driver, resp = Driver.get()
if not driver:
return await hellbot.error(hell, resp)
driver.get(search_query)
height = driver.execute_script(
"return Math.max(document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight);"
)
width = driver.execute_script(
"return Math.max(document.body.scrollWidth, document.body.offsetWidth, document.documentElement.clientWidth, document.documentElement.scrollWidth, document.documentElement.offsetWidth);"
)
driver.set_window_size(width + 100, height + 100)
image = driver.get_screenshot_as_png()
Driver.close(driver)
with io.BytesIO(image) as result:
result.name = "Hellbot_Webshot.png"
await hell.reply_document(result)
await hell.delete()
try:
os.remove("Hellbot_Webshot.png")
except:
pass
@on_message("cricket", allow_stan=True)
async def cricketScore(_, message: Message):
BASE = "http://static.cricinfo.com/rss/livescores.xml"
page = urllib.request.urlopen(BASE)
soup = BeautifulSoup(page, "html.parser")
result = soup.find_all("description")
final = "**Cricket Live Score:\n\n**"
for match in result:
final += f"{Symbols.bullet} `{match.text}`\n\n"
await hellbot.edit(message, final)
@on_message(["dictionary", "meaning"], allow_stan=True)
async def wordMeaning(_, message: Message):
BASE = "https://api.dictionaryapi.dev/api/v2/entries/en/{0}"
if len(message.command) < 2:
return await hellbot.edit(message, "Give some word to search.")
search_query = await hellbot.input(message)
hell = await hellbot.edit(message, f"Searching for `{search_query}`...")
response = requests.get(BASE.format(search_query))
if response.status_code == 404:
return await hellbot.delete(hell, "Word not found.")
data: dict = response.json()[0]
outStr = ""
outStr += f"**๐W:ord** `{data.get('word', search_query)}`\n"
outStr += f"**๐ Phonetic:** `{data.get('phonetic', 'Not Found')}`\n"
for meaning in data.get("meanings", []):
outStr += f"\n**{Symbols.bullet} Part of Speech:** `{meaning.get('partOfSpeech', 'Not Found').title()}`\n"
for definition in meaning.get("definitions", []):
outStr += f" {Symbols.check_mark} `{definition.get('definition', 'Not Found')}`\n"
synonyms = meaning.get("synonyms", [])
outStr += "**๐ Synonyms:** " + ", ".join(synonyms) if synonyms else "Not Found"
outStr += "\n"
antonyms = meaning.get("antonyms", [])
outStr += "**๐ Antonyms:** " + ", ".join(antonyms) if antonyms else "Not Found"
outStr += "\n"
audio = data.get("phonetics", [])[0].get("audio", "")
if audio:
await hell.reply_audio(audio, caption=outStr)
await hell.delete()
else:
await hell.edit(outStr)
@on_message(["translate", "tr"], allow_stan=True)
async def translateHandler(_, message: Message):
if message.reply_to_message:
if len(message.command) < 2:
return await hellbot.edit(message, "Give some language code to translate.")
toLang = message.command[1]
text = message.reply_to_message.text or message.reply_to_message.caption
elif len(message.command) > 2:
msg = await hellbot.input(message)
toLang = message.command[1]
text = msg.split(" ", 1)[1]
else:
return await hellbot.delete(
message,
f"Either reply to a message with a language code or give input text and language code.\n\n**Example:** `{handler}tr en ใใใซใกใฏไธ็`",
15,
)
hell = await hellbot.edit(message, f"Translating to `{toLang}`...")
text = emoji.demojize(text.strip())
translator = Translator(http2=False)
try:
translated = translator.translate(text, toLang)
outStr = f"**๐ ๐ณ๐๐บ๐๐๐
๐บ๐๐พ๐ฝ ๐ฟ๐๐๐** __{translated.src}__ **๐๐** __{translated.dest}__**:**"
outStr += f"\n\n`{translated.text}`"
await hell.edit(outStr)
except Exception as e:
return await hellbot.error(hell, f"`{str(e)}`")
@on_message("trcode", allow_stan=True)
async def translateCodes(_, message: Message):
outStr = None
if len(message.command) > 1:
language = message.command[1]
fromCodeToLang = LANGUAGES.get(language.lower(), None)
fromLangToCode = LANGCODES.get(language.lower(), None)
if fromCodeToLang:
outStr = f"**{Symbols.bullet} Language Code:** `{language.lower()}`\n**{Symbols.bullet} Language:** `{fromCodeToLang}`"
elif fromLangToCode:
outStr = f"**{Symbols.bullet} Language:** `{language.lower()}`\n**{Symbols.bullet} Language Code:** `{fromLangToCode}`"
else:
outStr = None
if not outStr:
outStr = "**Language Codes:**\n\n"
for code in LANGUAGES:
outStr += f"**{code}**: {LANGUAGES[code]}\n"
await hellbot.edit(message, outStr)
@on_message(["voice", "tts"], allow_stan=True)
async def textToSpeech(_, message: Message):
if message.reply_to_message:
text = message.reply_to_message.text or message.reply_to_message.caption
elif len(message.command) > 2:
text = await hellbot.input(message)
else:
return await hellbot.delete(
message,
f"Either reply to a message with a language code or give input text and language code.\n\n**Example:** `{handler}tr en ใใใซใกใฏไธ็`",
15,
)
hell = await hellbot.edit(message, "Processing...")
text = emoji.demojize(text.strip())
try:
comm = Communicate(
text,
"en-IN-NeerjaExpressiveNeural",
rate="+10%",
volume="+50%",
pitch="+5Hz",
)
path = f"{Config.DWL_DIR}tts{int(time.time())}.mp3"
await comm.save(path)
await message.reply_audio(
path,
caption=f"**๐ ๐ต๐๐๐ผ๐พ:** `{text[:100]}...`",
performer="HellyAI",
title="Hellbot TTS",
thumb="./Hellbot/resources/images/hellbot_logo.png",
)
await hell.delete()
except Exception as e:
return await hellbot.error(hell, f"`{str(e)}`")
@on_message("movie", allow_stan=True)
async def movieSearch(_, message: Message):
if len(message.command) < 2:
return await hellbot.edit(message, "Give a movie name to search on IMDb.")
query = await hellbot.input(message)
hell = await hellbot.edit(message, "Searching...")
try:
movieObj: Movie.Movie = imdb.search_movie(query)[0]
movieId = movieObj.movieID
movieObj = imdb.get_movie(movieId)
movieKeys = list(movieObj.keys())
title = "No title found."
for i in mov_titles:
if i in movieKeys:
title = movieObj[i]
break
airdate = "N/A"
if "original air date" in movieKeys:
airdate = movieObj["original air date"]
elif "year" in movieKeys:
airdate = movieObj["year"]
runtime = movieObj.get("runtimes", ["N/A"])[0] + " min"
rating = str(movieObj.get("rating", "N/A"))
rating += " (by " + str(movieObj.get("votes", "N/A")) + " votes)"
genres = ", ".join(movieObj.get("genres", ["N/A"]))
countries = ", ".join(movieObj.get("countries", ["N/A"]))
languages = ", ".join(movieObj.get("languages", ["N/A"]))
plot = movieObj.get("plot outline", "N/A")
cast = ", ".join([str(actor) for actor in movieObj.get("cast", ["N/A"])])
directors = ", ".join(
[str(actor) for actor in movieObj.get("director", ["N/A"])]
)
writers = ", ".join([str(actor) for actor in movieObj.get("writer", ["N/A"])])
composers = ", ".join(
[str(actor) for actor in movieObj.get("composer", ["N/A"])]
)
box_office_info = movieObj.get("box office", {})
box_office = (
"\n".join([f"{key} --> {value}" for key, value in box_office_info.items()])
if box_office_info
else "N/A"
)
image = movieObj.get("full-size cover url", None)
link = post_to_telegraph(
f"IMDb Search: {title}",
telegraph_msg.format(
image,
title,
movieId,
airdate,
genres,
rating,
runtime,
directors,
writers,
composers,
cast,
countries,
languages,
box_office,
plot,
),
)
await message.reply_photo(
image,
caption=final_msg.format(
title, movieId, airdate, genres, rating, runtime, directors, link
),
parse_mode="html",
)
await hell.delete()
except IndexError:
await hellbot.delete(hell, "No results found.")
except Exception as e:
await hellbot.error(hell, str(e))
HelpMenu("google").add(
"wikipedia",
"<query>",
"Searches for the given query on wikipedia.",
"wikipedia keanu reeves",
).add(
"google", "<query>", "Searches for the given query on google.", "google the hellbot"
).add(
"reverse",
"<reply to image/sticker>",
"Reverse searches the given image/sticker.",
"reverse",
).add(
"gps", "<place name>", "Sends the pin location of the given place.", "gps new york"
).add(
"webshot",
"<url>",
"Takes a screenshot of the given url.",
"webshot https://google.com",
).add(
"cricket", None, "Sends the live cricket scores.", "cricket"
).add(
"dictionary",
"<word>",
"Sends the meaning of the given word.",
"dictionary loyalty",
"An alias of 'meaning' can also be used.",
).add(
"translate",
"<lannguage code> <text/reply to message>",
"Translates the given text to the given language code.",
"translate en ใใใซใกใฏไธ็",
"An alias of 'tr' can also be used.",
).add(
"trcode",
"<language / code>",
"Sends the language code and language name if found.",
"trcode en",
"If no language code is given, sends all the language codes.",
).add(
"voice",
"<text/reply to message>",
"Sends the text as a voice message.",
"voice I'm Helly and this is an Text to Speech Example.",
"An alias of 'tts' can also be used.",
).add(
"movie", # Bugged: to-be-fixed
"<movie name>",
"Sends the details of the given movie.",
"movie the shawshak redemption",
).info(
"Every Google command you need."
).done()
|