(Discord.js) get channel by it's name - discord.js

So basically my goal is to get a specific channel by it's name. I want to store it in a variable so I can delete it later.
let channel = //store specific channel in this variable using its name// ;
channel.delete();
And yes, I know I should use its ID because it's better, but in this case I can't use it's ID, I have to use its name.

Use GuildChannelManager#find()
let channel = message.guild.channels.cache.find(channel => channel.name === 'channel-name-here');
channel.delete();

Related

Discord.js - How do you list every available text channels in a server?

I want to make a bot that can scan every available text channel ID in a server to object, then select the channel based on the name and channel ID. I already have the code to select channel ID from an object, but the objects are loaded from JSON file.
I know there are codes that can search channel ID from a specific channel name, but I have my reasons.
Is it possible to scan available text channel IDs in a server? Thanks.
Yes, there are many ways to achieve this, assuming you have a variable named client that is an instance of discord.js's Client then you can do the following.
First, you need to get the guild.
// if you have not disabled caching
const guild = client.guilds.cache.get('<GUILD_ID>')
// no cache
const guild = await client.guilds.fetch('<GUILD_ID>')
// if you are responding to a message / interaction
const guild = message.guild
Then you get all the channels in the guild
// if you have not disabled caching
let channels = guild.channels.cache
// no cache
let channels = await guild.channels.fetch()
this will give you a Collection of GuildChannel objects. If you want to have only text channels then you can do:
channels = channels.map((c) => c.type === "GUILD_TEXT")
You can convert the Collection into an array doing the following if you find it easier
channels = [...channels.values()]

How to store channel Id and use it/log it

command(client, 'explore', (message) => {
const name = message.content.replace('!explore ', '')
message.guild.channels
.create(name, {
type: 'text',
})
.then((channel) => {
const catagoryId = '847950191108554762'
channel.setParent(catagoryId)
})
const channelId = message.guild.channels.id
console.log(channelId)
})
I'm having an issue with saving the newly created channel's id so that way when the channel is done being used instead of typing the name, I can use the id to be inputted into the deletion command. Basically creating temp. predefined or newly found channels and then being able to log the Id and then with a deletion command be able to remove it without writing a name of the channel.
const channelId = message.guild.channels.id
console.log(channelId)
this was my attempt to retrieve/store then log it. I've been trying to do this on my own but have hit a roadblock.
To get a channel’s ID, just type <Channel>.id. There are multiple ways to get a channel, here is an example:
const channelID = <Message>.channel.id;
console.log(channelID);
The above example gets the ID of the message's channel
Also, <guild>.channels.id returns undefined, since guild.channels is a collection of multiple channels, and you can’t just get the id like that. This would be useless if you are trying to get the channel ID since you would have to fetch/get the channel by ID, or use a find method, which could return the wrong channel if there are multiple channels the bot has seen that goes with your condition, so what you are trying to do, it doesn’t make much sense.

Give Role when a member joins the voice channel. discord.js

Im trying to make discord.js code. When a member joins the voice channnel I want the bot to give them a role, when the member leaves, i want the role to be removed. thanks for your help.
const newChannelID = newState.channelID;
const oldChannelID = oldState.channelID;
if (oldChannelID === "835280102764838942"){
member.send('role given');
let role = message.guild.roles.cache.find(r => r.id === "835279162293747774");
member.roles.add(835279162293747774);
} else if(newChannelID === "835280102764838942"){
member.send('role removed');
member.roles.remove(835279162293747774);
}
})
There's a couple of things you need to clean up in your code. I'm going to assume you're using the voiceStateUpdate event to trigger your command.
Most importantly, (logic-wise) you actually need to flip-flop the way you add and remove roles. Currently, the general code states that if the user left the voice channel (thus oldChannelID = actual vc ID), then it would actually give the user a role. This seems to be the opposite of your intention, thus you'd simply swap out the code in each if/else if statement.
Second, the way you're assigning roles and adding them is incorrect. I'd recommend this resource for more info.
Third, you cannot access message if you were indeed using voiceStateUpdate as your event, since it only emits an oldState and a newState.
Lastly, you need to designate a text channel to send the message to. In my code, I manually grabbed the ID of the channel I wanted and plugged it into the code. You'll have to do the same by replacing the number strings I have with your own specific ones.
With that being said, here's the correct modified code:
client.on('voiceStateUpdate', (oldState, newState) => {
const txtChannel = client.channels.cache.get('803359668054786118'); //manually input your own channel
const newChannelID = newState.channelID;
const oldChannelID = oldState.channelID;
if (oldChannelID === "800743802074824747") { //manually put the voice channel ID
txtChannel.send('role removed');
let role = newState.guild.roles.cache.get("827306356842954762"); //added this
newState.member.roles.remove(role).catch(console.error);
} else if (newChannelID === "800743802074824747") {
txtChannel.send('role given');
let role = oldState.guild.roles.cache.get("827306356842954762"); //change this somewhat
oldState.member.roles.add(role).catch(console.error); //adding a catch method is always good practice
}
})

(Discord.js) Trying to get a channel id based on the name of the channel, and post a message in it

I'm trying to set up a server with a bunch of text channels named after users so that I can read their DMs to the bot. I can't figure out how to find if a text channel with that person's tag exists already, and I'm not sure if this is the correct code to do this.
Here is the code I'm trying to use:
try{
var txtChannel = client.guilds.cache.get(dmServerID).channels.find(channel => channel.name === (mesage.author.tag.replace('#','-')) && channel.type === "text");
}
catch(e){
client.guilds.cache.get(dmServerID).channels.create(message.author.tag.replace('#', '-'), 'text');
}
txtChannel.send(message.author.tag + ": " + message.content);
After running this code, it gives me an error that reads: Cannot read property 'send' of undefined.
I would also like to know if I am able to create the text channels inside of a category.
First of all, use let over var.
The error is caused by the fact that you declare txtChannel inside the try so it is not available outside that block of code.
Also, you forgot channels.cache (if you are using discord.js v12).
Here is what the code should look like:
let txtChannel = null;
// Already get the guild from the cache since we are gonna use it a bit
const guild = client.guilds.cache.get(guildID);
// Find a text channel that includes in the name the tag of the user
txtChannel = GUILD.channels.cache.find(c => c.type === "text" && c.name.includes(message.author.tag.replace('#','-'));
// If the channel doesn't exist we create the channel, using await to wait until the channel gets successfully created
if(!txtChannel) txtChannel = await GUILD.channels.create(message.author.tag);
// At the end we send the message in the gotten / created channel
txtChannels.send("the message to send");
Note that this code needs to be inside an async function, you can read more about that here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

How to check if a user is writing a message in a shared channel and tell him or her to write in a bot-specific channel

How to check if a user is writing a message in a shared channel and tell him to write in a bot-specific channel?
This is the code I tried:
if (message.channel.id === "bot-playground"){
// write code here
}else {
message.channel.send("Write commands in #bot-playground.").then(msg => {
timeout(3000, msg);
});
}
if (message.channel.id === "bot-playground"){
This needs a channel ID, not a name. To get the ID of the channel, right-click it and select copy ID then use this. if you don't have the copy ID button you may need to Enable developer mode
Also, your mention may not work
message.channel.send("Write commands in #bot-playground.")
See
this question for more
Your issue is caused by the first line if (message.channel.id === "bot-playground") you are trying to use the channel name as an ID.
You either need to look it up using the ID of the channel, which you can get by enabling Developer Mode
Or, you could just use the channel name to find it like so:
message.guilds.channels.cache.find(channel => channel.name === 'bots-playground')
Replace client with whatever variable or constant used to assign the Discord#Client object.
client.on("typingStart", (channel, user) => {
const bot_channel = channel.guild.channels.cache.find(chan => chan.name == "bot-playground");
if (channel.id != bot_channel.id) {
return message.channel.send(`Write commands in <#${bot_channel.id}>`);
}
});

Resources