I started building a Discord bot and the first function I made was kicking members. This is the code
const Discord = require("discord.js");
const { prefix, token } = require("./config.json");
const client = new Discord.Client();
client.once("ready", () => {
console.log("Ready!");
});
client.on("message", (message) => {
if (message.member.hasPermission(["KICK_MEMBERS", "BAN_MEMBERS"])) {
if (message.content.startsWith(`${prefix}kick`)) {
let member = message.mentions.members.first();
member.kick().then((member) => {
message.channel.send("```" + member.displayName + " has been kicked ```");
});
}
}
});
client.login(token);
If someone without the kick and ban permission tries it nothing happens so this part is working. If an admin types eg. :kick #someone then someone will be kicked. But if an Admin types :kick (without someone's username) I get an error and the bot stops working until I restart it manually. This is the error:TypeError: Cannot read property 'kick' of undefined. What can I do to make this fully working?
You'll need to check if that user exists.
Try is like this:
if (message.member.hasPermission(["KICK_MEMBERS", "BAN_MEMBERS"])) {
if (message.content.startsWith(`${prefix}kick`)) {
let member = message.mentions.members.first();
if(!member) return message.channel.send('Cannot find this member');
member.kick().then((member) => {
message.channel.send("```" + member.displayName + " has been kicked ```");
});
}
}
And if you want to handle even more possible errors you'll need to use a try-catch block:
if (message.member.hasPermission(["KICK_MEMBERS", "BAN_MEMBERS"])) {
if (message.content.startsWith(`${prefix}kick`)) {
let member = message.mentions.members.first();
if(!member) return message.channel.send('Cannot find this member');
try {
member.kick().then((member) => {
message.channel.send("```" + member.displayName + " has been kicked ```");
});
} catch (error) {
console.log(error);
message.channel.send('An error has occured');
}
}
}
Check if the user mentioned another user before kicking the member:
const Discord = require("discord.js");
const { prefix, token } = require("./config.json");
const client = new Discord.Client();
client.once("ready", () => {
console.log("Ready!");
});
client.on("message", (message) => {
if (message.member.hasPermission(["KICK_MEMBERS", "BAN_MEMBERS"])) {
if (message.content.startsWith(`${prefix}kick`)) {
let member = message.mentions.members.first();
if (!member)
return;
member.kick().then((member) => {
message.channel.send("```" + member.displayName + " has been kicked ```");
});
}
}
});
client.login(token);
You can't kick undefined.
Related
I'm pretty trash at coding so I need a little bit of help. I'm trying to code my discord bot to delete someone's messages for one minute after they click a react emoji. It sounds simple but for my tiny pea brain, it's not. This is what I have got so far. It deletes all messages from different users and guilds it's in, forever. I want it so it only delete messages in one channel for one minute.
client.once('message', async userMessage => {
if (userMessage.content.startsWith(''))
{
botMessage = await userMessage.channel.send('Who here likes goats?')
await botMessage.react("π")
await botMessage.react("π")
const filter = (reaction, user) => {
return (
["π", "π"].includes(reaction.emoji.name) && user.id === userMessage.author.id
);
};
botMessage
.awaitReactions(filter, { max: 1, time: 60000, errors: ["time"] })
.then((collected) => {
const reaction = collected.first();
if (reaction.emoji.name === "π") {
userMessage.channel.send(`${userMessage.author}, how dare you. I guess no on here likes me. Hmmm, because of that I shall now eat all your messages! BAAAAAHAHAHHAHAHA!`)
setTimeout(() => {
client.on("message", async msg => {
if (author.msg.content.startsWith("")) {
userMessage.channel = await msg.delete();
}
});
}, 2000);
} else {
userMessage.reply("Thanks!");
}
})
.catch((_collected) => {
userMessage.channel.send("Hehe")
});
}
});
Btw, the code is in discord.js!
Your problem is this chunk of code
setTimeout(() => {
client.on("message", async msg => {
if (author.msg.content.startsWith("")) {
userMessage.channel = await msg.delete();
}
});
}, 2000);
This is not how you use events.
A) Your message event is nested within another which could cause memory leaks.
B) To get the content you need to use msg.content, author.msg Is not a thing.
C) I assume your intention here: msg.content.startsWith("") is to always fire the if statement, in that case why not do if (true).
Here's how I would do it:
Create a Set in the namespace which will hold id's of users who's messages should be deleted
const toDelete = new Set();
If they react with a π add them to the set.
if (reaction.emoji.name === "π") {
userMessage.channel.send('Your message here');
if (!toDelete.has(userMessage.author.id)) {
toDelete.add(userMessage.author.id);
}
}
On each message event check if the author of the message has their id in the set, If so delete their message
client.once('message', async userMessage => {
if (toDelete.has(userMessage.author.id)) {
return userMessage.delete()
.catch(console.error);
}
if (userMessage.content.startsWith('')) {
// Rest of your code
I think your problem in understanding how everything works.
I took everything from discord.js documentation.
Type reaction command to see how it works.
const Discord = require("discord.js");
require("dotenv").config();
const TOKEN = process.env.TOKEN||"YOUR TOKEN";
const PREFIX = process.env.PREFIX||"YOUR PREFIX";
const bot = new Discord.Client();
bot.on("ready", async function(e) {
console.log("Loaded!");
})
bot.on("message", async function(message) {
if (message.author.bot) return;
if (!message.content.startsWith(PREFIX)) return;
let args = message.content.slice(PREFIX.length).trim().split(/\s+/);
let command = args.splice(0, 1).toString().toLowerCase();
if (command == "reaction") {
message.delete();
let msg = await message.channel.send("Click on the reaction");
await msg.react("π");
await msg.react("π");
let filter = (reaction, user) => {
return ["π", "π"].includes(reaction.emoji.name) && user.id == message.author.id;
}
msg.awaitReactions(filter, {max: 1, time: 10000, errors: ["time"]}).then(collected => {
let reaction = collected.first();
if (reaction.emoji.name == "π") {
return message.channel.send("downvote");
}
return message.channel.send("upvote");
}).catch(e => {
message.channel.send("user didn't vote");
})
}
})
bot.login(TOKEN);
Im trying to get a ban command and im using my pervious kick command as a sort of template, i cant quite get the ban reason to work, im assuming thats the only issue the code is below.
const Discord = require('discord.js')
module.exports.run = async (bot, message, args) => {
if (!message.member.hasPermission('BAN_MEMBERS')) return message.reply('**No permission**')
const user = message.mentions.users.first();
if (user) {
const member = message.guild.member(user);
if (member) {
member
.ban('no reason')
.then(() => {
message.channel.send(`${user.tag} Has been banned`)
})
.catch(err => {
message.reply('Unable');
console.error(err);
});
} else {
message.reply("Error");
}
} else {
message.reply("You forgot to mention someone");
}
};
module.exports.help = {
name: "ban"
}
You must supply the correct parameters for .ban()
in this case .ban({reason: 'no reason'})
so your corrected code is
if (!message.member.hasPermission("BAN_MEMBERS"))
return message.reply("**No permission**");
const user = message.mentions.users.first();
if (user) {
const member = message.guild.member(user);
if (member) {
member
.ban({ reason: "no reason" })
.then(() => {
message.channel.send(`${user.tag} Has been banned`);
})
.catch((err) => {
message.reply("Unable");
console.error(err);
});
} else {
message.reply("Error");
}
} else {
message.reply("You forgot to mention someone");
}
also, please supply errors in future and look for Other information beforehand.
Adding on, a lot of that will not work in V13
if (!message.member.permissions.has("BAN_MEMBERS"))
return message.reply("**You do not have the proper permissions.**");
const user = message.mentions.users.first();
if (user) {
const member = message.guild.members.cache.get(user.id);
if (member) {
member
.ban({ reason: "no reason" })
.then(() => {
message.channel.send(`${user.tag} Has been banned`);
})
.catch((err) => {
message.reply(`Unable to ban User. \`\`\`${err}\`\`\` `);
console.error(err);
});
} else {
message.reply("Error");
}
} else {
message.reply("You forgot to mention someone, <#${message.author.id}>");
}
// Β© Ahmed1Dev
const Discord = require('discord.js')
module.exports.run = async (bot, message, args) => {
if (!message.member.hasPermission('BAN_MEMBERS')) return message.reply('**No permission**')
const user = message.mentions.users.first();
let reason = args.slice(2).join(' ');
if (user) {
const member = message.guild.member(user);
if (member) {
member
.ban('no reason')
.then(() => {
message.channel.send(`${user.tag} Has been banned`)
})
.catch(err => {
message.reply('Unable');
console.error(err);
});
} else {
message.reply("Error");
}
} else {
message.reply("You forgot to mention someone");
}
};
module.exports.help = {
name: "ban"
}
// Β© Ahmed1Dev
Well, I would create a discord bot that will stock given data in a database, .then I began to learn js
Until now i haven't any problem and found a lot of help in the web, before to create the database i tried to show detected data on the console but now I'm blocked and can't understand by myself where is the problem.
here is my code
const Discord = require('discord.js')
const client = new Discord.Client();
const { promisify } = require('util')
const sleep = promisify(setTimeout)
require('dotenv').config();
const BOT_TOKEN = '******'
client.on('ready', async () => {
console.log(`The bot is now working !\n\n`);
});
client.on('message', async (receivedMessage) => {
// Prevent bot from responding to its own messages
if (receivedMessage.author == client.user) {
return;
}
const { author, content, channel } = receivedMessage;
const { id } = author;
const trimmedContent = content.trim();
if (trimmedContent.startsWith('!ins')) {
console.log('Inside ins');
module.exports = {
prefix: "!ins",
fn: (msg) => {
let application = {}
let filter = (msg) => !msg.author.bot;
let options = {
max: 1,
time: 15000
};
msg.member.send("nom ?")
.then(dm => {
// After each question, we'll setup a collector on the DM channel
return dm.channel.awaitMessages(filter, options)
})
.then(collected => {
// Convert the collection to an array & get the content from the first element
application.name = collected.array()[0].content;
// Ask the next question
return msg.member.send("Parfait, maintenant votre mail ?")
})
.then(dm => {
return dm.channel.awaitMessages(filter, options)
})
.then(collected => {
application.emailAddress = collected.array()[0].content;
return msg.member.send("Excellent. Enfin, quel est votre Γ’ge ?")
})
.then(dm => {
return dm.channel.awaitMessages(filter, options)
})
.then(collected => {
application.pitch = collected.array()[0].content;
console.log(application)
})
}
}
}
});
// client.login logs the bot in and sets it up for use. You'll enter your token here.
client.login(' ');
The problem is that bot doesn't react to !ins command and on the console I only have the console.log 2 and 3
if you need any more info, feel free to ask them and thanks for taken time
I do think that you should code your main structure like mine because yours is a bit messy.
const Discord = require('discord.js');
const client = new Discord.Client();
const BOT_TOKEN = '...';
client.on('ready', async () => {
console.log(`The bot is now working !\n\n`);
});
client.on('message', async (receivedMessage) => {
// Prevent bot from responding to its own messages
if (receivedMessage.author == client.user) {
return;
}
const { author, content, channel } = receivedMessage;
const { id } = author;
// Removes whitespace from both ends of a string, "I personally do like this"
const trimmedContent = content.trim();
if (trimmedContent.startsWith('!ins')) {
console.log('Inside ins');
}
});
client.login(BOT_TOKEN);
process.on('exit', () => {
client.destroy();
console.log(`The bot is now disconnected !\n\n`);
});
const { Client, RichEmbed } = require("discord.js");
const chalk = require("chalk");
const { token, prefix } = require("../config/config.js");
const client = new Client();
client.on("ready", () => {
console.log(chalk.red("Witamy w konsoli bota Island"));
console.log(chalk.green(`Zalogowano jako ${client.user.tag}!`));
});
client.on("message", (msg) => {
const { author, guild } = msg;
if (author.bot || !guild) {
return;
}
if (msg.content === "-info") {
msg.channel.send("Witam, jestem botem stworzonym przez Rewera");
}
});
client.on("message", (msg) => {
const { author, guild } = msg;
if (author.bot || !guild) {
return;
}
if (msg.content === "-komendy") {
msg.channel.send("JuΕΌ wkrΓ³tce, zostanΔ
dodane. SΔ
w trakcie tworzenia");
}
if (msg.content === "-wersja") {
msg.channel.send("Wersja: ALPHA 0.04");
}
if (msg === "-tworca") {
const botAuthor = "Rewer";
const botVersion = "v1.1";
msg.channel.send(
"Autorem bota jest: **${botAuthor}**! Wersja *${botVersion}*. "
);
}
if (message.content.startsWith("$kick")) {
if (!message.member.roles.find("name", "Admin"))
return;
// Easy way to get member object though mentions.
var member = message.mentions.members.first();
// Kick
member.kick().then((member) => {
// Successmessage
message.channel.send(":wave: " + member.displayName + " has been successfully kicked :point_right: ");
}).catch(() => {
// Failmessage
message.channel.send("Access Denied");
});
}
});
// Error handler
client.on("debug", () => {});
client.on("warn", () => {});
client.on("error", () => {});
client.login(token);
I have a problem with this code after adding the kick player command. The rest of the bot doesn't work and neither does this command
I don't know what to do with it when I remove the kick code. The bot magically starts working.
Anyone have any ideas on how to fix it, I'm a beginner so please understand
When you handle the message event you pass "msg" as the argument
client.on("message", (msg) => {
So you should use "msg" throughout
However in you kick command you start using "message"
if (message.content.startsWith("$kick")) {
and if (!message.member.roles.find("name", "Admin"))
You must change "message" to "msg" to match the name you gave the variable at the start
client.on("message", (msg) => {
So I'm trying to get my bot to work but the code says message not defined. I have tried everything I know to do:
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', () => {
console.log('ready!');
});
if (message.content === '!ping') {
message.channel.send('Pong.');
}
if (command === "!hug") {
let user = message.mentions.users.first();
message.channel.send("You have been hugged " + user);
}
client.login('my-bot-token');
You forgot to add a event listener for a message, I think.
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', () => {
console.log('ready!');
});
client.on("message", (message) => {
if (message.content === '!ping') {
message.channel.send('Pong.');
}
if (command === "!hug") {
let user = message.mentions.users.first();
message.channel.send("You have been hugged " + user);
}
}
client.login('my-bot-token');