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

discord.js中set未定义错误及机器人暂停功能异常求助

问题解决与代码修正

核心错误分析

  1. set函数未定义:代码里用了不存在的set()函数,修改暂停状态直接赋值client.isPaused = true/false就行,不需要额外调用这个不存在的函数。
  2. 混淆赋值与比较运算符:所有if (client.isPaused = true)里的=是赋值操作,会直接把变量改成true,不是用来判断当前状态的。判断相等必须用===。
  3. 永久暂停的根源:最后一行if (client.isPaused = true) {return};是强制赋值,每次收到消息都会把client.isPaused设为true,导致机器人启动后立刻进入永久暂停状态,重启也没用。

修正后的代码

const prefix = "!";

// 默认未暂停
client.isPaused = false;

client.on("messageCreate", (message) => {
  // 忽略机器人自身发送的消息
  if (message.author.id === client.user.id) return;

  const args = message.content.slice(prefix.length).split(/ +/);
  const command = args.shift()?.toLowerCase();

  // 优先处理暂停/取消暂停命令(不受当前暂停状态限制)
  if (command === 'pause') {
    if (client.isPaused === true) {
      message.reply({ content: `The bot is already paused. Use \`${prefix}unpause\` to unpause it.` });
    } else {
      client.isPaused = true;
      message.reply({ content: `The bot is paused. Use \`${prefix}unpause\` to unpause it.` });
    }
    return; // 处理完命令直接退出,避免触发后续逻辑
  }

  if (command === 'unpause') {
    if (client.isPaused === false) {
      message.reply({ content: `The bot is already listening to commands, can't unpause it.` });
    } else {
      client.isPaused = false;
      message.reply({ content: `The bot is now unpaused.` });
    }
    return; // 处理完命令直接退出,避免触发后续逻辑
  }

  // 如果处于暂停状态,不处理其他命令
  if (client.isPaused === true) return;

  // 这里写其他命令的处理逻辑
});

额外说明

  • 重启后状态重置:当前client.isPaused只存在内存里,机器人重启后会变回初始的false。如果需要重启后保留暂停状态,可以把状态写入本地JSON文件或数据库,启动时读取初始值。
  • 逻辑优化:用else替代独立的if判断减少冗余,处理完暂停类命令后直接return,避免后续的暂停判断干扰命令执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 03:20:31