So I want it where, if a user gets banned from this specified guild, it will ban them in every other guild that the bot is in. Do I use fetch bans to do this?
Before we continue you need to make sure that you are requesting the following intents when creating your bot, as they are necessary to achieve your goal: GUILDS, GUILD_BANS.
const { Client, Intents } = require('discord.js');
const client = new Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_BANS]
});
You should also set up a constant called MAIN_GUILD_ID or something along those lines:
const MAIN_GUILD_ID = 'ID';
Now you need to listen to the guildBanAdd event and check if the GuildBan.guild#id equals the main Guild#id (making sure the user was banned in the main Guild).
client.on('guildBanAdd', async ban => {
if (ban.guild.id !== MAIN_GUILD_ID) return;
});
Then you can loop through all of the Guilds your bot is in and ban the user there.
client.on('guildBanAdd', async ban => {
if (ban.guild.id !== MAIN_GUILD_ID) return;
// Getting the guilds from the cache and filtering the main guild out.
const guilds = await client.guilds.cache.filter(guild => guild.id !== MAIN_GUILD_ID);
guilds.forEach(guild => {
guild.members.ban(ban.user, {
reason: `${ban.user.tag} was banned from ${guild.name}.`
}).then(() => {
console.log(`Banned ${ban.user.tag} from ${guild.name}.`);
}).catch(err => {
console.error(`Failed to ban ${ban.user.tag} from ${guild.name}.`, err);
});
})
});
I'm assuming this is for a private bot that is in a few guilds, otherwise, if the bot is in a few hundred or more guilds it will get your application rate-limited pretty fast.
Related
I want to change the name of a discord bot and I have read numerous tutorials and Stack Overflow posts and I still cannot get it. The code is primarily taken from open source bot code, so I know it works (something with my bot setup maybe?)
As I understand it, this code loops through each guild the bot is a member of and sets the nickname.
I found the botId by right clicking the bot in the channel and copying ID.
const { guildId } = require('../config');
module.exports = (client, botId, nickname) => {
client.guilds.cache.forEach((guild) => {
const { id } = guild;
client.guilds.cache
.get(id)
.members.cache.get(botId)
.setNickname(nickname);
});
};
The bot shows up in the channel (after using oauth2 url), so I'm assuming that means they are a member of the guild.
However, when running this code the bot is not found. I've tried several things from other posts like guild.array() to try and see a full list of the members in the guild, but nothing has worked.
const guild = client.guilds.cache.get('943284788004012072');
const bot = guild.members.cache.get('956373150864642159')
if (!bot) return console.log('bot not found');
Here is the full bot
require('dotenv').config();
const { Client, Intents } = require('discord.js');
const eventBus = require('../utils/events/eventBus');
const setNickname = require('../utils/setNickname');
const getPrice = require('../modules/statsGetters/getPriceDEX');
const { bots } = require('../config');
const client = new Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES],
});
client.once('ready', async () => {
console.log('DEX Price Watch Bot Ready');
client.user.setPresence({
activities: [{ name: 'DEX Price', type: 'WATCHING' }],
status: 'online',
});
const price = await getPrice();
setNickname(client, bots.priceDEX, price);
eventBus.on(drip.update, async () => {
const price = await getPrice();
setNickname(client, bots.priceDEX, price); //update price in config file
});
});
client.login(process.env.DISCORD_PRICE_DEX);
This is the sample of changing bot's nickname for every guild that bot joined
client.guilds.cache.forEach((guild) => { //This is to get all guild that the bot joined
const nickname = args.slice(0).join(" ") //You wanted to change nickname
guild.me.setNickname(nickname); //setting the nickname of your bot
});
I believe you're doing it wrong.
Docs: https://discord.js.org/#/docs/discord.js/stable/class/GuildMember?scrollTo=setNickname
I would suggest using this module code:
const { guildId } = require('../config');
module.exports = (client, nickname) => {
client.guilds.cache
.get(guildId).me.setNickname(nickname);
};
And use it in this way in your main bot code: setNickname(client, price)
Edit:
Oh wait, I just realised you didn't use the correct intents (guild members), so you definitely need to use guild.me (as written above by me) or use guild.members.fetch() as it fetches members which aren't cached.
More info: https://discord.js.org/#/docs/discord.js/stable/class/GuildMemberManager?scrollTo=fetch
I want to know when a guild member logs in, not when the member joins, so guildMemberAdd does not work in this case. Perhaps there is another way of going about what I want to do, so I will explain here.
When users of my website upgrade to a standard or pro membership they are able to join my discord server among other things. I still have to sort out how to determine that the discord user is a Standard/Pro subscribing member on my website, but I think I can send a one time invite link or a password which the member has to enter send the discord bot after the bot sends a welcome message asking for the password or something, but that should be relatively straightforward to do.
My concern is after a user has joined the discord server, what should I do if, for example, that user decides to unsubscribe from the standard/pro membership on my website? I want to kick that user now, so I was thinking that I could just detect when a guild member starts a session on my discord server with the bot and test to see if the user is still a standard/pro member from my website, but there doesn't appear to be any event for this.
Perhaps I should be thinking of this in another way. Is there a method for just kicking members from my discord server outside of the event callback context?? I just started with the API this morning, so forgive me if what I'm asking is simple. I literally and shamefully just copy/pasted the discord.js example in their docs to see if simple message detection works and it thankfully does (code below)
const Discord = require("discord.js")
const client = new Discord.Client()
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`)
});
client.on("message", (msg) => {
if (msg.content === "ping") {
msg.reply("Pong!")
}
});
client.on("guildMemberAdd", (member) => {
member.send(
`Welcome on the server! Please be aware that we won't tolerate troll, spam or harassment.`
);
});
client.login(process.env.DISCORD_EVERBOT_TOKEN);
In order to track the users, I made an invite process which starts when a member of my website upgrades to a Pro or Standard account. I couldn't find a way to confirm the user connecting is in fact connecting with a specific invite to know which user it was other than sending a temporary discord server password. So I coded the bot to prompt a new user to input the temp password as a DM to the bot when the guildMemberAdd event is fired, this password points to the user on my website and then I store the discord member id during this transaction so if a member decides to cancel their subscription, I remove roles accordingly.
The solution below is working like a charm:
client.on("message", async (msg) => {
if(msg.author.id === client.user.id) { return; }
if(msg.channel.type == 'dm'){
try{
let user = await User.findOne({ discord_id: msg.member.id }).exec();
if(user)
await msg.reply("I know you are, but what am I?");
else {
user = await User.findOne({ discord_temp_pw: msg.content }).exec();
if(!user){
await msg.reply(`"${msg.content}" is not a valid password. Please make sure to enter the exact password without spaces.`)
}
else {
const role = user.subscription.status;
if(role === "Basic")
{
await msg.reply(`You have a ${role} membership and unfortunately that means you can't join either of the community channels. Please sign up for a Standard or Pro account to get involved in the discussion.
If you did in fact sign up for a Pro or Standard account, we're sorry for the mistake. Please contact us at info#mydomain.com so we can sort out what happened.`)
}
else{
const roleGranted = await memberGrantRole(msg.member.id, role);
const userId = user._id;
if(roleGranted){
let responseMsg = `Welcome to the team. With a ${role} membership you have access to `
if(role === "Pro")
await msg.reply(responseMsg + `both the Standard member channel and the and the Pro channel. Go and introduce yourself now!`);
else
await msg.reply(responseMsg + `the Standard member channel. Go and introduce yourself now!`);
}
else{
await msg.reply("Something went wrong. Please contact us at info#mydomain.com so we can sort out the problem.");
}
user = { discord_temp_pw: null, discord_id: msg.member.id };
await User.findByIdAndUpdate(
userId,
{ $set: user }
).exec();
}
}
}
}
catch(err){
console.log(err);
}
}
}
client.on("guildMemberAdd", (member) => {
member.send(
`Welcome to the server ${member.username}!
Please enter the password that you received in your email invitation below to continue.`
);
});
const memberGrantRole = async(member_id, role) => {
const guild = client.guilds.cache.get(process.env.DISCORD_SERVER_ID);
const member = guild.members.cache.get(member_id);
try{
await member.roles.add(role);
}
catch(err){
return {err, success: false};
}
return {err: null, success: true};
}
I have two servers with my bot on it with two groups of friends. On one server, the bot and I both have admin perms, and I can mute someone who doesn't have those perms. On the other server, I'm the owner and the bot has admin, but I can't mute anyone. I get the error 'Missing Permissions'.
Here's the code:
const Discord = require('discord.js')
const ms = require('ms')
module.exports = {
name: 'mute',
execute(message, args) {
if(!args.length) return message.channel.send("Please Specify a time and who to mute. For example, '!mute #antobot10 1d' And then send the command. Once the command is sent, type the reason like a normal message when I ask for it!")
const client = message.client
if (!message.member.hasPermission('MANAGE_ROLES')) return message.channel.send("You don't have permission to use that command!")
else {
const target = message.mentions.members.first();
const filter = (m) => m.author.id === message.author.id
const collector = new Discord.MessageCollector(message.channel, filter, { time: 600000, max: 1 })
const timeGiven = args[1]
message.channel.send('The reason?')
collector.on('collect', m => {
collector.on('end', d => {
const reason = m
message.channel.send(`${target} has been muted`)
target.send(`You have been muted on ${message.guild.name} for the following reason: ***${reason}*** for ${timeGiven}`)
if(message.author.client) return;
})
})
let mutedRole = message.guild.roles.cache.find(role => role.name === "MUTE");
target.roles.add(mutedRole)
setTimeout(() => {
target.roles.remove(mutedRole); // remove the role
target.send('You have been unmuted.')
}, (ms(timeGiven))
)
}
}
}
Ok, I'm not exactly sure what I did, but it's working now. I think I just changed it so that the MUTE role had 0 permissions instead of normal permissions but making it so that if you have the role you can't talk in that certain channel.
Thanks for the answers!
If your bot's role is below the role of the user you are attempting to mute, there will be a missing permissions error. In your server settings, drag and drop the bot role as high in the hierarchy it will go. This will solve your problem.
So i'm making a command that outputs every user in a role
module.exports = {
name: 'in-role',
description: 'Find all users in a specified role.',
aliases: ['inrole'],
async execute(message, args, Discord) {
const role = message.guild.roles.cache.get(args[0])
if (role) {
const roleMembers = role.members.map(member => member.toString())
const inRoleEmbed = new Discord.MessageEmbed()
.setTitle(role.name)
.setDescription(roleMembers.join('\n'))
.setColor(role.hexColor);
message.channel.send(inRoleEmbed).catch(error => {
message.channel.send('There was an error executing the command.')
console.log(error)
})
}
}
};
heres the code, it's only caching the top/first 2 members in the guild. Wondering if there is a way to make it get every member and then output all of the users in that role instead of only looking at top 2 members.
If you're only getting 2 members in your cache, it seems you haven't yet enabled privileged intents. Find out how to do that.
However, even after enabling intents, you still probably won't have every member of your guild cached, which is when you should use GuildMemberManager#fetch()
// make sure you make your `execute` function async!
await guild.members.fetch();
const role = message.guild.roles.cache.get(args[0]);
...
1 day ago i publish an issue with for a discord bot that said that my id was not a property of null. Now its works. But it still not able to ban, and it gives me the error marked on the code: message.reply("I was unable to ban the member :(");
This is the code:
const Discord = require('discord.js');
const client = new Discord.Client();
module.exports = {
name: 'ban',
description: "ban peoples ;D",
execute(message, args, client) {
if (!message.member.hasPermission("BAN_MEMBERS") ||
!message.member.hasPermission("ADMINISTRATOR")) return message.channel.send("You don't have a permissions to do this, maybe later ;) ");
const user = message.mentions.users.first();
const member = message.guild.member(user);
if (!user) return message.channel.send("Please mention the user to make this action");
if (user.id === message.author.id) return message.channel.send("You can't ban yourself, I tried :(");
member.ban(() => {
message.channel.send('Successfully banned **${user.tag}**');
}).catch(err => {
message.reply("I was unable to ban the member :(");
})
}
}
i checked to see if the bot needs permissions, i gave it him but it still not working.
The issue is here
member.ban(() => {
message.channel.send('Successfully banned **${user.tag}**');
}).catch(err => {
message.reply("I was unable to ban the member :(");
})
You are passing an entire function into the ban method
Really you should be calling the function then using .then(() => {}) to handle the promise
It should look like this
member.ban()
.then(() => {
message.channel.send('Successfully banned **${user.tag}**');
})
.catch((err) => {
message.reply("I was unable to ban the member :(");
console.error(err);
});