Send a message with Discord.js - javascript

I am trying to make a discord bot, but I can't quite understand Discord.js.
My code looks like this:
client.on('message', function(message) {
if (message.content === 'ping') {
client.message.send(author, 'pong');
}
});
And the problem is that I can't quite understand how to send a message.
Can anybody help me ?

The send code has been changed again. Both the items in the question as well as in the answers are all outdated. For version 12, below will be the right code. The details about this code are available in this link.
To send a message to specific channel
const channel = <client>.channels.cache.get('<id>');
channel.send('<content>');
To send a message to a specific user in DM
const user = <client>.users.cache.get('<id>');
user.send('<content>');
If you want to DM a user, please note that the bot and the user should have at least one server in common.
Hope this answer helps people who come here after version 12.

You have an error in your .send() line. The current code that you have was used in an earlier version of the discord.js library, and the method to achieve this has been changed.
If you have a message object, such as in a message event handler, you can send a message to the channel of the message object like so:
message.channel.send("My Message");
An example of that from a message event handler:
client.on("message", function(message) {
message.channel.send("My Message");
});
You can also send a message to a specific channel, which you can do by first getting the channel using its ID, then sending a message to it:
(using async/await)
const channel = await client.channels.fetch(channelID);
channel.send("My Message");
(using Promise callbacks)
client.channels.fetch(channelID).then(channel => {
channel.send("My Message");
});
Works as of Discord.js version 12

The top answer is outdated
New way is:
const channel = await client.channels.fetch(<id>);
await channel.send('hi')
To add a little context on getting the channel Id;
The list of all the channels is stored in the client.channels property.
A simple console.log(client.channels) will reveal an array of all the channels on that server.

There are four ways you could approach what you are trying to achieve, you can use message.reply("Pong") which mentions the user or use message.channel.send("Pong") which will not mention the user, additionally in discord.js you have the option to send embeds which you do through:
client.on("message", () => {
var message = new Discord.MessageEmbed()
.setDescription("Pong") // sets the body of it
.setColor("somecolor")
.setThumbnail("./image");
.setAuthor("Random Person")
.setTitle("This is an embed")
msg.channel.send(message) // without mention
msg.reply(message) // with mention
})
There is also the option to dm the user which can be achieved by:
client.on("message", (msg) => {
msg.author.send("This is a dm")
})
See the official documentation.

Below is the code to dm the user:
(In this case our message is not a response but a new message sent directly to the selected user.)
require('dotenv').config({ path: __dirname + '/.env.local' });
const Discord = require("discord.js");
const client = new Discord.Client();
client.on("ready", () => {
console.log(client.users.get('ID_OF_USER').send("hello"));
});
client.login(process.env.DISCORD_BOT_TOKEN);
Further documentation:
https://github.com/AnIdiotsGuide/discordjs-bot-guide/blob/master/frequently-asked-questions.md#users-and-members

You can only send a message to a channel
client.on('message', function(message) {
if (message.content === 'ping') {
message.channel.send('pong');
}
});
If you want to DM the user, then you can use the User.send() function
client.on('message', function(message) {
if (message.content === 'ping') {
message.author.send('pong');
}
});

Types of ways to send a message:
DM'ing whoever ran the command:
client.on('message', function(message) {
if (message.content === 'ping') {
message.author.send('pong');
}
});
Sends the message in the channel that the command was used in:
client.on('message', function(message) {
if (message.content === 'ping') {
message.channel.send('pong');
}
});
Sends the message in a specific channel:
client.on('message', function(message) {
const channel = client.channels.get("<channel id>")
if (message.content === 'ping') {
channel.send("pong")
}
});

It's message.channel.send("content"); since you're sending a message to the current channel.

Related

Discord bot not reading message.content

My bot is not reading the Discord chat. I want it to read the chat and if it finds certain words it will give a certain response. This is my current message event code. This is my first JavaScript project and I have just started learning it so please rip it apart so I can learn quicker :)
At the moment I can get the bot to load into discord. I can turn it on with .node but I can not get it to read a message using message.content.
const Discord = require("discord.js");
const client = new Discord.Client({ intents: ["GUILD_MESSAGES", "DIRECT_MESSAGES"] });
var name = "Poker Bot";
var usersHand
let firstCardValue
let secondCardValue
let firstCardSuit
let secondCardSuit
//starts the bot and sets activity to a funny quote. it also will give a command prompt notification that the
// bot is online
client.on("ready", () => {
console.log(`Bot is online: ${name} !`);
client.user.setActivity('Burning The Fucking Casino Down');
});
//check discord chat to see if a user has posted.
client.on("messageCreate", message => {
//console.log is there to test user input. If it works the message in the discord channel will appear in console
console.log(`The user has said: ${message} `);
//look for poker hand ~~~ position ~~~~ event (ex: AA CO PF ) (PF= PreFlop)
if (message.content.toLowerCase == 'AK' || message.content.toLowerCase == 'AA' || message.content.toLowerCase == 'KK'){
message.reply("RECOMMENDED PLAY SHOVE: ALL IN")
}
.content is not a method, it's a property, you must now also enable the Message Content intent on your bot page as well as in your code.
const Discord = require("discord.js");
const client = new Discord.Client({ intents: ["GUILD_MESSAGES", "DIRECT_MESSAGES"] });
client.on("messageCreate", message => {
// || "String" like you did before would return "true" in every single instance,
// this is case sensitive, if you wanna make it case insensitive
// use `message.content.toLowerCase() == "lowercasestring"`
if (message.content == "AK" || message.content = "AA" || message.content == "KK") {
message.channel.send("Recommend Play is to shove all in" + message.author);
}
})
client.login(token);
Judging by your information, you dont just want to send a response if the message contains only those strings, but may just contain then.
To check for that, I would suggest to use regex#test
Still as #iiRealistic_Dev rightfully mentioned: message.content is not a function, so removing the brackets is the way to go.
client.on("messageCreate", (message) => {
if (/AK|AA|KK/.test(message.content)) {
message.channel.send("Recommend Play is to shove all in" + message.author);
console.log('it got to here');
}
});

how to send a message to specific channel Discord.js

I need the code to send a message to a channel I have looked on stack overflow but there all too old and through up a error
There is a guide for this on the discord.js guide.
const channel = <client>.channels.cache.get('<id>');
channel.send('<content>');
An improved version would be:
<client>.channels.fetch('<id>').then(channel => channel.send('<content>'))
At first you need to get the channel ID or Channel Name to do that
/* You handle in command and have message */
// With Channel Name
const ChannelWantSend = message.guild.channels.cache.find(channel => channel.name === 'Channel Name');
// With Channel ID
const ChannelWantSend = message.guild.channels.cache.get(channelId);
ChannelWantSend.send('Your Message');
/* If you start from root of your bot , having client */
// With Channel Name
const ChannelWantSend = client.channels.cache.find(channel => channel.name === 'Channel Name');
// With Channel ID
const ChannelWantSend = client.channels.cache.get(channelId);
ChannelWantSend.send('Your Message');
// In both case If ChannelWantSend is undefined where is a small chance that discord.js not caching channel so you need to fetch it
const ChannelWantSend = client.channels.fetch(channelId);
Discord.js sending a message to a specific channel
Not sure if you have tested out this code yet, but it looks like this may answer your question?
I haven't tested this, but the thread I linked seems to have tested it as of June 2020!
Shortly, I send message to specific channel like under.
<client>.channels.cache.get("<channel_id>").send("SEND TEXT");
Under code piece is my own usage.
In my case, I save all of Direct Messages to my own channel.
const Discord = require('discord.js');
const client = new Discord.Client();
function saveDMToAdminChannel(message) {
var textDM = `${message.author.username}#${message.author.discriminator} : ${message.content}`;
client.channels.cache.get("0011223344556677").send(textDM);
// "0011223344556677" is just sample.
}
client.on("message", async message => {
if(message.author.bot) return;
if(message.channel.type == 'dm') {
saveDMToAdminChannel(message);
}
});
In my own channel, DM's are saved like,
00:00 User1#1234 : Please fix bug
07:30 User2#2345 : Please fix bug!!
10:23 User3#3456 : Please fix bug!!!!

Move all users to your Channel (Discord JS)

I'd like to create a command, that moves all users in my Discord voice channel.
Here is what i tried.
...
client.on('message', async message =>{
//Check message is not Bot
if(message.author.bot) return;
if(message.content=="!movetome"){
if(message.member.voice.channel) {//Is user in voicechannel
message.guild.members.cache.forEach(member => { //Loop every user
if(member.id!=message.member.id&&member.voice.channel){//Is user in voicechannel and is user the command executer
member.setVoiceChannel(message.member.voice.channel)//Sets user to channel
}
});
}
}
});
...
After I tried to run the command "!movetome" in discord chat I got the following error message:
(node:12268) UnhandledPromiseRejectionWarning: TypeError: member.setVoiceChannel is not a function
Thanks for your help :)
Firstly this seems like a bad idea if any user can do it but regardless, .setVoiceChannel is v11, they moved it to <GuildMember>.voice.setChannel()
Change the contents inside of if(message.content=="!movetome") to this
const channel = message.member.voice.channel;
message.guild.members.cache.forEach(member => {
//guard clause, early return
if(member.id === message.member.id || !member.voice.channel) return;
member.voice.setChannel(channel);
});

Trying to make a bot that sends DMs to users

I'm attempting to make a discord bot that checks messages sent in channels for a prefix and argument (!send #Usermention "message"), but despite running, the program closes out as soon as a message is typed in my discord server, not outputting any error messages, so I'm not really sure what to do...
const Discord = require('discord.js');
const client = new Discord.Client();
const auth = require('./auth.json');
const prefix = "!";
client.on("message", (message) =>
{
msg = message.content.toLowerCase();
if (message.author.bot) { return; }
mention = message.mention.users.first(); //gets the first mention of the user's message
if (msg.startsWith (prefix + "send")) //!send #name [message]
{
if (mention == null) { return; } //prevents an error sending a message to nothing
message.delete();
mentionMessage = message.content.slice (6); //removes the command from the message to be sent
mention.sendMessage (mentionMessage); //sends message to mentioned user
message.channel.send ("message sent :)");
}
});
client.login(auth.token);
mention = message.mention.users.first();
It is message.mention**s**. You were missing an s.
Also, you might want to use send, rather than sendMessage, since sendMessage is deprecated.

Discord js deafening an user

Hello I'm trying to deafen a particular person in discord but I keep getting the following error:
TypeError: message.setDeaf is not a function
The discord js docs state that you should deafen members like this.
.setDeaf(deaf)
Deafen/undeafen a user.
I'm unsure as to why I'm getting this error, below is my code;
var Discord = require("discord.js");
var client = new Discord.Client();
var user = "30898500862111287"
client.on('ready', () => {
console.log('I am ready!');
});
client.on('message', function(message) {
if (message.content === '$deafen') {
message.setDeaf(user);
}
});
setDeaf() is a function derived from GuildMember, not Message. Since Message does not contain a function called setDeaf(), it gave you that error.
In order to get GuildMember, which is the user you want to deafen/undeafen, you can first get the user from the Message, in your case, it will be message.author, which will return the user who sent that message.
Now, on Guild, there is a FetchMember() function that returns a GuildMember datatype. For that function's argument, all you have to do is just to put in your user that you want to target.
(Your Guild will of course be the guild where the message is in! Message.Guild should do the trick.)
Last step is just to deafen/undeafen the user.
You're using setDeaf() on a Message and not a GuildMember (SetDeaf() is a GuildMember method).
Additionally, you're passing an unexisting value user to setDeaf(). I'm guessing you were trying to pass the message.author, but setDeaf() takes a boolean and an optional reason string, not a User.
You can achieve what you're looking for with this:
if(message.content == "$deafen")
message.member.setDeaf(true);
Alternatively, add a reason:
if(message.content == "$deafen")
message.member.setDeaf(true, "reason");
References:
Message Object
GuildMember Object
you cannot invoke a Server Deaf on Message. You can do it on Guild_Member.
If you want to get the first mentioned member:
let mMember = message.mentions.members.first()
mMember.setDeaf(true)
You can also invoke it on the message_author with a member property.
message.member.setDeaf(true)
But you cannot set a Server Deaf on a Message.
It looks like they've changed the code for this a little bit, instead of:
member.setDeaf(true);
You now use:
member.voice.setDeaf(true);
The code below is solution:
const user = message.mentions.members.first()
if(!args[1]) {
message.channel.send('send me a user to mute in voice')
} else {
user.voice.setDeaf(true, `${args[2]}`)
}
Seeing as you may only deafen guild members a useful approach could be getting the guild member.
You pass the set deaf an id, this would in short throw a logic error because you passed an invalid argument type.
The following should achieve what you were going for.
var Discord = require("discord.js");
var client = new Discord.Client();
client.on('ready', () => {
console.log('I am ready!');
});
const guild = client.guilds.cache.get("YOUR GUILD ID");
const user = guild.members.cache.get("30898500862111287");
client.on('message', message => {
if (message.content === '$deafen') {
user.voice.setDeaf(true);
}
});
However, if you instead want to deafen a mentioned member you could take this approach.
var Discord = require("discord.js");
var client = new Discord.Client();
client.on('ready', () => {
console.log('I am ready!');
});
client.on('message', message => {
let mentioned = message.mentions.members.first();
if (message.content === '$deafen') {
mentioned.voice.setDeaf(true);
}
});
(On a side note I'd recommend the use of constants for your discord and client object so they may not be mutated)
const Discord = require("discord.js");

Categories