Files and Media¶
A panel shows an image from a link or from a file uploaded with its message. A link goes straight into a builder, and Discord loads the image itself. An upload has two parts that travel apart: the builder puts the file's name in the panel, and the file goes with the request that sends or edits the message.
This panel shows a member's avatar from its link beside a chart the bot draws and uploads:
import io
import discord
from cascadeui import StatefulLayoutView, card, gallery, image_section
async def draw_weekly_chart(member):
# Stands in for your own drawing code, which returns the chart as PNG bytes.
return await member.display_avatar.with_format("png").read()
class WeeklyStats(StatefulLayoutView):
def __init__(self, *, member, **kwargs):
super().__init__(**kwargs)
self.member = member
async def on_load(self):
png = await draw_weekly_chart(self.member)
self.chart = discord.File(io.BytesIO(png), filename="weekly.png")
self.clear_items()
self.add_item(card(
image_section(
f"## {self.member.display_name}", "This week",
url=self.member.display_avatar, # (1)!
),
gallery(self.chart), # (2)!
))
def get_files(self): # (3)!
return self.chart
- A link: Discord loads the avatar from its address.
- An upload: the file stands for its name,
attachment://weekly.png, which shows the file uploaded with the message. - Gives the library the chart for every send and edit it makes, including the ones no code of yours calls.
Images From a Link¶
gallery(), image_section(), and a leaderboard's banner= take a web address, and Discord loads the image
from it. Anything with a string .url stands for its address, so a member's avatar works as
member.display_avatar as well as member.display_avatar.url. A link carries no file and needs nothing more, and
Layout Builders shows each builder.
file_attachment() is the one that takes no link: Discord's File component shows only a file uploaded with
the message, and a web address raises ValueError.
Uploading a File¶
Give the builder the discord.File, and give send() the same file:
import discord
from cascadeui import StatefulLayoutView, card, gallery
class PhotoOfTheWeek(StatefulLayoutView):
def __init__(self, *, photo, **kwargs):
super().__init__(**kwargs)
self.add_item(card("## Photo of the Week", gallery(photo))) # (1)!
photo = discord.File("photos/week_44.png")
await PhotoOfTheWeek(interaction=interaction, photo=photo).send(files=[photo]) # (2)!
- Puts the file's name,
attachment://week_44.png, in the panel.gallery("attachment://week_44.png")names the same file. - Uploads the file with the message.
file=phototakes a single one.
The builder takes the file's description as the image's alt text, and blurs the image when the file is a
spoiler (discord.File(..., spoiler=True)). A description= or spoiler= given to the builder wins over
the file's.
In a StatefulView the name goes in an embed, embed.set_image(url=photo.uri), and the file goes to
send() the same way.
Edits that pass no files keep the ones the message holds, so a panel whose images never change needs nothing
more. A view whose files change returns them from get_files().
A name with no file
Discord refuses a send or edit that leaves an attachment:// name in a panel without its file, and an
embed image naming a missing file shows no image. send() logs a warning naming each such reference,
and so does an edit known to leave one: one whose attachments= list leaves it out, or, with
get_files(), one whose message never got the file.
Files the View Supplies¶
The code that calls send() is not the only sender. The library sends and edits the view itself where no
caller can pass a file: reload(), a render refresh_cooldown_ms held
back, a push or pop, and the final edit of a timeout or exit(). A file the view draws in on_load() does
not exist yet when reload() is called. Override get_files() to return the files the panel names, as the
panel at the top of this page does, and every request the library makes carries them:
- A send uploads a file for each name the panel shows, unless its own
files=already carries one by that name. - An edit uploads only when the panel shows a name new to the message or a file whose contents changed, and then uploads a file for every name the panel shows, because an edit's file list replaces the message's.
- In a V2 panel, the hook's files the panel does not show go up too, while the request has room under Discord's ten, and wait on the message unseen: Discord shows a V2 panel only the uploads it names. A V1 message shows every upload, so a V1 panel sends only the files it names.
- Return the same
discord.Filewhile its contents stay the same. A new one with the same contents is not uploaded again: files are compared by their bytes.
The hook must be a plain def, since it runs while a request is being put together: an async def raises
TypeError when the class is defined. Build the files where the data loads, usually on_load(), and return
them here. A leaderboard already returns its banner's file, so an override on one adds to
super().get_files(), which returns a list or None:
Changing a File¶
A view with get_files() changes a file the way it changes anything else: it builds the new file, renders,
and the edit uploads it. The panel at the top of this page draws its chart in on_load(), so
await self.reload() draws a new one and puts it on the message.
Without the hook, pass the files to refresh(attachments=[...]) along with the new panel:
async def swap_photo(self, photo):
self.clear_items()
self.add_item(card("## Photo of the Week", gallery(photo)))
await self.refresh(attachments=[photo])
The list replaces the message's files, so it needs a file for every name the panel shows, not only the one
that changed: a panel showing four images passes four. attachments=[] removes every file, for a panel that
no longer shows one.
A panel that pages through images returns every page's file from get_files(). The first send uploads them
all and the pages not shown wait on the message, so a page turn uploads nothing. A message holds ten files,
so past ten the pages that did not fit go up when they are shown. Without the hook, the first
send(files=[...]) can upload every page at once too.
Fetching a File From a Link¶
fetch_as_file()
downloads a link into a discord.File, for a panel that needs an upload rather than a link: a
file_attachment(), which shows only uploads, or an image that should stay after its link stops working.
from cascadeui import fetch_as_file
avatar = await fetch_as_file(member.display_avatar.url, "avatar.png")
Pass one aiohttp.ClientSession as session= when a callback fetches several, so they share one connection
pool:
import aiohttp
async with aiohttp.ClientSession() as session:
cover = await fetch_as_file(cover_url, "cover.png", session=session)
back = await fetch_as_file(back_url, "back.png", session=session)
An error status raises aiohttp.ClientResponseError, so an error page never becomes the file. A body larger
than max_bytes raises ValueError, and the download stops as soon as it passes the limit. The default,
100 MiB, is the most Discord takes from a bot, and max_bytes=interaction.guild.filesize_limit refuses whatever
the server would. spoiler= and description= go to the discord.File.
After a Restart¶
Discord keeps a message's uploads for as long as the message lives, so a
persistent panel restored after a restart shows its images with
nothing uploaded again. A name the panel shows for the first time after the restart needs its file, through
refresh(attachments=[...]) or get_files(). A panel with get_files() uploads its files again on its first
edit after a restart, since it cannot tell which ones its message already holds.
Less common cases
Refused references. A media argument that is not a string, a discord.File, a
discord.UnfurledMediaItem, or something with a string .url raises TypeError where the builder is
called, naming the builder and the argument. An empty or blank one raises ValueError, except a blank
banner=, which means no banner.
file= and files= together. discord.py raises TypeError, so pass one.
A file passed again. Every send and edit the library makes reads a file from its start, so a file
sent once can go out again. A direct discord.py call such as channel.send(file=...) does not, and
uploads an empty file the second time: give it a new discord.File.
A failed send closes the files given to it, so a file opened from a path is not left open.
Ten files. A message holds at most ten, and Discord refuses a request carrying more. The library
warns when get_files() takes a request past ten.
A file passed beside the hook. A file given to send(files=) or refresh(attachments=) goes out in
place of the hook's for its name in that call, and the next edit uploads the hook's file again if the
two may differ (a discord.Attachment kept from the message counts as different, since its contents
were never read). A file given for a name the hook does not supply stays on the message. A view with
get_files() keeps the contents of each file a caller gives it until an upload replaces it, so a later
edit can upload it again: a file opened from a path is held in memory whole.
Slow downloads. A fetch_as_file() without session= opens its own, with aiohttp's default limit
of five minutes in all. Pass a session with a shorter timeout for a download someone waits on.
A leaderboard's banner. A restored leaderboard whose banner is an upload, sent to a new message, reads the banner back from its old one.
Related¶
- Layout Builders:
gallery(),image_section(), andfile_attachment(). - Ephemeral Views: the Continue button.
- Panels That Survive Restarts: restoring a panel after a restart.
get_files()andfetch_as_file(): every parameter.examples/v2_attachments.py: a gallery, thumbnails, a download, and a swap throughget_files().