Splitting arguments - discord.js

I am trying to split the member mention (message) and the reason (args) but it fails to do so: I have it getting both the mention and the reason but it mentions the member and puts the reason under the reason field on the embed.
const Discord = require("discord.js");
module.exports = {
name: "kick",
guildOnly: true,
nsfw: false,
description: "Kick a member from the server with or without a reason.",
execute(message, args) {
if (!message.mentions.users.size) {
return message.channel.send("You need to mention a member to kick.");
} else {
const member = message.mentions.members.first();
const reason = args;
const kickEmbed = new Discord.RichEmbed()
.setColor("#ff00ea")
.setAuthor("User Kicked")
.setDescription(member.displayName + " was removed from the server.")
.addField("Assigned by", message.author.username, true)
.addField("Reason", reason, true);
member.kick(reason);
message.channel.send(kickEmbed);
message.react("👌")
}
}
};

args is an array, the first index contains the user and the second index contains the reason in your case.
So this should work, it depends on your input.
reason = args[1]

Related

MessageEmbed description must be a string

This is my code and im getting this error: RangeError [EMBED_DESCRIPTION]: MessageEmbed description must be a string can can someone help me please? I updated from v12 to v13 and now this error happens, haven't found a solution yet.
const { MessageEmbed } = require('discord.js');
const Command = require('../../Structures/Command');
module.exports = class extends Command {
constructor(...args) {
super(...args, {
aliases: ['halp'],
description: 'Displays all the commands in the bot',
category: 'Utilities',
usage: '[command]'
});
}
async run(message, [command]) {
const embed = new MessageEmbed()
.setColor('BLUE')
.setAuthor(`${message.guild.name} Help Menu`, message.guild.iconURL({ dynamic: true }))
.setThumbnail(this.client.user.displayAvatarURL())
.setFooter(`Requested by ${message.author.username}`, message.author.displayAvatarURL({ dynamic: true }))
.setTimestamp();
if (command) {
const cmd = this.client.commands.get(command) || this.client.commands.get(this.client.aliases.get(command));
if (!cmd) return message.channel.send(`Invalid Command named. \`${command}\``);
embed.setAuthor(`${this.client.utils.capitalise(cmd.name)} Command Help`, this.client.user.displayAvatarURL());
embed.setDescription([
`**❯ Aliases:** ${cmd.aliases.length ? cmd.aliases.map(alias => `\`${alias}\``).join(' ') : 'No Aliases'}`,
`**❯ Description:** ${cmd.description}`,
`**❯ Category:** ${cmd.category}`,
`**❯ Usage:** ${cmd.usage}`
]);
return message.channel.send(embed);
} else {
embed.setDescription([
`These are the available commands for ${message.guild.name}`,
`The bot's prefix is: ${this.client.prefix}`,
`Command Parameters: \`<>\` is strict & \`[]\` is optional`
]);
let categories;
if (!this.client.owners.includes(message.author.id)) {
categories = this.client.utils.removeDuplicates(this.client.commands.filter(cmd => cmd.category !== 'Owner').map(cmd => cmd.category));
} else {
categories = this.client.utils.removeDuplicates(this.client.commands.map(cmd => cmd.category));
}
for (const category of categories) {
embed.addField(`**${this.client.utils.capitalise(category)}**`, this.client.commands.filter(cmd =>
cmd.category === category).map(cmd => `\`${cmd.name}\``).join(' '));
}
return message.channel.send(embed);
}
}
};
Since you updated discord.js to v13, <MessageEmbed>.setDescription no longer accepts arrays, you need to put a string or use <Array>.join like this:
embed.setDescription([
`These are the available commands for ${message.guild.name}`,
`The bot's prefix is: ${this.client.prefix}`,
`Command Parameters: \`<>\` is strict & \`[]\` is optional`
].join('\n'));
Discord.js is expecting a string but you give it an array.
I would remove the array brackets [ ] and the commas from the setDescriptions

How to ban user on pinging someone?

I'm trying to make a discord bot on, when pinging the owner, auto bans the author that pinged the player. The issue is, it bans the player for saying anything, how would I make it that it'd only ban if they pinged the owner?
Here's the code.
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = '<#329005206526361610>'
client.once('ready', () => {
console.log("Wary's Defender Bot is up");
});
function getUserFromMention(mention) {
if (!mention) return;
if (mention.startsWith('!')) {
mention = mention.slice(1);
}
if (mention.startsWith('<#329005206526361610') && mention.endsWith('>')) return {
// mention = mention.slice(2, -1),
return: client.users.cache.get(mention)
}
}
client.on('message', _message => {
// if(!_message.content.users.has('#warycoolio')) return;
const user = getUserFromMention(_message.content);
if(user) return;
console.log('found target')
var member = _message.author
var rMember = _message.guild.member(_message.author)
// ban7, 'lol.'
rMember.ban({ days: 7, reason: 'They deserved it'}); {
// Successmessage
console.log('target dead.')
}
});
You can do this by checking _message.mentions.users with .has() and passing in the guild owner's id.
Use .has() instead of checking message content, this will automatically check the Message#mentions collection.
Dynamically get the guild owner's id using Guild#ownerID.
client.on('message', _message => {
if (_message.mentions.users.has(_message.guild.ownerID)) {
_message.author.ban({ days: 7, reason: 'They deserved it'});
}
});
You could just do a quick check to see if the mentions include a mention to the owner of the server, and then ban the user.
client.on("message", _message => {
if (_message.mentions.users.first().id === "owner id") {
message.author.ban()
}
})

How do I select multiple args in a command and assign it to a variable? Discord.js

I want to do so that when I use !pm (user) (some message), my bot will send a private message to the user, although I have no idea how to select everything after the (user) and assign it to a variable, to send it to the user.
My current code looks like this:
module.exports = {
name: 'pm',
description: 'Sends a personal message!',
execute(message, args, client) {
const pmMessage = args[1];
client.users.cache.get('464839066781745167').send(pmMessage);
}
}
Since you know the array index of the pmMessage, with the help of that index, you can use the slice method which returns the array from specified stating to end index.
Eg:
let pmMessage = args.slice(2); //returns array.
Note: If the end index is not specified, then it considers till the last index of the array.
Now, using the join method, you can join all the indexes with whatever specified character. Eg:
let MessageContent = pmMessage.join(' '); //joined by space.
let args = ["UserID","This","represents","the","message","content","to","be","sent"];
console.log(args.slice(1));
console.log(args.slice(1).join(' '));
Try this, I think this should work:
let pm_args = args.slice(1).join(' ')
if(args[0]){
let user = getUserFromMention(args[0])
if(!user){
return message.reply('please mention a user.');
}
return client.users.cache.get(user.id).send(pm_args);
}
return message.reply('please mention a user.');
(This is what I used for mention thingie:)
function getUserFromMention(mention){
if(!mention) return;
if(mention.startsWith('<#') && mention.endsWith('>')){
mention = mention.slice(2, -1);
if(mention.startsWith('!')){
mention = mention.slice(1);
}
return bot.users.cache.get(mention);
}
};
client.on("message", message => {
if(!message.content.startsWith(config.prefix)) return;
const withoutPrefix = message.content.slice(config.prefix.length);
const split = withoutPrefix.split(/ +/);
const command = split[0];
const args = split.slice(1);
// Code...
});

discord.js v12 | TypeError: Cannot read property 'send' of undefined

Here is my entire code for my ban command. Good to note I am using Discord.JS Commando as well I have been struggling with this error but literally cannot figure out why I am getting it everything looks fine unless I have used a deprecated function. Would really appreciate someone to help me on this one I've been getting along quite well creating a rich featured bot before this happened.
const { Command } = require('discord.js-commando');
const { MessageEmbed } = require('discord.js');
const db = require('quick.db');
module.exports = class banCommand extends Command {
constructor(client) {
super(client, {
name: 'ban',
memberName: "ban",
group: 'moderation',
guildOnly: true,
userPermissions: ['BAN_MEMBERS'],
description: 'Bans the mentioned user from the server with additional modlog info.'
});
}
async run(message, args) {
if (!args[0]) return message.channel.send('**Please Provide A User To Ban!**')
let banMember = message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.guild.members.cache.find(r => r.user.username.toLowerCase() === args[0].toLocaleLowerCase()) || message.guild.members.cache.find(ro => ro.displayName.toLowerCase() === args[0].toLocaleLowerCase());
if (!banMember) return message.channel.send('**User Is Not In The Guild**');
if (banMember === message.member) return message.channel.send('**You Cannot Ban Yourself**')
var reason = args.slice(1).join(' ');
if (!banMember.bannable) return message.channel.send('**Cant Kick That User**')
banMember.send(`**Hello, You Have Been Banned From ${message.guild.name} for - ${reason || 'No Reason'}**`).then(() =>
message.guild.members.ban(banMember, { days: 7, reason: reason })).catch(() => null)
message.guild.members.ban(banMember, { days: 7, reason: reason })
if (reason) {
var sembed = new MessageEmbed()
.setColor('GREEN')
.setAuthor(message.guild.name, message.guild.iconURL())
.setDescription(`**${banMember.user.username}** has been banned for ${reason}`)
message.channel.send(sembed)
} else {
var sembed2 = new MessageEmbed()
.setColor('GREEN')
.setAuthor(message.guild.name, message.guild.iconURL())
.setDescription(`**${banMember.user.username}** has been banned`)
message.channel.send(sembed2)
}
let channel = db.fetch(`modlog_${message.guild.id}`)
if (channel == null) return;
if (!channel) return;
const embed = new MessageEmbed()
.setAuthor(`${message.guild.name} Modlogs`, message.guild.iconURL())
.setColor('#ff0000')
.setThumbnail(banMember.user.displayAvatarURL({ dynamic: true }))
.setFooter(message.guild.name, message.guild.iconURL())
.addField('**Moderation**', 'ban')
.addField('**Banned**', banMember.user.username)
.addField('**ID**', `${banMember.id}`)
.addField('**Banned By**', message.author.username)
.addField('**Reason**', `${reason || '**No Reason**'}`)
.addField('**Date**', message.createdAt.toLocaleString())
.setTimestamp();
var sChannel = message.guild.channels.cache.get(channel)
if (!sChannel) return;
sChannel.send(embed)
}
};
The reason you are getting the TypeError: args.slice(...).join is not a function error is because the slice method creates a new array of the sliced data, and so can not join(' ') since there is no space to join with. (i.e. it is not a string)
What you are looking for is args.slice(1).toString().replace(",", " ")
This removes the 2nd part of the args array object, then converts it to a string, then removes the commas in the string and replaces them with spaces.

Call Exports.run async from a member phrase

Please help me understand how can i call that ping.js from user input, like if a user type ping it will Trigger cuz of the aliases but if a user types a full phrase it won't trigger.
Or in a non headic question how can i implent this to work -> if (message.content.includes('ping'))
Sorry in advance and thanks a lot
ping.js
const Discord = require('discord.js')
const colors = require('../lib/colors.json')
exports.run = async (client, message, args, level) => {
try {
const pingEmbed = new Discord.RichEmbed()
.setColor(colors.default)
.setFooter('ping)
.addField(`${message.author.id}`, 'hey')
const msg = await message.channel.send(pingEmbed)
const embed = new Discord.RichEmbed()
.setColor(colors.default)
.addField('...',
`${msg.createdTimestamp - message.createdTimestamp}ms`)
msg.edit(embed)
} catch (err) {
message.channel.send('There was an error!\n' + err).catch()
}
}
exports.conf = {
enabled: true,
aliases: ['ping'],
guildOnly: false,
permLevel: 'User'
}
exports.help = {
name: 'ping,
category: 'tools,
description: 'ping pong',
usage: 'ping'
}
If you want to check whether a message contains any of the aliases you can just use Array.some() like this:
let aliases = ['your', 'command', 'aliases']
client.on('message', message => {
if (aliases.some(trigger => message.content.includes(trigger))) {
// The message includes at least one of your keywords
}
})
In this example is just declared aliases, but you can use the array from your command and integrate this method in your normal command handler.

Resources