Args is not defined - javascript

I used a role color changer peice of code, and it was pretty cool, until I uploaded it to glitch.com, now all I get is the "args is not defined" error again, here is a small chunk of the code I was using
const Discord = require('discord.js');
const client = new Discord.Client();
const TOKEN = process.env.TOKEN
require('events').EventEmitter.defaultMaxListeners = 75;
var red = ['#ff0000']
client.on('message', message => {
if (message.content.startsWith('grimm!change red')) {
message.channel.send('color for changed to Red')
const colorRole = message.mentions.roles.first() || message.guild.roles.cache.find(R => R.name === args.join(" "));
colorRole.edit({
color: red[0]
})
}})
client.login(TOKEN)
could anyone tell me how I could possibly fix this? I have been researching everywhere but I have no clue on how to fix this. Thanks!

Try this
client.on('message', message => {
...
const args = message.content.slice(prefix.length).trim().split(' ');
...
});
Command with user input

Related

Discord.js Bots // Say Command

I've coded a "say command" that's supposed to execute a message every time I type in -say.
It's working fine, I just want the prefix to be set to "?" instead of "-" only for that one command, the other ones are supposed to be set to the main one ("-"). On top of that I want it to delete the command after typing it in, so all that remains is the message [(e.g ?say hello --> (delete "?say hello" --> send message "hello" to text channel)]. I also want to specify the text channel in my command, instead of just setting it to send the messages only to one specific channel [e.g -say (message) (text channel)] It would also be pretty cool if it said something like "Done." and deleting that confirmation after ~5 sec.
So here is the code:
client.on('message', function(message) {
if(message.author.bot) return;
else if(isValidCommand(message, "say")) {
let sendMessage = message.content.substring(4);
let sendChannel = client.channels.cache.get('767374258492932106');
sendChannel.send(sendMessage)
}
});
In the following I will show you my not working code, trying to set the prefix to "?" but it didnt execute, only saying "declaration or statement expecting and missing or wrong punctuation..
client.on('message', function(message) {
if (['?'].every((prefix) => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
else if(isValidCommand(message, "say")) {
let sendMessage = message.content.substring(4);
let sendChannel = client.channels.cache.get('767374258492932106');
sendChannel.send(sendMessage)
}
});
It'd be really grateful if someone helped me with this. Thank you!
I am not sure what you trying to achieve with
if (['?'].every((prefix) => {
but this is what I would do
using args, substring and switch to identify the command.
The usage of the
client.on('message', async message =>{
if (message.author.bot) return;
if (message.content.startsWith(prefix)) {
let args = message.content.substring(prefix.length).split(" ");
switch (args[0].toLowerCase()){
case 'say': {
let sendMessage = message.content.substring(prefix.length +args[0].length+ args[1].length + 2); //2 is accounting for the 2 space between prefix and # and prefix and the main content
setTimeout(()=>{message.delete()},5000)
let sendChannel = client.channels.cache.get(args[1]);
sendChannel.send(sendMessage)
break;
}
}
}
if (message.content.startsWith(otherPrefix)) {
let args = message.content.substring(otherPrefix.length).split(" ");
switch (args[0].toLowerCase()){
case 'say': {
// Do something else
break;
}
}
}
});
Edit: The usage of the commend would be like
!say #generalTextChannel abc
where #generalTextChannel is tagging the channel
or
!say 767374258492932106 abc
where 767374258492932106 is the channel Id
I don't quite understand what are you trying to do with the prefixes.
When trying to detect a prefix in front of a command, you can just use the other line you used without ['?'].every
Use just this: if (!message.content.startsWith(prefix) || message.author.bot) return;.
Then check for each command individually under this. if (command == 'say')
A very simple way of getting arguments:
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
The say command would look something like this:
if(command == 'say'){
//then you could find the channel
//https://discord.js.org/#/docs/main/stable/class/ChannelManager?scrollTo=fetch
client.channels.fetch('222109930545610754')
.then(channel => {
channel.send(args.join(" ")) //sending the arguments joined with a space in the fetched channel
.then(msg => {setTimeout(function(){msg.delete()},5000)}) //delete after 5 seconds, please check if delete is a function (I didn't)
})
.catch(console.error);
}
['?'].every got me thinking you could use if(!['?', '-'].some(prefix => content.startsWith(prefix))) return to use more prefixes instead of the if statement.
I don't know what your saying. But here is how I would do it.
const Discord = require("discord.js");
const client = new Discord.Client();
const prefix = '!';
client.on('message', message => {
const args = message.content.slice(prefix.length).trim().split(/+ /);
const command = args.shift().toLowerCase();
if (command === 'say') {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const user = message.author;
if (!args[0]) {
user.send("Provide a word to say in the say command\nExample: !say Hello")
}
const say = args.join(" ");
message.channel.send(say)
message.delete()
}
})
client.login("PUT YOUR TOKEN HERE")
For the other prefix, you could do this:
client.on('message', async message => {
if(message.content === '?say') {
//the code (I don't know what is the code, I'm giving the way for the prefix)
} else {}
if(!message.content.startsWith(prefix) || message.author.bot) return
const args = message.content.slice(prefix.length).trim().split(/+ /);
const command = args.shift().toLowerCase();
//bla bla bla (the rest of the commands, etc.)
}

Discord bot not responding to command javascript

I have been trying to make a Discord bot that responds to the user when they ask for help. Sadly I can't seem to get the bot to work. I am using Discord.JS on Node.JS. Any help would be welcome.
const Discord = require('discord.js');
const bot = new Discord.Client();
const token = '[token removed]';
const PREFIX = '!';
bot.on('ready', () => {
console.log('K08 Help Bot is online!');
})
bot.on('message', message=>{
let args = message.content.substring(PREFIX.lenght).split(" ");
switch(args[0]){
case 'help':
message.reply('HELLO');
break;
}
})
bot.login(token);
This might be the issue:
let args = message.content.substring(PREFIX.lenght).split(" "); - length is mistyped as lenght
On a side note: I've submitted an edit to hide your token in this question. For security, you should never share your token; it would allow someone to take over your bot!

Discord.js Delete message through an existing function

The Issue
When executing my code i am really getting no errors at the moment but would like to add to a function but have tried almost every way of handling it. At this point the variable has been removed due to confusion and frustration.
What needs to happen is, the User that initiates the command, their message gets deleted after a short delay. I have tried message.delete(1000) and other Variants for v12 but no luck. Not able to pass the "message" variable from my active function?
Maybe i am completely off and just making it hard on myself, i don't know. Honestly embarrassing that i couldn't figure out a message.delete. Please help. Apologies for the ignorance.
const Discord = require('discord.js');
const bot = new Discord.Client();
const token = "";
const PREFIX = "!";
const fs = require('fs');
bot.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
for(const file of commandFiles){
const command = require(`./commands/${file}`);
bot.commands.set(command.name, command);
}
bot.on('ready', () => {
console.log("The bot is active and ready to go!");
});
bot.on('message', function(message) {
if(message.content[0] === PREFIX) {
let command = message.content.substring(message.content.indexOf(" ") + 1, message.content.length);
}
});
bot.on('message', message => {
let args = message.content.substring(PREFIX.length).split(" ");
switch (args[0]) {
case "crash":
bot.commands.get('crash').execute(message, args);
break;
case "hello":
bot.commands.get('hello').execute(message, args);
break;
case "purge":
bot.commands.get('purge').execute(message, args);
break;
}
});
bot.login(token);
Here is an example of "crash.js" for reference. Don't know if i need to execute delete from there?
module.exports = {
name: 'crash',
description: "Crash",
execute(message, args){
message.author.send("Here is the link you requested");
}
}
You can execute delete from within your module. The message is passed as a full object so you just call the delete method on it. However, the Options are an Object which means it needs to be defined as such. For clarity, I'm going to use another variable but this can be done inline.
let options = {
timeout: 1000,
reason: 'Because I said so.'
}
message.delete(options);
or inline...
message.delete({timeout: 1000});

JavaScript list all members in discord server

So im trying to make a command that lists all the members in a discord server but it doesnt seem to be working. I did research, tried different methods and none seem to work. This is the code im working with right now.
const bot = new Discord.Client();
bot.on("message", async msg => {
if (msg.author.id !== config.id) return;
let content = msg.content;
let text = content.toLowerCase();
let author = msg.author;
let member = msg.member;
let args = content.split(" ").slice(1);
let argsLower = text.split(" ");
let command = argsLower[0].replace(prefix, "");
if (!msg.content.startsWith(config.prefix)) return;
if (command === "listmembers"){
msg.delete();
msg.channel.guild.fetchMembers().then(guild =>{
console.log("test");
guild.members.forEach(member => console.log(member.user.username));
} );
}
i tried console logging "test" in the function but that doesnt show up in console so i cant seem to get into the function.
If you want to console.log() all of the members, it's just:
message.guild.members.forEach(member => console.log(member.user.username));
but if you're trying to list them out into chat you need to:
var list = [];
message.guild.members.forEach(member => list.push(member.user.username));
message.reply(`Total members: ${message.guild.memberCount}`);
const embed4 = new Discord.RichEmbed()
.setColor(0x684dad)
.setTitle('Member List:')
.setDescription(list);
message.channel.send(embed4);
You can customize it as you wish but that's just an example.

Why doesn't my discord bot know its #Mention?

I'm working on a discord bot (This is just the AI module, there's another one connecting to the same bot for commands and stuff), but it doesnt know its own #Mention.
const token = process.env.PixelBot_token;
const keep_alive = require('./keep_alive.js');
const sendReply = require('./sendReply.js');
const Discord = require('discord.js');
const client = new Discord.Client();
// Set the client user's presence
client.on('ready', () => {
var prefix = client.user.tag;
console.log('PixelBot AI Loaded!');
console.log(prefix);
});
client.on('message', message => {
if (message.author.bot) return;
var prefix = + client.user.tag;
console.log(prefix);
if (message.content.substring(0, prefix.length) === prefix) {
//useful variables
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if (command === "help") {
console.info("Help Message Sent!\n");
};
};
});
client.login(token);
The above code prints out:
PixelBot AI Loaded!
PixelBot#9188
But does nothing when I send #PixelBot help. However, if I change the prefix to a string, eg: "pb", it works. It obviously knows it in "client.on('ready')", as it gets printed out. Any ideas?
EDIT: Here is the code with #Discord Expert's suggestion in:
const token = process.env.PixelBot_token;
const keep_alive = require('./keep_alive.js');
const sendReply = require('./sendReply.js');
const Discord = require('discord.js');
const client = new Discord.Client();
// Set the client user's presence
client.on('ready', () => {
console.log('PixelBot AI Loaded!');
});
client.on('message', message => {
if (message.author.bot) return;
if (message.mentions.users.first() === client.user) {
//useful variables
const command = message.content.slice(message.mentions.users.first().length).trim().split(/ +/g);
const identifier = command.shift().toLowerCase();
console.log('identifier = "' + identifier + '"');
console.log('command = "' + command +'"');
console.log('message content = "' + message.content + '"');
if (command === "help") {
console.info("Help Message Sent!\n");
};
};
});
client.login(token);
This prints out:
PixelBot AI Loaded!
identifier = "<#569971848322744320>"
command = "help"
message content = "<#569971848322744320> help"
So it knows that command === "help", so why does it not execute the if statement?
when people ping you on discord, an ID follows as with everything on discord,
So in reality is:
<#USERID>
I recommend exploring message.mentions.users.first()
and comparing it to your client.user
Alternatively message.mentions.users.first().id
and client.user.id
Best regards
Discord Expert
Ok, I'm answering my own post here because I found the problem. For some reason, using === instead of == stops it from working. I don't know why.

Categories

Resources