Discord.js variable does not exist when defined? - discord

I'm trying to code a bot command using discord.js and Minecraft-server-util but my code is not using the const I defined and is saying it does not exist. If you spot any other problems you can correct me on them.
client.on('message', message => {
if (message.content === `${prefix}javaserverstatus`) {
const args = message.content.slice(prefix.length).trim().split(' '); // this is where args is defined.
if (!args.length) {
return message.channel.send(`You didn't provide a server, ${message.author}!`); // checks if args exist
}
if (args.length > 1) {
return message.channel.send(`Wrong input! EG. play.hypixel.net, ${message.author}`); // checks if there are only 1 arguments
}
}
const util = require('minecraft-server-util');
var serverinfo = null
util.status(args) // This code is giving an error saying args does not exist.
.then((response) => {
console.log(response);
serverinfo = response;
const embed = new Discord.MessageEmbed()
.setTitle('play.hypixel.net Server Status')
.setColor(0xff0000)
.setDescription('IP: ' + response.host + '\n' + 'Port: ' + response.port + '\n' + 'Version: ' + response.version + '\n' + 'Online Players: ' + response.onlinePlayers.toString() + '\n' + 'Max Players: ' + response.maxPlayers.toString() + '\n');
message.channel.send(embed);
})
.catch((error) => {
console.error(error);
});
});

The error is due to the scope that you've defined args in.
args is defined in your first if statement when it should be defined a line above.
const args = message.content.slice(prefix.length).trim().split(' ');
if (message.content === `${prefix}javaserverstatus`) {
// this is where args is defined.
if (!args.length) {
return message.channel.send(`You didn't provide a server, ${message.author}!`); // checks if args exist
}
if (args.length > 1) {
return message.channel.send(`Wrong input! EG. play.hypixel.net, ${message.author}`); // checks if there are only 1 arguments
}
}

You've defined args in a if statement. You need to put it out of there.
client.on('message', (message) => {
const args = message.content.slice(prefix.length).trim().split(' ') // this is where args is defined.
if (message.content === `${prefix}javaserverstatus`) {
if (!args.length) {
return message.channel.send(`You didn't provide a server, ${message.author}!`) // checks if args exist
}
if (args.length > 1) {
return message.channel.send(`Wrong input! EG. play.hypixel.net, ${message.author}`) // checks if there are only 1 arguments
}
}
const util = require('minecraft-server-util')
var serverinfo = null
util
.status(args) // This code is giving an error saying args does not exist.
.then((response) => {
console.log(response)
serverinfo = response
const embed = new Discord.MessageEmbed()
.setTitle('play.hypixel.net Server Status')
.setColor(0xff0000)
.setDescription('IP: ' + response.host + '\n' + 'Port: ' + response.port + '\n' + 'Version: ' + response.version + '\n' + 'Online Players: ' + response.onlinePlayers.toString() + '\n' + 'Max Players: ' + response.maxPlayers.toString() + '\n')
message.channel.send(embed)
})
.catch((error) => {
console.error(error)
})
})
If this isn't working, pls send me the command you sent in the discord chat.

Related

I was making a Discord bot...... and i keep geting this error

I was making a discord bot with a 'ban' command (discord.js) and I keep getting this error.... [parsing error unexpected token case]
the script:
case 'ban': {
if (!isMod)
return;
let userID = args.includes('<#!') ? args.replace('<#!', '').replace('>', '')
: args.includes('<#') ? args.replace('<#', '').replace('<', '') : '';
if (userID == '') {
message.reply('Invalid user ID or mention.');
return;
}
message.guild.fetchMember(userID).then(member => {
member.kick("Banned by " + message.author.tag).then(m => {
message.channel.send('🔨 Banned <#' + userID + '>.');
}).catch(() => {
console.error;
message.reply('Could not ban the specified member.');
});
};
break;
});
User.ban({reason: banReason})
You missed a bracket.
case 'ban': {
if (!isMod)
return;
let userID = args.includes('<#!') ? args.replace('<#!', '').replace('>', '')
: args.includes('<#') ? args.replace('<#', '').replace('<', '') : '';
if (userID == '') {
message.reply('Invalid user ID or mention.');
return;
}
message.guild.fetchMember(userID).then(member => {
member.kick("Banned by " + message.author.tag).then(m => {
message.channel.send('🔨 Banned <#' + userID + '>.');
}).catch(() => {
console.error;
message.reply('Could not ban the specified member.');
});
});
break;
}
Check before break statement - that was the problem.

How to delete a user's sent command after bot's reply in discord.io

First of all, normal discord.js stuff seems to not work in my code.
So I want to make it so that the user calls the command, the bot replies and deletes the user's message ,that called the command, as well.
bot.on('message', function (user, userID, channelID, message, evt) {
if (message.substring(0, 1) == '?') {
var args = message.substring(1).split(' ');
var cmd = args[0];
args = args.splice(1);
switch(cmd) {
case 'gw':
var gw = args.slice(1).join(' ');
var thumb = args[0];
let date = new Date();
let smalldate = date.getDate() + '/' + (date.getMonth() +1) + ' | ' + date.getHours() + ':' + date.getMinutes();
bot.sendMessage({
to: channelID,
message: `\n <#&${'806183931065401405'}>` + `\n` + `\n 🎉 __**Giveaway**__ 🎉`,
embed: {
color: 16580705,
footer: {
text: 'Started On : ' + smalldate,
},
thumbnail:{
url : thumb
},
title: gw,
description: 'Hosted By: ' + user,
}
});
bot.deleteMessage(message);
}
}
});
Thank you from the core of my heart for any replies.
As I discussed in my comment, here are the changes:
bot.on('message', message => {// arrow function
if (message.content.startsWith(PREFIX) {
body = message.content.slice(PREFIX.length)
var args = message.content.substring(1).split(' ');
var cmd = args[0];
args = args.splice(1);
switch(cmd) {
case 'gw':
var gw = args.slice(1).join(' ');
var thumb = args[0];
let date = new Date();
let smalldate = date.getDate() + '/' + (date.getMonth() +1) + ' | ' + date.getHours() + ':' + date.getMinutes();
message.channel.send({
to: channelID,
message: `\n <#&${'806183931065401405'}>` + `\n` + `\n 🎉 __**Giveaway**__ 🎉`,
embed: {
color: 16580705,
footer: {
text: 'Started On : ' + smalldate,
},
thumbnail:{
url : thumb
},
title: gw,
description: 'Hosted By: ' + user,
}
});
message.delete();
}
}
});
I add some code formating for you.
bot.on('message') return only message object, you can't add some other variables.
For delete initial message, you can use message.delete()
Use Discord.js documentation :) to learn methods of libery
const Discord = require('discord.js');
const bot = new Discord.Client();
const prefix = '?';
bot.on('ready', () => {
console.log('\x1b[32m%s\x1b[0m', `${bot.user.username} is online on ${bot.guilds.cache.size} servers!`);
});
bot.on('message', async (message) => {
if (!message.content.startsWith(prefix)) return;
let args = message.content.substring(prefix.length).split(' ');
let cmd = args.shift();
switch (cmd) {
case 'gw':
let gw = args.join(' ');
let thumb = args[0];
let date = new Date();
let smallDate = date.getDate() + '/' + (date.getMonth() + 1) + ' | ' + date.getHours() + ':' + date.getMinutes();
let embed = new Discord.MessageEmbed();
embed.setDescription(`Hosted By: ${message.author}`);
embed.setColor(16580705);
embed.setFooter(`Started On : ${smallDate}`); //Better use embed.setTimestamp(), because its will convert time yo user local timezone
embed.setTitle(gw);
await message.channel.send(`\n <#&${'806183931065401405'}>` + `\n` + `\n 🎉 __**Giveaway**__ 🎉`, embed)
await message.delete()
}
});

Why does my code run when it is not supposed to?

if (command == "lookup") {
var user = message.content.split(" ").slice(1).join(" ")
Blocked.forEach(bl => {
if (message.author.id == bl) {
message.reply("You have been blocked from using commands.")
IsBlocked = 1
}
if (IsBlocked == 0) {
rblxAPI.getUserIdFromUsername(user).then(found => {
found.getStatus().then(stat => {
found.getFriendsCount().then(count => {
let rblxLookup = new Discord.MessageEmbed()
.setTitle("Lookup of: " + found.name)
.setDescription("User ID: " + found.id + " \n User Description: " + stat + " \n User Friends Count: " + count)
message.channel.send(rblxLookup)
})
})
}).catch(console.error());
}
})
}
So this is my code and when the user is blocked it still continues with the script. I get no errors. Why does this happen?
I think you need to return where you check if they are blocked. Here is my guess on fixing it:
if (command == "lookup") {
var user = message.content.split(" ").slice(1).join(" ")
Blocked.forEach(bl => {
if (message.author.id == bl) {
message.reply("You have been blocked from using commands.")
IsBlocked = 1
// I think you could just return here to end it if the user is blocked
return;
}
if (IsBlocked == 0) {
rblxAPI.getUserIdFromUsername(user).then(found => {
found.getStatus().then(stat => {
found.getFriendsCount().then(count => {
let rblxLookup = new Discord.MessageEmbed()
.setTitle("Lookup of: " + found.name)
.setDescription("User ID: " + found.id + " \n User Description: " + stat + " \n User Friends Count: " + count)
message.channel.send(rblxLookup)
})
})
}).catch(console.error());
}
})
}
But i might just be stupid right now.

DiscordJS role set returns API Error: Missing Permissions

I try to set the member roles, but it doesn't set the permissions.
My index.js file:
var u, s, m;
await bot.users.fetch(message.author.id)
.then(user => { u = user; });
await bot.guilds.fetch('419248578121433100')
.then(guild => { s = guild; });
await s.members.fetch(u)
.then(member => { m = member; });
axios.get('/process')
.then(function (response)
{
var dptos = response.data.dptos;
var attrs = response.data.userAttrs;
var roles = response.data.roles;
if(dptos.length > 0) m.setNickname(dptos[0].position + ' | ' + attrs.name + ' ' + attrs.surname);
else m.setNickname(attrs.name + ' ' + attrs.surname + ' | ' + '123456');
m.roles.set(roles)
.then(function(member)
{
let fd = fs.openSync('log.txt', 'w');
fs.writeSync(fd, JSON.stringify(member.roles.cache));
fs.closeSync(fd);
})
.catch(function(error)
{
let fd = fs.openSync('error.txt', 'w');
fs.writeSync(fd, error);
fs.closeSync(fd);
});
return message.reply('Congrats!');
})
.catch(function (error)
{
return message.reply('error!');
});
}
The axios request works as expected and the data is obtained correctly.
Screenshots:
Bot position
Bot general permissions
UPDATE 1: Nickname permissions
What could be the issue?

How to retrieve all members of a guild by user object?

I have the following code setup, but it often doesn't find members on my server.
How can I solve this problem?
BOT.on('message', function(message) {
if (!message.content.startsWith(prefix)) return;
const args = message.content.slice(prefix.length).split(' ');
const command = args.shift().toLowerCase();
const chan = message.channel;
if (command == "grabreacts" && chan.name == "the-purge") {
var role = message.guild.roles.find(role => role.name === "2019 Purge Survivor");
if (!role) return message.channel.send(`**${message.author.username}**, role not found`);
//console.log(role);
chan.fetchMessage(args)
.then(function(value) {
const react = value.reactions.filter(r => r.emoji == "👍").first();
var reacts = react.count;
react.fetchUsers()
.then(function(users) {
var fetchedMemebers = users.size;
users.map(async user => {
console.log(user.tag);
message.guild.fetchMember(user, false)
.then((memeber) => {
member.addRole(role)
.then((mem) => {
react.remove(user)
.catch((err) => console.log("Cannot remove user: " + user.tag + ". ex: " + ex + "!"));
})
.catch(ex => {
console.log(ex);
});
})
.catch((err) => {
console.log("Cannot find member object for: " + user.tag + "!");
});
});
var assignedusers = role.members.size;
message.reply("Reacts found: " + reacts + "; users fetched: " + fetchedMemebers + "; roles assigned: " + assignedusers);
})
.catch(err => message.reply("Cannot fetch users for react: '" + reacts + "', err: " + err + "!"));
})
.catch(err => message.reply("Cannot fetch message: '" + args + "', err: " + err + "!"));
}
});
It works fine, up until message.guild.fetchMember(user, false), where I fall into the catch block and print many "Cannot find member object for: ******#****!" messages.
I am not getting back any actual exception blocks, and the code worked for the first 62 or 788 reacts. It seems like if the bot doesn't have the user info cached, even using a false in message.guild.fetchMember(user, boolean) doesn't work.
The user object for that member, however is defined. I need the member object to use member.addRole().
Can someone help me figure out how to get this to work, please? Or what I am doing wrong?
I am running node v11.6.0 with "discord.js": "^11.4.2" as a dependency.
Thanks!
I found that the guild object from BOT.guilds.first() has:
members: 656,
memberCount: 2470
So, if I do:
BOT.guilds.first().fetchMembers().then((guild) => {
...
}
That fixes my issue, as the fetchMembers() returns a Promise<Guild> that I can see in the .then() clause, and that Guild object has all members fetched inside of it.
Hope this helps others out!

Resources