command.execute is not a function - discord.js

i was trying to make an afk command with discord.js
i keep getting command.execute is not a function, and i have no idea how to fix it. please help!
client.on("message", async message => {
if (message.author.client) return;
if (message.channel.type === "dm") return;
let prefix = config.prefix;
let messageArray = message.content.split(" ");
let command = messageArray[0].toLowerCase();
let args = messageArray.slice(1);
if (message.content.includes(message.mentions.members.first())) {
let mentioned = client.afk.get(message.mentions.users.first().id);
if (mentioned) message.channel.send(`**${mentioned.usertag}** is currently afk. Reason: ${mentioned.reason}`);
}
let afkcheck = client.afk.get(message.author.id);
if (afkcheck) return [client.afk.delete(message.author.id), message.reply(`you have been removed from the afk list!`).then(msg => msg.delete(5000))];
if (!command.startsWith(prefix)) return;
let cmd = client.commands.get(command.slice(prefix.length));
if (cmd) cmd.run(client, message, args);
});```

In the scope of your function, command is the variable that is equal to messageArray[0].toLowerCase();, which is a string and does not have a execute method.
I guess you are trying to call the execute method of an object you called command, try to change the naming of your variables to avoid overriding the one you need.

Related

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...
});

Read message sent after command start

I am trying to make a sort of trivia bot but the problem is that I can't get it working. I have it so that when you type "-quiz" it sends a embed with a random question. Now you might say that I need to make a separate JSON file and put the questions and answers there, the problem is, is that I need variables in those strings and when I tried it, it wouldn't work because the order or something like that. I tried to fix that but it seems like a bad solution anyway. I set it up so it looks for a message after the initial commands, problem is that it reads it's own embed and I honestly don't know how to make it skip bot messages
client.on('message', message =>{
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if(command === 'quiz'){
var TypeID = (Math.floor(Math.random() * 11))
var toLog = (Math.floor(Math.random() * 2))
{ //there is something here that is used for the variables above but it is super long
}
var question = [`Question one`, `Question two`]
var answers = [[Answer1_1, Answer1_2],[Answer1_1]]
if(toLog === 0){
const quizEmbed1 = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle('quiz')
.setDescription(`${question[0]}`)
message.channel.send(quizEmbed1)
if(!message.content || message.author.bot) return;
if(message.content === [answers[0], answers[1], answers[2], answers[3], answers[4], answers[5]]){
message.channel.send('Good Job! That is right!')
}else{
message.channel.send('Oops! that is wrong.')
}
}else if(toLog == 1){
const quizEmbed2 = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle('quiz')
.setDescription(`${question[1]}`)
message.channel.send(quizEmbed2)
if(!message.content || message.author.bot) return;
if(message.content === [answers[6]]){
message.channel.send('Good Job! That is right!')
}else{
message.channel.send('Oops! That is wrong.')
}
}
}
});
if something it wrong it is most likely because I changed it to make it smaller, I am fairly newer to coding in JavaScript
Try using a MessageCollector. There is a good guide on the discord.js guide
Or using awaitMessages. Again there is a guide on the discord.js guide
Here is the example using awaitMessages
const filter = response => {
return item.answers.some(answer => answer.toLowerCase() === response.content.toLowerCase());
};
message.channel.send(item.question).then(() => {
message.channel.awaitMessages(filter, { max: 1, time: 30000, errors: ['time'] })
.then(collected => {
message.channel.send(`${collected.first().author} got the correct answer!`);
})
.catch(collected => {
message.channel.send('Looks like nobody got the answer this time.');
});
});

I need help I am trying to put a kick and ban command inside the code but I don't know where I need put it

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 message.channel.send('Cannot find this member');
member.kick().then((member) => {
message.channel.send("```" + member.displayName + " has been kicked ```");
});
}
}
This is the code of kick and ban.^^
https://sourceb.in/2e6ba31dc3 - this is my discord bot code where I want to put the ban and kick command code
You want to put the command inside of the client.on("message", (message) block.
I'll use it in your code as an example:
client.on('message', message =>{
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if(command === 'ping'){
client.commands.get('ping').execute(message, args);
}
// Kick start
if (command === 'kick') {
// Only check if the command caller has permission,
// AFTER the command is called, not before.
if (message.member.hasPermission(["KICK_MEMBERS", "BAN_MEMBERS"])) {
// Define which member needs to get kicked by grabbing the first mentioned guild member
let member = message.mentions.members.first();
// If the tagged member is not found in your guild,
// throw this message
if(!member) return message.channel.send('Cannot find this member');
// Proceed to kick the member
member.kick().then((member) => {
message.channel.send("```" + member.displayName + " has been kicked ```");
});
}
});
I hope this answers your question. Check the discordjs docs here if you haven't checked them already. They feature a nice tutorial on setting up your bot.

Arguments for Discord.js

how do I read args in discord.js? I am trying to create a support bot and I want to have an !help {topic} command. how do I do that?
my current code is very basic
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = ("!")
const token = ("removed")
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', msg => {
if (msg.content === 'ping') {
msg.reply('pong');
}
if (msg.content === 'help') {
msg.reply('type -new to create a support ticket');
}
});
client.login(token);
You can make use of a prefix and arguments like so...
const prefix = '!'; // just an example, change to whatever you want
client.on('message', message => {
if (!message.content.startsWith(prefix)) return;
const args = message.content.trim().split(/ +/g);
const cmd = args[0].slice(prefix.length).toLowerCase(); // case INsensitive, without prefix
if (cmd === 'ping') message.reply('pong');
if (cmd === 'help') {
if (!args[1]) return message.reply('Please specify a topic.');
if (args[2]) return message.reply('Too many arguments.');
// command code
}
});
you can use Switch statement instead of
if (command == 'help') {} else if (command == 'ping') {}
client.on ('message', async message => {
var prefix = "!";
var command = message.content.slice (prefix.length).split (" ")[0],
topic = message.content.split (" ")[1];
switch (command) {
case "help":
if (!topic) return message.channel.send ('no topic bro');
break;
case "ping":
message.channel.send ('pong!');
break;
}
});
let args = msg.content.split(' ');
let command = args.shift().toLowerCase();
this is the simplified answer from #slothiful.
usage
if(command == 'example'){
if(args[0] == '1'){
console.log('1');
} else {
console.log('2');
You can create a simple command/arguments thing (I don't know how to word it correctly)
client.on("message", message => {
let msgArray = message.content.split(" "); // Splits the message content with space as a delimiter
let prefix = "your prefix here";
let command = msgArray[0].replace(prefix, ""); // Gets the first element of msgArray and removes the prefix
let args = msgArray.slice(1); // Remove the first element of msgArray/command and this basically returns the arguments
// Now here is where you can create your commands
if(command === "help") {
if(!args[0]) return message.channel.send("Please specify a topic.");
if(args[1]) return message.channel.send("Too many arguments.");
// do your other help command stuff...
}
});
You can do
const args =
message.content.slice(prefix.length).trim().split(' ');
const cmd = args.shift().toLocaleLowerCase();
Word of advice, use a command handler and slash commands - this will solve both the need for a help command and reading arguments. Also helps with readability.
Anyways...
message.content.split(' '): This will split your string into an array of sub-strings, then return a new array.
.shift(): This will remove the first index in the array.
Combining this will get you your arguments: const args = message.content.split(' ').shift()

Is there a way to toggle an event with command?

Is there any way to make an event toggleable with a command?
I'm trying to make a welcome/farewell event but I don't want it to be active on default.
This is how my event looks right now:
client.on("guildMemberAdd", (member) => {
const guild = member.guild;
let memberTag = member.user.tag;
guild.channels.sort(function(chan1, chan2) {
if (chan1.type !== `text`) return 1;
if (!chan1.permissionsFor(guild.me).has(`SEND_MESSAGES`)) return -1;
return chan1.position < chan2.position ? -1 : 1;
}).first().send(memberTag + " just joined <:floshed:533687801741443082>");
});
As requested here is an example of my comment:
One way to do it is to store a variable for a guild in some database which has a value of either true or false. Then you'd grab that variable and check if said guild has the option turned on or off
client.on("guildMemberAdd", (member) => {
const guild = member.guild;
let memberTag = member.user.tag;
// Code here to get the guild from database, this is just a non-working example
let dbGuild = database.get('Guild', guild.id);
// Check if the guild has the welcome command disabled
if (dbGuild.enableWelcomeCmd === false) {
// Breaks the function, no further message will be send
return;
}
guild.channels.sort(function(chan1,chan2){
if(chan1.type!==`text`) return 1;
if(!chan1.permissionsFor(guild.me).has(`SEND_MESSAGES`)) return -1;
return chan1.position < chan2.position ? -1 : 1;
}).first().send(memberTag + " just joined <:floshed:533687801741443082>");
});
client.on("message", async message => {
// Check if the msg has been send by a bot
if(message.author.bot) return;
// Check if message has correct prefix
if(message.content.indexOf(config.prefix) !== 0) return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
// Code for actually changing the guild variable
if (command === 'toggleWelcome') {
// Code here to get the guild from database, this is just a non-working example
let dbGuild = database.get('Guild', message.guild.id);
dbGuild.enableWelcomeCmd = !dbGuild.enableWelcomeCmd;
// Save the new variable for the guild (also a non-working example)
database.save('Guild', message.guild.id, dbGuild);
}
});
You'll have to look into databases and such yourself, there is a wide variety of (free) options which all have a different syntax. That part is something for you to figure out but I hope this can give you a general idea.

Resources