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

discord.py中message.attachments无法正常工作,附件下载功能报错如何解决?

问题原因分析

你的代码存在4处核心错误,直接触发运行报错:

  • 变量未定义:你在代码中直接使用了message变量,但命令回调函数的入参只有ctx、strucaction、strucname,没有定义过message,正确的调用方式是通过上下文对象获取触发消息:ctx.message
  • 错误调用列表方法:ctx.message.attachments返回的是附件对象的列表,不能直接对整个列表调用save()方法,需要先取出单个附件对象再执行保存操作
  • 路径格式化失效:你定义的cmp_structure_path路径没有预留格式化占位符{},调用.format(filename)不会把文件名拼入路径,无法生成合法的保存路径
  • 冗余的文件名提取逻辑:discord.py的Attachment对象原生带有filename属性,不需要手动将附件列表转成字符串再拆分提取文件名,反而容易出现索引异常
修正后的可用代码
import discord
from discord.ext import commands

# ---CONFIG---
cmp_structure_path = '/root/servers/creative/server/world-cmp0/generated/minecraft/structures/'
# ---CONFIG---

class structure(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
    @commands.has_role(890473812917891092)
    @commands.command(help = 'Download and upload structure files to/from cmp')
    async def structure(self, ctx, strucaction, strucname=None):
        if strucaction == 'upload':
            # 直接判断附件列表是否为空
            if not ctx.message.attachments:
                return
            # 取第一个附件,需要支持多附件上传可以遍历列表处理
            attachment = ctx.message.attachments[0]
            if attachment.filename.endswith(".nbt"):
                # 拼接完整保存路径
                save_path = cmp_structure_path + attachment.filename
                # 调用单个附件的save方法
                await attachment.save(fp=save_path)
                embed = discord.Embed(
                    title = f'Structure {attachment.filename} uploaded'
                )
                embed.set_footer(text='Chronos™')
                await ctx.send(embed=embed)
        elif strucaction == 'download':
            # 后续可自行补充下载逻辑
            return
        else:
            embed = discord.Embed(
                title = 'Invalid Arguments'
            )
            embed.set_footer(text='Chronos™')
            await ctx.send(embed=embed)

def setup(bot):
    bot.add_cog(structure(bot))

内容的提问来源于stack exchange,提问作者Chezloc

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 12:57:01