reverse.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import os
  2. from asyncio import get_running_loop
  3. from random import randint
  4. import aiofiles
  5. import aiohttp
  6. import requests
  7. from bs4 import BeautifulSoup
  8. from pyrogram import filters
  9. from wbb import app
  10. from wbb.core.decorators.errors import capture_err
  11. from wbb.modules.nsfw import get_file_id_from_message
  12. @app.on_message(filters.command("reverse"))
  13. @capture_err
  14. async def reverse_image_search(_, message):
  15. if not message.reply_to_message:
  16. return await message.reply_text(
  17. "Reply to a message to reverse search it."
  18. )
  19. reply = message.reply_to_message
  20. if (
  21. not reply.document
  22. and not reply.photo
  23. and not reply.sticker
  24. and not reply.animation
  25. and not reply.video
  26. ):
  27. return await message.reply_text(
  28. "Reply to an image/document/sticker/animation to reverse search it."
  29. )
  30. m = await message.reply_text("Downloading")
  31. file_id = await get_file_id_from_message(reply)
  32. if not file_id:
  33. return await m.edit("Can't reverse that")
  34. image = await app.download_media(
  35. file_id, f"{randint(1000, 10000)}.jpg"
  36. )
  37. await m.edit("Uploading to google's server")
  38. async with aiofiles.open(image, "rb") as f:
  39. if image:
  40. search_url = "http://www.google.com/searchbyimage/upload"
  41. multipart = {
  42. "encoded_image": (image, await f.read()),
  43. "image_content": "",
  44. }
  45. def post_non_blocking():
  46. return requests.post(
  47. search_url, files=multipart, allow_redirects=False
  48. )
  49. loop = get_running_loop()
  50. response = await loop.run_in_executor(
  51. None, post_non_blocking
  52. )
  53. location = response.headers.get("Location")
  54. os.remove(image)
  55. else:
  56. return await m.edit("Something wrong happened.")
  57. headers = {
  58. "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:58.0) Gecko/20100101 Firefox/58.0"
  59. }
  60. await m.edit("Scraping query")
  61. async with aiohttp.ClientSession() as session:
  62. async with session.get(location, headers=headers) as resp:
  63. soup = BeautifulSoup(await resp.text(), "html.parser")
  64. div = soup.find_all("div", {"class": "r5a77d"})[0]
  65. anchor_element = div.find("a")
  66. text = anchor_element.text
  67. try:
  68. await m.edit("Trying to send a photo")
  69. await app.send_photo(
  70. message.chat.id,
  71. photo=f"https://webshot.amanoteam.com/print?q={location}",
  72. caption=f"**Result**: [{text}]({location})",
  73. )
  74. await m.delete()
  75. except Exception:
  76. text = f"**Result**: [Link]({location})"
  77. await m.edit(text)