2
votes

I'm creating a discord bot using node.js and i want it to create a private text channel on a server and add to it the user sending the command "!create" and the bot itself.

I have found a way to make a text channel using this answer: How to create a text channel but i can't find a way to make it private and add people to it.

3

3 Answers

3
votes

I do it always like this:

const everyoneRole = client.guilds.get('SERVER ID').roles.find('name', '@everyone');

const name = message.author.username;
message.guild.createChannel(name, 'text')
    .then(r => {
        r.overwritePermissions(message.author.id, { VIEW_CHANNEL: true });
        r.overwritePermissions(client.id, { VIEW_CHANNEL: true });
        r.overwritePermissions(everyoneRole, { VIEW_CHANNEL: false });
    })
    .catch(console.error);

First, we define the everyoneRole. Then we use the method overwritePermissions() to overwrite the permissions of the newly created guild textchannel. There we give the message author and the bot the permission to view the channel and we revoke the everyone role the permission to view this channel.

1
votes

Thanks to @gilles-heinesch for the lead. The API of discord.js got drastically changed over time, so here is an updated version:

const { Client, Permissions } = require('discord.js');

/** @param {string|number} serverId - a "snowflake" ID you can see in address bar */
async function createPrivateChannel(serverId, channelName) {
  const guild = await client.guilds.fetch(serverId);
  const everyoneRole = guild.roles.everyone;
  const channel = await guild.channels.create(channelName, 'text');
  await channel.overwritePermissions([
    {type: 'member', id: message.author.id, allow: [Permissions.FLAGS.VIEW_CHANNEL]},
    {type: 'member', id: client.user.id, allow: [Permissions.FLAGS.VIEW_CHANNEL]},
    {type: 'role', id: everyoneRole.id, deny: [Permissions.FLAGS.VIEW_CHANNEL]},
  ]);
}
0
votes

https://discord.js.org/#/docs/main/stable/class/ChannelManager

Use cache collection

const channels = message.guild.channels.cache
const myChannel = channels.find(channel => channel.name === 'channel name')