I have a problem while trying to upload files to discord. If I get it right, algorithm of uploading files to discord is next: I am sending information about the file that i want to upload, discord sending me link where i must put the file, i am put the file to the address given.
I have this code:
def Upload(link, channel, token):
api_url = 'https://discord.com/api/v9/channels/'+channel+'/attachments'
file_name = link[-10:]
file_id = 1
response = requests.get(link)
open(file_name, "wb").write(response.content)
file_size = os.path.getsize(file_name)
upload = {"files":[{"filename":file_name,"file_size":file_size,"id":file_id}]}
file = open(file_name, 'rb')
header = {'authorization' : token}
response = requests.post(api_url, headers=header, json=upload)
put_url = response.json()['attachments'][0]['upload_url']
put_name = response.json()['attachments'][0]['upload_filename']
put_headers = {'Content-Length': str(file_size), 'Connection': 'keep-alive', 'Content-Type': 'image/png', 'authorization' : token}
response = requests.put(put_url, headers=put_headers, data=file)
return response
As first sight everything seems to be working. Response code is 200, everything ok.
But if I try to get headers - print(response.headers), I've got next message:
{'X-GUploader-UploadID': 'bla-bla-bla', 'ETag': '"bla-bla"', 'x-goog-generation': '1682338706931190', 'x-goog-metageneration': '1', 'x-goog-hash': 'bla-bla-bla', 'x-goog-stored-content-length': '1112324', 'x-goog-stored-content-encoding': 'identity', 'Vary': 'Origin', 'Content-Length': '0', 'Date': 'Mon, 24 Apr 2023 12:18:26 GMT', 'Server': 'UploadServer', 'Content-Type': 'text/html; charset=UTF-8'}
I've got:
'Content-Length' = '0', 'Content-Type' = 'text/html; charset=UTF-8'
.
And changing the "put_headers" does not affect it, absolutely. I've sent 1112324 bytes, wtf? I see the 'x-goog-stored-content-length' = '1112324',
but I don't know what's going wrong.
In addition, if I'm trying to use the "uploaded" attachment in next message - I'm receiving error (wrong attachment).
What I'm doing wrong?
I tried to use POST, but discord does not accept this method for attachments.
The problem was in the row 'file_id = 1' I tried to change it to 'file_id = 0' and all started to work! @AKX thank you for help and for very good advice about tempfile and raise_for_status. Its very useful!