reverse.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import os
  2. from random import randint
  3. import aiofiles
  4. import aiohttp
  5. import requests
  6. from asyncio import get_running_loop
  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 m.edit("Can't reverse that")
  34. image = await app.download_media(file_id, f"{randint(1000, 10000)}.jpg")
  35. await m.edit("Uploading to google's server")
  36. async with aiofiles.open(image, "rb") as f:
  37. if image:
  38. search_url = "http://www.google.com/searchbyimage/upload"
  39. multipart = {
  40. "encoded_image": (image, await f.read()),
  41. "image_content": "",
  42. }
  43. def post_non_blocking():
  44. return requests.post(
  45. search_url, files=multipart, allow_redirects=False
  46. )
  47. loop = get_running_loop()
  48. response = await loop.run_in_executor(None, post_non_blocking)
  49. location = response.headers.get("Location")
  50. os.remove(image)
  51. else:
  52. return await m.edit("Something wrong happened.")
  53. headers = {
  54. "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:58.0) Gecko/20100101 Firefox/58.0"
  55. }
  56. await m.edit("Scraping query")
  57. async with aiohttp.ClientSession() as session:
  58. async with session.get(location, headers=headers) as resp:
  59. soup = BeautifulSoup(await resp.text(), "html.parser")
  60. div = soup.find_all("div", {"class": "r5a77d"})[0]
  61. anchor_element = div.find("a")
  62. text = anchor_element.text
  63. try:
  64. await m.edit("Trying to send a photo")
  65. await app.send_photo(
  66. message.chat.id,
  67. photo=f"https://webshot.amanoteam.com/print?q={location}",
  68. caption=f"**Result**: [{text}]({location})",
  69. )
  70. await m.delete()
  71. except Exception:
  72. text = f"**Result**: [Link]({location})"
  73. await m.edit(text)