Sending message to specific channel in discord.js - javascript

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' });

Related

How to get "snowflake" value for user_id?

I'm trying to write a command that messages a specified user. The user can type something like /warn #user insert warning here. Here is the code:
const user = await client.users
.fetch(interaction.options.getString("user"))
.catch(console.error);
const embed = new MessageEmbed()
.setColor("#FCE100")
.setTitle(`⚠️ Warning!`)
.setDescription(`${interaction.options.getString("warning")}`);
await user.send({ embeds: embed }).catch(() => {
interaction.channel.send("Error: user not found");
});
Here's the error I'm getting:
user_id: Value "<#!9872345978#####>" is not snowflake.
How do I get the correct "snowflake" value to actually be able to DM the user?
You have to use getUser instead of getString and also change your user option type to "USER" to make it work!

message channel name returning an undefined

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');

How to make discord bot send scraped message?

I want to make an a discord bot that sends a scraped message.
I expected it to send the message but it gave me an error:
throw new DiscordAPIError(request.path, data, request.method, res.status);
DiscordAPIError: Cannot send an empty message
I tried to use message.channel.send(); but it doesn't seem to work.
Code:
let data = await page.evaluate(() => {
let Name = document.querySelector('div[id="title"]').innerText;
let Description = document.querySelector('div[id="content"]').innerText;
return {
Name,
Description
}
});
console.log(data);
message.channel.send(data);
debugger;
await browser.close();
The problem is that you shouldn't send the dictionary directly. While message.channel.send only accepts StringResolvable or APIMessage, data as a dictionary is neither. For more information, see the documentation.
Instead, you can convert data to a string first. The following is one of the solutions.
// Convert using JSON.stringify
message.channel.send(JSON.stringify(data));
Full code example (I tried it on https://example.com and thus there are different queries):
let data = await page.evaluate(() => {
let Name = document.querySelector('h1').innerText;
let Description = document.querySelector('p').innerText;
return {
Name,
Description
}
});
console.log(data);
message.channel.send(JSON.stringify(data));
Message sent by the bot without errors being thrown:
{"Name":"Example Domain","Description":"This domain is for use in illustrative examples in documents. You may use this domain in literature without prior coordination or asking for permission."}
If you expect a different message, just make sure that the argument you are passing to message.channel.send is acceptable or errors might be thrown.

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)

discord.js Greeting message not sending

I was following the discord.js docs and when I tried to test the greeting thing the message didn't send. The channel is right, I even tried doing it with the channel ID (with different code), I also tried just sending a direct message. No error appears, the console is just empty and the message doesn't appear.
client.on('guildMemberAdd', member => {
const channel = member.guild.channels.cache.find(ch => ch.name === 'member-log');
if (!channel) return;
message.channel.send(`Welcome to the server, ${member}!`);
});
There is no need for "cache" in guildMemberAdd, that's why the channel was not found. The message variable was also not defined.
client.on('guildMemberAdd', member => {
const channel = member.guild.channels.find(ch => ch.name === 'member-log');
if (!channel) return;
channel.send(`Welcome to the server, ${member}!`);
});
I had this same exact problem and for me it wasn't a problem in the code itself, I just gave the bot every single permission on the category of the welcome channel as well as the welcome channel itself.
It could also be that you have something else as the const name instead of 'client'.

Categories

Resources