Changing variables with commands discord.js - discord.js

How can I toggle between false/true a variable's value with a command
my code
var tagdetect = true;
const command = args.shift().toLowerCase();
if (command === 'tagdetect'){
if (args[1] === 'true'){
}
}
if (tagdetect){
if (message.mentions.users.has('id')){
client.TagİDAlgılayıcı.get('nick').execute(message, args);
}
i am using a command handler, i want to do something like {prefix}tagdetect true/false

Assuming tagdetect is the variable you want to switch, you can use two if statements to switch the boolean's state based on user input.
if (args[1] === 'true'){
tagdetect = true;
} else if (args[1] === 'false'){
tagdetect = false;
} else {
// User has given an invalid setting, let them know by sending an error message.
}
The comment is just there to let you know what you should add.

Related

command.execute is not a function

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.

How to change a global variable within an if else statement?

I have declared a variable beforehand called:
var mathsLesson = 'https://www.link1.com';
The value of this variable will change
if (message.content === '!change') { //this checks if the user messages !change
mathsLesson = 'https://www.link2.com'
message.channel.send(mathsLesson); //This outputs www.link2.com
}
However when I output mathsLesson outside the if statement, it shows 'www.link1.com' instead of 'www.link2.com' which I wanted. How do I make it output 'www.link2.com'? Thanks in advance!
You shouldnt be using a VAR or CONST if the value of the variable tends the change. Dont use VAR because its pretty old and has many shortcomings change the var to let if you wanat the variable globally you can always export a function to return its value andmany other options
let mathsLesson = 'https://www.link1.com';
if (message.content === '!change') { //this checks if the user messages !change
let mathsLesson = 'https://www.link2.com'
message.channel.send(mathsLesson); //This outputs www.link2.com
}
Others have suggested that you should change var to let, but it won't make any difference. I'm not sure where you're checking the value, but as you can see below, it works as expected, if the statement is true:
var mathsLesson = 'https://www.link1.com';
var message = {
content: '!change'
};
console.log('outside if, before updating:', mathsLesson);
if (message.content === '!change') {
mathsLesson = 'https://www.link2.com';
console.log('inside if:', mathsLesson);
}
console.log('outside if, after updated:', mathsLesson);
And won't work if the statement is false:
var mathsLesson = 'https://www.link1.com';
var message = {
content: 'no command for you today'
};
console.log('outside if, before updating:', mathsLesson);
if (message.content === '!change') {
mathsLesson = 'https://www.link2.com';
console.log('inside if:', mathsLesson);
}
console.log('outside if, after updated:', mathsLesson);
let mathsLesson = 'https://www.link1.com';
//The value of this variable will change
if (message.content === '!change') { //this checks if the user messages
mathsLesson = 'https://www.link2.com'
message.channel.send(mathsLesson); //This outputs www.link2.com
}
Reason
"var" can not be renew

(Discord.js) Bot does not respond

I've made a bot, and I have this purge function, it worked before i added the if that checked for the user's role. It gives me no errors and doesnt reply at all, no matter if i have the roles or not.
Code:
client.on("message", message => {
if (message.content.startsWith(prefix("purge"))) {
if (!message.guild.member.roles.cache.get('703727486009213048') || !message.guild.member.roles.cache.get('702847833241550859') || !message.guild.member.roles.cache.get('703727579328151562')) {
console.log('ssadd')
return message.reply('you can\'t use that command!')
};
const args = message.content.slice(prefix.length).split(" ");
const amount = args[1];
if (!amount) {
return message.reply("please specify the number of messages to purge!");
}
if (isNaN(amount * 1)) {
return message.reply(
"you'll need to specify a number, not whatever \"" +
`${amount}` +
'" is.'
);
}
message.delete();
message.channel.bulkDelete(amount * 1 + 1);
};
});
client.login(process.env.token);```
If it never replied to anything that either means the bot didn't log in or it never passed the first if condition. To check if the bot logged in, just do client.on("ready", () => console.log("ready"))
But I think it's more likely it just failed the first condition, is prefix a function?
prefix("purge") should be prefix + "purge".
There are some other flaws in your code too. Heres just the redo, if you need me to explain anything just lmk.
client.on("message", msg => {
if (msg.author.bot || !msg.content.startsWith(prefix)) return;
const args = msg.content.slice(1).split(" ");
//later on you should move to modules but for now this is fine ig
if (args[0] === "purge") {
//other flags here https://discord.js.org/#/docs/main/stable/class/Permissions?scrollTo=s-FLAGS
if (!msg.member.hasPermission("ADMINISTRATOR")) {
return msg.reply("you can't use that command!")
}
const amount = args[1] && parseInt(args[1]);
if (!amount) {
return msg.reply("please specify an integer of messages to purge!");
}
msg.delete();
msg.channel.bulkDelete(amount);
};
});
client.login(process.env.token);

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