使用discord.py斜杠命令实现附件保存发送的报错求助
错误修复方案
错误1:TypeError: unknown parameter given: image_file
原因:@client.tree.command定义的命令函数必须把interaction: discord.Interaction作为第一个参数,你的upload函数缺少该参数,导致参数匹配失败。
修复:给upload函数添加interaction参数,并在函数开头处理交互响应,避免超时。
错误2:Expected type 'Union[BufferedIOBase, PathLike]', got 'list' instead
原因:discord.Attachment.save()的fp参数需要传入文件路径(字符串/Path对象)或文件流对象,你传入了列表upload_images,类型不匹配。且你的需求是记录上传图片用于后续发送,应保存图片到本地后,将图片URL(或本地路径)添加到列表中。
完整修正代码
import random import discord from discord import app_commands from pathlib import Path # 存储图片的URL列表 upload_images = [] # 定义本地图片保存目录(会自动创建,无需手动提前建) IMAGE_DIR = Path("./uploaded_images") IMAGE_DIR.mkdir(exist_ok=True) @client.tree.command(description='上传图片文件') @app_commands.describe(image_file="拖拽你的图片文件到这里") async def upload(interaction: discord.Interaction, image_file: discord.Attachment): # 发送临时响应,避免交互超时 await interaction.response.defer(ephemeral=True) # 生成本地保存路径,使用原文件名 file_path = IMAGE_DIR / image_file.filename # 保存图片到本地 await image_file.save(fp=file_path, use_cached=True) # 将图片的CDN链接加入列表,发送时直接调用更高效 upload_images.append(image_file.url) # 上传完成提示 await interaction.followup.send(f"图片上传成功!当前累计上传{len(upload_images)}张图片。") @client.tree.command(description='发送随机图片') async def send(interaction: discord.Interaction): if upload_images: image_url = random.choice(upload_images) embed = discord.Embed(title='你的随机图片', color=discord.Color.random()).set_image(url=image_url) await interaction.response.send_message(embed=embed) else: await interaction.response.send_message("还没有上传任何图片哦。")
补充说明
interaction.response.defer():上传图片可能耗时,用该方法避免discord判定交互超时(默认3秒超时)。- 使用
image_file.url:直接调用discord附件的CDN链接,无需读取本地文件即可发送,效率更高。若需发送本地图片,可替换为discord.File(file_path)。 - 自动创建目录:
Path.mkdir(exist_ok=True)确保保存目录存在,避免因目录缺失报错。
内容的提问来源于stack exchange,提问作者le nam
相关产品推荐
相关产品推荐

