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

使用discord.js发送内容至Discord频道时出现JSON解析错误

问题分析与解决

你的代码里JSON解析逻辑是正常的(控制台能打印随机内容就是证明),报错“error parsing json null”其实是错误处理逻辑误导,真实问题出在Discord频道发送环节:

核心问题点

  • client.channels.cache.get(myChannel)可能返回了null,导致调用send()时触发错误,但你的catch块错误地把这个错误当成JSON解析错误来输出。
  • 导致get()返回null的常见原因:
    • myChannel变量未正确赋值,不是有效的Discord频道ID(需为字符串格式)
    • 目标频道未被机器人的缓存加载(比如机器人刚启动,缓存还没同步,或者机器人没有该频道的访问权限)

修复步骤

  1. 验证频道ID有效性
    确保myChannel是目标频道的正确ID字符串,比如:

    const myChannel = "123456789012345678"; // 替换成你的频道ID
    
  2. 改用fetch确保获取到频道
    缓存可能存在未加载的情况,改用channels.fetch()来可靠获取频道:

    // 替换原发送代码
    client.channels.fetch(myChannel)
      .then(channel => channel.send(randomText))
      .catch(sendErr => console.log("发送到Discord失败:", sendErr));
    
  3. 修正错误处理逻辑
    把JSON解析的错误和发送错误分开处理,避免混淆:

    fs.readFile("text.json","utf-8", (err, jsonString) => {
      if(err) {
        console.log("读取文件失败:", err);
        return;
      }
      try {
        const data = JSON.parse(jsonString);
        const randomText = data.question[Math.floor(Math.random() * data.question.length)];
        console.log(randomText);
        
        // 用fetch发送
        client.channels.fetch(myChannel)
          .then(channel => channel.send(randomText))
          .catch(sendErr => console.log("发送消息失败:", sendErr));
      }
      catch(parseErr) {
        console.log("解析JSON失败:", parseErr);
      }
    })
    
  4. 检查机器人权限
    确保你的机器人账号在目标频道拥有发送消息的权限,并且已经加入了该频道所在的服务器。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 10:20:41