Discordjs DM all server members - javascript

I'm trying to DM all server members by a bot trough a command and it only DMs 4 people that are Administrators
message.guild.members.cache.forEach(member => { // Looping through each member of the guild.
// Trying to send a message to the member.
// This method might fail because of the member's privacy settings, so we're using .catch
member.send(`hi`)
.catch(() => (`Couldn't DM member ${member.user.tag}`));
message.channel.send(`Success`)
.catch(console.error);
});

This operation can be extremely time-consuming. #SuleymanCelik's answer was partially correct because not every user is stored in the bot member cache. To get every single user in the server, you need to make a fetch() call for all the users like this.
guild.members
.fetch()
.then(members => members.forEach(member => {
member
.send("Hello!")
.catch(() => {
console.error(`Failed to send ${member.user.tag} a message`)
})
}))

you can send a message to all users whose privacy settings are not turned on in this way
message.guild.members.cache.forEach(member => { // Looping through each member of the guild.
// Trying to send a message to the member.
// This method might fail because of the member's privacy settings, so we're using .catch
member.send("Hello, this is my message!").catch(e => console.error(`Couldn't DM member ${member.user.tag}`));
});

Related

How can I make the channel.send know where its being sent

I tried messing around with it and couldn't get it to work - all I want is for it to send in the channel that the user initiated the bot to talk.
client.once('ready', async () => {
// [beta]
const storedBalances = await Users.findAll();
storedBalances.forEach(b => currency.set(b.user_id, b));
client.channels.fetch("/*the channel where channel.send will go to*/").then((c) => {
channel = c;
})
console.log(`Logged in as ${client.user.tag}!`);
});
It's quite easy, in fact. If you haven't created the client.on("messageCreate", message => {}); event handler, I very strongly recommend creating it in the main file (if you use multiple files). Then, all you have to do is use message.channel.send(); inside those curly brackets {} to send message in the channel the user initiated the bot to talk. It's a good idea to check out the discord.js guide: https://discordjs.guide/#before-you-begin and watch YouTube tutorials on discord.js v13.

Discord.js how to check if user has a role on a specific server

I'm trying to check if the user has a role on a specific server regardless on which server they use the bot.
For example, if I have 2 servers, server A and server B, I want to check if the user has the role "Beginner" on server A, even if I use the command in server B.
I couldn't find a way to do this on the internet, message.member.roles seems to only return the roles of the server the command was written in.
You can do it like this:
function hasRole(guildId, roleId) {
// Get second guild
const guild = client.guilds.cache.get(guildId);
// Get member in that guild, by ID
const member = guild.members.cache.get(message.author.id);
// If member is in that guild,
if (member) {
// return whether they have this role
return member.roles.cache.has(roleId);
}
}
Of course the bot has to be in both servers.
A solution is to find the server then find the member from inside the server.
To find the guild you will use the guild.fetch(...) method and from there you then use the guildMember.fetch(...) function to find the member.
Example:
client.on("messageCreate", function(message) {
// Find the guild
let guild = client.guilds.fetch("guild-id");
// Find the member in the guild
let member = guild.members.fetch(message.author.id);
if (member)
message.reply("You are in the server " + guild.name);
});

How Do i Check if a Certain Bot Exists in a Guild | discord.js

Hey So I Have a Bot That Requires Two Bots to Work with each other I need to know How to Check if a bot is in the guild if not then to Tell the user to invite it.
Heres My Current Code:
if(message.guild.users.id === "ID") {
//If its in the Server
} else {
//If it isnt
}
I recommend fetching all members of a guild to ensure all members are cached. This will return a promise, resolve the promise to get the Collection of the Guild Members. Use has() with the bot's id, This will return true if the id was found in the Collection, false otherwise.
message.guild.members.fetch().then(memberList => {
if (memberList.has("ID")) {
// If it's in the server
} else {
// if it's not
}
}).catch(console.error);
You can also try to fetch the bot directly and check if a GuildMember object returned.
message.guild.members.fetch("ID")
.then(botObject => {
// If found
})
.catch(err => {
// If not found
});
You will need to enable the GuildMember's Intent for fetching to work.

discord.js Greeting message not sending

I was following the discord.js docs and when I tried to test the greeting thing the message didn't send. The channel is right, I even tried doing it with the channel ID (with different code), I also tried just sending a direct message. No error appears, the console is just empty and the message doesn't appear.
client.on('guildMemberAdd', member => {
const channel = member.guild.channels.cache.find(ch => ch.name === 'member-log');
if (!channel) return;
message.channel.send(`Welcome to the server, ${member}!`);
});
There is no need for "cache" in guildMemberAdd, that's why the channel was not found. The message variable was also not defined.
client.on('guildMemberAdd', member => {
const channel = member.guild.channels.find(ch => ch.name === 'member-log');
if (!channel) return;
channel.send(`Welcome to the server, ${member}!`);
});
I had this same exact problem and for me it wasn't a problem in the code itself, I just gave the bot every single permission on the category of the welcome channel as well as the welcome channel itself.
It could also be that you have something else as the const name instead of 'client'.

Await reply in private message discord.js

So, this works ALMOST as intended. I have the bot private messaging the user who uses the correct command in the correct channel of the server. Instead of clogging up the server with profile creation messages, I have the bot do profile creation privately. I know/think the problem is with the message.channel.awaitMessages, because it only sees the replies in the original channel on the server where the command was put into place.
I am not sure what I should replace the message.channel.awaitMessages with in order for it to pick up on the reply in the private message conversation rather than the original profile creation channel on the server.
I have not tested the sql message yet. I haven't tested what I have but I am pretty sure it won't work. I want the reply that is given by the user in the private message to be inserted (updated maybe?) into a mysql database I have already set up and properly got working. The users ID and username has been put into this table with the rest of the profile related questions being null at this moment. As they reply to these questions, those fields can be filled out/updated. Any ideas/suggestions are welcome!
module.exports.run = async (bot, message, args) => {
if(message.channel.id === '460633878244229120') return message.author.send(`Greetings, ${message.author.username}! FIRST QUESTION, **What is the name of your Brawler or Character?**`)
.then(function(){
message.channel.awaitMessages(response => message.content, {
max: 1,
time: 5000,
errors: ['time'],
})
.then((collected) => {
message.author.send(`Your Name is: ${collected.first().content}`);
var sql = (`UPDATE profile SET name = '${message.content}' WHERE id = ${message.author.id}`);
})
.catch(function(){
message.author.send('Please submit a name for your character. To restart Profile creation, please type "!profilecreate" command in Profile Creation channel on the server.');
});
});
}
Thanks in advance for your time!
I don't use SQL so, since the question is not specifically on that, don't ask me.
When you're using message.channel.awaitMessages, message is still the first one that you passed in the module.exports.run function, not the one that comes from send(). When send is resolved, it passes a new message, that you have to include in the arguments of the function you put inside then: so, instead of .then(function() {}) you'll need something like .then(function(new_message_sent_in_private) {})
This should fix the problem:
module.exports.run = async (bot, message, args) => {
if(message.channel.id === '460633878244229120') return message.author.send(`Greetings, ${message.author.username}! FIRST QUESTION, **What is the name of your Brawler or Character?**`)
.then((newmsg) => { //Now newmsg is the message you sent
newmsg.channel.awaitMessages(response => response.content, {
max: 1,
time: 5000,
errors: ['time'],
}).then((collected) => {
newmsg.channel.send(`Your Name is: ${collected.first().content}`);
var sql = (`UPDATE profile SET name = '${message.content}' WHERE id = ${message.author.id}`);
}).catch(() => {
newmsg.channel.send('Please submit a name for your character. To restart Profile creation, please type "!profilecreate" command in Profile Creation channel on the server.');
});
});
}
Let me now if that worked :)

Categories

Resources