Sending private messages to user - javascript

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

Related

How to send a message to another Discord server on a specific channel? [duplicate]

I'm failing to achieve something very simple. I can't send a message to a specific channel. I've browsed trough the documentation and similar threads on stack overflow.
client.channels.get().send()
does NOT work.
It is not a function.
I also do not see it as a method on the Channel class on the official documentation yet every thread I've found so far has told me to use that.
I managed to have the bot reply to a message by listening for a message and then using message.reply() but I don't want that. I want my bot to say something in a specific channel in client.on('ready')
What am I missing?
You didn't provide any code that you already tested so I will give you the code for your ready event that will work!
client.on('ready', client => {
client.channels.get('CHANNEL ID').send('Hello here!');
})
Be careful that your channel id a string.
Let me know if it worked, thank you!
2020 Jun 13 Edit:
A Discord.js update requires the cache member of channels before the get method.
If your modules are legacy the above would still work. My recent solution works changing the send line as follows.
client.channels.cache.get('CHANNEL ID').send('Hello here!')
If you are using TypeScript, you will need to cast the channel in order to use the TextChannel.send(message) method without compiler errors.
import { TextChannel } from 'discord.js';
( client.channels.cache.get('CHANNEL ID') as TextChannel ).send('Hello here!')
for v12 it would be the following:
client.on('messageCreate', message => {
client.channels.cache.get('CHANNEL ID').send('Hello here!');
})
edit: I changed it to log a message.
This will work for the newest version of node.js msg.guild.channels.cache.find(i => i.name === 'announcements').send(annEmbed)
This should work
client.channels.fetch('CHANNEL_ID')
.then(channel=>channel.send('booyah!'))
Here's how I send a message to a specific channel every time a message is deleted. This is helpful if you'd like to send the message without a channel ID.
client.on("messageDelete", (messageDelete) => {
const channel = messageDelete.guild.channels.find(ch => ch.name === 'channel name here');
channel.send(`The message : "${messageDelete.content}" by ${messageDelete.author} was deleted. Their ID is ${messageDelete.author.id}`);
});
Make sure to define it if you're not using messageDelete.

How to Make a discord bot send a message in the servers that it is in?

So I'm trying to make a bot that send a message to all the servers that it is in, but the problem is that I don't really know how to make the user chose the specific channel that he wants, and that I don't know how to make the bot send a message to the servers that the bot is in. If someone could help, or tell me about a tutorial that would be appreciated!
Problem #1: How to make a user chose a channel that that the bot sends the message in.
Problem #2: How to Make the bot send a message to all the servers that he is in.
If you would like to state all servers a bot is in, you can use a forEach method. Like so:
let servernames = "";
bot.guilds.cache.forEach(guild => {
servernames += `${guild.name}, `;
});
message.channel.send(`**${servernames.slice(0, servernames.length - 2)}**`)
However, if you are looking to send a message to every server regardless, you would still need a forEach method, simply join with the .send function. Example:
bot.guilds.cache.forEach(guild => {
guild.defaultChannel.send("hi")
});
If you want to send a message to a specific channel, you need to cache it and find using the channel ID. Example:
let channelSend = bot.channels.cache.find(channel => channel.id === 'channel id here')
channelSend.send("hi")

Problems with messageDelete in Discord js

I try to make my bot on Discord server. Want to make a function, which will copy all deleted message in text channel, but, messageDelete hear only deleted message which was writing after bot start. When I delete message which make earlier bot start, its not work.
{
client.on ("messageDelete", messageDelete =>{
let channel = client.channels.find(channel => channel.name === 'log-deleted-message')
console.log(`Deleted :${messageDelete.content}`)
channel.send(`${messageDelete.author.username} write : ${messageDelete.content}`
})
}
The above answer is now outdated.
With Discord.js V12 you can now Cache messages on the messageDelete event, You would need to enable Partials. Once this is enabled, you can fetch the message beforehand like this:
if(message.partial){
let msg = await message.fetch()
console.log(msg.content)
}
That will then log the content of the previously uncached message.
messageDelete is an event that is called when a message is deleted while the bot is on. If a message is deleted before the bot is turned on there is no way to recover it, which is why it's known as deleted. The only way to accomplish the goal that you want is to leave the bot on permanently. Read more in the docs if you want more information.

How to make a bot find a channel owner / compare to the author's ID

I'm making a bot where if you do d!move, the bot will move the channel where the message was sent in under a category via ID. I also want to make it so that whoever does the command has permissions such as MANAGE_CHANNELS, which I've already added. The problem is that when I want to confirm whoever created that channel is the person that activated the command, the bot says yes. I did this on an alt account, where I made the channel and my alt was the one initializing it, and the bot said "success!" I also wanted to make it so if someone else made the channel, and when I did it, it would work because I made the bot know my ID.
I've researched Google and found nothing.
I've tried using a function with fetchAuditlog but get anywhere.
if(!message.channel.client.user.id == message.author || !message.author.id == `329023088517971969`) return message.channel.send("You don't own this channel!")
else message.channel.send("success!");
message.channel.setParent(`576976244575305759`);
I expect the bot to be able to check if the author created the channel, and lead to You don't own this channel if they don't own it. But if they do then the bot moves the channel.
The actual result is the bot moving the channel anyway regardless if they own the channel or not.
As #André has pointed out, channel.client represents the client itself, not the user who created the channel. Also, the last line in your code is not part of the else statement, so that's why it's run regardless of the conditions you defined.
To reach a solution, you can make use of the guild's audit logs. You can search for entries where the user is the message author and a channel was created. Then, all you have left is to check if one of those entries is for the current channel, and run the rest of your code if so.
Sample:
message.guild.fetchAuditLogs({
user: message.author,
type: 'CHANNEL_CREATE'
}).then(logs => {
if (!logs.entries.find(e => e.target && e.target.id === message.channel.id)) return message.channel.send('You don\'t own this channel.');
else {
// rest of code
}
}).catch(err => console.error(err));
When you go <anything>.client.user it will return the bot client.
If you want to see who created the channel you would have to check the Audit Logs or save it internally.
I've checked the documents. Here's what it says for .client about the
channel. It says the person that initialized the channel, or the
person that created it.
On documentation I see this:
The client that instantiated the Channel
instantiated is different of initialized

Return the channel ID of a channel mentioned in a command

The title says all. I'm making a Discord bot in node.js, and one part that I'm trying to add is a .setup command, to make the bot less dependent on manually changing the value of client.channels.get().send(), allowing it to be more easily set up in the future.
Anyway, in my case, I'm trying to have the user reply to a message with a channel mention (like #welcome for example), and have the bot return that ID and save it to a variable.
Currently, I have this:
function setupChannel() {
client.channels.get(setupChannelID).send('Alright. What channel would you like me to send my reminders to?');
client.on('message', message => {
checkChannel = message.mentions.channels.first().id;
client.channels.get(setupChannelID).send('Ok. I\'ll send my reminders to that channel.');
});
}
message.mentions.channels returns undefined.
I know that the message.mentions.channels.first().id bit works when its a user instead of a channel, is there a different way of getting a channel mention in a message?
Here is the most easy and understandable way i found :
message.guild.channels.cache.get(args[0].replace('<#','').replace('>',''))
But it not really what we want we could use <#####9874829874##><<<547372>> and it will work. So i figured out this :
message.guild.channels.cache.get(args[0].substring(2).substring(0,18))
I like to just remove all non-integers from the message, as this allows for both IDs and mentions to be used easily, and it will return the ID for you from that, as mentions are just IDs with <# and > around them. To do this you would use
message.content.replace(/\D/g,'')
With this, your code would look like this:
function setupChannel() {
client.channels.get(setupChannelID).send('Alright. What channel would you like me to send my reminders to?');
client.on('message', message => {
checkChannel = message.content.replace(/\D/g,'');
client.channels.get(setupChannelID).send('Ok. I\'ll send my reminders to <#' + checkChannel + '>.');
});
}
From this you will always get an ID. And we can surround the ID to trun it into a mention.

Categories