Why does my code run when it is not supposed to? - discord.js

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.

Related

Repetitive data when loading a select

I'm calling EventListener so that when something is typed into the username field, it will list that user's companies for me.
var ent = document.getElementById("username");
//var str = "";
ent.addEventListener('change', async () => {
localStorage.clear();
self.empUsuario = new Array();
self.rucEmp = new Array();
var newUser = document.getElementById("username");
$('#empresa').empty();
await fetch(environment.apiPoint + '/empresas?usuario=' + newUser.value, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then(datos => {
datos.forEach(e => {
self.todasEmpresasUsuario.push({
ruc: e.ruc,
nombEmp: e.nombreCorto
});
});
})
await self.todasEmpresasUsuario().forEach(
function (element) {
self.empUsuario.push(element.nombEmp);
self.rucEmp.push(element.ruc);
}
);
Then I give it a conditional if the user is different from null, that it shows me with the rucEmp, and if not an empty space.
var str = "";
var item = "";
if (newUser.value != '') {
self.cont = 0;
let vacio = '';
for (item of self.empUsuario) {
vacio = "<option value=''>" + ' ' + "</option>"
str += "<option value='" + self.rucEmp[self.cont] + "'>" + item + "</option>"
self.cont++;
}
if (newUser.value == '') {
//str += "";
str += "<option value='" + self.rucEmp[self.cont] + "'>" + item + "</option>"
$('#empresa').empty().append(str);
}
$('#empresa').empty().append(vacio + str);
}
I expected the company lists to appear for each user and not accumulate, but the lists accumulate in the select.
enter image description here

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.

Discord.js variable does not exist when defined?

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.

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!

Avoid message repeating?

I need some help here I have a code that shows a message being updated per 2 seconds but I want a single message that replaces itself.
let channel = guild.channels.find(channel => channel.name === guilds[guild.id].digitchan);
let channel2 = guild.channels.find(channel => channel.name === guilds[guild.id].countdownchan);
if (channel && channel2) {
channel.send(embed);
scrims[guild.id] = {
timer: setTimeout(function() {
channel2.join().then(connection => {
const dispatcher = connection.playFile('./Audio/test.mp3');
console.log('dispatcher');
console.log(dispatcher == null);
dispatcher.on('end', () => {
channel2.leave();
const embed2 = new RichEmbed()
.setColor(0xc1d9ff)
.addField("message x", false);
channel.send(embed2);
scrims[guild.id].codes = true;
scrims[guild.id].codedata = {};
scrims[guild.id].playerinterval = setInterval(function() {
const embed4 = new RichEmbed()
.setColor(0xc1d9ff)
.setTitle("codes:");
Object.keys(scrims[guild.id].codedata).forEach(function(key) {
let codeobj = scrims[guild.id].codedata[key];
let user_str = "";
Object.keys(scrims[guild.id].codedata[key]).every(function(key2, count) {
let user = scrims[guild.id].codedata[key][key2];
user_str = user_str + user + "\n"
if (count >= 15) {
if (count > 15) user_str = user_str + "and more";
return false;
};
})
embed4.addField(key + " (" + Object.keys(codeobj).length + " codes)", user_str, true);
})
channel.send(embed4);
}, 2000);
scrims[guild.id].timer2 = setTimeout(function() {
scrims[guild.id].codes = false;
clearInterval(scrims[guild.id].playerinterval);
const embed3 = new RichEmbed()
.setColor(0xc1d9ff)
.setTitle("codes:");
Object.keys(scrims[guild.id].codedata).forEach(function(key) {
let codeobj = scrims[guild.id].codedata[key];
let user_str = "";
Object.keys(scrims[guild.id].codedata[key]).every(function(key2, count) {
let user = scrims[guild.id].codedata[key][key2];
user_str = user_str + user + "\n"
if (count >= 15) {
if (count > 15) user_str = user_str + "y mas..";
return false;
};
})
embed3.addField(key + " (" + Object.keys(codeobj).length + " codes)", user_str, true);
})
channel.send(embed3);
}, 1 * 60000);
});
});
}, time * 60000);
};
};
This is the discord action:
Codes:
Codes:
Codes:
Codes:
Codes:
Codes:
Codes:
Codes: 3c5
Codes: 3c5
So could be some kind of message deleting before sending the same message updated again, please let me know how to do it or some kind of code changing.
Just use message.edit() to edit the message.
message.edit() on discord.js docs

Resources