message channel name returning an undefined - javascript

Hi I'm trying to get the channel name of a channel I've created. however, I'm getting undefined as if the channel I created does not exist, which it does.
Here is my code:
const new_channel = message.guild.channels.create("New Name").then((channel) => {
channel.setParent(categoryId)
channel.setTopic(topic)
})
message.channel.send(`Ticket created in ${new_channel}`);
What I'm doing wrong here?

new_channel is NOT the GuildChannel you just created. It is a Promise<GuildChannel>. In other words, it is "promising" that it can deliver you a text channel, and will deliver it to you once the channel has been created via .then.
Basically, creating a text channel in Discord takes some time. Discord.js has to send a request to the Discord API, wait for Discord to create the channel, and then get the Discord API's response. Only then will Discord.js give you the data for the text channel you created. Hence why we use .then(); once the channel has been created, only then will the code inside .then() be executed.
As for why new_channel is undefined, it may be because you are not returning a value in your .then(). Therefore, there is nothing further to promise.
So the solution to your problem is to reference the actual variable that contains the created channel; the channel parameter passed into your .then(). Here is an example:
const new_channel = message.guild.channels.create("New Name").then((channel) => {
channel.setParent(categoryId);
channel.setTopic(topic);
message.channel.send(`Ticket created in ${channel.name}`);
})
As you can see, your code was already setting the parent and topic of channel, not new_channel. So it logically makes sense that the name of the channel is also in channel, not new_channel.

It's best to reference the channel ID of the channel created instead of the object when sending a message. See the example below.
Example:
let guild = await client.guilds.fetch(message.guild.id);
let newChannel = await guild.channels.create("name");
newChannel.setParent("catagory-id");
newChannel.setTopic("The topic of the channel");
message.channel.send(`<#!${message.author.id}> Your ticket was created in <#!${newChannel.id}>`);
Full Example:
let Discord = require('discord.js');
let client = new Discord.Client();
client.on('messageCreate', async function(message) {
// Do something
let guild = await client.guilds.fetch(message.guild.id);
let newChannel = await guild.channels.create("name");
newChannel.setParent("catagory-id");
newChannel.setTopic("The topic of the channel");
message.channel.send(`<#!${message.author.id}> Your ticket was created in <#!${newChannel.id}>`);
});
client.login('your-token');

Related

Sending message to specific channel in discord.js

I want to send a message to a specific channel but it doesn't work, I've tried
client.guilds.cache.get("<id>").send("<msg>")
but I get the error ".send is not a function".
What am I missing here?
There are three ways of sending message to a specific channel.
1. Using a fetch method
const channel = await <client>.channels.fetch('channelID')
channel.send({content: "Example Message"})
2. Using a get method
const channel = await <client>.channels.cache.get('channelID')
channel.send({content: "Example Message"})
3. Using a find method
a.
const channel = await <client>.channels.cache.find(channel => channel.id === "channelID")
channel.send({content: "Example Message"})
b.
const channel = await <client>.channels.cache.find(channel => channel.name === "channelName")
channel.send({content: "Example Message})
Your current code line is getting the GUILD_ID not the CHANNEL_ID.
You are trying to get from the cache a Guild not a Channel, or more specifically a TextChannel, that's why what you try is not working, you should try to change the code to something like this and it should work.
const channel = client.channels.cache.get('Channel Id');
channel.send({ content: 'This is a message' });
Also, as something extra, I would recommend using the fetch method for these things, since it checks the bot's cache and in the case of not finding the requested object it sends a request to the api, but it depends on the final use if you need it or not.
const channel = await client.channels.fetch('Channel Id');
channel.send({ content: 'This is a message' });

Discord bot log

So, I created a discord.js bot and added the following into index.js:
client.on("guildCreate", guild = {
const logsServerJoin = client.channels.get('757945781352136794');
console.log(`The bot just joined to ${guild.name}, Owned by ${guild.owner.user.tag}`);
client.channels.cache.get('channel id paste here').send(`The bot just joined to ${guild.name}, Owned by ${guild.owner.user.tag}`);
var guildMSG = guild.channels.find('name', 'general');
if (guildMSG) {
guildMSG.send(` Hello there! My original name is \`Bryant\`!\n\ This bot created by **R 1 J 4 N#7686**\n\ For more info
type \`/help\`!\n\ \`Bryant - Official Server:\`
https://discord.gg/UsQFpzy`);
} else {
return;
}
});
// Logs of the bot leaves a server and changed the game of the bot
client.on("guildDelete", guild = {
client.channels.cache.get('757945781352136794').send(`The bot just
left ${guild.name}, Owned by ${guild.owner.user.tag}`);
console.log(`The bot has been left ${guild.name}, Owned by ${guild.owner.user.tag}`);
logsServerLeave.send(`The bot has been left ${guild.name}, Owned by ${guild.owner.user.tag}`);
});
It does not show any error in the terminal. It is supposed to log me where the bot joined and left in the mentioned channel but does not 🤷‍♂️. Can anyone help me out with this?
If you are getting no console log and no message in the channel / an error telling you that the channel could not be found, the issue is most likely in how you are registering the events, make sure client is an instance of the discord.js Client, below is a minimal working example
const { Client } = require("discord.js")
const client = new Client()
client.on("guildCreate", guild => {
console.log(`The bot just joined to ${guild.name}, Owned by ${guild.owner.user.tag}`)
})
client.login("yourtoken")
If you are trying to get the logs from your bot alert you in your home discord server you can do this multiple ways: Getting the channel from cache, Constructing the channel or Using webhooks. Currently you are trying to fetch the channel from cache. Although a decent solution it can fall down when using sharding later down the line. Personally I prefer webhooks as they are the easiest and most isolated.
Channel from cache
This technique is very similar to the way you were doing it.
const channel = client.channels.cache.get('757945781352136794')
channel.send('An Event occurred')
Just place this code anywhere you want to log something and you'll be fine.
Constructing the channel
const guild = new Discord.Guild(client, { id: '757945781352136794' });
const channel = new Discord.TextChannel(guild, { id: '757945781352136794' });
channel.send('An Event occurred')
This method is similar to fetching the channel from cache except it will be faster as you are constructing your home guild and channel and then sending to it. Mind you will need a client which you can get from message.client
Webhooks
My Favourite method uses webhooks. I recommend you read up on how discord webhooks work in both Discord and Discord.js
You will also need to create a webhook. This is very easy. Go into the channel you want the webhooks to be sent to and then go to integrations and create a new webhook. You can change the name and profile as you wish but copy the url and it should look something like this:
https://discord.com/api/webhooks/757945781352136794/OkMsuUHwdStR90k7hrfEi5*********
The last part of the path is the webhook token and the bit before is the channel ID
I recommend you create a helper function that can be called like this:
sendWebhook('An event occurred');
And then write the function to create and then send to the webhook
function sendWebhook(text) {
const webhook = new Discord.WebhookClient('757945781352136794', 'OkMsuUHwdStR90k7hrfEi5*********');
webhook.send(text);
webhook.destroy();
}
This will not be very dynamic and will be a pain to change the channel but for constant logging ( like guild joins and leaves ) I think it is the best solution
The problem is probably that you don't have "Privileged Gateway Intents" enabled. To turn them on, go to https://discord.com/developers, click on your application, then on "Bot" then scroll down and enable "PRESENCE INTENT" and "SERVER MEMBERS INTENT" and save. It should probably work for you now.

how to detect an embed and then resend it (discord.js)

so what i am trying to do is detect when a bot sends an embed in a channel, and when it does detect this, to take that embed and resend it the same as it was sent as.
For example, if the bot detects an embed sent in one channel, it will send that exact same embed in another channel. But the reason for this is because I want to take the embeds from multiple bots.
in discordjs.guide it says to use this code:
const receivedEmbed = message.embeds[0];
const exampleEmbed = new Discord.MessageEmbed(receivedEmbed).setTitle('New title');
channel.send(exampleEmbed);
but this has not worked for me
You need to replace channel in the line channel.send(exampleEmbed); with an actual reference to a channel. Since you will be using the message event handler, you can get the channel the message was sent in using message.channel.
I have also added in a check to ensure that the message was sent by a bot and contains an embed.
client.on('message', message => {
// check to ensure message was sent by bot and contains embed
if (!message.author.bot || !message.embeds[0]) return;
const receivedEmbed = message.embeds[0];
const exampleEmbed = new Discord.MessageEmbed(receivedEmbed).setTitle('New title');
// send in same channel
message.channel.send(exampleEmbed);
// send in different channel
client.channels.fetch(/* Channel ID */).then(channel => {
channel.send(exampleEmbed);
});
// alternatively, you can use this (but the function must be asynchronous)
const channel = await client.channels.fetch(/* Channel ID */);
channel.send(exampleEmbed);
});
For more information on valid properties and methods, read the Discord.js docs.
The following code will check if the message has any embeds and will resend the first one.
if (message.embeds) {
message.channel.send({ embed: message.embeds.first() || message.embeds[0] })
};
const embed = message.embeds[0];
const editedEmbed = embed
.setTitle('Edited!')
.addField('Test Field!', 'This is a test', true);
message.channel.send(editedEmbed);
This worked perfectly fine for me.
The problem will be that you don't have a TextChannel selected. (message.channel)

can someone help me fix this script?

const Discord = require("discord.js");
const client = new Discord.Client();
const config = require("./config.json");
client.on("guildMemberAdd", member =>{
var role = member.guild.roles.find("ID", "here I put the role id");
member.addRole(role);
});
This script is giving error and I don't know how to fix it. The error is:
member.guild.roles.find is not a function
discord.js v12+ uses Managers, so you will have to add the cache property.
Replace:
var role = member.guild.roles.find("ID", "here I put the role id");
with:
var role = member.guild.roles.cache.find(role => role.id === 'ID Here')
An even easier way to do it is with the .get() method:
var role = member.guild.roles.cache.get("ID Here")
Although either would work.
Since discord.js v12+, the addRole() method is also deprecated. Instead, replace it with:
member.roles.add(role)
Please consider reading on the Discord.js v12 docs regarding adding roles to members here
Things in the cache are now found directly on the cache
and members/roles/users/channels are all found on the cache, sooo
const Discord = require("discord.js");
const client = new Discord.Client();
const config = require("./config.json");
client.on("guildMemberAdd", member =>{
var role = member.guild.roles.cache.find(role => role.id == "ROLE ID HERE");
member.roles.add(role.id);
});
Hi #Joaozwy (Brazilian like me or not? :)
First things first. Why you are receiving this error?
The event "guildMemberAdd" from Discord.Client send the member object as a parameter.
It has the guild property which has the property roles.
But member.guild.roles which is from type RoleManager doesn't have the method find.
That's why it's giving you the error you are receiving.
Now, It seems to me, with the available information you gave us, you are trying to get the role by it's ID and add to the member.
If that's the case, try this:
const Discord = require("discord.js");
const client = new Discord.Client();
const config = require("./config.json");
client.on("guildMemberAdd", member =>{
let role = member.guild.roles.cache.find(role => role.id === "here I put the role id");
member.roles.add(role, "Optional string saying why are you adding this role to the member");
});
Remember to change the string "here I put the role id" to the string with the correct role ID you wanna add to the user.
Also, the add method returns a Promise. Its a good practice to, at least, listen for errors or rejections on promises so if something goes wrong, you can know why.

How to remove a message after a specific period of time in DiscordJS?

I have a question demanding DiscordJS.
It is, how to properly delete a Discord message that the bot sent?
I know it's a newbie question, but I'm new to DiscordJS.
I'm very thankful for all the responses I get, no matter if helpful or not.
You have to use the .delete method for the message object in order to delete the message. Just wait until the message is sent and then delete it after a certain period of time.
For (Rich)embeds, use the following code:
const Discord = require('discord.js');
const RichEmbed = new Discord.RichEmbed()
.setAuthor('test');
const message = await message.channel.send({ embed: RichEmbed }).then(r => r.delete('time in milliseconds'));
For normal messages, use the following code:
const message = await message.channel.send('Hello').then(r => r.delete('time in milliseconds'))

Categories

Resources