Some problems with the !kick command code - javascript

I'm having some problem with my Discord.js kick command.
My code:
const Discord = require('discord.js');
const { prefix, token } = require('../config.json');
module.exports = {
name: 'kick',
description: 'kick users',
execute(message, args) {
if (!message.member.hasPermission('KICK_MEMBERS')) {
return message.channel.send({
embed: {
color: 16777201,
description: `:x: | ${message.author}, You are not allowed to use this command.`,
footer: {
text: ` | Required permission: KICK_MEMBERS`,
},
},
});
}
if (!message.guild.me.permissions.has('KICK_MEMBERS')) {
return message.channel.send({
embed: {
color: 16777201,
description: `:x: | ${message.author}, I am not allowed to use this command.`,
footer: {
text: ` | Required permission: KICK_MEMBERS`,
},
},
});
}
if (!args[0]) {
return message.channel.send({
embed: {
color: 16777201,
description: `:x: | ${message.author}, You need to mention a user first.`,
footer: {
text: ` | Example: !kick #Bot`,
},
},
});
}
const member =
message.mentions.members.first() || message.guild.members.cache.get(args[0]);
if (member.user.id === message.author.id) {
return message.channel.send({
embed: {
color: 16777201,
description: `:x: | ${message.author}, You cannot expel yourself.`,
footer: {
text: ` | Example: !kick #Bot`,
},
},
});
}
try {
member.kick();
message.channel.send(`${member} has been kicked!`);
} catch (e) {
return message.channel.send(`User isn't in this server!`);
}
},
};
Ignore the code not being complete, I'm still thinking about the design of the embeds!
I'm trying to do 3 things:
I would like if someone tried to use the command by mentioning the bot, they would say something like "you are not allowed to do this"
The other thing I want is that it is not possible for a user to kick someone above him
I want the member to be kicked you have to react with yes or no

I'm going to try to solve your problems one by one:
First of all, I would like if someone tried to use the command by mentioning the bot, they would say something like "you are not allowed to do this"
You can execute an if statement to detect if the member mentioned shares the same ID as your bot using the client.user property (the user your client is logged in as)
if (member.id === client.user.id)
return message.channel.send('You cannot ban me');
The other thing I want is that it is not possible for a user to kick someone above him
You can solve this by comparing the roles.highest.position property of both members. This property will return a number. the higher the number, the higher the role in priority.
if (message.member.roles.highest.position <= member.roles.highest.position)
return message.channel.send(
'Cannot kick that member because they have roles that are higher or equal to you.'
);
And lastly, I want the member to be kicked you have to react with yes or no
For this you'll need to use a reaction collector. This is how you can do it using Message.awaitReactions. This method will wait for someone to react to a message, then log the emoji reacted.
// first send the confirmation message, then react to it with yes/no emojis
message.channel
.send(`Are you sure you want to kick ${member.username}?`)
.then((msg) => {
msg.react('👍');
msg.react('👎');
// filter function
const filter = (reaction, user) =>
['👍', '👎'].includes(reaction.emoji.name) && user.id === message.author.id; // make sure it's the correct reaction, and make sure it's the message author who's reacting to it
message
.awaitReactions(filter, { time: 30000 }) // make a 30 second time limit before cancelling
.then((collected) => {
// do whatever you'd like with the reactions now
if (message.reaction.name === '👍') {
// kick the user
} else {
// don't kick the user
}
})
.catch(console.log(`${message.author.username} didn't react in time`));
});

Related

Send a message to a specific channel with discord bot

I am looking on how to send a message to a specific channel. I saw some people to use
client.channels.cache.get('channelidhere').send('text')
however that whole thing is an error for me.
Here is my whole code. working on a ticket bot for a friend not anything crazy.
import { ICommand } from "wokcommands";
export default {
category: 'Utility',
description: 'Makes a support ticket.',
slash: false,
testOnly: true,
callback: async({ message, args, client, guild, member }) => {
let number = 0
let timeout = 200
const channel = await message.guild?.channels.create('Ticket', {
permissionOverwrites: [
{
id: message.author,
allow: ['VIEW_CHANNEL', 'READ_MESSAGE_HISTORY'],
}
],
})
channel?.setParent('956314466201514064')
console.log(channel?.id)
let setID = channel?.id
client.channels.cache.get('956314466201514064').send('')
}
} as ICommand```
For anyone still looking for an answer here it is.
For regular messages do
message.guild.channels.cache.get('channel-id').send('message')
For interactions do
interaction.guild.channels.cache.get('channel-id').send('message')

Discord.js v13 Reaction Roles

I already have this code to post an embed and to add a reaction, I'm just wondering how I would go about adding a role to a user when they add the reaction?
if (message.content.startsWith(`${prefix}rr`)) {
let embed = new MessageEmbed()
.setColor("#ffffff")
.setTitle("📌 Our Servers Rules 📌")
.setDescription("To keep our server safe we need a few basic rules for everyone to follow!")
.setFooter("Please press ✅ to verify and unlock the rest of the server!")
.addFields(
{
name: "1.",
value: "Stay friendly and don't be toxic to other users, we strive to keep a safe and helpful environment for all!",
},
{
name: "2.",
value: "Keep it PG-13, don't use racist, homophobic or generally offensive language/overly explicit language!",
},
{
name: "3.",
value: "If you want to advertise another server/website etc please contact me first!",
},
{ name: "4.", value: "Don't cause drama, keep it civil!" },
{
name: "5.",
value: "If you have any questions please contact me #StanLachie#4834",
}
);
message.channel.send({ embeds: [embed] }).then((sentMessage) => {
sentMessage.react("✅");
});
}
You may want to check this Discord.js Guide page. But in summary...
const filter = (reaction, user) => {
return reaction.emoji.name === '✅' && user.id === message.author.id;
};
const collector = message.createReactionCollector({ filter });
collector.on('collect', (reaction, user) => {
const role = await message.guild.roles.fetch("role id");
message.guild.members.fetch(user.id).then(member => {
member.roles.add(role);
});
});

cannot read property of 'channels' of undefined discord.js

const reason = args.slice(0).join(" ");
if (!reason) return message.channel.send('Reason for ticket?');
const user = message.guild.member(message.author);
const ticket = db.fetch(`Ticket_user_${user.id}`)
if(ticket) message.channel.send("You already made a ticket senpai! Close your old ticket.");
const channel = message.guild.channels.cache.find
(channel => channel.name === 'ticket')
if (!channel)
guild.channels.create('ticket', {
type: 'text',
permissionOverwrites: [
{
id: message.guild.id,
deny: ['VIEW_CHANNEL'],
},
{
id: message.author.id,
allow: ['VIEW_CHANNEL'],
},
],
})
.then(console.log)
.catch(err => {
message.channel.send("An error occurred while running the command. Please report this error to the support server:"+ err)
return;
})
db.add(`Ticket_user_${user.id}`)
const time = "3"
setTimeout(() => {
const embed = new Discord.MessageEmbed()
.setTitle(`Ticket#0001`)
.setDescription(`Reason: ${reason}`)
.addField("Welcome to my ticket senpai!! We are waiting for staff")
.setColor("PURPLE")
message.channel.send(embed)
}, ms(time))
}
}
I'm making a ticket system for my bot and ik you people smart because top.gg won't help
Thank you for the help this will help my bot and my code and make me smart plus I'm removing the dot becccause of downvote ig
Here in this code
if (!channel){
guild.channels.create('ticket', { //...... rest of the code
You didn't define guild. Try replacing guild with message.guild
Like this:
if (!channel){
message.guild.channels.create('ticket', { //.... rest of the code
Also, please remove the unnecessary part (dots) from the question

Discord.js auto-ban user if they use a certain command

I'm attempting to make a simple $ping command but if a user uses said command, they'll automatically be banned from the server (a small little funny)
Here's the code for the functioning $ping but I don't know how to have the ${user} that uses it auto-banned from the bot. (Will have sufficient perms obviously)
I'll be removing the whole embed: section down basically, as I don't need any text or actual command running. Just the auto-ban, only thing ran will be a description: ${user} was banned
exports.exec = async (Cuckbot, message) => {
try {
let responseMessage = await message.channel.send({
embed: {
color: Cuckbot.colors.BLUE,
description: 'PINGing...'
}
});
await responseMessage.edit({
embed: {
color: Cuckbot.colors.BLUE,
title: `${Cuckbot.user.username} PING Statistics`,
fields: [
{
name: 'Response Time',
value: `${responseMessage.createdTimestamp - message.createdTimestamp}ms`,
inline: true
},
{
name: 'WebSocket PING',
value: `${Cuckbot.ping}ms`,
inline: true
}
]
}
});
}
catch (e) {
Cuckbot.log.error(e);
}
};
member.ban() is a function you can use to ban a member.
Example from Documentation:
// Ban a guild member
member.ban("Banned because used ping")
.then(() => console.log(`Banned ${member.displayName}`))
.catch(console.error);

Discord bot - Purge command not working discord.js-commando

I have created a discord bot recently using node js which when I do !purge, responds with Unknown command, do !help to view a list of command but after saying it, it is purging the messages. That is, it works well but posting that error message. I don't know what's the problem please help me
const commando = require('discord.js-commando');
const bot = new commando.Client();
const prefix = '!';
bot.on('message', message => {
let msg = message.content.toUpperCase();
let sender = message.author;
let cont = message.content.slice(prefix.length).split(" ");
let args = cont.slice(1);
if (msg.startsWith(prefix + 'PURGE')) {
async function purge() {
message.delete();
if (isNaN(args[0])) {
message.channel.send('Please input a number of messages to be deleted \n Syntax: ' + prefix + 'purge <amount>');
return;
}
const fetched = await message.channel.fetchMessages({limit: args[0]});
console.log(fetched.size + ' messages found, deleting...');
// Deleting the messages
message.channel.bulkDelete(fetched)
.catch(error => message.channel.send(`Error: ${error}`));
}
purge();
}
});
bot.login('MY BOT TOKEN HERE');
Right now you're using the discord.js-commando library. Any reason you decided to use that library? It looks like you're just using standard discord.js functions like bot.on, message.channel.send, message.channel.fetchMessages, message.channel.bulkDelete...
You should be good just useing the standard discord.js library, starting your code with this:
const Discord = require('discord.js');
const bot = new Discord.Client();
You can find this code on the main "Welcome" page of Discord.js
Edit:
I'm still not sure why you're using discord.js-commando, but that doesn't matter. Here's an example command I came up with using the discord.js-commando library:
const commando = require('discord.js-commando');
class PurgeCommand extends commando.Command {
constructor(client) {
super(client, {
name: 'purge',
group: 'random', // like your !roll command
memberName: 'purge',
description: 'Purge some messages from a Text Channel.',
examples: ['purge 5'],
args: [
{
key: 'numToPurge',
label: 'number',
prompt: 'Please input a number ( > 0) of messages to be deleted.',
type: 'integer'
}
]
});
}
run(msg, { numToPurge }) {
let channel = msg.channel;
// fail if number of messages to purge is invalid
if (numToPurge <= 0) {
return msg.reply('Purge number must be greater than 0');
}
// channel type must be text for .bulkDelete to be available
else if (channel.type === 'text') {
return channel.fetchMessages({limit: numToPurge})
.then(msgs => channel.bulkDelete(msgs))
.then(msgs => msg.reply(`Purge deleted ${msgs.size} message(s)`))
.catch(console.error);
}
else {
return msg.reply('Purge command only available in Text Channels');
}
}
};
module.exports = PurgeCommand
I'd also recommend using a new type instead of integer so you can validate the user's response and make sure they enter a number greater than 0.
If you need help setting up an initial discord.js-commando script, I'd take a look at this repo provided by the Discord team: https://github.com/discordjs/Commando/tree/master/test
You might wanna use this. This purge command is intended for discord.js v11.5.1 and I haven't tested to see if it works on v12, but I think this might work for you. I should say that THIS DELETES ALL THE CONTENT INSIDE THE CHANNEL (Nested command)
exports.run = (bot, message, args) => {
let filter = m => message.author.id === message.author.id;
message.channel.send("Are you sure you wanna delete all messages? (y/n)").then(() => {
message.channel.awaitMessages(filter, {
max: 1,
time: 30000,
errors: ['time']
})
.then(message => {
message = message.first();
if (message.content.toUpperCase() == "YES" || message.content.toUpperCase() == "Y") {
message.channel.bulkDelete(100);
} else if (message.content.toUpperCase() == "NO" || message.content.toUpperCase() == "N") {
message.channel.send("Terminated").then(() => {message.delete(2000)});
} else {
message.delete();
}
})
.catch(collected => {
message.channel.send("Timeout").then(() => {message.delete(2000)});
});
}).catch(error => {
message.channel.send(error);
});
};

Categories

Resources