You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord.py调用IPB REST API上传文件报NO_FILES错误求助

问题修复方案

核心问题分析

返回NO_FILES错误的原因:

  • 文件上传参数格式错误:你把文件数据放到了URL查询参数(params)里,而IPB REST API要求文件通过multipart/form-data格式提交,需使用requests.post的files参数传递。
  • 获取Discord附件时直接传入Attachment对象给requests.get,应使用附件的url属性。
  • 文件数据格式不符合requests上传规范,需用元组指定文件名、内容和MIME类型。

修复后的代码

import requests
import discord

async def some_command(interaction: discord.Interaction, file: discord.Attachment):
    # 正确获取Discord附件内容,使用附件的url属性
    response1 = requests.get(file.url)
    response1.raise_for_status()  # 捕获附件下载失败的情况
    
    # 构造requests要求的文件上传格式:(文件名, 文件内容, MIME类型)
    file_data = (file.filename, response1.content, file.content_type)
    files = {'files': file_data}
    
    # 调用上传函数
    response = upload_file(
        title="prova",
        category=30,
        author_id=2,
        api_key=IPS4_API_KEY,
        description="provaprov",
        filesupload=files
    )
    print(response)

def upload_file(title, category, author_id, api_key, description, filesupload):
    url = "https://mysite/api/downloads/files"
    # 非文件字段放入表单数据参数
    form_data = {
        "title": title,
        "category": category,
        "author": author_id,
        "description": description
    }
    # API key作为URL查询参数传递
    params = {"key": api_key}
    
    # 按规范发送POST请求:data放表单字段,files放文件,params放API密钥
    response = requests.post(
        url,
        params=params,
        data=form_data,
        files=filesupload
    )
    response.raise_for_status()  # 捕获HTTP请求错误
    return response.json()

关键修复点说明

  • Discord附件获取:使用file.url作为下载地址,确保能正确拉取附件内容。
  • 文件格式构造:采用(文件名, 文件内容, MIME类型)的元组格式,既符合requests的文件上传规范,也匹配IPB API的接收要求。
  • 请求参数拆分:将标题、分类等表单字段放到data参数,文件放到files参数,API密钥放到params,严格遵循IPB API的multipart/form-data提交规则。
  • 错误捕获:添加raise_for_status()可以及时发现请求过程中的HTTP错误,便于调试排查。

内容的提问来源于stack exchange,提问作者Sert-X

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 00:42:11