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

无法让Discord机器人从本地文件夹发送图片

解决Discord机器人发送图片时的FileNotFoundError问题

你遇到的问题大概率是绝对路径硬编码带来的隐患,或是文件权限、实际路径匹配的细节问题,以下是可行的解决方法:

1. 改用动态相对路径(推荐)

不要写死绝对路径,基于脚本所在目录动态拼接路径,避免环境变化导致路径失效:

import discord
from discord.ext import commands
import os

bot = commands.Bot(command_prefix='!')
folder_name = "testing"

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name}')

@bot.command()
async def hello(ctx):
    await ctx.channel.send(f'Hello {ctx.author.name}!')

@bot.command()
async def add(ctx, num1: int, num2: int):
    result = num1 + num2
    await ctx.channel.send(f'The sum of {num1} and {num2} is {result}')

@bot.command()
async def send_file(ctx, image_name):
    # 获取脚本所在目录
    script_dir = os.path.dirname(__file__)
    # 用os.path.join拼接路径,避免手动拼接出错
    file_path = os.path.join(script_dir, folder_name, f"{image_name}.png")
    
    # 先检查文件是否存在
    if not os.path.exists(file_path):
        await ctx.channel.send(f"找不到文件:{file_path}")
        return
    
    try:
        await ctx.channel.send(file=discord.File(file_path))
    except Exception as e:
        await ctx.channel.send(f"发送文件失败:{str(e)}")

bot.run('TOKEN')

2. 排查路径与权限细节

  • 确认文件名大小写:MacOS默认大小写不敏感,但终端操作的文件可能存在大小写差异,比如你输入cat但实际文件是Cat.png
  • 检查文件权限:用终端命令ls -l /Users/user/Documents/Projects/Discord_bot/testing/cat.png查看权限,确保运行机器人的用户有读取权限
  • 验证路径准确性:可以在代码里打印file_path,复制到终端用open命令测试能否打开文件

3. 兼容用户输入的后缀

如果用户可能输入带.png后缀的文件名,可提前处理:

# 移除用户输入中的.png后缀(如果存在)
image_name = image_name.rstrip('.png')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 14:22:15