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

Heroku部署discord.py bot时Image.save()失效问题排查求助

解决方案:Heroku上discord.py机器人Image.save()失败问题
  • 先确认目标目录是否存在
    Heroku的/app目录默认存在,但/app/Pictures子目录不会自动创建。在调用save()前,先确保目录存在:
import os
save_path = "/app/Pictures/ss0.png"
# 创建保存目录(如果不存在)
os.makedirs(os.path.dirname(save_path), exist_ok=True)
stitched_image.save(save_path)
  • 检查Pillow的系统依赖
    Heroku上运行Pillow需要底层系统库支持,缺少的话会导致保存图片时静默失败。你需要:

    1. 在项目根目录创建Aptfile文件,添加以下内容:
      libjpeg-dev
      zlib1g-dev
      
    2. 在requirements.txt里明确指定Pillow版本(避免依赖兼容问题):
      Pillow>=9.0.0
      discord.py>=2.0.0
      selenium>=4.0.0
      
    3. 重新部署到Heroku,确保这些依赖被安装。
  • 改用临时文件更可靠
    Heroku的文件系统是临时的,直接指定固定路径可能有权限或路径问题,用Python的tempfile模块生成临时文件更稳妥:

from tempfile import NamedTemporaryFile
import os

# 创建临时PNG文件
with NamedTemporaryFile(suffix=".png", delete=False) as tmp_file:
    stitched_image.save(tmp_file.name, format="PNG")

# 上传到Discord(这里替换成你的上传逻辑)
await channel.send(file=discord.File(tmp_file.name))

# 删除临时文件
os.unlink(tmp_file.name)
  • 捕获异常排查具体错误
    之前程序静默停止,大概率是有未捕获的异常。给save()代码加异常捕获,打印错误信息:
try:
    stitched_image.save(save_path)
except Exception as e:
    print(f"图片保存失败:{type(e).__name__} - {str(e)}")

查看Heroku日志(heroku logs --tail)就能看到具体错误,比如权限问题、编码缺失等。

另外,Heroku并没有禁止文件写入操作,只是文件系统是临时的,重启后所有文件都会丢失,所以你的场景(临时保存后上传删除)是完全支持的,不需要立刻转AWS,先排查上面的点。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 22:15:05