I'm new to this platform and desperately running in circles to unban a player on discord.
Its id has spaces, and I always run into 400 or 404 errors ...
Do you have any idea to solve my problem ?
I tested a lot of codes, and the last one I have is this :
if (message.content.startsWith('!unban')) {
let args = message.content.split(/ +/g);
let user = message.guild.members.cache.get(args[1]);
if (!user) return message.channel.send('Please specify a user ID');
user.unban().then(() => message.channel.send('Success'));
}
I am currently receiving the message 'Please specify a user ID'.
For information, I am not using the async function :
const Discord = require('discord.js');const client = new Discord.Client();client.on('message', message => {}
Thanks for your help !
Since the user is banned he's not in the guild, and you're trying to get the user from the guild members and this returns undefined so the bot keeps sending the error message.
To unban a user you need to use the GuildMemberManager#unban method.
Here's an example:
if (message.content.startsWith('!unban')) {
let args = message.content.split(/ +/g);
let user = args[1];
if (!user) return message.channel.send('Please specify a user ID');
message.guild.members.unban(user).then((u) => {
message.channel.send(`Successfully unbanned ${u.tag}`);
}).catch((err) => {
console.log(err);
message.channel.send("I couldn't unban this user, please check if i have the required permissions and if the user id is correct");
});
}
if I understand you correctly, you want to use a command like !unban idBeforeSpace afterSpace.
In that case, your code runs like this:
if (message.content.startsWith('!unban')) {
let args = message.content.split(/ +/g); //args = ["!unban", "idBeforeSpace", "afterSpace"]
let user = message.guild.members.cache.get(args[1]); //args[1] = "idBeforeSpace"; user = null
if (!user) return message.channel.send('Please specify a user ID');
user.unban().then(() => message.channel.send('Success'));
}
but instead you wanted this:
args = ["!unban", "idBeforeSpace afterSpace"]
You split your arglist on every whitespace you find. Instead of splitting at every occurence of the regex, just split after the first.
Related
I was working on my discord bot and when I tried to run the ban command, this error came. I'm kind of new so can anyone please help me.
Contacting on discord will help me more:
my discord: AlanITD#0630
let args = message.content.slice(prefix.length).split(' ');
let cont = args.shift().toLowerCase();
module.exports.run = async (bot, message) => {
const user = message.mentions.users.first().id // returns the user object if an user mention exists
const banReason = args.slice(1).join(' '); // Reason of the ban (Everything behind the mention)
// Check if an user mention exists in this message
if (!user) {
try {
// Check if a valid userID has been entered instead of a Discord user mention
if (!message.guild.members.get(args.slice(0, 1).join(' '))) throw new Error('Couldn\' get a Discord user with this userID!');
// If the client (bot) can get a user with this userID, it overwrites the current user variable to the user object that the client fetched
user = message.guild.members.get(args.slice(0, 1).join(' '));
user = user.user;
} catch (error) {
return message.reply('Couldn\'t get a Discord user with this userID!');
}
}
if (user === message.author) return message.channel.send('You can\'t ban yourself, stupid 😑'); // Check if the user mention or the entered userID is the message author himsmelf
if (!reason) return message.reply('You forgot to enter a reason for this ban!'); // Check if a reason has been given by the message author
if (!message.guild.member(user).bannable) return message.reply('You can\'t ban this user because you the bot has not sufficient permissions, lmao 😂'); // Check if the user is bannable with the bot's perms
const banConfirmationEmbedModlog = new Discord.RichEmbed()
.setAuthor(`Banned by **${msg.author.username}#${msg.author.discriminator}**`, msg.author.displayAvatarURL)
.setThumbnail(user.displayAvatarURL)
.setColor('RED')
.setTimestamp()
.setDescription(`**Action**: Ban
**User**: ${user.username}#${user.discriminator} (${user.id})
**Reason**: ${reason}`);
message.channel.send(banConfirmationEmbedModlog)
}
module.exports.config = {
name: "ban",
description: "Ban those naughty folks",
usage: ">ban",
accessableby: "Moderators and Admins",
}
I would really appreciate all of your support
I want the user to input !fn maxtl and the bot would reply by putting out this link
https://fortnitetracker.com/profile/all/maxtl/event
This is what I am thinking it would look like. Can someone provide me with any suggestions on how to improve this Discord bot API usage?
bot.on("message", (msg) => {
if (msg.content === `!fn ${Username}`) {
msg.reply(`https://fortnitetracker.com/profile/all/${Username}/events`);
}
});
Assuming you aren't doing any other processing of the message, this is what you'll probably need to do.
bot.on("message", (msg) => {
if (!msg.content.startsWith('!')) return;
const arguments = msg.content.split(' ');
const command = arguments.shift();
if (command === '!fn') {
msg.reply(`https://fortnitetracker.com/profile/all/${arguments[0]}/events`);
}
});
This will
Check and see that the message begins with your command identifier (assuming it's "!")
Split the message in to an array of arguments;
Remove and store the command in a command variable
Check to see if the command is equal to "!fn"
Reply with a url that includes argument[0] which at this point would be equal to the username if one was provided.
I think this block of code is something you are looking for, I am not 100% because I don't know what the rest of your bot is doing.
This code will
Listen for a message
The bailout of the code execution if the message doesn't start with !fn
Attempts to find the message with mentioned Username (your snippet shows this variable
available so I assume it's known beforehand, if not we can figure that out too)
The Bot tries to post the message
bot.on('message', async (msg) => {
if (!msg.content.startsWith('!fn')) return;
const commandFound = msg.content.find(mentioned => mentioned === `!fn ${Username}`)
const arguments = commandFound.split(' ');
const userName = arguments.shift();
if (userName) {
try {
await msg.reply(`https://fortnitetracker.com/profile/all/${userName}/events`);
} catch (err) {
console.warn('Failed to respond to mention.');
console.warn(err);
}
}
});
bot.on('messageReactionAdd', async (reaction, user) => {
// Define the emoji user add
let role = message.guild.roles.find(role => role.name === 'Alerts');
if (message.channel.name !== 'alerts') return message.reply(':x: You must go to the channel #alerts');
message.member.addRole(role);
});
Thats the part of my bot.js. I want the user to react in a certain channel and receive role Alerts
You haven't really stated what the problem is, what works and what doesn't work but I'll take a wild stab at some parts which catch my eye.
For starters you are calling properties on the variable message whilst in the code you supplied, you didn't create/set a variable named message. My guess is that you want the message to which a reaction has been added. To do that you have to use the MessageReaction parameter which is supplied in the messageReactionAdd event as reaction.
From there you can replace message.<something> with reaction.message.<something> everywhere in the code you supplied.
Something also to note is that you add the role Alerts to message.member. This won't work how you want it to, since it will give the Alerts role to the author of the original message.
What (I think) you want to do, is fetch the user who just reacted with the emoji and assign them the Alerts role. You'll have to find the member in the guild first and then assign them the Alerts role. To do this you'll have to use the User parameter and find the correct Member because you can't add a role to a User object but you can to a Member object. Below is some code which should hopefully put you on the right track.
// Fetch and store the guild (the server) in which the message was send.
const guild = reaction.message.guild;
const memberWhoReacted = guild.members.find(member => member.id === user.id);
memberWhoReacted.addRole(role);
You are using message.member variable despite not defining message.
Any of these methods won't really work in v12 so I updated it for someone else searching.
If you find any mistakes be sure to make me aware of it.
const Discord = require('discord.js');
const client = new Discord.Client({ partials: ['MESSAGE', 'CHANNEL', 'REACTION'] }); //partials arent really needed but I woudld reccomend using them because not every reaction is stored in the cache (it's new in v12)
const prefix = "-";
client.on('messageReactionAdd', async (reaction, user) => {
if (reaction.partial) { //this whole section just checks if the reaction is partial
try {
await reaction.fetch(); //fetches reaction because not every reaction is stored in the cache
} catch (error) {
console.error('Fetching message failed: ', error);
return;
}
}
if (!user.bot) {
if (reaction.emoji.id == yourEmojID) { //if the user reacted with the right emoji
const role = reaction.message.guild.roles.cache.find(r => r.id === yourRoleID); //finds role you want to assign (you could also user .name instead of .id)
const { guild } = reaction.message //store the guild of the reaction in variable
const member = guild.members.cache.find(member => member.id === user.id); //find the member who reacted (because user and member are seperate things)
member.roles.add(role); //assign selected role to member
}
}
})
Here's a quick answer, though way too late. So I'll be updating the answer with Discord.js v.12.x (or the same as Discord.js Master)
bot.on('messageReactionAdd', async (reaction, user) => {
//Filter the reaction
if (reaction.id === '<The ID of the Reaction>') {
// Define the emoji user add
let role = message.guild.roles.cache.find((role) => role.name === 'Alerts');
if (message.channel.name !== 'alerts') {
message.reply(':x: You must go to the channel #alerts');
} else {
message.member.addRole(role.id);
}
}
});
So I have been search far and wide over the internet, trying to find a possible way to make a purge command. Now I have found quite a lot of different ways to make one, but none of them either suited me in the way I wanted, or simply worked for me.
SO to start off, here is my code
const Discord = require("discord.js"); // use discord.js
const BOT_TOKEN = "secret bot token :)" // bot's token
const PREFIX = "*" // bot's prefix
var eightball = [ // sets the answers to an eightball
"yes!",
"no...",
"maybe?",
"probably",
"I don't think so.",
"never!",
"you can try...",
"up to you!",
]
var bot = new Discord.Client(); // sets Discord.Client to bot
bot.on("ready", function() { // when the bot starts up, set its game to Use *help and tell the console "Booted up!"
bot.user.setGame("Use *info") // sets the game the bot is playing
console.log("Booted up!") // messages the console Booted up!
});
bot.on("message", function(message) { // when a message is sent
if (message.author.equals(bot.user)) return; // if the message is sent by a bot, ignore
if (!message.content.startsWith(PREFIX)) return; // if the message doesn't contain PREFIX (*), then ignore
var args = message.content.substring(PREFIX.length).split(" "); // removes the prefix from the message
var command = args[0].toLowerCase(); // sets the command to lowercase (making it incase sensitive)
var mutedrole = message.guild.roles.find("name", "muted");
if (command == "help") { // creates a command *help
var embedhelpmember = new Discord.RichEmbed() // sets a embed box to the variable embedhelpmember
.setTitle("**List of Commands**\n") // sets the title to List of Commands
.addField(" - help", "Displays this message (Correct usage: *help)") // sets the first field to explain the command *help
.addField(" - info", "Tells info about myself :grin:") // sets the field information about the command *info
.addField(" - ping", "Tests your ping (Correct usage: *ping)") // sets the second field to explain the command *ping
.addField(" - cookie", "Sends a cookie to the desired player! :cookie: (Correct usage: *cookie #username)") // sets the third field to explain the command *cookie
.addField(" - 8ball", "Answers to all of your questions! (Correct usage: *8ball [question])") // sets the field to the 8ball command
.setColor(0xFFA500) // sets the color of the embed box to orange
.setFooter("You need help, do you?") // sets the footer to "You need help, do you?"
var embedhelpadmin = new Discord.RichEmbed() // sets a embed box to the var embedhelpadmin
.setTitle("**List of Admin Commands**\n") // sets the title
.addField(" - say", "Makes the bot say whatever you want (Correct usage: *say [message])")
.addField(" - mute", "Mutes a desired member with a reason (Coorect usage: *mute #username [reason])") // sets a field
.addField(" - unmute", "Unmutes a muted player (Correct usage: *unmute #username)")
.addField(" - kick", "Kicks a desired member with a reason (Correct usage: *kick #username [reason])") //sets a field
.setColor(0xFF0000) // sets a color
.setFooter("Ooo, an admin!") // sets the footer
message.channel.send(embedhelpmember); // sends the embed box "embedhelpmember" to the chatif
if(message.member.roles.some(r=>["bot-admin"].includes(r.name)) ) return message.channel.send(embedhelpadmin); // if member is a botadmin, display this too
}
if (command == "info") { // creates the command *info
message.channel.send("Hey! My name is cookie-bot and I'm here to assist you! You can do *help to see all of my commands! If you have any problems with the Minecraft/Discord server, you can contact an administrator! :smile:") // gives u info
}
if (command == "ping") { // creates a command *ping
message.channel.send("Pong!"); // answers with "Pong!"
}
if (command == "cookie") { // creates the command cookie
if (args[1]) message.channel.send(message.author.toString() + " has given " + args[1].toString() + " a cookie! :cookie:") // sends the message saying someone has given someone else a cookie if someone mentions someone else
else message.channel.send("Who do you want to send a cookie to? :cookie: (Correct usage: *cookie #username)") // sends the error message if no-one is mentioned
}
if (command == "8ball") { // creates the command 8ball
if (args[1] != null) message.reply(eightball[Math.floor(Math.random() * eightball.length).toString(16)]); // if args[1], post random answer
else message.channel.send("Ummmm, what is your question? :rolling_eyes: (Correct usage: *8ball [question])"); // if not, error
}
if (command == "say") { // creates command say
if (!message.member.roles.some(r=>["bot-admin"].includes(r.name)) ) return message.reply("Sorry, you do not have the permission to do this!");
var sayMessage = message.content.substring(4)
message.delete().catch(O_o=>{});
message.channel.send(sayMessage);
}
if(command === "purge") {
let messagecount = parseInt(args[1]) || 1;
var deletedMessages = -1;
message.channel.fetchMessages({limit: Math.min(messagecount + 1, 100)}).then(messages => {
messages.forEach(m => {
if (m.author.id == bot.user.id) {
m.delete().catch(console.error);
deletedMessages++;
}
});
}).then(() => {
if (deletedMessages === -1) deletedMessages = 0;
message.channel.send(`:white_check_mark: Purged \`${deletedMessages}\` messages.`)
.then(m => m.delete(2000));
}).catch(console.error);
}
if (command == "mute") { // creates the command mute
if (!message.member.roles.some(r=>["bot-admin"].includes(r.name)) ) return message.reply("Sorry, you do not have the permission to do this!"); // if author has no perms
var mutedmember = message.mentions.members.first(); // sets the mentioned user to the var kickedmember
if (!mutedmember) return message.reply("Please mention a valid member of this server!") // if there is no kickedmmeber var
if (mutedmember.hasPermission("ADMINISTRATOR")) return message.reply("I cannot mute this member!") // if memebr is an admin
var mutereasondelete = 10 + mutedmember.user.id.length //sets the length of the kickreasondelete
var mutereason = message.content.substring(mutereasondelete).split(" "); // deletes the first letters until it reaches the reason
var mutereason = mutereason.join(" "); // joins the list kickreason into one line
if (!mutereason) return message.reply("Please indicate a reason for the mute!") // if no reason
mutedmember.addRole(mutedrole) //if reason, kick
.catch(error => message.reply(`Sorry ${message.author} I couldn't mute because of : ${error}`)); //if error, display error
message.reply(`${mutedmember.user} has been muted by ${message.author} because: ${mutereason}`); // sends a message saying he was kicked
}
if (command == "unmute") { // creates the command unmute
if (!message.member.roles.some(r=>["bot-admin"].includes(r.name)) ) return message.reply("Sorry, you do not have the permission to do this!"); // if author has no perms
var unmutedmember = message.mentions.members.first(); // sets the mentioned user to the var kickedmember
if (!unmutedmember) return message.reply("Please mention a valid member of this server!") // if there is no kickedmmeber var
unmutedmember.removeRole(mutedrole) //if reason, kick
.catch(error => message.reply(`Sorry ${message.author} I couldn't mute because of : ${error}`)); //if error, display error
message.reply(`${unmutedmember.user} has been unmuted by ${message.author}!`); // sends a message saying he was kicked
}
if (command == "kick") { // creates the command kick
if (!message.member.roles.some(r=>["bot-admin"].includes(r.name)) ) return message.reply("Sorry, you do not have the permission to do this!"); // if author has no perms
var kickedmember = message.mentions.members.first(); // sets the mentioned user to the var kickedmember
if (!kickedmember) return message.reply("Please mention a valid member of this server!") // if there is no kickedmmeber var
if (!kickedmember.kickable) return message.reply("I cannot kick this member!") // if the member is unkickable
var kickreasondelete = 10 + kickedmember.user.id.length //sets the length of the kickreasondelete
var kickreason = message.content.substring(kickreasondelete).split(" "); // deletes the first letters until it reaches the reason
var kickreason = kickreason.join(" "); // joins the list kickreason into one line
if (!kickreason) return message.reply("Please indicate a reason for the kick!") // if no reason
kickedmember.kick(kickreason) //if reason, kick
.catch(error => message.reply(`Sorry #${message.author} I couldn't kick because of : ${error}`)); //if error, display error
message.reply(`${kickedmember.user.username} has been kicked by ${message.author.username} because: ${kickreason}`); // sends a message saying he was kicked
}
});
bot.login(BOT_TOKEN); // connects to the bot
It is the only file in my bot folder except the package.json, package-lock.json and all the node_modules.
What I'm trying to do is type in discord *purge [number of messages I want to purge] and get the bot to delete the amount of the messages I asked it to delete, PLUS the command I entered (for example, if I ask the bot to delete 5 messages, he deletes 6 including the *purge 5 message.
Any help would be much appreciated, thanks!
What you are looking for is this (bulkDelete()) method for Discord.js.
It bulk deletes a message, just simply pass in a collection of message in the method and it will do the job for you.
(You can use messages property from channel, otherwise if you prefer promises, then try fetchMessages() method. )
Just make sure that the channel is not a voice channel, or a DM channel. And finally, your bot needs to have permission too.
You can get your own bot's permission for the guild using message.guild.member(client).permissions, or you can just directly use message.guild.member(client).hasPermission(permission), which returns a boolean that determines if your bot have a desired permission.
(The method docs for hasPermission() is here)
note sure if this is still relevant but this what i use in my bots
if (!suffix) {
var newamount = "2";
} else {
var amount = Number(suffix);
var adding = 1;
var newamount = amount + adding;
}
let messagecount = newamount.toString();
msg.channel
.fetchMessages({
limit: messagecount
})
.then(messages => {
msg.channel.bulkDelete(messages);
// Logging the number of messages deleted on both the channel and console.
msg.channel
.send(
"Deletion of messages successful. \n Total messages deleted including command: " +
newamount
)
.then(message => message.delete(5000));
console.log(
"Deletion of messages successful. \n Total messages deleted including command: " +
newamount
);
})
.catch(err => {
console.log("Error while doing Bulk Delete");
console.log(err);
});
basic function is to specify number of messages to purge and it will delete that many plus the command used, the full example is here
I am creating a Discord bot with discord.js and I'd like to create a command that can clear messages. For now, I have this code (only the interesting part) and I can't figure out why it doesn't work:
// Importing discord.js, creating bot and setting the prefix
const Discord = require('discord.js');
const bot = new Discord.Client();
const prefix = "/";
// Array that stores all messages sent
messages = [];
bot.on('message', (message) => {
// Store the new message in the messages array
messages.push(message);
// Split the command so that "/clear all" becames args["clear", "all"]
var args = message.content.substring(prefix.length).split(" ");
// If the command is "/clear all"
if(args[0] == "clear" && args[1] == "all") {
bot.deleteMessages(messages); // Code that doesn't work
// Resets the array
messages = [];
}
}
// CONNECT !!!
bot.login('LOGING TOKEN HERE');
Can you help me ?
You should use <TextChannel>.bulkDelete instead.
Example:
msg.channel.bulkDelete(100).then(() => {
msg.channel.send("Purged 100 messages.").then(m => m.delete(3000));
});
This would delete 2 - 100 messages in a channel for every call to this method so you would not receive 429 (Too many Requests) Error frequently which might result in your token being revoked.
I see two problems:
the messages array is always empty; there is no code that adds items to the array, so the call to bot.deleteMessages will always get an empty array;
it does not appear that deleteMessages is an available method on Discord.Client;
Based on the documentation, I think what you want is sweepMessages. The description of that states:
Sweeps all text-based channels' messages and removes the ones older than the max message lifetime. If the message has been edited, the time of the edit is used rather than the time of the original message.
Try changing the code to instead call bot.sweepMessages(1);, which I think will tell the client to clear all messages older than one second.
Another way to do this, without sweepMessages is by using fetchMessages:
let user = message.mentions.users.first();
let amount = !!parseInt(message.content.split(' ')[1]) ? parseInt(message.content.split(' ')[1]) : parseInt(message.content.split(' ')[2])
var prefix = '!'
if (message.content.startsWith(prefix + 'clear') && !amount)
return message.reply('Must specify an amount to clear!');
if (message.content.startsWith(prefix + 'clear') && !amount && !user) return message.reply('Must specify a user and amount, or just an amount, of messages to clear!');
message.channel.fetchMessages({
limit: amount,
}).then((messages) => {
if (user) {
const filterBy = user ? user.id : bot.user.id;
messages = messages.filter(m => m.author.id === filterBy).array().slice(0, amount);
}
message.channel.bulkDelete(messages).catch(error => console.log(error.stack));
});
This will allow users to use the command !clear [#] to delete that number of messages when sent. If it is run as just !clear you can set how many get deleted, without a specified number.
discord.js Documentation - TextChannel#fetchMessages
You can swap
bot.deleteMessages()
to:
messages.forEach(x => x.delete())
Its not like that. you should fetch the messages first then use bulkDelete to delete them
, here is a simple example
// Normal Javascript
<Message>.channel.fetchMessages()
.then(messages => {
// Here you can use bulkDelete(101) to delete 100 messages instead of using fetchMessages and deleting only 50
<Message>.channel.bulkDelete(messages);
});
// ES6
let messages = await <Message>.channel.fetchMessages();
// Here you can use bulkDelete(101) to delete 100 messages instead of using fetchMessages and deleting only 50
await <Message>.channel.bulkDelete(messages);