Sending private message to a group of user (Discord.js) - discord.js

I'm looking a way to send a private message to à group of users, who have the same role (using discord.js)
I found the way to send a message (client.users.get("ID").send("Message");
But not the way to get all member who have the same role and loop on that list to send them a private message. Someone can help me?

You could do so by first making a list of all the members with the desired role (see Collection.filter()), and then loop through (see Map.forEach()) and send a DM to each member. Check out the code below for an example.
// Assuming 'guild' is defined as the guild with the desired members.
const roleID = ''; // Insert ID of role.
const members = guild.members.filter(m => m.roles.has(roleID) && m.user.id !== client.user.id);
members.forEach(member => {
member.send('Hello there.')
.catch(() => console.error(`Unable to send DM to ${member.user.tag}.`));
// The above error would most likely be due to the user's privacy settings within the guild.
});

Related

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 Guild Member Add

I'm making a bot to detect when a user joined. The code below does not work when my test account joins. Does it only work when it's the first time a user joins. If so, how can I make it work everytime.
client.on('guildMemberAdd', member => {
// Send the message to a designated channel on a server:
const channel = member.guild.channels.cache.find(ch => ch.name === 'general-chat');
// Do nothing if the channel wasn't found on this server
if (!channel) return;
// Send the message, mentioning the member
channel.send(`Welcome to the server, ${member}`);
});
You might have to enable Presence Intent on your bot settings on the Discord Developer Portal, which makes it able to detect new members.Here's an screenshot.

How to send a private message to members of a specific role not in a voice channel?

This is the code I use to count members with a specific role whom are in a voice channel. I want to send a private message to members with the role and not in a voice channel. How can I do so?
var takaci = 0;
let a = client.guilds
.get(sunucuid)
.roles.get(rolid)
.members.filter(o => o.voiceChannel).size;
let ses = a;
Inverse your predicate function in Collection.filter() to acquire only those members with the role and not in a voice channel. Use the ! character, or logical NOT operator.
Iterate over your Collection.
Use GuildMember.send() to send a direct message to each member individually.
const membersToMsg = client.guilds.get(sunucuid).roles.get(rolid).members.filter(m => !m.voiceChannel);
for (const [, member] of membersToMsg) {
member.send('Hello, world!')
.catch(console.error); // 'Cannot send messages to this user' is most likely due to privacy settings
}
I'm using a for...of loop in this code rather than Map.forEach() because the latter will simply fire promises and move on, possibly resulting in uncaught rejections.

Trying to implement Patreon-only commands/functions on my discord bot, how would I accomplish this?

My discord bot gives the role of 'Patreon' to my patreon supporters. This role is given on my main discord bot server. So right now I'm trying to write some commands that would be only available to users who have the role 'Patreon' in the BOTS discord server, how can I accomplish this?
Like is there a way I can be like -
message.member.has('Patreon Role').in('My Discord Server)?
Let's go over the tasks you need to accomplish this.
Get the "home guild" with your users and corresponding Patreon role.
See Client.guilds and Map.get().
Find the user in the guild.
See Guild.member().
Check whether or not the user has the Patreon role.
See GuildMember.roles and Collection.find().
You can define a function to help you out with this, export it and require it where you need it (or define it within relevant scope), and then call it to check if a user is one of your Patreon supporters.
Here's what this function would look like...
// Assuming 'client' is the instance of your Discord Client.
function isSupporter(user) {
const homeGuild = client.guilds.get('idHere');
if (!homeGuild) return console.error('Couldn\'t find the bots guild!');
const member = homeGuild.member(user);
if (!member) return false;
const role = member.roles.find(role => role.name === 'Patreon');
if (!role) return false;
return true;
}
Then, as an example, using this function in a command...
// Assuming 'message' is a Message.
if (!isSupporter(message.author)) {
return message.channel.send(':x: This command is restricted to Patreon supporters.')
.catch(console.error);
}
message.member.roles.find('name', 'Patreon Role');//this returns either undefined or a role
What that does is it searches the users collection to see if the have "Patreon Role"
If the message is on the same server, otherwise you could do
client.guild.find('name','My Discord Server').member(message.author).roles.find('name', 'Patreon Role'); //this also returns undefined or a role
Clearly that second option is long, but what is basically does is searches the servers the bot is in for a server called 'My Discord Server' then it finds the GuildMember form of the message.author user resolvable, then it searches their roles for the role 'Patreon Role'
There is a chance it will crash though if they aren't on the server(the documentation doesn't say if it returns and error or undefined for some reason) so if it does crash you could instead do
client.guild.find('name','My Discord Server').members.find('id', message.author.id).roles.find('name', 'Patreon Role'); //this also returns undefined or a role
You can read more here: https://discord.js.org/#/docs/main/stable/class/User
and here
https://discord.js.org/#/docs/main/stable/class/Client
and here
https://discord.js.org/#/docs/main/stable/class/Guild
To try and give a full example, assuming this is in your message event
if (message.member.roles.find(r => r.name === 'Patreon') == undefined &&
commandIsExclusive || message.guild.id !== 'this-id-for-BOTS-server') {
// Don't allow them in here
}
Essentially, to run a command they must be a supporter, in a specific server and if it is exclusive and the other criteria aren't met, they are denied

Obtain User ID from a DM message Sent To Bot

I want to find the user id of the person who DMs the bot. Is there any way to do it? I am using Discord.js
I tried by storing member author and member Id but it didn't work. But when I store channel, it store it as authors tag. But the id for that channel does not matches with the id of the user who DM the bot. I am trying to make support mail bot. But it requires the user id so that I can continue the thread by DMing the user. But it's not possible until I get the user id or server member object. And I can't store that DMchannel in my database because i use json for storing datas.
Due to my low reputation, I can't comment, sorry if this does not answer your question.
You can get the ID of the person who DM'd your bot by message.author.id (keep in mind, message will need to change to whatever variable your message is stored in).
You can also get the channel ID with message.channel.id.
The channel ID is not the same as the user's ID (they are two different things), which I assumed you misunderstood from id for that channel does not matchs with the id of the user who DM the bot.
Try this:
const client = new discord.Client();
client.login('token here');
/* On message event since you want to
* recieve DM and get ID from user who sent DM to your bot.
*/
client.on("message", (msg) => {
// checks if the message's channel type is 'DM'.
if(msg.channel.type === "dm") {
// you can do anything you want here. In my case I put console.log() function.
// since you wanted user ID, you can use msg.author.id property here.
console.log(`Recieved DM from ${msg.author.tag}, DM content is`, msg.content);
}
});
Please remember, author/member ID and dm message channel ID is completely separate thing.
Also storing member related data in JSON or an SQL is not a really good idea here. I suggest you only doing that for custom data you've generated, or that would be wasting a lot of memory.

Resources