使用discord.py开发Discord机器人发送Zip文件遇FileNotFoundError求助
排查discord.py机器人发送Zip文件时的FileNotFoundError问题
问题描述
使用discord.py开发Discord机器人,totem命令功能为获取附件图片、处理后压缩为Zip文件发送,但发送时触发FileNotFoundError,错误信息显示指定的Zip文件路径不存在:
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Hesam\\Desktop\\New folder\\export_bdce64fb-079e-4b51-b6f0-8f798475aba6.zip'
错误原因
核心问题是**shutil.make_archive的参数使用错误**:
该函数的第一个参数是归档文件的基础名称(不需要带格式扩展名),它会自动根据你指定的格式(第二个参数'zip')添加对应的扩展名。
你的代码中:
zip_name = os.path.join(os.getcwd(), f"export_{unicId}.zip") shutil.make_archive(zip_name, 'zip', destination_path)
实际生成的文件是export_xxxx.zip.zip(在基础名后重复添加了.zip后缀),但后续调用discord.File(zip_name)时使用的是不带重复后缀的路径,自然找不到文件。
修复方案
调整zip_name的定义,去掉后缀,发送时再补充正确的扩展名:
@bot.command() async def totem(ctx): try: url = ctx.message.attachments[0].url except IndexError: print("Error: No attachments") await ctx.send("No attachments detected!") else: if url.startswith("https://cdn.discordapp.com"): r = requests.get(url, stream=True) if r.status_code == 200: now = datetime.datetime.now() destination_path = os.path.join("exports", f"{now.year}", f"{now.month}", f"{now.day}", f"{now.hour}", f"{now.minute}", f"{now.second}") src = os.path.join(os.getcwd(), "src") print(src) # 先删除已存在的目录再创建,避免copytree冲突 if os.path.exists(destination_path): shutil.rmtree(destination_path) os.makedirs(destination_path, exist_ok=True) shutil.copytree(src, destination_path) file_name = os.path.join(destination_path, "assets", "minecraft", "textures", "item", "totem_of_undying.png") await ctx.send("making resource pack...") with open(file_name, 'wb') as f: for chunk in r.iter_content(1024): f.write(chunk) unicId = uuid.uuid4() # 定义zip基础名称,不带.zip后缀 zip_base_name = os.path.join(os.getcwd(), f"export_{unicId}") print(f"Generating zip at: {zip_base_name}.zip") shutil.make_archive(zip_base_name, 'zip', destination_path) # 发送时使用带正确后缀的路径 await ctx.send(file=discord.File(f"{zip_base_name}.zip")) else: await ctx.send("Error: Failed to fetch the image!") else: await ctx.send("Invalid image link!")
额外优化点:
- 调整目录创建逻辑:先删除已存在的
destination_path再创建,避免shutil.copytree因目标目录已存在报错 - 简化时间变量定义,直接通过
now属性调用年、月等参数
内容的提问来源于stack exchange,提问作者hesam21188
相关产品推荐
相关产品推荐

