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

Discord机器人运行数分钟后报ENOENT错误求助

Discord机器人运行数分钟后出现ENOENT错误的解决方案

问题描述

我在Visual Studio Code中运行Discord机器人,起初能正常运行4-5分钟,之后突然抛出ENOENT(文件或目录不存在)错误,无法解决。

我的代码

const { Client, GatewayIntentBits} = require('discord.js');
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] });
const TOKEN = ':P';
setInterval(function () {
    var User = [
        "User1",
        "User2"
    ]


    client.on('ready', client => {
        const someFunc = () => {
            var randomUser = User[Math.floor(Math.random() * User.length)];
            var randomUser2 = User[Math.floor(Math.random() * User.length)];
            var randomUser3 = User[Math.floor(Math.random() * User.length)];
            var randomUser4 = User[Math.floor(Math.random() * User.length)];

            var Action = [
                { content: (randomUser) + " rembered 😀", files: [{ attachment: "./Image/" + (randomUser) + ".png" }] },
                { content: (randomUser) + " forgor 💀", files: [{ attachment: "./Image/" + (randomUser) + ".png" }] }


            ]

            client.channels.cache.get('1246634621874213007').send(Action[Math.floor(Math.random() * Action.length)]);

            setTimeout(someFunc, 60000);
        }
        setTimeout(someFunc, 60000); 
    }),
    client.login(TOKEN) 
}, 60000);

client.on('ready', () => {
    console.log(`Logged in as ${client.user.tag}!`)
})

报错信息

node:internal/fs/promises:1026
    binding.stat(pathModule.toNamespacedPath(path),
            ^

Error: ENOENT: no such file or directory, stat
    at Object.stat (node:internal/fs/promises:1026:13)
    at DataResolver.resolveFile (J:\Desktop\Folder\R&R Anything 2.0\node_modules\discord.js\src\util\DataResolver.js:131:30)
    at MessagePayload.resolveFile (J:\Desktop\Folder\R&R Anything 2.0\node_modules\discord.js\src\structures\MessagePayload.js:261:54)
    at J:\Desktop\Folder\R&R Anything 2.0\node_modules\discord.js\src\structures\MessagePayload.js:225:85
    at Array.map (<anonymous>)
    at MessagePayload.resolveFiles (J:\Desktop\Folder\R&R Anything 2.0\node_modules\discord.js\src\structures\MessagePayload.js:225:56)
    at TextChannel.send (J:\Desktop\Folder\R&R Anything 2.0\node_modules\discord.js\src\structures\interfaces\TextBasedChannel.js:175:50)
    at Timeout.someFunc [as _onTimeout] (J:\Desktop\Folder\R&R Anything 2.0\index.js:136:62)
    at listOnTimeout (node:internal/timers:573:17)
    at process.processTimers (node:internal/timers:514:7) {
  errno: -4058,
  code: 'ENOENT',
  syscall: 'stat'
}

问题分析与解决方案

核心问题1:重复绑定事件+重复登录

代码用setInterval每隔60秒重复绑定ready事件、调用client.login,导致机器人多次登录产生多实例,叠加的定时器让消息发送逻辑混乱,最终触发文件读取异常。

核心问题2:定时器嵌套逻辑冗余

someFunc内部、外层ready事件、最外层setInterval多重定时器叠加,导致消息发送频率持续升高,资源占用飙升。

修复后的代码

const { Client, GatewayIntentBits} = require('discord.js');
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] });
const TOKEN = ':P';

// 全局定义用户和动作模板,避免重复创建
const User = ["User1", "User2"];
const ActionTemplates = [
    (user) => ({ content: `${user} remembered 😀`, files: [{ attachment: `./Image/${user}.png` }] }),
    (user) => ({ content: `${user} forgor 💀`, files: [{ attachment: `./Image/${user}.png` }] })
];

function sendRandomAction() {
    const randomUser = User[Math.floor(Math.random() * User.length)];
    const randomAction = ActionTemplates[Math.floor(Math.random() * ActionTemplates.length)](randomUser);
    
    // 先校验频道是否存在
    const channel = client.channels.cache.get('1246634621874213007');
    if (!channel) {
        console.error('目标频道不存在');
        return;
    }
    
    // 捕获发送异常避免程序崩溃
    channel.send(randomAction).catch(err => {
        console.error('消息发送失败:', err);
    });
}

// 机器人就绪后启动单次定时任务
client.on('ready', () => {
    console.log(`Logged in as ${client.user.tag}!`);
    sendRandomAction();
    setInterval(sendRandomAction, 60000);
});

// 仅登录一次机器人
client.login(TOKEN);

额外检查项

  • 确认./Image/User1.png和./Image/User2.png文件真实存在,路径大小写匹配(Linux系统区分大小写)
  • 确保机器人拥有Image目录的读取权限
  • 可添加文件存在性检查增强稳定性:
const fs = require('fs').promises;

async function sendRandomAction() {
    const randomUser = User[Math.floor(Math.random() * User.length)];
    const filePath = `./Image/${randomUser}.png`;
    
    try {
        await fs.access(filePath);
        const randomAction = ActionTemplates[Math.floor(Math.random() * ActionTemplates.length)](randomUser);
        
        const channel = client.channels.cache.get('1246634621874213007');
        if (!channel) {
            console.error('目标频道不存在');
            return;
        }
        
        await channel.send(randomAction);
    } catch (err) {
        console.error(`文件无法访问: ${filePath}`, err);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 20:34:59