【问题标题】:How can I send a picture with the Discord API and Python Requests如何使用 Discord API 和 Python 请求发送图片
【发布时间】:2021-09-30 15:06:38
【问题描述】:

这是我第一次在这里发帖,我想问你是否可以帮助我找到一种方法,使用 Discord API with Python Requests 在频道中发送图片。 (我不是在谈论 discord.py 或 Discord Bots)。

为了编写代码,我首先检查了网络选项卡并上传了一张图片以查看它实际发送的请求。 在表单数据中,我可以看到它正在发送两个信息:

file: (binary)
payload_json: {"content": "", "tts": false}

最后需要的是在 header 中发送我们的 Discord Token

当我尝试编写代码时,他们给我的回应是

{"message": "Cannot send an empty message", "code": 50006}

即使我在内容中添加文本,它们也会给我同样的错误。 我想我没有在数据中输入正确的信息。

代码如下:

import requests

# User's Token
header = {
    'authorization': "token",
}

# Data
payload = {
    "file" : open("picture.jpg", "rb").read(), # The picture that we want to send in binary
    "payload_json": {"content":"","tts":False},
}

channel_id = "829628868860051480" # Channel where we send the picture

r = requests.post(f"https://discord.com/api/v9/channels/{channel_id}/messages", data=payload, headers=header).text
print(r)

【问题讨论】:

  • I'm not talking here about discord.py or Discord Bots 为什么你不能只使用 discord.py,你很难尝试使用请求手动发送数据。与 discord.py it is a single line of code with open('my_image.png', 'rb') as f: channel.send(file=discord.File(f))
  • @user9321739 听起来他们想在用户帐户上发送消息。这是针对Discord's ToS。 (我可能错了,但他们确实说“我在这里不是在谈论 discord.py 或 Discord Bots”)

标签: python image python-requests discord


【解决方案1】:

您必须根据docs 将文件作为multipart/form-data 发送。

将它们放在嵌套在字典中的元组中。

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

r = requests.post(f"https://discord.com/api/v9/channels/{channel_id}/messages", data=payload, headers=header, files=files).text

【讨论】:

    【解决方案2】:

    感谢isopach,我想出了要写什么,我把它贴在这里以防有人需要和我做同样的事情

    import requests
    
    # User's Token
    header = {
        'authorization': "token",
    }
    
    # File
    files = {
        "file" : ("./picture.jpg", open("./picture.jpg", 'rb')) # The picture that we want to send in binary
    }
    
    # Optional message to send with the picture
    payload = {
        "content":"message"
    }
    
    channel_id = "channel_id" # Channel where we send the picture
    
    r = requests.post(f"https://discord.com/api/v9/channels/{channel_id}/messages", data=payload, headers=header, files=files)
    

    【讨论】:

    • 它只是显示为您可以下载的通用文件,而不是图像。即使你点击它保存它仍然无法打开
    猜你喜欢
    • 1970-01-01
    • 2021-09-01
    • 2021-10-12
    • 2021-07-21
    • 2022-07-08
    • 2018-10-29
    • 1970-01-01
    • 2023-03-08
    • 2018-11-22
    相关资源
    最近更新 更多