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

如何让Discord机器人向所有服务器发消息?代码报错求助

解决Discord机器人全局发送公告的报错问题

嘿,我帮你排查出问题所在啦!你遇到的TypeError: Cannot read property 'array' of undefined报错,主要是代码里的几个小细节错误导致的,我给你一步步修正并解释清楚:

错误原因拆解

  1. 公会列表获取方式错误:你写的bot.guilds.array少了括号,array是Discord.js旧版本(v11及以前)的方法,必须加()调用才能获取公会数组;如果用的是v12+版本,guilds已经变成了GuildManager,需要通过bot.guilds.cache来访问缓存的公会集合。
  2. 遍历逻辑错误:你直接把公会列表当成频道数组遍历了——guildList.array.forEach(channel => { ... }),这里的guildList是公会数组,得先遍历每个公会,再在公会里找可发送消息的文本频道。

修正后的代码(适配Discord.js v12+ 新版本)

现在大多用v12及以上版本,我给你写适配这个版本的代码,还加了一些实用的优化:

bot.on('message', async message => {
  if (message.content.startsWith(`${prefix}globalannounce`)) {
    // 提取用户输入的公告内容,避免空消息
    const announcementContent = message.content.split(" ").slice(1).join(" ");
    if (!announcementContent) {
      return message.reply("嘿,得输入要发送的公告内容呀!");
    }

    // 创建嵌入消息
    const announceEmbed = new Discord.MessageEmbed()
      .setTitle("Hello, you don't see me messaging in your server often...")
      .setDescription(`I have just flown in to tell you that my developers have something to say:\n${announcementContent}`);

    try {
      // 遍历机器人加入的所有服务器
      for (const guild of bot.guilds.cache.values()) {
        // 找到服务器里第一个机器人有权限发消息的文本频道
        const targetChannel = guild.channels.cache.find(channel => 
          channel.type === 'GUILD_TEXT' && 
          channel.permissionsFor(bot.user).has('SEND_MESSAGES')
        );

        if (targetChannel) {
          // 发送嵌入消息,v12+需要用embeds数组包裹
          await targetChannel.send({ embeds: [announceEmbed] }).catch(err => {
            console.log(`❌ 无法发送到服务器 ${guild.name}: ${err}`);
          });
        } else {
          console.log(`⚠️ 在服务器 ${guild.name} 中找不到可发送消息的文本频道`);
        }
      }
      message.reply("✅ 全局公告已尝试发送到所有服务器啦!");
    } catch (error) {
      console.error("发送公告时出现异常:", error);
      message.reply("😮‍💨 发送公告时出错了,你可以去控制台看看具体日志哦");
    }
  }
});

如果你用的是Discord.js v11旧版本

那需要调整几个地方,比如嵌入消息的类名和公会获取方式:

bot.on('message', message => {
  if (message.content.startsWith(`${prefix}globalannounce`)) {
    const announcementContent = message.content.split(" ").slice(1).join(" ");
    if (!announcementContent) {
      return message.reply("嘿,得输入要发送的公告内容呀!");
    }

    // v11里嵌入消息用RichEmbed
    const announceEmbed = new Discord.RichEmbed()
      .setTitle("Hello, you don't see me messaging in your server often...")
      .setDescription(`I have just flown in to tell you that my developers have something to say:\n${announcementContent}`);

    try {
      // v11用array()方法获取公会数组
      const guildList = bot.guilds.array();
      guildList.forEach(guild => {
        const targetChannel = guild.channels.find(channel => 
          channel.type === 'text' && 
          channel.permissionsFor(bot.user).has('SEND_MESSAGES')
        );

        if (targetChannel) {
          targetChannel.send(announceEmbed).catch(err => {
            console.log(`❌ 无法发送到服务器 ${guild.name}: ${err}`);
          });
        } else {
          console.log(`⚠️ 在服务器 ${guild.name} 中找不到可发送消息的文本频道`);
        }
      });
      message.reply("✅ 全局公告已尝试发送到所有服务器啦!");
    } catch (error) {
      console.error("发送公告时出现异常:", error);
      message.reply("😮‍💨 发送公告时出错了,你可以去控制台看看具体日志哦");
    }
  }
});

一些重要提醒

  • 全局发送消息可能违反Discord的服务条款,不要滥用哦,不然机器人可能会被封禁
  • 确保你的机器人在每个服务器都有「发送消息」的权限,不然会发送失败
  • 如果服务器数量很多,建议在发送之间加一点延迟(比如用setTimeout),避免触发Discord的速率限制

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 12:07:32