hikari.files
#
Utilities and classes for interacting with files and web resources.
LazyByteIteratorish module-attribute
#
LazyByteIteratorish = Union[AsyncIterator[bytes], AsyncIterable[bytes], Iterator[bytes], Iterable[bytes], AsyncIterator[str], AsyncIterable[str], Iterator[str], Iterable[str], AsyncGenerator[bytes, Any], Generator[bytes, Any, Any], AsyncGenerator[str, Any], Generator[str, Any, Any], StreamReader, StreamReader]
Type hint representing an iterator/iterable of bytes.
This may be one of:
typing.AsyncIterator
[bytes
]typing.AsyncIterable
[bytes
]typing.Iterator
[bytes
]typing.Iterator
[bytes
]typing.AsyncIterator
[str
] (assuming UTF-8 encoding).typing.AsyncIterable
[str
] (assuming UTF-8 encoding).typing.Iterator
[str
] (assuming UTF-8 encoding).typing.Iterable
[str
] (assuming UTF-8 encoding).asyncio.StreamReader
aiohttp.StreamReader
Pathish module-attribute
#
Type hint representing a literal file or path.
This may be one of:
str
path.os.PathLike
derivative, such aspathlib.PurePath
andpathlib.Path
.
Rawish module-attribute
#
Type hint representing valid raw data types.
This may be one of:
bytes
bytearray
memoryview
io.BytesIO
io.StringIO
(assuming UTF-8 encoding).
Resourceish module-attribute
#
Type hint representing a file or path to a file/URL/data URI.
This may be one of:
hikari.files.Resource
or a derivative.str
path.os.PathLike
derivative, such aspathlib.PurePath
andpathlib.Path
.bytes
bytearray
memoryview
io.BytesIO
io.StringIO
(assuming UTF-8 encoding).
AsyncReader #
Bases: AsyncIterable[bytes]
, ABC
Protocol for reading a resource asynchronously using bit inception.
This supports being used as an async iterable, although the implementation detail is left to each implementation of this class to define.
Bytes #
Bytes(data: Union[Rawish, LazyByteIteratorish], filename: str, /, mimetype: Optional[str] = None, *, spoiler: bool = False)
Bases: Resource[IteratorReader]
Representation of in-memory data to upload.
PARAMETER | DESCRIPTION |
---|---|
data | The raw data. TYPE: |
filename | The filename to use. TYPE: |
mimetype | The mimetype, or |
spoiler | Whether to mark the file as a spoiler in Discord. TYPE: |
data instance-attribute
#
data: Union[bytes, LazyByteIteratorish] = data
The raw data/provider of raw data to upload.
is_spoiler instance-attribute
#
is_spoiler: bool = spoiler
Whether the file will be marked as a spoiler.
from_data_uri staticmethod
#
Parse a given data URI.
PARAMETER | DESCRIPTION |
---|---|
data_uri | The data URI to parse. TYPE: |
filename | Filename to use. If this is not provided, then this is generated instead. |
RETURNS | DESCRIPTION |
---|---|
Bytes | The parsed data URI as a |
RAISES | DESCRIPTION |
---|---|
ValueError | If the parsed argument is not a data URI. |
save async
#
Save this resource to disk.
This writes the resource file in chunks, and so does not load the entire resource into memory.
PARAMETER | DESCRIPTION |
---|---|
path | The path to save this resource to. If this is a string, the path will be relative to the current working directory. TYPE: |
executor | The executor to run in for blocking operations. If |
force | Whether to overwrite an existing file. TYPE: |
stream #
stream(*, executor: Optional[Executor] = None, head_only: bool = False) -> AsyncReaderContextManager[IteratorReader]
Start streaming the content in chunks.
PARAMETER | DESCRIPTION |
---|---|
executor | Not used. Provided only to match the underlying interface. |
head_only | Not used. Provided only to match the underlying interface. TYPE: |
RETURNS | DESCRIPTION |
---|---|
AsyncReaderContextManager[IteratorReader] | An async context manager that when entered, produces the data stream. |
File #
Bases: Resource[ThreadedFileReader]
A resource that exists on the local machine's storage to be uploaded.
PARAMETER | DESCRIPTION |
---|---|
path | The path to use. If passing a This will all be performed as required in an executor to prevent blocking the event loop. TYPE: |
filename | The filename to use. If this is |
spoiler | Whether to mark the file as a spoiler in Discord. TYPE: |
is_spoiler instance-attribute
#
is_spoiler: bool = spoiler
Whether the file will be marked as a spoiler.
save async
#
Save this resource to disk.
This writes the resource file in chunks, and so does not load the entire resource into memory.
PARAMETER | DESCRIPTION |
---|---|
path | The path to save this resource to. If this is a string, the path will be relative to the current working directory. TYPE: |
executor | The executor to run in for blocking operations. If |
force | Whether to overwrite an existing file. TYPE: |
stream #
stream(*, executor: Optional[Executor] = None, head_only: bool = False) -> AsyncReaderContextManager[ThreadedFileReader]
Start streaming the resource using a thread pool executor.
PARAMETER | DESCRIPTION |
---|---|
executor | The thread executor to run the blocking read operations in. If Only |
head_only | Not used. Provided only to match the underlying interface. TYPE: |
RETURNS | DESCRIPTION |
---|---|
AsyncReaderContextManager[ThreadedFileReader] | An async context manager that when entered, produces the data stream. |
RAISES | DESCRIPTION |
---|---|
IsADirectoryError | If the file's path leads to a directory. |
FileNotFoundError | If the file doesn't exist. |
IteratorReader #
Bases: AsyncReader
Asynchronous file reader that operates on in-memory data.
data class-attribute
instance-attribute
#
data: Union[bytes, LazyByteIteratorish] = field()
The data that will be yielded in chunks.
Resource #
Bases: Generic[ReaderImplT]
, ABC
Base for any uploadable or downloadable representation of information.
These representations can be streamed using bit inception for performance, which may result in significant decrease in memory usage for larger resources.
read async
#
Read the entire resource at once into memory.
data = await resource.read(...)
# ^-- This is a shortcut for the following --v
async with resource.stream(...) as reader:
data = await reader.read()
Warning
If you simply wish to re-upload this resource to Discord via any endpoint in Hikari, you should opt to just pass this resource object directly. This way, Hikari can perform byte inception, which significantly reduces the memory usage for your bot as it grows larger.
PARAMETER | DESCRIPTION |
---|---|
executor | The executor to run in for blocking operations. If |
RETURNS | DESCRIPTION |
---|---|
bytes | The entire resource. |
save async
#
Save this resource to disk.
This writes the resource file in chunks, and so does not load the entire resource into memory.
PARAMETER | DESCRIPTION |
---|---|
path | The path to save this resource to. If this is a string, the path will be relative to the current working directory. TYPE: |
executor | The executor to run in for blocking operations. If |
force | Whether to overwrite an existing file. TYPE: |
stream abstractmethod
#
stream(*, executor: Optional[Executor] = None, head_only: bool = False) -> AsyncReaderContextManager[ReaderImplT]
Produce a stream of data for the resource.
PARAMETER | DESCRIPTION |
---|---|
executor | The executor to run in for blocking operations. If |
head_only | If TYPE: |
RETURNS | DESCRIPTION |
---|---|
AsyncReaderContextManager[AsyncReader] | An async iterable of bytes to stream. This will error on enter if the target resource doesn't exist. |
ThreadedFileReader #
Bases: AsyncReader
Asynchronous file reader that reads a resource from local storage.
This implementation works with pools that exist in the same interpreter instance as the caller, namely thread pool executors, where objects do not need to be pickled to be communicated.
URL #
Bases: WebResource
A URL that represents a web resource.
Note
Some components may choose to not upload this resource directly and instead simply refer to the URL as needed. The main place this will occur is within embeds.
If you need to re-upload the resource, you should download it into a bytes
and pass that instead in these cases.
PARAMETER | DESCRIPTION |
---|---|
url | The URL of the resource. TYPE: |
filename | The filename for the resource. If not specified, it will be obtained from the url. |
WebReader #
Bases: AsyncReader
Asynchronous reader to use to read data from a web resource.
charset class-attribute
instance-attribute
#
Optional character set information, if known.
head_only class-attribute
instance-attribute
#
If True
, then only the HEAD was requested.
In this case, reading data off the object will return an empty byte string
size class-attribute
instance-attribute
#
The size of the resource, if known.
stream class-attribute
instance-attribute
#
stream: StreamReader = field(repr=False)
The aiohttp.StreamReader
to read the content from.
WebResource #
Bases: Resource[WebReader]
, ABC
Base class for a resource that resides on the internet.
The logic for identifying this resource is left to each implementation to define.
For a usable concrete implementation, use hikari.files.URL
instead.
Some components may choose to not upload this resource directly and
instead simply refer to the URL as needed. The main place this will
occur is within embeds. If you need to re-upload the resource, you
should download it into a [`bytes`][] and pass that instead in these cases.
stream #
stream(*, executor: Optional[Executor] = None, head_only: bool = False) -> AsyncReaderContextManager[WebReader]
Start streaming the content into memory by downloading it.
You can use this to fetch the entire resource, parts of the resource, or just to view any metadata that may be provided.
PARAMETER | DESCRIPTION |
---|---|
executor | Not used. Provided only to match the underlying interface. |
head_only | If TYPE: |
Examples:
Downloading an entire resource at once into memory:
async with obj.stream() as stream:
data = await stream.read()
Checking the metadata:
async with obj.stream() as stream:
mimetype = stream.mimetype
if mimetype is None:
...
elif mimetype not in whitelisted_mimetypes:
...
else:
...
Fetching the data-uri of a resource:
async with obj.stream() as stream:
data_uri = await stream.data_uri()
RETURNS | DESCRIPTION |
---|---|
AsyncReaderContextManager[WebReader] | An async context manager that when entered, produces the data stream. |
RAISES | DESCRIPTION |
---|---|
BadRequestError | If a 400 is returned. |
UnauthorizedError | If a 401 is returned. |
ForbiddenError | If a 403 is returned. |
NotFoundError | If a 404 is returned. |
ClientHTTPResponseError | If any other 4xx is returned. |
InternalServerError | If any other 5xx is returned. |
HTTPResponseError | If any other unexpected response code is returned. |
ensure_path #
Convert a path-like object to a pathlib.Path
instance.
ensure_resource #
ensure_resource(url_or_resource: Resourceish) -> Resource[AsyncReader]
Given a resource or string, convert it to a valid resource as needed.
PARAMETER | DESCRIPTION |
---|---|
url_or_resource | The item to convert. If a TYPE: |
RETURNS | DESCRIPTION |
---|---|
Resource | The resource to use. |
generate_filename_from_details #
generate_filename_from_details(*, mimetype: Optional[str] = None, extension: Optional[str] = None, data: Optional[bytes] = None) -> str
Given optional information about a resource, generate a filename.
PARAMETER | DESCRIPTION |
---|---|
mimetype | The mimetype of the content, or |
extension | The file extension to use, or |
data | The data to inspect, or |
RETURNS | DESCRIPTION |
---|---|
str | A generated quasi-unique filename. |
guess_file_extension #
guess_mimetype_from_data #
Guess the mimetype of some data from the header.
Warning
This function only detects valid image headers that Discord allows the use of. Anything else will go undetected.
PARAMETER | DESCRIPTION |
---|---|
data | The byte content to inspect. TYPE: |
RETURNS | DESCRIPTION |
---|---|
Optional[str] | The mimetype, if it was found. If the header is unrecognised, then |