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

Discord.js v14机器人重复创建用户ID频道问题求助

解决Discord.js v14中DM记录频道重复创建的问题

问题根源

  1. 属性名错误:Discord.js v14中频道的父分类ID属性为parentId(驼峰小写d),你代码里误用了parentID(大写D),导致频道匹配条件始终不成立,每次都会判定频道不存在并重复创建。
  2. 缓存同步问题:仅依赖guild.channels.cache可能无法获取最新创建的频道数据,尤其是机器人重启或频道刚创建时,缓存未及时更新。

解决方案

修正属性命名,同时优化数据获取方式确保拿到最新频道数据,以下是修改后的完整代码:

const {
  EmbedBuilder,
  ChannelType,
} = require("discord.js");

const serverId = "1110927555693924659";
const categoryId = "1114273709084191765";

client.on("messageCreate", async (message) => {
  if (message.channel.type === ChannelType.DM && !message.author.bot) {
    try {
      // 从API拉取最新服务器数据,避免缓存过期
      const guild = await client.guilds.fetch(serverId);
      // 直接获取目标分类频道,确保数据最新
      const category = await guild.channels.fetch(categoryId);

      // 强制刷新频道缓存,确保包含刚创建的频道
      await guild.channels.fetch();
      // 修正属性名,同时限定频道类型避免误匹配
      const channel = guild.channels.cache.find(
        (channel) =>
          channel.name === message.author.id &&
          channel.parentId === category.id &&
          channel.type === ChannelType.GuildText
      );

      const embed = new EmbedBuilder()
        .setColor("#0099ff")
        .setTitle("New Message")
        .setDescription(message.content)
        .setAuthor({
          name: message.author.tag,
          iconURL: message.author.displayAvatarURL(),
        });

      if (channel) {
        await channel.send({ embeds: [embed] });
      } else {
        const newChannel = await guild.channels.create({
          name: message.author.id,
          type: ChannelType.GuildText,
          parent: category,
        });

        await newChannel.send({ embeds: [embed] });
      }
    } catch (error) {
      console.error("处理DM记录时出错:", error);
    }
  }
});

关键修改说明

  • 替换cache.get为fetch方法:确保从Discord API拉取最新的服务器、分类频道数据,避免缓存缺失。
  • 增加await guild.channels.fetch():强制刷新频道缓存,保证刚创建的频道能被后续查找匹配到。
  • 修正parentID为parentId:符合Discord.js v14的属性命名规范,确保父分类匹配逻辑生效。
  • 新增频道类型判定:避免误匹配到语音频道等非文本频道。
  • 加入try-catch块:捕获并打印错误,方便调试排查问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 05:58:25