The only code I have is this:
module.exports = {
name: "kick",
description: "This command kicks a member!",
execute(message, args) {
const target = message.mentions.users.first();
if (target) {
const memberTarget = message.guild.members.cache.get(target.id);
memberTarget.kick();
message.channel.send("User has been kicked");
} else {
message.channel.send(`You coudn't kick that member!`);
}
},
};
Good Morning. So I'm trying to get it to message the person that got kicked the reason why they got kicked. (!kick user reason) I want it so the bot DMs the person what the reason was but I don't know how to do that.
You would only need to add the following:
const reason = args.splice(1).join(` `) || 'Not specified';
memberTarget.send(`You have been kicked: \nReason: ${reason}`)
module.exports = {
name: "kick",
description: "This command kicks a member!",
execute(message, args) {
const target = message.mentions.users.first();
if (target) {
const memberTarget = message.guild.members.cache.get(target.id);
const reason = args.splice(1).join(` `) || 'Not specified';
memberTarget.kick();
message.channel.send("User has been kicked");
memberTarget.send(`You have been kicked: \nReason: ${reason}`)
} else {
message.channel.send(`You coudn't kick that member!`);
}
},
};
The const reason = args.splice(1).join( ) || 'Not specified'; defines the 'reason' property, if there isn't a reason, it defaults to 'Not specified'.
memberTarget.send(You have been kicked: \nReason: ${reason})
Just sends the message to the targeted member.
Right off the bat, I see that you are getting the target using message.mentions.users and getting the memberTarget from the guild's cache. You should avoid this and use message.mentions.members.
You'll have to use the send method of GuildMember, but since it returns a Promise, you'll have to catch any errors. (e.g: the bot cannot DM the member)
// You should do some sanity checks in case you haven't. You don't want everyone to be able to kick members using the bot.
// Getting the first member in message.mentions.members.
const target = message.mentions.members.first();
// Making sure that target is defined.
if (!target) return message.channel.send('Please mention a member to kick.');
// Making sure a reason is provided. (args[0] is the mention)
if (!args[1]) return message.channel.send('Please provide a reason.');
// Making sure the bot can kick the target.
if (!target.kickable) return message.channel.send('Couldn\'t kick the target.');
// Trying to send a message to the target, notifying them that they got kicked, and catching any errors.
target.send(`You have been kicked from ${message.guild.name} for ${args.slice(1, 2000).join(' ')}`).catch(console.error).finally(() => {
// After the message was sent successfully or failed to be sent, we kick the target and catch any errors.
target.kick(`Kicked by ${message.author.tag} for ${args.slice(1, 2000).join(' ')}}.`).then(() => {
message.channel.send(`${target.user.tag} has been kicked for ${args.slice(1, 2000).join(' ')}.`);
}).catch(error => {
console.error(error)
message.channel.send(`Something went wrong...`);
});
});
This is working kick command with reason made by me (you can try it):-
It has every validation you should have in a kick command
const Discord = require('discord.js')
exports.kick = async(message , prefix , client) => {
if(!message.member.hasPermission("KICK_MEMBERS")) return message.channel.send('Missing Permission! You need to have `KICK_MEMBERS` permissions in order kick this member.')
if(!message.guild.me.hasPermission("KICK_MEMBERS")) return message.channel.send('Missing Permission! I need to have `KICK_MEMBERS` permissions to kick this member.')
const args = message.content.slice(prefix.length).trim().split(' ');
const command = args.shift().toLowerCase();
let member = message.mentions.members.first();
if(!member){
let err = "```css\n[ Agrument Error : You Have not mentioned the user on first args. ]\n```\n\n"
let embed = new Discord.MessageEmbed()
.setAuthor(`${client.user.username} Help Manual` , client.user.displayAvatarURL({format : "png"}))
.setTitle(`${message.guild.name}`)
.setDescription(err)
.addField('Help Command:' , `\`\`\`\n${prefix}kick #user#0001 Reason\n\`\`\``)
.setTimestamp()
.setColor('RED')
return message.channel.send(embed)
}
if(args[0] != `<#!${member.id}>`){
let err = "```css\n[ Agrument Error : You Have not mentioned the user on first args. ]\n```"
let embed = new Discord.MessageEmbed()
.setAuthor(`${client.user.username} Help Manual` , client.user.displayAvatarURL({format : "png"}))
.setTitle(`${message.guild.name}`)
.setDescription(err)
.addField('Help Command:' , `\`\`\`\n${prefix}kick #user#0001 Reason\n\`\`\``)
.setTimestamp()
.setColor('RED')
return message.channel.send(embed)
}
if(member.id === message.author.id) return message.channel.send(`Why? No Just Say Why Do you want to kick yourself?`)
let reason = args.slice(1).join(' ');
if(!reason || reason.length <= 1){
reason = "No Reason Was Provided."
}
if(!member.kickable){
return message.channel.send(`I Don't Have Permissions to Kick ${member.user.username}`)
}
member.kick().then(() => {
return message.channel.send(`Successfully Kicked ${member.user.username} for Reason ==> \`${reason}\``)
}).catch(() => {
return message.channel.send(`I Don't Have Permissions to Kick ${member.user.username}`)
})
}
Related
I can't understand why doesn't send the welcome message
Here's Code from index.js
client.on('guildMemberAdd', (member) => {
let chx = db.get(`welchannel_${member.guild.id}`);
if (chx === null) {
return;
}
client.channels.cache.get(chx).send(`Welcome to ${message.guild.name}`);
});
Here's Code From channel.js
module.exports = {
name: "channel",
description: "Help Command",
category: "Help",
execute(client, message, args, Discord) {
const db = require("quick.db")
let channel = message.mentions.channels.first() //mentioned channel
if(!channel) { //if channel is not mentioned
return message.channel.send("Please Mention the channel first")
}
db.set(`welchannel_${message.guild.id}`, channel.id)
const embed = new Discord.MessageEmbed()
.setColor('#b5b5b5')
.setTitle(`Channel set: ${channel.name} `)
message.channel.send({ embeds: [embed] });
}
}
EDIT: I found out the problem i didn't have a intent flag GUILD_MEMBERS
and also thanks UltraX that helped also
Basically, the reason is simple, you need to go to your dev portal then after choosing your bot/application just go to bot and you need to enable member intents Server Member Intent after that it should work, if it didn't just give it a 10 minute, then try again!
The best way to ensure you get a channel object within the event is to use the guild property off the emitted member.
client.on("guildMemberAdd", (member) => {
const { guild } = member;
let chx = db.get(`welchannel_${member.guild.id}`);
if(chx === null) {return}
const channel = guild.channels.cache.get(chx);
if (!channel) return;
channel.send(`Welcome to ${message.guild.name}`)
.catch(console.error);
})
You will need the Guild Member's intent enabled as stated in This Answer for the event to emit.
I'm making a timed mute command, but i get a lot of errors, the principal one being :
(node:6584) UnhandledPromiseRejectionWarning: DiscordAPIError: Unknown Role
at RequestHandler.execute (c:\Users\user\Desktop\DiscordJSBOT\node_modules\discord.js\src\rest\RequestHandler.js:154:13)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async RequestHandler.push (c:\Users\user\Desktop\DiscordJSBOT\node_modules\discord.js\src\rest\RequestHandler.js:39:14)
at async GuildMemberRoleManager.remove (c:\Users\user\Desktop\DiscordJSBOT\node_modules\discord.js\src\managers\GuildMemberRoleManager.js:125:7)
(Use `node --trace-warnings ...` to show where the warning was created)
Here is the bugged code :
const ms = require('ms');
module.exports = {
name : 'mute',
description: 'Mutes given user',
execute(client, message, args) {
if(!message.member.hasPermission('MUTE_MEMBERS') && message.member.hasPermission('MANAGE_ROLES')) {
return message.reply('You need permissions to use this command !');
}
const target = message.mentions.users.first();
if(target) {
const member = message.guild.members.cache.get(target.id)
if(member) {
const muteRole = message.guild.roles.cache.find(role => role.name === "Muted");
if(muteRole) {
const RoleFolder = []
const roles = member.roles.cache.map(role => role);
roles.forEach(role => {
RoleFolder.push(role.id)
member.roles.remove(role.id)
});
member.roles.add(muteRole.id)
setTimeout(function () {
member.roles.remove(muteRole.id)
RoleFolder.forEach(roles => {
member.roles.add(roles)
})
}, ms(args[1]));
} else {
return message.reply('Make sure you have a role nammed "Muted" when trying to mute a member');
}
} else {
return message.reply('There was an error while attempting to get member object of mentioned user !')
}
} else {
return message.reply('You need a user to mute ! ');
}
}
}
The problem comes from the fact that I get all roles from the user, store it and then give it back. I don't know if there is any other way to do it but that's what I found.
Thanks !
The error DiscordAPIError: Unknown Role is showing up because you are trying to remove a role from a user that the discord API cannot find. This role is the #everyone role which all members have.
You also do not need to run map on the roles, as you can already iterrate over the cache collection.
The code in your question:
const RoleFolder = []
const roles = member.roles.cache.map(role => role);
roles.forEach(role => {
RoleFolder.push(role.id)
member.roles.remove(role.id)
});
Can be changed to:
const RoleFolder = []
member.roles.cache.forEach(role => {
if (role.id === member.guild.id) return;
RoleFolder.push(role.id)
member.roles.remove(role.id)
});
To ignore the role that doesn't exist in the discord API, you can check for:
role.id === member.guild.id or role.rawPosition === 0
You can use return to skip executing code for that particular role, meaning it isn't added to the RoleFolder, and doesn't try to remove the role.
Edit: I would avoid using role.name === '#everyone' as a user can create a role called #everyone and this would be missed, so I have updated my answer to check for a better condition.
How to give permissions to a specific channel by command? Sorry, I’m new at discord.js so any help would be appreciated.
const Discord = require('discord.js');
module.exports = {
name: 'addrole',
run: async (bot, message, args) => {
//!addrole #user RoleName
let rMember =
message.guild.member(message.mentions.users.first()) ||
message.guild.members.cache.get(args[0]);
if (!rMember) return message.reply("Couldn't find that user, yo.");
let role = args.join(' ').slice(22);
if (!role) return message.reply('Specify a role!');
let gRole = message.guild.roles.cache.find((r) => r.name === role);
if (!gRole) return message.reply("Couldn't find that role.");
if (rMember.roles.has(gRole.id));
await rMember.addRole(gRole.id);
try {
const oofas = new Discord.MessageEmbed()
.setTitle('something')
.setColor(`#000000`)
.setDescription(`Congrats, you have been given the role ${gRole.name}`);
await rMember.send(oofas);
} catch (e) {
message.channel.send(
`Congrats, you have been given the role ${gRole.name}. We tried to DM `
);
}
},
};
You can use GuildChannel.updateOverwrites() to update the permissions on a channel.
// Update or Create permission overwrites for a message author
message.channel.updateOverwrite(message.author, {
SEND_MESSAGES: false
})
.then(channel => console.log(channel.permissionOverwrites.get(message.author.id)))
.catch(console.error);
(From example in the discord.js docs)
Using this function, you can provide a User or Role Object or ID of which to update permissions (in your case, you can use gRole).
Then, you can list the permissions to update followed by true, to allow, or false, to reject.
Here is a full list of permission flags you can use
This method is outdated and doesn't work on V13+ the new way is doing this:
channel.permissionOverwrites.edit(role, {SEND_MESSAGES: true }
channel.permissionOverwrites.edit(member, {SEND_MESSAGES: true }
I am trying to make a command using discord.js that would execute a command on multiple servers.
this is what I have done so far.
if (isCommand('globalban', message)) {
if(!member.roles.cache.some(role => role.name === 'Staff'))
return message.reply("You can't use this command.");
var targetID = args[1]; // this is the targets UserID
if (!targetID)
return message.channel.send("Please provide the targets ID");
//rest of code goes here.
return;
}
I am not sure on how to continue this.
client.guilds.cache.forEach(a => a.members.ban(targetID))
well, just have the bot loop through all the guilds it's in and search for that user. I could try giving you some code, but idk what version of discord.js you are using.
EDIT: in discord.js v12 --->
client.guilds.cache.forEach(a => a.members.cache.get(targetID.)ban()
const { MessageEmbed } = require("discord.js");
const Owner = require("../config.json")
module.exports = {
name: "globalban",
description: "bans the user from all servers the bot is in",
aliases: "gb",
execute(message, args, client){
const targetID = args[0];
const reason = args.slice(0).join(' ')
if(!message.author === Owner) return message.channel.send("You need to be bot owner to use this command");
else{
client.guilds.cache.forEach(a => a.members.ban(targetID));
const embed = new MessageEmbed()
.setTitle(`Successfully banned`)
.setDescription(`I have successfully banned ${targetID.tag} from all servers`)
.setColor("#FF0000")
.setThumbnail("https://cdn.discordapp.com/emojis/764396593964122132.gif?v=1")
message.channel.send(embed)
const dmembed = new MessageEmbed()
.setTitle("You have been banned from all the servers i am in")
.setDescription('Your Crime was `${reason}`. If you want to apeal, You may join [Appeal Server by Clicking here](https://discord.gg/ZWWYy37atN)')
.setColor("#FF0000")
message.targetID.send(embed)
}
}
}
I'm working on a command where when you do the command, d!woa the following happens
A webhook gets created with a certain name, Then a role gets created with the channel name, after that the bot watches if there's a webhook with that certain name for the channel, and just sees if anyone sends a message in that channel. If it does, then the bot will add that role with the certain name.
The problem is that there's this error : TypeError: Cannot read property 'guild' of undefined
The error will most likely appear at the end of the code provided.
I've tried rearranging the code, defining guild, and defining message. It does not seem to work even after trying all of this. I only want it to rely off of the ID instead of Name to be accurate for this command.
const Discord = require('discord.js');
const commando = require('discord.js-commando');
class woa extends commando.Command
{
constructor(client) {
super(client, {
name: 'watchoveradd',
group: 'help',
memberName: 'watchoveradd',
description: 'placeholder',
aliases: ['woa'],
})
}
async run(message, args){
if (message.channel instanceof Discord.DMChannel) return message.channel.send('This command cannot be executed here.')
else
if(!message.member.guild.me.hasPermission(['MANAGE_WEBHOOKS'])) return message.channel.send('I don\'t have the permissions to make webhooks, please contact an admin or change my permissions!')
if(!message.member.guild.me.hasPermission(['MANAGE_ROLES'])) return message.channel.send('I don\'t have the permissions to make roles, please contact an admin or change my permissions!')
if (!message.member.hasPermission(['MANAGE_WEBHOOKS'])) return message.channel.send('You need to be an admin or webhook manager to use this command.')
if (!message.member.hasPermission(['MANAGE_ROLES'])) return message.channel.send('You need to be an admin or role manager to use this command.')
const avatar = `...`;
const name2 = "name-1.0WOCMD";
let woaID = message.mentions.channels.first();
if(!woaID) return message.channel.send("Channel is nonexistant or command was not formatted properly. Please do s!woa #(channelname)");
let specifiedchannel = message.guild.channels.find(t => t.id == woaID.id);;
specifiedchannel.send('test');
const hook = await woaID.createWebhook(name2, avatar).catch(error => console.log(error))
await hook.edit(name2, avatar).catch(error => console.log(error))
message.channel.send("Please do not tamper with the webhook or else the command implied before will no longer function with this channel.")
setTimeout(function(){
message.channel.send('Please wait...');
}, 10);
setTimeout(function(){
var role = message.guild.createRole({
name: `Name marker ${woaID.name} v1.0`,
color: 0xcc3b3b,}).catch(console.error);
if(role.name == "name marker") {
role.setMentionable(false, 'SBW Ping Set.')
role.setPosition(10)
role.setPermissions(['CREATE_INSTANT_INVITE', 'SEND_MESSAGES'])
.then(role => console.log(`Edited role`))
.catch(console.error)};
}, 20);
var sbwrID = member.guild.roles.find(`Synthibutworse marker ${woaID} v1.0`);
let specifiedrole = message.guild.roles.find(r => r.id == sbwrID.id)
setTimeout(function(){
message.channel.send('Created Role... Please wait.');
}, 100);
message.guild.specifiedchannel.replacePermissionOverwrites({
overwrites: [
{
id: specifiedrole,
denied: ['SEND_MESSAGES'],
allowed: ['VIEW_CHANNEL'],
},
],
reason: 'Needed to change permissions'
});
var member = client.user
var bot = message.client
bot.on('message', function(message) { {
if(message.channel.id == sbwrID.id) {
let bannedRole = message.guild.roles.find(role => role.id === specifiedrole);
message.member.addRole(bannedRole);
}
}})
}};
module.exports = woa;
I expect a command without the TypeError, and the command able to create a role and a webhook (for a marker), and the role is automatically set so that the user that has the role won't be able to speak in the channel, and whoever speaks in the channel will get the role.
The actual output is a TypeError: Cannot read property 'guild' of undefined but a role and webhook are created.
You have var sbwrID = member.guild...
You did not define member. Use message.member.guild...
You can setup a linter ( https://discordjs.guide/preparations/setting-up-a-linter.html ) to find these problems automatically.