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

Discord机器人在线但无响应:Replit迁移VSCode编译后故障求助

问题描述

我用Chalk实现了防崩溃功能的Discord反应角色机器人,在Replit上运行正常。为提升在线时长,将代码存入仓库并导入VSCode编译为可执行文件后出现故障。尝试修改Intents无效,在discord.js官方Discord服务器求助无回应,相关代码如下:

const express = require('express')
const app = express()
const chalk = require("chalk")

app.get('/', (req, res) => {
  res.send('Bot Loaded! Changes Saved!');
});

app.listen(3000, () => {
  console.log(
    chalk.white('['),
    chalk.cyan('Express'),
    chalk.white(']'),
    chalk.gray(':'),
    chalk.white('Connected')
  );
});




const {
    Client,
    Collection,
    GatewayIntentBits,
    Partials,
} = require("discord.js");
const Discord = require('discord.js')

const client = new Client({
  intents: [
    "Guilds",
    "GuildMessages",
    "DirectMessages",
    GatewayIntentBits.DirectMessages,
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildBans,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
  ],
});

const db = require("quick.db")
let pagination = require('./function/pagination')
// ———————————————[Global Variables]———————————————
client.commands = new Collection();
client.aliases = new Collection();
client.cooldowns = new Collection();
client.slashCommands = new Collection();
const Timeout = new Collection();
client.snipes = new Collection()
client.config = require("./botconfig/main.json");
require("./handler")(client);
// Initializing the project.



// ———————————————[Logging Into Client]———————————————
  client.login('');

// ———————————————[Error Handling]———————————————
process.on("unhandledRejection", (reason, p) => {
  console.log(chalk.gray("—————————————————————————————————"));
  console.log(
    chalk.white("["),
    chalk.red.bold("AntiCrash"),
    chalk.white("]"),
    chalk.gray(" : "),
    chalk.white.bold("Unhandled Rejection/Catch")
  );
  console.log(chalk.gray("—————————————————————————————————"));
  console.log(reason, p);
});
process.on("uncaughtException", (err, origin) => {
  console.log(chalk.gray("—————————————————————————————————"));
  console.log(
    chalk.white("["),
    chalk.red.bold("AntiCrash"),
    chalk.white("]"),
    chalk.gray(" : "),
    chalk.white.bold("Uncaught Exception/Catch")
  );
  console.log(chalk.gray("—————————————————————————————————"));
  console.log(err, origin);
});
process.on("multipleResolves", (type, promise, reason) => {
  console.log(chalk.gray("—————————————————————————————————"));
  console.log(
    chalk.white("["),
    chalk.red.bold("AntiCrash"),
    chalk.white("]"),
    chalk.gray(" : "),
    chalk.white.bold("Multiple Resolves")
  );
  console.log(chalk.gray("—————————————————————————————————"));
  console.log(type, promise, reason);
});



const Levels = require("discord-xp");

const { mongooseConnectionString } = require("./botconfig/main.json");

Levels.setURL(mongooseConnectionString); 





// ———————————————[Anti Ghost ping]———————————————
let { MessageEmbed } = require("discord.js")
client.on('messageCreate', message => { 
  if(message.author.bot) return;
  if(!message.guild) return;
const args = message.content.split(" ").slice(1)
if(message.content.toLowerCase().startsWith("+ghostpingdetector")) {
  //=====
 let embedon = new MessageEmbed()
 .setDescription(":green_square: | Turned On GhostPingDetector")
 .setTimestamp()

 //===
  let embedoff = new MessageEmbed()
 .setDescription(":red_square: | Turned Off GhostPingDetector")
 .setTimestamp()
 //====
   if(!args[0]) return message.reply('Do You Want To Turn On or Off ghostpingdetector? Please Type `w?ghostpingdetector true/false` or `on/off`');
     if(args[0] === "on" || args[0] === "true") {
   message.reply({embeds: [embedon]})
   db.set(`gp_${message.author.id}`, true)
     } else if(args[0] === "off" || args[0] === "false") {
     db.delete(`gp_${message.author.id}`)
     message.reply({embeds: [embedoff]})
   }
   }
})
client.on('messageDelete', message => {
message.mentions.users.forEach(m => {
  if(db.has(`gp_${m.id}`) && m.id !== message.author.id && !message.author.bot){
    
    let emb = new MessageEmbed()
    emb.setTitle('GhostPingDetector')
    emb.setDescription(`<@${m.id}>, You've Been Ghost Pinged.\nUserName: \`${message.author.username}\`\nUserID: \`${message.author.id}\`\nServerName: ${message.guild.name}\nChannel: <#${message.channel.id}>\nContent: ${message.content}`)
    emb.setColor("GREEN")
    emb.setFooter(`Anti-Ghost Ping! woop woop`)
    m.send({embeds: [emb]})
    message.channel.send({embeds: [emb]})
    }
  
})
})

client.on('message', message => {
    if (message.channel.id === '1029286082879180832') {
        message.react('✅');
    }
});
问题排查与修复方案

1. Intents配置错误

discord.js v14要求必须使用GatewayIntentBits枚举配置Intents,不能混用字符串枚举值,原代码中同时存在字符串(如"Guilds")和枚举,且存在重复项,会导致客户端初始化失败。

修复:仅保留GatewayIntentBits枚举项,移除重复和字符串值,同时确保在Discord开发者后台开启MessageContent权限:

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildBans,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.DirectMessages,
    GatewayIntentBits.MessageContent,
  ],
});

2. 废弃事件监听报错

discord.js v14已移除message事件,原代码中同时监听messageCreate和message事件,会触发运行时错误。

修复:将message事件合并到messageCreate监听中:

client.on('messageCreate', message => { 
  // 原ghostping逻辑...
  
  // 合并频道自动反应逻辑
  if (message.channel.id === '1029286082879180832') {
    message.react('✅');
  }
})

3. 编译为可执行文件的潜在问题

依赖打包不全

使用pkg/nexe等工具打包时,需确保静态文件(如botconfig/main.json、function/pagination.js)被正确包含。若用pkg,在package.json中添加:

"pkg": {
  "assets": [
    "botconfig/**/*",
    "function/**/*"
  ]
}

环境变量缺失

原代码中client.login('')为空,且未使用环境变量存储Token,打包后无法读取敏感信息。修复:用环境变量注入Token:

client.login(process.env.DISCORD_BOT_TOKEN);

打包运行时通过环境变量传入:DISCORD_BOT_TOKEN=你的机器人令牌 ./你的可执行文件名

Chalk颜色兼容性

打包后的可执行文件可能在部分终端环境下不支持颜色输出,可强制禁用Chalk颜色避免异常:

const chalk = require("chalk").disable();

4. 防崩溃逻辑优化

补充捕获uncaughtExceptionMonitor事件,完善错误监控:

process.on("uncaughtExceptionMonitor", (err, origin) => {
  console.log(chalk.gray("—————————————————————————————————"));
  console.log(
    chalk.white("["),
    chalk.red.bold("AntiCrash"),
    chalk.white("]"),
    chalk.gray(" : "),
    chalk.white.bold("Uncaught Exception Monitor")
  );
  console.log(chalk.gray("—————————————————————————————————"));
  console.log(err, origin);
});
修改后的完整代码
const express = require('express')
const app = express()
// 若打包后颜色异常,可添加.disable()
const chalk = require("chalk")

app.get('/', (req, res) => {
  res.send('Bot Loaded! Changes Saved!');
});

app.listen(3000, () => {
  console.log(
    chalk.white('['),
    chalk.cyan('Express'),
    chalk.white(']'),
    chalk.gray(':'),
    chalk.white('Connected')
  );
});

const {
    Client,
    Collection,
    GatewayIntentBits,
    Partials,
    MessageEmbed
} = require("discord.js");

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildBans,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.DirectMessages,
    GatewayIntentBits.MessageContent,
  ],
});

const db = require("quick.db")
let pagination = require('./function/pagination')

// ———————————————[Global Variables]———————————————
client.commands = new Collection();
client.aliases = new Collection();
client.cooldowns = new Collection();
client.slashCommands = new Collection();
const Timeout = new Collection();
client.snipes = new Collection()
client.config = require("./botconfig/main.json");
require("./handler")(client);

// ———————————————[Logging Into Client]———————————————
// 使用环境变量传入Token
client.login(process.env.DISCORD_BOT_TOKEN);

// ———————————————[Error Handling]———————————————
process.on("unhandledRejection", (reason, p) => {
  console.log(chalk.gray("—————————————————————————————————"));
  console.log(
    chalk.white("["),
    chalk.red.bold("AntiCrash"),
    chalk.white("]"),
    chalk.gray(" : "),
    chalk.white.bold("Unhandled Rejection/Catch")
  );
  console.log(chalk.gray("—————————————————————————————————"));
  console.log(reason, p);
});
process.on("uncaughtException", (err, origin) => {
  console.log(chalk.gray("—————————————————————————————————"));
  console.log(
    chalk.white("["),
    chalk.red.bold("AntiCrash"),
    chalk.white("]"),
    chalk.gray(" : "),
    chalk.white.bold("Uncaught Exception/Catch")
  );
  console.log(chalk.gray("—————————————————————————————————"));
  console.log(err, origin);
});
process.on("multipleResolves", (type, promise, reason) => {
  console.log(chalk.gray("—————————————————————————————————"));
  console.log(
    chalk.white("["),
    chalk.red.bold("AntiCrash"),
    chalk.white("]"),
    chalk.gray(" : "),
    chalk.white.bold("Multiple Resolves")
  );
  console.log(chalk.gray("—————————————————————————————————"));
  console.log(type, promise, reason);
});
process.on("uncaughtExceptionMonitor", (err, origin) => {
  console.log(chalk.gray("—————————————————————————————————"));
  console.log(
    chalk.white("["),
    chalk.red.bold("AntiCrash"),
    chalk.white("]"),
    chalk.gray(" : "),
    chalk.white.bold("Uncaught Exception Monitor")
  );
  console.log(chalk.gray("—————————————————————————————————"));
  console.log(err, origin);
});

const Levels = require("discord-xp");
const { mongooseConnectionString } = require("./botconfig/main.json");
Levels.setURL(mongooseConnectionString); 

// ———————————————[Anti Ghost ping]———————————————
client.on('messageCreate', message => { 
  if(message.author.bot) return;
  if(!message.guild) return;
  const args = message.content.split(" ").slice(1)
  if(message.content.toLowerCase().startsWith("+ghostpingdetector")) {
    const embedon = new MessageEmbed()
      .setDescription(":green_square: | Turned On GhostPingDetector")
      .setTimestamp()

    const embedoff = new MessageEmbed()
      .setDescription(":red_square: | Turned Off GhostPingDetector")
      .setTimestamp()

    if(!args[0]) return message.reply('Do You Want To Turn On or Off ghostpingdetector? Please Type `w?ghostpingdetector true/false` or `on/off`');
    if(args[0] === "on" || args[0] === "true") {
      message.reply({embeds: [embedon]})
      db.set(`gp_${message.author.id}`, true)
    } else if(args[0] === "off" || args[0] === "false") {
      db.delete(`gp_${message.author.id}`)
      message.reply({embeds: [embedoff]})
    }
  }
  // 频道自动反应逻辑
  if (message.channel.id === '1029286082879180832') {
    message.react('✅');
  }
})

client.on('messageDelete', message => {
  message.mentions.users.forEach(m => {
    if(db.has(`gp_${m.id}`) && m.id !== message.author.id && !message.author.bot){
      const emb = new MessageEmbed()
        .setTitle('GhostPingDetector')
        .setDescription(`<@${m.id}>, You've Been Ghost Pinged.\nUserName: \`${message.author.username}\`\nUserID: \`${message.author.id}\`\nServerName: ${message.guild.name}\nChannel: <#${message.channel.id}>\nContent: ${message.content}`)
        .setColor("GREEN")
        .setFooter(`Anti-Ghost Ping! woop woop`)
      m.send({embeds: [emb]})
      message.channel.send({embeds: [emb]})
    }
  })
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 02:05:16