首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >需要检查类别中是否存在通道,如果不存在,则在Discord.js中创建一个新通道

需要检查类别中是否存在通道,如果不存在,则在Discord.js中创建一个新通道
EN

Stack Overflow用户
提问于 2021-08-10 21:40:32
回答 1查看 31关注 0票数 0

在创建channel1channel2channel3channel4之前,我需要检查它们是否存在。

代码语言:javascript
复制
const Discord = require('discord.js');
const disbut = require('discord-buttons');
const client = new Discord.Client();
const guild = new Discord.Guild();
const { prefix, token, categoryID } = require('./config.json');
const { MessageEmbed } = require('discord.js');
const command = require('./command');

client.on('ready', () => {
  console.log('The client is ready!')
});

client.login(token);

const embed = new MessageEmbed()
 .setTitle("Title")
 .setColor("#ff00ff")
 .setDescription("Description")
 .setFooter("Footer")
 .setImage("myimage")
 .setTimestamp()

client.on("message", async (message) => {
    if (message.content == "server") {
        try {
            await message.guild.setIcon('./icon.png');
            await message.guild.setName("My Server");
            await message.guild.channels.create("channel1", { type: 'text', parent: categoryID });
            await message.guild.channels.create("channel2", { type: 'text', parent: categoryID });
            await message.guild.channels.create("channel3", { type: 'text', parent: categoryID });
            await message.guild.channels.create("channel4", { type: 'text', parent: categoryID });
            message.channel.send({embed});
        } catch {
            message.channel.send("Unknown error occurred.");
        }
    }
});

请帮帮我!

EN

回答 1

Stack Overflow用户

发布于 2021-08-10 21:49:24

使用以下代码:

代码语言:javascript
复制
//msg is an instance of Message
const { guild } = msg;
await guild.channels.fetch();

for (let i = 1; i < 5; i++) {
  const channel = await guild.channels.cache.find(c => c.name === `channel${i}`)
  if (!channel) {
    //channel not found
  }
  if (channel.parentId !== 'CATEGORY_ID') {
    //not in the category
  }
}

这将检查该频道是否存在于类别中。

如果找不到通道,此代码将创建通道

代码语言:javascript
复制
const { guild } = msg;
await guild.channels.fetch();

for (let i = 1; i < 5; i++) {
  const channel = await guild.channels.cache.find(c => c.name === `channel${i}`)
  if (!channel || channel.parentId !== 'categoryId') {
    guild.channels.create(`channel${i}`, { type: 'text' });
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68733751

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档