Discord.js bot responds when mentioned - javascript

I'm trying to make my discord.js bot send a message when it is pinged. I was unsure how to do this so I referred to this code:
client.on('message', message => {
if (message.content === '<#745648345216712825>') {
message.channel.send('Message Here');
}
});
However, this doesn't work.
Also, is it possible that my bot responds when a person mentions a specific user for example if I am mentioned by the user anywhere in a message the bot responds? If yes, can you show me how to do it?

Message has a property called mentions, which contains all the channels, members, roles, and users mentioned in the message. You can use the method .has(data, [options]) of MessageMentions to see if your bot was mentioned.
client.on("messageCreate", (message) => {
if (message.author.bot) return false;
if (message.content.includes("#here") || message.content.includes("#everyone") || message.type == "REPLY") return false;
if (message.mentions.has(client.user.id)) {
message.channel.send("Hello there!");
}
});
The message event has been renamed to messageCreate in Discord.JS v13. Using message will still work, but you'll receive a deprecation warning until you switch over.

discord.js just got updated you can use
client.on('message', message => {
if (message.mentions.has(client.user)) {
message.channel.send('your message');
}
});

One of the best ways to check if only your bot is mentioned in the entire message is, regex. You can use this regular expression to check if only the client is mentioned:
/^<#!?${<client>.user.id}>( |)$/
You can check message by using the match method of String. In our case, String is message.content:
if (message.content.match(/^<#!?${client.user.id}>( |)$/)) {
return message.channel.send("Thanks for mentioning me! my prefix is ...");
};

Related

How can I check if someone is replying to a message from someone specific

I am using Discord.js v13
My goal is in a message event, like this:
client.on('messageCreate', async message => {
//Code comes here
})
to check if anyone, no matter who, is replying to any message from a specific person
Using the reference field, you can get whether the message is a reply.
For example
client.on('messageCreate', async message => {
if (message.reference.messageId) { // the message is a reply to another message
let referenceMessage = message.channel.messages.cache.get(message.reference.messageId);
if (referenceMessage.author.id == MY_USER_SNOWFLAKE) {
// The reply was to the specific user!
}
}
})
Keep in mind that the reference message must be cached. If it isn't cached, you can use message.fetchReference().

How can I make a discord bot check the contents of a message and reply with a different message depending on the author?

How can I make a discord bot check the contents of a message and reply with a different message depending on the author?
This is my code so far, I found it in a tutorial but it doesn't work. (no error messages for some reason)
client.on('message', function (userID, channelID, message) {
const thisWord = "i'm so cool";
if(message.content.includes(thisWord)) {
if(userID === '<#ID>'){
client.sendMessage({
to: channelID,
message: "agreed"
})
}}
else {
client.sendMessage({
to: channelID,
message: "disagreed"
})
}
})
First of all you must be using a later version of DJS. Please update to the newest stable version v12.5.3. Second, the message event only accepts one parameter whereas you gave three parameters. Third, if you want to send different replies to different messages, then you need to handle the message content. That is, split the message content by space and then handle them.
This might guide you on working with user input commands.
The issue here looks like you're using the old version of DJS. use the latest one.
This would be the correct usage for discord.js v 12.5.3
// the id should be like this '429493473259814923' :)
client.on('message', async message => {
const thisWord = 'i\'m so cool';
if (message.content.toLowerCase().includes(thisWord)) {
if (message.author.id === 'ID') message.reply('disagreed');
else message.reply('disagreed');
}
});

How to make discord.js bots check if the channel is NSFW and reply?

I want to make my discord bot send different messages when anyone types a command in a normal channel or NSFW channels.
I followed the documentation, which I didn't quite get it. I wrote the testing commands below:
client.on('message', message => {
if (command === 'testnsfw') {
if (this.nsfw = Boolean(true.nsfw)) {
return message.channel.send('yes NSFW');
} else return message.channel.send('no NSFW');
}
})
I think it is not working. The bot only responds "no NSFW" on both channels.
You cannot refer to the TextChannel using this in the anonymous function. (Also, this is always undefined in an arrow function) You can access the TextChannel using the Message class, stored in the message variable.
client.on("message", message => {
// Making the sure the author of the message is not a bot.
// Without this line, the code will create an infinite loop of messages, because even if a message is sent by a bot account, the client will emit the message event.
if (message.author.bot) return false;
// message.content is a String, containing the entire content of the message.
// Before checking if it equals to "testnsfw", I would suggest to transform it to lowercase first.
// So "testNSFW", "testnsfw", "TeStNsFw", etc.. will pass the if statement.
if (message.content.toLowerCase() == "testnsfw") {
// You can get the Channel class (which contains the nsfw property) using the Message class.
if (message.channel.nsfw) {
message.channel.send("This channel is NSFW.");
} else {
message.channel.send("This channel is SFW.");
}
}
});
What I encourage you to read:
Message
TextChannel
now you can just do this instead
if(!message.channel.nsfw) return message.channel.send('a message to send to channel')
this is using
discord.js verson 13.6.0

How do i make a discord bot send a message when a specific user is mentioned?

I'm fairly new to javascript and have been using Discord.js to make one or two Discord Bots. I'm working on a feature that sends a message when I'm pinged in my discord server. I've tried a few things and none have worked.
I have this so far, it detects when any user is pinged, not just me.
client.on('message', (message) => {
if (message.mentions.members.first()) {
message.channel.send('Do not ping this user.');
}
});
You can compare User IDs. How to get User IDs.
if (message.mentions.users.first().id === 'Your ID') // if the person mentioned was you
return message.channel.send('Do not mention this user');
Furthermore, as the name suggests, Collection.first() will fetch the first element of a collection. This means that the if statement will only return true if the first mention was you. For example:
User: 'Hello #you' // detected
User: 'Hello #notYou and #you' // not detected
To circumvent this, you can use Collection.has():
// will return true if *any* of the mentions were you
if (message.mentions.users.has('Your ID'))
return message.channel.send('Do not mention this user');

Sending private messages to user

I'm using the discord.js library and node.js to create a Discord bot that facilitates poker. It is functional except the hands are shown to everyone, and I need to loop through the players and send them a DM with their hand.
bot.on("message", message => {
message.channel.sendMessage("string");
});
This is the code that sends a message to the channel when any user sends a message. I need the bot to reply in a private channel; I've seen dmChannel, but I do not understand how to use it. I have the username of the member that I want to send a message to.
An example would be appreciated.
Edit:
After looking around for a user object, I found that I can get all of the users using the .users property of the client (bot). I will try using the user.sendMessage("string") method soon.
In order for a bot to send a message, you need <client>.send() , the client is where the bot will send a message to(A channel, everywhere in the server, or a PM). Since you want the bot to PM a certain user, you can use message.author as your client. (you can replace author as mentioned user in a message or something, etc)
Hence, the answer is: message.author.send("Your message here.")
I recommend looking up the Discord.js documentation about a certain object's properties whenever you get stuck, you might find a particular function that may serve as your solution.
To send a message to a user you first need to obtain a User instance.
Obtaining a User instance
use the message.author property of a message the user sent .
call client.users.fetch with the user's id
Once you got a user instance you can send the message with .send
Examples
client.on('message', (msg) => {
if (!msg.author.bot) msg.author.send('ok ' + msg.author.id);
});
client.users.fetch('487904509670337509', false).then((user) => {
user.send('hello world');
});
The above answers work fine too, but I've found you can usually just use message.author.send("blah blah") instead of message.author.sendMessage("blah blah").
-EDIT- : This is because the sendMessage command is outdated as of v12 in Discord Js
.send tends to work better for me in general than .sendMessage, which sometimes runs into problems.
Hope that helps a teeny bit!
If your looking to type up the message and then your bot will send it to the user, here is the code. It also has a role restriction on it :)
case 'dm':
mentiondm = message.mentions.users.first();
message.channel.bulkDelete(1);
if (!message.member.roles.cache.some(role => role.name === "Owner")) return message.channel.send('Beep Boing: This command is way too powerful for you to use!');
if (mentiondm == null) return message.reply('Beep Boing: No user to send message to!');
mentionMessage = message.content.slice(3);
mentiondm.send(mentionMessage);
console.log('Message Sent!')
break;
Just an FYI for v12 it's now
client.users.fetch('487904509670337509', false).then((user) => {
user.send('heloo');
});
where '487904509670337509' is an id number.
If you want to send the message to a predetermined person, such as yourself, you can set it so that the channel it would be messaging to would be their (your) own userID. So for instance, if you're using the discord bot tutorials from Digital Trends, where it says "to: ", you would continue with their (or your) userID. For instance, with how that specific code is set up, you could do "to: userID", and it would message that person. Or, if you want the bot to message you any time someone uses a specific command, you could do "to: '12345678890'", the numbers being a filler for the actual userID. Hope this helps!
This is pretty simple here is an example
Add your command code here like:
if (cmd === `!dm`) {
let dUser =
message.guild.member(message.mentions.users.first()) ||
message.guild.members.get(args[0]);
if (!dUser) return message.channel.send("Can't find user!");
if (!message.member.hasPermission('ADMINISTRATOR'))
return message.reply("You can't you that command!");
let dMessage = args.join(' ').slice(22);
if (dMessage.length < 1) return message.reply('You must supply a message!');
dUser.send(`${dUser} A moderator from WP Coding Club sent you: ${dMessage}`);
message.author.send(
`${message.author} You have sent your message to ${dUser}`
);
}
Make the code say if (msg.content === ('trigger') msg.author.send('text')}

Categories