Why doesn't kicking people work using discord.js - javascript

const Discord = require("discord.js"),
bot = new Discord.Client();
let pre = "?"
bot.on("message", async msg => {
var msgArray = msg.content.split(" ");
var args = msgArray.slice(1);
var prisonerRole = msg.guild.roles.find("name", "Prisoner");
let command = msgArray[0];
if (command == `${pre}roll`) {
if (!msg.member.roles.has(prisonerRole.id)) {
roll = Math.floor(Math.random()*6)+1;
msg.reply(`You rolled a ${roll}`)
} else {
msg.reply(`HaHa NOOB, you're in prison you don't get priveleges!`)
}
}
if (command == `${pre}kick`) {
var leaderRole = msg.guild.roles.find("name", "LEADER");
var co_leaderRole = msg.guild.roles.find("name", "CO-LEADER");
if (msg.member.roles.has(leaderRole.id) ||
msg.member.roles.has(co_leaderRole.id)) {
var kickUser = msg.guild.member(msg.mentions.users.first());
var kickReason = args.join(" ").slice(22);
msg.guild.member(kickUser).kick();
msg.channel.send(`${msg.author} has kicked ${kickUser}\nReason: ${kickReason}`);
} else {
return msg.reply("Ya pleb, you can't kick people!");
}
}
})
bot.login("token").then(function() {
console.log('Good!')
}, function(err) {
console.log('Still good, as long as the process now exits.')
bot.destroy()
})
Everything works except actually kicking the person. The message sends nut it doesn't kick people. For example, when I type in ?kick #BobNuggets#4576 inactive, it says
#rishabhase has kicked #BobNuggets
Reason: inactive
But it doesn't actually kick the user, which is weird, can you help me?

Change
msg.guild.member(kickUser).kick();
to
kickUser.kick();
also, make sure the bot is elevated in hierarchy

Use kickUser.kick();
I recommend using a command handler to neaten up your code. You don't want all your commands in one .js file.

Try something like this for the Ban command itself. I use this for my Bot:
client.on("message", (message) => {
if (message.content.startsWith("!ban")) {
if(!message.member.roles.find("name", "Role that can use this bot"))
return;
// Easy way to get member object though mentions.
var member= message.mentions.members.first();
// ban
member.ban().then((member) => {
// Successmessage
message.channel.send(":wave: " + member.displayName + " has been successfully banned :point_right: ");
}).catch(() => {
// Failmessage
message.channel.send("Access Denied");
});
}
});
That should work, set the role you want to use it (cAsE sEnSiTiVe) and change !ban to whatever you feel like using. If you change all "ban"s in this to kick, it will have the same effect. If this helped you, mark this as the answer so others can find it, if not, keep looking :)

Related

Antispam thtottler

I am working on creating a telegram bot, I want to make an anti-spam system, that is, when a person presses a button too many times, the bot will freeze for him for a certain number of seconds, it is possible to write a message about blocking. People in other matters do not help me.
import {
bot
} from '../token.js';
import {
keyboardMain
} from '../keyboards/keyboardsMain.js';
export function commands() {
bot.on('message', msg => {
const text = msg.text;
const chatId = msg.chat.id;
if (text === '/start') {
return bot.sendMessage(chatId, 'hello', keyboardMain);
}
return bot.sendMessage(chatId, 'error');
});
}
Do you use telegraf as telegram module ? If yes, you can kick users from channels or groups.
here is a little piece that i made for you :)
you can apply it to anything ^_^
var tps = 0;
var allowpassage = false;
var detectspamon = document;
c = function() {
setTimeout(()=>{
console.log("got clicks:",tps);
if (tps==0) {console.log("no clicking detected");}
else if (tps==1) {console.log("success");allowpassage=true;}
else {console.log("too many clicks per second");}
tps=0;
console.log("setting clicks to 0");
},500);
}
detectspamon.onclick = () => {tps++;console.log(tps);c(tps);}

Why does role.permissions.remove() not work?

I tried to make a command to remove the MENTION_EVERYONE permission from all roles. It didn't work for some reason. I tried console logging which roles have the permission, and it did, but the only thing is that the permission isn't being taken away. I get no error but here is my code.
client.on('message', msg => {
if(msg.content === 'checkroleperms' && msg.author.id === 'xxxxxxxxxx') {
var roles = msg.guild.roles.cache.array()
var all = '{Placeholder}'
roles.forEach(role => {
if(role.permissions.has('MENTION_EVERYONE')) {
all+= ', ' + role.name;
//RIGHT HERE IS THE WHERE THE PROBLEM IS!!
//Changed this to msg.guild.role.cache.get(role.id).permissions.re...
role.permissions.remove('MENTION_EVERYONE');
console.log(role.name);
}
})
setTimeout(() => msg.channel.send(all), 500);
}
})
Was there something I did wrong? Also, the bot has Admin perms and is the second highest role in the server (right under me). The point is that the command is running but the perms are not being removed.
EDIT: I realized I was only modifying the array, but nothing is happening even when I get it from msg.guild.roles.cache
You were pretty close, the problem is you remove the permission but you never update the role itself.
role.permissions.remove() removes bits from these permissions and returns these bits or a new BitField if the instance is frozen. It doesn't remove or update the role's permissions though.
To apply these changes, you need to use the setPermissions() method that accepts a PermissionResolvable, like the bitfield returned from the permissions.remove() method.
It's probably also better to use roles.fetch() to make sure roles are cached.
Check the working code below:
client.on('message', async (msg) => {
if (msg.content === 'checkroleperms' && msg.author.id === 'xxxxxxxxxx') {
try {
const flag = 'MENTION_EVERYONE';
const roles = await msg.guild.roles.fetch();
const updatedRoles = [];
roles.cache.each(async (role) => {
if (role.permissions.has(flag)) {
const updatedPermissions = role.permissions.remove(flag);
await role.setPermissions(updatedPermissions.bitfield);
updatedRoles.push(role.name);
}
});
const roleList = updatedRoles.join(', ') || `No role found with \`${flag}\` flag`;
setTimeout(() => msg.channel.send(roleList), 500);
} catch (error) {
console.log(error);
}
}
});

Discord.js bot was working, added one extra command and everything broke. Can anyone help me figure out why?

Tried to venture in to the realm of making discord bots. Followed along with a fairly simple tutorial, tweaking it along the way to fit what I was trying to make. The bot originally worked, but I went back in to add the "Mistake" command, and suddenly it's not working. I added in console.log pretty much everywhere, trying to figure out how far everything was getting.
When I start the bot, it will spit out the "Bot Online" log. When I input a command, it will spit out the "Commands" log, but it won't register the command at all. I've tried looking for any minor typos, missing brackets, etc... but I just can't seem to figure out what's gone wrong. I'm hoping that someone here can help! Thank you!
const Discord = require('discord.js');
const config = require('./config.json');
const client = new Discord.Client();
const SQLite = require('better-sqlite3');
const sql = new SQLite('./scores.sqlite');
client.on('ready', () => {
console.log('Bot Online');
const table = sql.prepare("SELECT count(*) FROM sqlite_master WHERE type='table' AND name = 'goals';").get();
if (!table['count(*)']) {
sql.prepare('CREATE TABLE goals (id TEXT PRIMARY KEY, user TEXT, guild TEXT, goals INTEGER);').run();
sql.prepare('CREATE UNIQUE INDEX idx_goals_id ON goals (id);').run();
sql.pragma('synchronous = 1');
sql.pragma('journal_mode = wal');
}
//Statements to get and set the goal data
client.getGoals = sql.prepare('SELECT * FROM goals WHERE user = ? AND guild = ?');
client.setGoals = sql.prepare('INSERT OR REPLACE INTO goals (id, user, guild, goals) VALUES (#id, #user, #guild, #goals);');
});
client.on('message', (message) => {
if (message.author.bot) return;
let goalTotal;
if (message.guild) {
goalTotal = client.getGoals.get(message.author.id, message.guild.id);
if (!goalTotal) {
goalTotal = {
id: `${message.guild.id}-${message.author.id}`,
user: message.author.id,
guild: message.guild.id,
goals: 0,
};
}
}
if (message.content.indexOf(config.prefix) !== 0) return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
console.log('Commands');
if (command === 'Goals') {
console.log('Goals');
return message.reply(`You Currently Have ${goalTotal.goals} Own Goals.`);
}
if (command === 'OwnGoal') {
console.log('Own Goal');
const user = message.mentions.users.first() || client.users.cache.get(args[0]);
if (!user) return message.reply('You must mention someone.');
let userscore = client.getGoals.get(user.id, message.guild.id);
if (!userscore) {
userscore = {
id: `${message.guild.id}-${user.id}`,
user: user.id,
guild: message.guild.id,
goals: 0,
};
}
userscore.goals++;
console.log({ userscore });
client.setGoals.run(userscore);
return message.channel.send(`${user.tag} has betrayed his team and now has a total of ${userscore.goals} own goals.`);
}
if (command === 'Mistake') {
console.log('Mistake');
const user = message.mentions.users.first() || client.users.cache.get(args[0]);
if (!user) return message.reply('You must mention someone.');
let userscore = client.getGoals.get(user.id, message.guild.id);
if (!userscore) {
return message.reply('This person has no Rocket Bot activity.');
}
if (userscore === 0) {
return message.reply('This player currently has no goals.');
}
if (userscore > 0) {
userscore.goals--;
}
console.log({ userscore });
client.setGoals.run(userscore);
return message.channel.send(`${user.tag} was falsely accused and now has a total of ${userscore.goals} own goals.`);
}
if (command === 'Leaderboard') {
console.log('Leaderboard');
const leaderboard = sql.prepare('SELECT * FROM goals WHERE guild = ? ORDER BY goals DESC;').all(message.guild.id);
const embed = new Discord.MessageEmbed()
.setTitle('Rocket Bot Leaderboard')
.setAuthor(client.user.username, client.user.avatarURL())
.setDescription('Total Goals Scored Against Own Team:')
.setFooter('Rocket Bot')
.setThumbnail('https://imgur.com/a/S9HN4bT')
.setColor('0099ff');
for (const data of leaderboard) {
embed.addFields({
name: client.users.cache.get(data.user).tag,
value: `${data.goals} goals`,
inline: true,
});
}
return message.channel.send({ embed });
}
if (command === 'RocketHelp') {
console.log('Help');
return message.reply(
'Rocket Bot Commands:' +
'\n' +
'!Goals - See How Many Goals You Have Scored Against Your Own Team' +
'\n' +
'!OwnGoal - Tag Another Player With # To Add One To Their Total' +
'\n' +
'!Mistake - Tag Another Player With # To Subtract One From Their Total' +
'\n' +
'!Leaderboard - Show The Current Leaderboard'
);
}
});
client.login(config.token);
You are improperly splitting the message content. You added g to the regex by accident.
Correct line:
const args = message.content.slice(config.prefix.length).trim().split(/ +/);
Because of improper args split, it could not find any command at all, hence no console log was invoked after Commands.

Why is my script not letting my bot add reactions to the embed message it is sending? (discord.js)

I am a big novice with JavaScript coding so if you can make this a pre simple explanation that'd be MUCH appreciated.
So basically I have made this small script in order to send a poll to another channel using the arguments I have made the user put in and then format it and send it as an embedded message
The script is sending the whole thing formated however the final step of not adding the reactions is the issue.
(they are custom reactions which I have already defined you'll see below)
if (args.length >= 1) {
message.delete().then(() => {
const pollEmbed = new Discord.RichEmbed()
.setColor('#ABDFF2')
.setTitle("** " + pollArgs[0] + " **")
.setDescription(pollArgs[1])
.addField('*Click on the reactions below to cast your opinion on this poll!*', 'If you would like to start your own poll: !help in <#726235250136580106>')
.setTimestamp()
.setThumbnail(message.author.displayAvatarURL)
.setFooter(message.author.tag + " | Peace Keeper", message.author.displayAvatarURL)
let yes = message.guild.emojis.find('name', "yes")
let no = message.guild.emojis.find('name', "no")
suggestionschannel.send(pollEmbed).then(message.react(yes, no));
In case you need to see the full code here it is:
const Discord = require("discord.js");
const client = new Discord.Client();
module.exports.run = async (bot, message, args) => {
const suggestionschannel = message.guild.channels.find("name", "suggestions");
let pollArgs = args.slice(0).join(" ").split('|');
if (args.length >= 1) {
message.delete().then(() => {
const pollEmbed = new Discord.RichEmbed()
.setColor('#ABDFF2')
.setTitle("** " + pollArgs[0] + " **")
.setDescription(pollArgs[1])
.addField('*Click on the reactions below to cast your opinion on this poll!*', 'If you would like to start your own poll: !help in <#726235250136580106>')
.setTimestamp()
.setThumbnail(message.author.displayAvatarURL)
.setFooter(message.author.tag + " | Peace Keeper", message.author.displayAvatarURL)
let yes = message.guild.emojis.find('name', "yes")
let no = message.guild.emojis.find('name', "no")
suggestionschannel.send(pollEmbed).then(message.react(yes, no));
})
} else {
message.delete().catch();
const pollErrEmbed = new Discord.RichEmbed()
.setColor('FF6961')
.setTitle("**error!**")
.addField("use the correct format: !polls-start <title> | <message>", "If you need help do: `!polls-help`.")
.setTimestamp()
.setFooter(message.author.tag + " | Peace Keeper", message.author.displayAvatarURL)
message.reply(pollErrEmbed).then(msg => msg.delete(10000));
}
}
module.exports.help = {
name: "polls-start"
}
Your code seems good only one tiny edit!
Instead of
suggestionschannel.send(pollEmbed).then(message.react(yes, no));
You would need to use
suggestionschannel.send(pollEmbed).then(message => {
message.react(yes);
message.react(no);
});
Also remember about Updating Discord.js to v12, as soon v11 support is going to end!

roles are not being changed for the mentioned user

When a staff does !mute #user time , it should give the role Muted and take away the role Speaker, this does not happen though, instead everything else happens and the roles are not given or taken away.
const Discord = require('discord.js');
const bot = new Discord.Client();
const ms = require('ms');
const token = '';
const PREFIX = '!';
bot.on('ready', () => {
console.log('This bot is active!');
})
bot.on('message', message => {
let args = message.content.substring(PREFIX.length).split(" ");
switch (args[0]) {
case 'mute':
if(!message.member.hasPermission("MUTE_MEMBERS")) return message.reply("You cannot run this command");
let mperson = message.guild.member(message.mentions.users.first() || message.guild.members.cache.get(args[1]));
if(!mperson) return message.reply("I cannot find the user " + mperson)
var mainrole = message.guild.roles.cache.get("718166462862196777");
var muterole = message.guild.roles.cache.get("717606607910993930");
if(!muterole) return message.reply("Couldn't find the mute role.")
let time = args[2];
if(!time){
return message.reply("You didnt specify a time!");
}
mperson.roles.add(mainrole).catch(console.error)
mperson.roles.remove(muterole).catch(console.error);
message.channel.send(`${mperson.user} has now been muted for ${ms(ms(time))}`)
setTimeout(function(){
mperson.roles.add(mainrole)
mperson.roles.remove(muterole);
console.log(muterole)
message.channel.send(`${mperson.user} has been unmuted.`)
}, ms(time));
break;
}
});
bot.login(token);
The roles that I want to add and remove from the mentioned player do not change, any way that I can fix this?
I changed mperson.roles.add(mainrole).catch(console.error) to mperson.roles.add("717631710761844757").catch(console.error) and now everything works. This is discord.js v12.

Categories