首页 > 解决方案 > 我如何向不和谐请求添加附件?

问题描述

我正在尝试制作发送不和谐消息+附件的python脚本,但我不知道该怎么做。此外,我需要从我的不和谐帐户发送消息,而不是从机器人/网络钩子发送消息。到目前为止,这是我的代码:

payload = {
    'content': "Hello" 
}

header = {
    'authorization': "token"
}

r = requests.post("https://discord.com/api/v9/channels/874777490781003787/messages?limit=50", data=payload, headers=header)

标签: pythonapipython-requestsdiscord

解决方案


使用discord.py而不是 requests 库的一站式解决方案:

with open('my_image.png', 'rb') as f: channel.send(file=discord.File(f))

如果您确实必须使用 requests 库,则必须使用Content-Type: multipart/form-data文件属性Content-Disposition: form-data; name="file"; filename="your_attachment.png" Content-Type: image/png和消息属性来上传文件Content-Disposition: form-data; name="payload_json" {"content":"your_content","tts":false}

所以把它们放在一个嵌套在这样的字典中的元组中:

files = {
    'file': ('./picture.jpg', open('./picture.jpg', 'rb')),
    
}

r = requests.post("https://discord.com/api/v9/channels/874777490781003787/messages?limit=50", data=payload, headers=header, files=files)

在此处阅读文档


推荐阅读