files.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import os
  2. from PIL import Image
  3. import math
  4. from pyrogram import Client, raw
  5. from pyrogram.file_id import FileId
  6. STICKER_DIMENSIONS = (512, 512)
  7. async def resize_file_to_sticker_size(file_path: str) -> str:
  8. im = Image.open(file_path)
  9. if (im.width, im.height) < STICKER_DIMENSIONS:
  10. size1 = im.width
  11. size2 = im.height
  12. if im.width > im.height:
  13. scale = STICKER_DIMENSIONS[0]/size1
  14. size1new = STICKER_DIMENSIONS[0]
  15. size2new = size2 * scale
  16. else:
  17. scale = STICKER_DIMENSIONS[1]/size2
  18. size1new = size1 * scale
  19. size2new = STICKER_DIMENSIONS[1]
  20. size1new = math.floor(size1new)
  21. size2new = math.floor(size2new)
  22. sizenew = (size1new, size2new)
  23. im = im.resize(sizenew)
  24. else:
  25. im.thumbnail(STICKER_DIMENSIONS)
  26. try:
  27. os.remove(file_path)
  28. file_path = f"{file_path}.png"
  29. return file_path
  30. finally:
  31. im.save(file_path)
  32. async def upload_document(client: Client, file_path: str, chat_id: int) -> raw.base.InputDocument:
  33. media = await client.send(
  34. raw.functions.messages.UploadMedia(
  35. peer=await client.resolve_peer(chat_id),
  36. media=raw.types.InputMediaUploadedDocument(
  37. mime_type=client.guess_mime_type(file_path) or "application/zip",
  38. file=await client.save_file(file_path),
  39. attributes=[
  40. raw.types.DocumentAttributeFilename(
  41. file_name=os.path.basename(file_path)
  42. )
  43. ]
  44. )
  45. )
  46. )
  47. return raw.types.InputDocument(id=media.document.id, access_hash=media.document.access_hash, file_reference=media.document.file_reference)
  48. async def get_document_from_file_id(file_id: str) -> raw.base.InputDocument:
  49. decoded = FileId.decode(file_id)
  50. return raw.types.InputDocument(id=decoded.media_id, access_hash=decoded.access_hash, file_reference=decoded.file_reference)