I want a discord bot send a dm to somebody by their id - discord

if (message.content === "!test"){
client.users.cache.get('id').send('message');
console.log("message sent")
}
This method doesn't work and I wasn't able to find any other methods that worked
Is there a spelling mistake or this method is outdated?

I've actually encountered this error myself once. There are two problems you might be facing here:
The user isn't cached by discord.js yet
There isn't a DMChannel open for that user yet
To solve the first one, you have to fetch the user before doing anything with it. Remember this is a Promise, so you'll have to either await for it to complete or use .then(...).
const user = await client.users.fetch('id')
Once you've fetched your user by their ID, you can then create a DMChannel which, again, returns a promise.
const dmChannel = await user.createDM()
You can then use your channel like you normally would
dmChannel.send('Hello!')

Try to create a variable like this:
var user = client.users.cache.find(user => user.id === 'USER-ID')
And then do this:
user.send('your message')

Related

How do I fetch all reactions from a specific message? [Discord.js]

So, I want to make a command for my bot which can fetch all reactions from a given message ID and store these three categories into arrays, for each reaction:
the name of the reaction (eg. :smile:)
the users who reacted (eg. RandomUser#4654, ILikePotatoes#1639)
and how many people reacted with this emoji (eg. Count: 2)
I've tried using the ReactionCollector, but it doesn't work for reactions added prior to the event being called. I've also tried using an external module called discord-fetch-all but all it does is either sending Promise { <Pending> } or undefined when I use .then().
PS: I've already set up a command handler that takes a message ID for argument.
Thank you in advance for helping.
You can get the specific message you want to be check for reactions by using:
const messageReacted = client.channels.cache.get('channelId').messages.fetch('messageId')
Then, you can go through each reaction in the message's cached reactions by using forEach
Then, in the .forEach, you can get the emoji name by using reaction._emoji.name, the number of users who used this reaction by reaction.count and all the users who reacted on the message by fetching them: await reaction.users.fetch().
Your final code might look something like:
const messageReacted = await client.channels.cache
.get('channelId')
.messages.fetch("messageId");
messageReacted.reactions.cache.forEach(async(reaction) => {
const emojiName = reaction._emoji.name
const emojiCount = reaction.count
const reactionUsers = await reaction.users.fetch();
});

Discord.js V13 dont know how to check if a user ID is in the current guild

I have been trying to check if a certain user ID exists in the current guild,
I have been looking at countless stack overflow questions and documentations hoping i could find the answer but nothing I try actually works.
i use Discord.js V13 with the latest node.js version
const server = client.guilds.fetch( message.guild.id );
if ( !server.member(args[0]) ) return commandFailed('a user with this ID does not exist');
// args[0] contains the userID
could someone please help me with this.
First: fetch returns a promise, you must handle that promise. However, you don't need to fetch the server since the server is already accessible through message.guild.
Second: Guild#member() is deprecated, try fetching the member directly and checking if a member returned.
I'll be using Async/Await for this example, make sure you're inside an Async function.
// const server = await client.guilds.fetch(message.guild.id); is not needed
const server = message.guild;
const member = await server.members.fetch(args[0]);
if (!member) return commandFailed('a user with this ID does not exist');
Take a look at this thread, which explains exactly what you want:
let guild = client.guilds.get('guild ID here'),
USER_ID = '123123123';
if (guild.member(USER_ID)) {
// there is a GuildMember with that ID
}

How to get permissions in discord js when we do direct message

I am trying to get a list of the permission that the user has in Discord. If it sends the message in the channel, it’s fine as we can use message.member.hasPermission, etc.
But what if the message is DM? I want my users to send a DM to the bot and the bot be able to check and see if the user has certain permissions.
I cannot find anything anywhere. I keep getting redirected to message.member, or message.guild which both are null when it’s in DM.
In DM no one has permissions. All you have is the permission to see messages and send messages which aren’t shown visually, or to bots. To make sure that it isn’t DM, just return if the channel type is dm, or guild is null.
if(!message.guild) return;
//before checking "perms"
If you want the permissions for a certain guild if the message is from DM, use this code
if(message.channel.type === 'dm') {
let guild = await client.guilds.fetch('THE ID OF THE GUILD YOU WANT TO SEE THE USER’S PERMS IN')
let member = await guild.members.fetch(message.author.id);
//you can now access member.permissions
}
Keep in mind await must be in an async callback.
You did not provide any code so I cannot give any more code than this.
You can fetch the member with the guild's context.
Fetching is recommended, as Guild#member() relies on cache and is also deprecated.
Member#hasPermission() will be deprecated as well, using MemberRoleManager#has() is recommended
The following example uses async/await, ensure you're inside an async function
// Inside async function
const guild = await client.guilds.fetch('guild-id');
const member = await guild.members.fetch(message.author.id);
const hasThisPermission = member.roles.cache.has('permission');

Discord JS v12: How do you get a message's content by it's ID?

I'm relatively new to discord.js, and I've started building a bot project that allows a user to create a message via command, have that message stored in a hidden channel on my private server, and then said message can be extracted through the message ID.
I have the write working and it returns the message ID of the message sent in the hidden channel, but I'm completely stumped on the get command. I've tried searching around online but every method I tried would return errors like "Cannot read property 'fetch' of undefined" or "'channel' is not defined". Here are some examples of what I tried, any help would be appreciated. Note that my args is already accurate, and "args[0]" is the first argument after the command. "COMMAND_CHANNEL" is the channel where the command is being executed while "MESSAGE_DATABASE" is the channel where the targeted message is stored.
let msgValue = channel.messages.cache.get(args[0])
client.channels.cache.get(COMMAND_CHANNEL).send(msgValue.content)
let msgValue = msg.channel.message.fetch(args[0])
.then(message => client.channels.cache.get(COMMAND_CHANNEL).send(msgValue.content))
.catch(console.error);
I even tried using node-fetch to call the discord API itself
const api = require("node-fetch")
let msgValue = api(`https://discordapp.com/api/v8/channels/${MESSAGE_DATABASE}/messages/${args[0]}`)
.then(message => client.channels.cache.get(COMMAND_CHANNEL).send(msgValue.content))
.catch(console.error);
Am I missing something or am I making some sort of mistake?
Edit: Thanks for the help! I finished my bot, it's just a little experimental bot that allows you to create secret messages that can only be viewed through their ID upon executing the command :get_secret_message <message_id>. I posted it on top.gg but it hasn't been approved yet, so in the meantime if anyone wants to mess around with it here is the link: https://discord.com/api/oauth2/authorize?client_id=800368784484466698&permissions=76800&scope=bot
List of commands:
:write_secret_message - Write a secret message, upon execution the bot will DM you the message ID.
:get_secret_message <message_id> - Get a secret message by its ID, upon execution the bot will DM you the message content.
:invite - Get the bot invite link.
NOTE: Your DMs must be turned on or the bot won't be able to DM any of the info.
My test message ID: 800372849155637290
fetch returns the result as promise so you need to use the then to access that value instead of assigning it to a variable (msgValue). Also you made a typo (channel.message -> channel.messages).
I would recommend using something like this:
msg.channel.messages
.fetch(args[0])
.then(message => {
client.channels
.fetch(COMMAND_CHANNEL)
.then(channel => channel.send(message.content))
.catch(console.error)
})
.catch(console.error)
I think you were quite close with the second attempt you posted, but you made one typo and the way you store the fetched message is off.
The typo is you wrote msg.channel.message.fetch(args[0]) but it should be msg.channel.messages.fetch(args[0]) (the typo being the missing s after message). See the messages property of a TextChannel.
Secondly, but this is only a guess really as I can't be sure since you didn't provide much of your code, when you try to fetch the message, you are doing so from the wrong channel. You are trying to fetch the message with a given ID from in the channel the command was executed from (the msg.channel). Unless this command was executed from the "MESSAGE_DATABASE" channel, you would need to fetch the message by ID from the "MESSAGE_DATABASE" channel instead of the msg.channel.
Thirdly, if you fetch a message, the response from the Promise can be used in the .then method. You tried to assign the response to a variable msgValue with let msgValue = msg.channel.message.fetch(args[0]) but that won't do what you'll expect it to do. This will actual assign the entire Promise to the variable. What I think you want to do is just use the respone from the Promise directly in the .then method.
So taking all that, please look at the snippet of code below, with inspiration taken from the MessageManager .fetch examples. Give it a try and see if it works.
// We no longer need to store the value of the fetch in a variable since that won't work as you expect it would.
// Also we're now fetching the message from the MESSAGE_DATABASE channel.
client.channels.cache.get(MESSAGE_DATABASE).fetch(args[0])
// The fetched message will be given as a parameter to the .then method.
.then(fetchedMessage => client.channels.cache.get(COMMAND_CHANNEL).send(fetchedMessage.content))
.catch(console.error);

Why doesn't Collection#find work for offline members who have no roles? (discord.js)

My Goal
My goal is to figure out why Collection#find returns undefined when I try to find a user in my server, but they're offline and have no roles.
Expectation
Usually the console logs an array of all the properties of the user
Actual Result
The console logs Collection#find, as undefined if the user in my server is offline and has no roles
What I've Tried
I've tried using Collection#get, but it turns out that it returns the same response. I've tried searching this up on Google, but no one has asked this question before.
Reproduction Steps
const Discord = require('discord.js');
const client = new Discord.Client();
const {prefix, token} = require('./config.json');
client.once('ready', () => {
console.log('Client is online');
const user = client.users.cache.find(user => user.tag === 'Someone#1234');
console.log(user);
};
client.login(token);
Make sure that whoever is helping you, whether it's an alt account or your friend, that they have no roles, and they're completely offline in your server
Output:
Client is online undefined
I had the same problem. I don't know why this happens, but I used this line to fix that:
((await m.guild.members.fetch()).filter(mb => mb.id === "The ID")).first()`
Basically, this collect all the members, then filters them with the property you want, and the first() at the end is to make it a single object instead of a collection.
Instead of the user.tag property, try using the user.username and the user.discriminator properties. This worked for me
const user = client.users.cache.find(user => user.username === 'Someone' && user.discriminator === '1234');
Also check spelling, capitalization, ect.
A simple solution to my problem is just create an async function and use await guild.members.fetch() to cache the users and then use Collection#find to get the user.

Resources