1
|
|
|
# Copyright Pincer 2021-Present |
|
|
|
|
2
|
|
|
# Full MIT License can be found in `LICENSE` at the project root. |
3
|
|
|
|
4
|
|
|
from __future__ import annotations |
5
|
|
|
|
6
|
|
|
from dataclasses import dataclass |
7
|
|
|
from io import BytesIO |
8
|
|
|
import os |
9
|
|
|
from typing import Optional |
10
|
|
|
|
11
|
|
|
from PIL.Image import Image |
12
|
|
|
|
13
|
|
|
from ...utils import APIObject |
14
|
|
|
|
15
|
|
|
|
16
|
|
|
@dataclass |
17
|
|
|
class File(APIObject): |
18
|
|
|
""" |
19
|
|
|
A file that is prepared by the user to be send to the discord |
20
|
|
|
API. |
21
|
|
|
|
22
|
|
|
:param content: |
23
|
|
|
File bytes. |
24
|
|
|
|
25
|
|
|
:param filename: |
26
|
|
|
The name of the file when its uploaded to discord. |
27
|
|
|
""" |
28
|
|
|
|
29
|
|
|
content: bytes |
30
|
|
|
filename: str |
31
|
|
|
|
32
|
|
|
@classmethod |
33
|
|
|
def from_file(cls, filepath: str, filename: str = None) -> File: |
34
|
|
|
""" |
35
|
|
|
:param filepath: |
36
|
|
|
The path to the file you want to send. Must be string. The file's |
37
|
|
|
name in the file path is used as the name when uploaded to discord |
38
|
|
|
by default. |
39
|
|
|
|
40
|
|
|
:param filename: |
41
|
|
|
The name of the file. Will override the default name. |
42
|
|
|
""" |
43
|
|
|
|
44
|
|
|
with open(filepath, "rb") as data: |
45
|
|
|
file = data.read() |
46
|
|
|
|
47
|
|
|
return cls( |
48
|
|
|
content=file, |
49
|
|
|
filename=filename or os.path.basename(filepath) |
50
|
|
|
) |
51
|
|
|
|
52
|
|
|
@classmethod |
53
|
|
|
def from_pillow_image( |
54
|
|
|
cls, |
|
|
|
|
55
|
|
|
img: Image, |
56
|
|
|
filename: str, |
57
|
|
|
image_format: Optional[str] = None, |
58
|
|
|
**kwargs |
59
|
|
|
) -> File: |
60
|
|
|
""" |
61
|
|
|
Creates a file object from a PIL image |
62
|
|
|
Supports GIF, PNG, JPEG, and WEBP. |
63
|
|
|
|
64
|
|
|
:param img: |
65
|
|
|
Pillow image object. |
66
|
|
|
|
67
|
|
|
:param filename: |
68
|
|
|
The filename to be used when uploaded to discord. The extension is |
69
|
|
|
used as image_format unless otherwise specified. |
70
|
|
|
|
71
|
|
|
Keyword Arguments: |
72
|
|
|
|
73
|
|
|
:param image_format: |
74
|
|
|
The image_format to be used if you want to override the file |
75
|
|
|
extension. |
76
|
|
|
|
77
|
|
|
:return: File |
78
|
|
|
""" |
79
|
|
|
|
80
|
|
|
if image_format is None: |
81
|
|
|
image_format = os.path.splitext(filename)[1][1:] |
82
|
|
|
|
83
|
|
|
if image_format == "jpg": |
84
|
|
|
image_format = "jpeg" |
85
|
|
|
|
86
|
|
|
# https://stackoverflow.com/questions/33101935/convert-pil-image-to-byte-array |
87
|
|
|
# Credit goes to second answer |
88
|
|
|
img_byte_arr = BytesIO() |
89
|
|
|
img.save(img_byte_arr, format=image_format) |
90
|
|
|
img_bytes = img_byte_arr.getvalue() |
91
|
|
|
|
92
|
|
|
return cls( |
93
|
|
|
content=img_bytes, |
94
|
|
|
filename=filename |
95
|
|
|
) |
96
|
|
|
|