Uploading files from a discord bot into discord is a bit tricky, and it's not immediately obvious that it is something you can do. This post will summarize the method I found to work, and hopefully it shows that it is not too complicated.
The discord developer docs particularly for uploading files needs some improvement (well, at least that's the case when I'm writing this). Perhaps an output of this writing will be a contribution there. However this blog does a great job documenting examples of the discord API in general.
An assumption that I will make here is that you've received an discord interaction which you are free to respond to in order to reply to a particular bot query. Then let's say that you have a particular file that you want to respond with.
Any well-designed HTTP library will provide you with an API for dealing with "multipart form-data". If you are using requests you can see an example of that part of the API in this stackoverflow question summarizing the usage.
I am making use of httpx
since I'm using async python and also desire a
similar experience to using the requests library, and this is the code required
for responding to the interaction with a file upload (here are the httpx
file
upload docs):
async with httpx.AsyncClient() as client, ndfd.gen_reports() as fps:
r = await client.patch(
url,
data={"payload_json": json.dumps({"embeds": [{"title": f"Relative Humidity for {location}"}]})},
files=[
(
"files[0]",
("rh.png", open(fps["rh"]["png"].name, "rb"), "image/png"),
),
],
)
Overall, you can see alignment with the discord file upload API docs. When responding to an interaction you can send JSON data in payload_json
and you can attach files using the files[n]
syntax. In this case I'm uploading a generated image file.
It turns out that the httpx
is a bit more ergonomic that the requests
API, I'm a fan!