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

如何向数据库存储的所有频道ID发消息?代码报错求助

问题解决

错误原因

你误用了mongoose.get()方法——这个函数是用来读取Mongoose的全局配置选项的,不是用来查询数据库中的文档数据。你传入的channelID_${interaction.guild.id}会被识别为无效的配置键,因此抛出错误。

修正方案

你需要使用导入的db模型(即guild模型)来查询数据库中的服务器文档,从中取出存储的频道ID列表。同时注意异步循环的正确写法(forEach配合async无法正确等待异步操作完成)。

修改后的代码

const { SlashCommandBuilder, PermissionFlagsBits, Client } = require("discord.js");
const db = require("../../Structures/models/guild");
const mongoose = require("mongoose");

module.exports = {
  data: new SlashCommandBuilder()
    .setName("post")
    .setDescription("Post Something")
    .setDefaultMemberPermissions(PermissionFlagsBits.SendMessages),

  async execute(interaction, client) {
    // 从数据库查询当前服务器的文档
    const guildDoc = await db.findOne({ guildId: interaction.guild.id });
    
    if (!guildDoc || !guildDoc.channelIDs?.length) {
      return interaction.reply({ content: "未找到该服务器绑定的频道ID", ephemeral: true });
    }

    // 使用for...of处理异步操作,确保每个消息发送完成后再执行下一个
    for (const id of guildDoc.channelIDs) {
      try {
        const channel = await client.channels.fetch(id);
        await channel.send('Something');
      } catch (error) {
        console.log(`发送消息到频道 ${id} 失败:`, error);
      }
    }

    await interaction.reply({ content: 'Brwww' });
  },
};

关键改动说明

  1. 替换查询方式:用db.findOne({ guildId: interaction.guild.id })替代mongoose.get(),从数据库中获取对应服务器的文档(假设你的guild模型里存储服务器ID的字段是guildId,存储频道ID列表的字段是channelIDs,如果字段名不同请自行调整)。
  2. 增加空值判断:避免因找不到文档或无频道ID导致后续代码报错。
  3. 修正异步循环:用for...of替代forEach,确保每个频道的消息发送操作能被正确等待,避免异步操作混乱。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 10:01:23