Search code examples
pythonpython-requestsdiscordbots

How to add images with Discord API and Python Requests


I want to send an image that I have stored on my computer through this code

import requests
import time
headers = {'authorization': TOKEN, 'Content-Type': 'application/json'}

url = f"https://discord.com/api/v9/channels/{CHANNEL}/messages"
        data = { "content": message }
        files = {
            'file': (open('image.png', 'rb')),
        }
        r = requests.post(url, headers=headers, json=data, files=files)
        if r.status_code == 200:
            print(f"sent message to {CHANNEL} {r}")
        else:
            print(f"error while sending to {CHANNEL} {r}")

But I ended up getting this error.

error while sending to CHANNELID <Response [400]>

I don't quite understand what the problem is, as it should work.

I tried to use embed or attachment, but it got same error.


Solution

  • When uploading files, Discord API expects that the Content-Type is set to multipart/form-data. If you want to let Discord automatically discover the Content-Type, you can omit this header in your request. I have tested the code below.

    import requests
    import time
    headers = {'authorization': TOKEN}
    
    url = f"https://discord.com/api/v9/channels/{CHANNEL}/messages"
    data = { "content": message }
    files = {
        'file': (open('image.png', 'rb')),
    }
    r = requests.post(url, headers=headers, json=data, files=files)
    if r.status_code == 200:
        print(f"sent message to {CHANNEL} {r}")
    else:
        print(f"error while sending to {CHANNEL} {r}")