# Sending files

> Attach files to a bot’s messages, edits, interaction replies and webhooks with multipart/form-data, as discord.js and discord.py already do. The size limits, which files show inline, alt text, attachment:// in embeds and components, files in ephemeral messages, and keeping or removing files when you edit.

## How it works

Klang takes files the way Discord’s API does: one `multipart/form-data` request with the message
as JSON in a `payload_json` field and each file in a `files[n]` field. Libraries already build it,
so their usual calls work:

```js
// discord.js
await channel.send({ content: 'Here you go', files: [{ attachment: buffer, name: 'cat.png' }] });
```

```py
# discord.py
await channel.send("Here you go", file=discord.File("cat.png"))
```

You can send files with:

- a new message: `POST /channels/{channel.id}/messages`;
- an edit: `PATCH /channels/{channel.id}/messages/{message.id}`;
- an interaction reply: the callback with type `4`, or `7` to update the message of a component;
- an interaction’s follow-ups and its `@original` message: `POST /webhooks/{app.id}/{token}` and
  `PATCH /webhooks/{app.id}/{token}/messages/{message.id}`;
- an incoming webhook: `POST /webhooks/{webhook.id}/{webhook.token}` and its message edits.

In `payload_json`, `attachments` describes the files: `[{ "id": 0, "filename": "cat.png" }]`,
where `id` is the `n` of `files[n]`. A `filename` there replaces the one in the form, and
`description` is the file’s [alt text](https://docs.klang.gg/bots/files/#alt-text).

Each file comes back in the message’s `attachments`, in Discord’s shape: `id`, `filename`, `size`,
`url`, `proxy_url` (the same URL: Klang’s files don’t expire), `content_type`, `description` when
it has one and, for images, `width` and `height`.

## Limits

| What                     | Limit                                                                                      |
| ------------------------ | ------------------------------------------------------------------------------------------ |
| Size of a file           | The server’s plan: 25 MB, 100 MB with Tier 1, 250 MB with Tier 2. In a DM or group, 25 MB. |
| Size of all the files    | The same number, for the whole message.                                                    |
| Files per message        | 10.                                                                                        |
| Your bot’s storage       | 2 GB in total while bots are in beta.                                                      |
| Uploads at the same time | 2 per bot. Another one gets `429` with `Retry-After`.                                      |
| Size of a request        | 100 MB for now, files and JSON together, whatever the server’s plan.                       |

A file over a limit gets `413` with error code `40005` (“Request entity too large”), and the
message names the limit. Klang stops reading the file at that point and keeps nothing from the
request: no message and no file. Too many files gets `400` with `50035` on `attachments`. A
request over 100 MB is turned away before it reaches Klang, with a `413` that has no JSON body.

Your bot needs **Attach Files** in the channel to send files in its own messages and edits.
Interaction replies don’t: as in Discord, the person chose to use your command there.

## Which files show inline

Klang looks at a file’s first bytes, not its name or its declared type. PNG, JPEG, WebP, GIF,
MP4, WebM, MP3, OGG, WAV and PDF files show in the chat with their real `content_type`. Anything
else is stored as `application/octet-stream` and downloaded when someone opens it, whatever its
name says: a `.png` that isn’t a picture is a download.

## Alt text

Give a file a `description` and Klang keeps it as its alt text: screen readers read it, and Klang
shows it as the image’s text where the picture can’t load. Up to 1,024 characters.

```js
await channel.send({
  files: [
    {
      attachment: './north-pier.png',
      name: 'north-pier.png',
      description: 'The north pier at low tide, with two boats on the sand',
    },
  ],
});
```

```python
await channel.send(
    file=discord.File(
        "north-pier.png", description="The north pier at low tide, with two boats on the sand"
    )
)
```

It comes back in the attachment, and only when the file has one:

```json
{
  "id": "1575719330800336896",
  "filename": "north-pier.png",
  "content_type": "image/png",
  "size": 179,
  "url": "https://cdn.klangcdn.com/adjuntos/251916454076743680/251916457763536896-tJGv8kRUb3nQNxYxyrgKjQ",
  "proxy_url": "https://cdn.klangcdn.com/adjuntos/251916454076743680/251916457763536896-tJGv8kRUb3nQNxYxyrgKjQ",
  "width": 96,
  "height": 64,
  "description": "The north pier at low tide, with two boats on the sand"
}
```

A file’s alt text is set when it’s sent: an edit that keeps the file keeps its text.

## Pointing at a file: `attachment://`

An embed can show one of the message’s files with `attachment://` and its filename, in `image`,
`thumbnail`, `author.icon_url` and `footer.icon_url`:

```js
// discord.js
await channel.send({
  embeds: [new EmbedBuilder().setTitle('A cat').setImage('attachment://cat.png')],
  files: [new AttachmentBuilder(buffer, { name: 'cat.png' })],
});
```

Klang stores the file’s URL in its place, so the embed you get back has the attachment’s `url`.
An `attachment://` name that matches no file of the message is left out of the embed.

[Layout components](https://docs.klang.gg/bots/components/#layout-components) work the same way: a thumbnail’s or gallery item’s `media.url`,
and a file component’s `file.url`, can be `attachment://filename`. There, a name that matches no
file is an error (`50035`), as in Discord.

## Editing files

When you edit a message, the files you send are added to the ones it has. To choose which ones
stay, send `attachments` with the `id` of each file to keep: the rest are removed. An empty list
removes them all.

```js
// discord.js: keep one file and add another
await message.edit({ attachments: [message.attachments.first()], files: [newFile] });
// remove them all
await message.removeAttachments();
```

```py
# discord.py
await message.edit(attachments=[message.attachments[0], discord.File("new.png")])
```

A component you send back with one of the message’s own attachment URLs works only if that file
stays after the edit. In a new message, upload the file and use `attachment://` instead.

## Files in ephemeral messages

An [ephemeral](https://docs.klang.gg/bots/interactions/#ephemeral-messages) reply, follow-up or edit takes files like
any other, with the same limits:

```js
await interaction.reply({
  content: 'Only you can see this chart.',
  files: ['./tides-week.png'],
  flags: MessageFlags.Ephemeral,
});
```

```python
await interaction.response.send_message(
    "Only you can see this chart.", file=discord.File("tides-week.png"), ephemeral=True
)
```

Ephemeral messages aren’t stored, and neither are their files for long: Klang deletes them **an
hour after the command was used**, or before, when your bot deletes the message or an edit leaves
them out. Their addresses stop working then. Don’t send anything in one that the person needs to
keep: a message that isn’t ephemeral keeps its files.

## Not supported yet

- **Files with callbacks that don’t send a message** (`5`, `6`, `8` and `9`) get `400`.
- **Voice messages** (`duration_secs` and `waveform`) and spoiler flags (`is_spoiler`). Naming a
  file `SPOILER_…` keeps the name, but it isn’t hidden.
