If statement firing when it shouldn't - javascript

Line 14 should fire if there are no commands with the guild id,
Line 15 should fire if the user has no commands in that guild,
but
!commands #Rusty#2746 returns No commands in this guild. in the server Go away. (I have a command in this server)
!commands #Rusty#2746 returns No commands in this guild. AND the actual command in the server SurgicalGoblin. ( I have a command in this server)
let user = message.mentions.users.first();
if (args.length !== 1) return message.reply("Incorrect arguments, " + args.length + " given, 1 required.");
if (message.mentions.users.size !== 1) return message.reply("You must mention a user to view the commands of.");
fs.readFile(path.join(__dirname, "../jsonFiles") + "/customCommands.json", "utf-8", function(err, data) {
if (err) throw err;
var arrayOfObjects = JSON.parse(data);
if (arrayOfObjects.commands.length === 0) return message.reply("No custom commands found.");
for (let i = 0; i < arrayOfObjects.commands.length; i++) {
console.log(message.guild.id) // matches the guild_id in json file
if (message.guild.id !== arrayOfObjects.commands[i].guild_id) return message.reply("No commands in guild.");
if (message.guild.id !== arrayOfObjects.commands[i].guild_id && user.id !== arrayOfObjects.commands[i].user_id) return message.reply(user.username + " has no commands in this guild.");
fs.writeFile(path.join(__dirname, "../jsonFiles") + "/customCommands.json", JSON.stringify(arrayOfObjects, null, 2), "utf-8", function(err) {
if (err) throw err;
const embed = new Discord.RichEmbed()
.setColor(0x08F258)
.setAuthor("Custom Commands for " + user.username, message.author.avatarURL)
.addField(arrayOfObjects.commands[i].command_name, arrayOfObjects.commands[i].command_reply)
return message.channel.sendEmbed(embed);
});
}
});
JSON: https://hastebin.com/zucogajita.json

In case the solution is helpful to anyone else, I discussed this with the OP in chat and discovered that the issue occurred because the OP wanted to compare the current message's guild with the corresponding guild in the JSON data. Therefore, I suggested taking out the for loop completely and instead finding the guild first (using find()) and then doing a comparison:
let user = message.mentions.users.first();
if (args.length !== 1) return message.reply("Incorrect arguments, " + args.length + " given, 1 required.");
if (message.mentions.users.size !== 1) return message.reply("You must mention a user to view the commands of.");
fs.readFile(path.join(__dirname, "../jsonFiles") + "/customCommands.json", "utf-8", function(err, data) {
if (err) throw err;
var arrayOfObjects = JSON.parse(data);
if (arrayOfObjects.commands.length === 0) return message.reply("No custom commands found.");
var guild = arrayOfObjects.commands.find(function(obj) { return obj.guild_id == message.guild.id; });
if (message.guild.id !== guild.guild_id) return message.reply("No commands in guild.");
if (message.guild.id !== guild.guild_id && user.id !== guild.user_id) return message.reply(user.username + " has no commands in this guild.");
fs.writeFile(path.join(__dirname, "../jsonFiles") + "/customCommands.json", JSON.stringify(arrayOfObjects, null, 2), "utf-8", function(err) {
if (err) throw err;
const embed = new Discord.RichEmbed()
.setColor(0x08F258)
.setAuthor("Custom Commands for " + user.username, message.author.avatarURL)
.addField(guild.command_name, guild.command_reply)
return message.channel.sendEmbed(embed);
});
});

Related

Problem with requesting discord cooldowns via sqlite, can't figure out the endless loop issue

I need to store cooldowns from users and then request them, so I can check if the user has the cooldown. But there is a problem, first example.
//DB thing
const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('cooldowns.db', sqlite3.OPEN_READWRITE, (err) => {
if (err) {
return console.error(err.message);
}
console.log('Connected to the cooldowns SQlite database.');
});
function getDBCooldown(userid)
{ return new Promise((resolve, reject) => {
let sql = `SELECT Author author,
Cooldown cooldown
FROM cooldowns
WHERE Author = ?`;
let author = userid
db.get(sql, [author], (err, row) => {
const now = new Date();
const cooldown = new Date(row.cooldown);
const value = date.subtract(cooldown,now);
const days = parseInt((cooldown - now) / (1000 * 60 * 60 * 24));
const hours = parseInt(Math.abs(cooldown - now) / (1000 * 60 * 60) % 24);
const minutes = parseInt(Math.abs(cooldown.getTime() - now.getTime()) / (1000 * 60) % 60);
const seconds = parseInt(Math.abs(cooldown.getTime() - now.getTime()) / (1000) % 60);
if (err) {
return console.error(err.message);
}
const expire = days + " days " + hours + " hours " + minutes + " minutes " + seconds + " seconds "
resolve(expire)
});
}) }
client.on("messageCreate", message => {
if (message.author.bot) return;
if (message.content.indexOf(config.prefix) !== 0) return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if(command === 'test') {
const dbcooldown = getDBCooldown(message.author.id)
if (dbcooldown) {
getDBCooldown(message.author.id)
.then(msg => message.reply(`Cooldown is set for you. ${msg}`))
.catch(err => console.error("Erorr getting cooldown: ", err))
return;
} //if cooldown is true, this statement will happen
createDBCooldown(message.author.id, Date.now() + cooldownTime);
// another stuff below this...
const cooldown = new Date(row.cooldown);
TypeError: Cannot read property cooldown of undefined
From what I understand and saw in several posts, issue is that cooldown is not known from the user as it does not exist in the database. Let's move on...
const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('cooldowns.db', sqlite3.OPEN_READWRITE, (err) => {
if (err) {
return console.error(err.message);
}
console.log('Connected to the cooldowns SQlite database.');
});
// Check User in DB
function checkDBUser(userid) {
let sql = `SELECT Author author,
Author author
FROM cooldowns
WHERE author = ?`;
let author = userid
db.get(sql, [author], (err, row) => {
if (err) {
return console.error(err.message);
}
if (row.author == author) {
return console.log(`Author ${author} is already in database!`)
}
});
};
// Create new DB user.
function createDBUser(userid) {
let author = userid
let expires = null
let MarkForDelete = false;
db.run(`INSERT INTO cooldowns (author, cooldown, MarkForDelete) VALUES(?, ?, ?)`, [author, expires, MarkForDelete], function(err) {
if (err) {
return console.log(err.message);
}
console.log(`New user added to DB ${author}`);
});
};
//Discord Message
client.on("messageCreate", message => {
if (message.author.bot) return;
if (message.content.indexOf(config.prefix) !== 0) return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if(command === 'test') {
const DBcheck = checkDBUser(message.author.id)
if (DBcheck) {
return;
}
createDBUser(message.author.id)
const cooldown = cooldowns.get(message.author.id); // this will check the cooldown
const dbcooldown = getDBCooldown(message.author.id)
if (dbcooldown) {
const remaining = humanizeDuration(cooldown - Date.now(), { round: true }, { units: ["d","h","m","s"] });
getDBCooldown(message.author.id)
.then(msg => message.reply(`Cooldown is set for you. ${msg}`))
.catch(err => console.error("Erorr getting cooldown: ", err))
return;
} //if cooldown is true, this statement will happen
createDBCooldown(message.author.id, Date.now() + cooldownTime);
if (row.author == author) {
^
TypeError: Cannot read property 'author' of undefined
Another error, because user/author is not known, if I use createDBUser(message.author.id) before the statement, it will endlessly create user in the DB, but problem is that user don't exist and statement will fail due error... Another problem is with the function getDBCooldown(userid), when I tried without checkDBuser statement and just added the user before dbcooldown statement, the bot will say the cooldown is something like -10000 days, also the user will be created in the DB XY times depending on how many times command was triggered. I don't know how to create "empty" user in DB meanwhile avoiding error const cooldown = new Date(row.cooldown); TypeError: Cannot read property cooldown of undefined, everything must be created before initialization and I feel that I'm trapped in the endless loop and there is no way out from it...

Capture MySQL query result as var [js]

I'm currently trying to build a discord bot, and I want to use a database for some aspects of it. Currently, I'm trying to add a command that would return the names of all the tables I have in the database, and for the most part I have it down.
The part that I'm struggling with is actually getting the names back out as a var. Every guide and stackoverflow question that I've been able to find on it assume that you just want to get that result and then print it to the console, but I need to return it back to the method that called this.
My previous attempt was setting an outside variable and using a promise to wait for it to change, but I couldn't get that to work, most likely because I don't fully understand how Promises work. My current attempt uses setTimeout() to check, but that just returns the asyncID of either the first or second iteration.
Any help either in making either of these work or completely scrapping them and doing this a different way is very welcome.
Previous code:
function listTables() {
db.query('SELECT table_name FROM information_schema.tables WHERE table_schema=\'' + dbName + '\'', (error, results) => {
if(error) throw error;
let temp = '';
results.forEach((item) => {
temp += item.table_name + ', ';
}); temp = temp.slice(0, -2);
setReturn(temp);
});
let out = checkReturn().then((value) => {
return value();
}).catch((error) => {
console.log(error);
return '';
});
returnValue = null;
return out;
}
var returnValue = null;
function setReturn(value) {
returnValue = value;
}
async function checkReturn() {
console.log('Checking Return: ' + returnValue);
let promise = new Promise((resolve, reject) => {
if(returnValue === null) reject('Var not set');
else resolve(returnValue)
});
return await promise;
}
Current Code:
function listTables() {
setReturn(null);
db.query('SELECT table_name FROM information_schema.tables WHERE table_schema=\'' + dbName + '\'', (error, results) => {
if(error) throw error;
let temp = '';
results.forEach((item) => {
temp += item.table_name + ', ';
}); temp = temp.slice(0, -2);
setReturn(temp);
});
return checkReturn();
}
var returnValue = null;
function setReturn(value) {
returnValue = value;
}
function checkReturn() {
console.log('Checking Return: ' + returnValue);
if(returnValue === null) {
return setTimeout(checkReturn, 50);
} else {
return returnValue;
}
}
You need to modify the listTables function to return a promise.
function listTables() {
return new Promise((resolve, reject) => {
db.query('SELECT table_name FROM information_schema.tables WHERE table_schema=\'' + dbName + '\'', (error, results) => {
if(error) {
reject(error);
return;
}
let temp = '';
results.forEach((item) => {
temp += item.table_name + ', ';
}); temp = temp.slice(0, -2);
resolve(temp);
});
});
}
// Usage of `listTables()`
listTables()
.then(result -> {
// Do process result
});

Creating a BulkDelete command | Discord.JS

As you read by the title I'm trying to make a clear command for my Discord bot, but I can't get it to work.
Here's a snippet:
client.on('message', message => {
if (message.content = "clear") {
let args = message.content.substring(prefix.length).split(" ");
var deleteCount = message.guild.members.cache.get(args[1]);
if (message.member.hasPermission("MANAGE_MESSAGES")) {
const deleteCount = args[2];
const fetched = ({
limit: deleteCount
});
message.delete(fetched)
try {
} catch (error) {
}(error => message.reply(`Couldn't delete messages because of: ${error}`));
if (!deleteCount || deleteCount < 2 || deleteCount > 100)
return message.reply("Please provide a number between 2 and 100 for the number of messages to delete");
message.channel.send('Successfully deleted ' + `${deleteCount}` + 'messages!');
}
}
});
Also, don't ask me what I'm doing and why I copied some stuff from other people trying to make it but the code was outdated.
Can someone help me?
client.on("message", message => {
if (message.content.indexOf(prefix) !== 0) {return false};
const arguments = message.content.slice(prefix.length).trim().split(/ +/g);
const command = arguments.shift().toLowerCase();
if (command == "clear") {
if (!message.member.hasPermission("MANAGE_MESSAGES")) return message.channel.send("You are not allowed to use this command.");
if (!arguments[0]) return message.channel.send("Please provide a number between 2 and 100.")
if (arguments[0] < 2 || arguments[0] > 100) return message.channel.send("Please provide a number between 2 and 100.")
message.channel.bulkDelete(arguments[0]).then(messages => {
message.channel.send(`Deleted ${messages.size} messages.`);
}).catch(e => console.log(e));
};
});

Cannot read property 'first' of null

So I'm currently making a discord bot so whenever someone types !true #USER [Location] it will DM the #USER a message, add a role and then nickname the user to [Location] with the following code :
const mention = message.mentions.members.first();
msg = message.content.toLowerCase();
if (msg.startsWith(prefix)){
if(message.channel.id === '12345'){
if (msg.startsWith (prefix + "true")){
if(!message.member.hasPermission("MANAGE_NICKNAMES")) return message.reply("You have no permission!");
if (mention == null) { return; }
let args = message.content.split(" ").slice(2);
if ((mention.displayName + " " + args.join(" ")).length > 32) return message.channel.send("The nickname exceeds 32 characters")
if(mention.roles.cache.has('1234567890')){
message.reply("User is already accepted.")
} else {
mention.roles.add('1234567890').then(() => mention.setNickname(mention.displayName+" "+args.join(' ')))
.catch((e) => {
console.log('handle error here: ', e.message)
})
}
}}}
However, most of the time it will return with Cannot read property 'first' of null and it won't change the user's nickname (only roles and DM). Is there anything wrong with my code? Thanks.
const mention = message.mentions.members.first();
In the above code, message.mentions.members is null so you can't access a property (here first) in a null object.
The culprit is probably somewhere you set members property, not the code you provided here. do some debugging and console.log and you'll fix the issue.
You got error because you can`t get first of null. Better check mention in a command, like this.
if (msg.startsWith(prefix)) {
if (message.channel.id === '12345') {
if (msg.startsWith(prefix + 'true')) {
if (args.length < 0) return message.reply('PLS mention a member or write his ID');
const mention = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
if (!mention) return message.reply('Can`t find a member');
msg = message.content.toLowerCase();
if (!message.member.hasPermission('MANAGE_NICKNAMES')) return message.reply('You have no permission!');
if (mention == null) {
return;
}
let args = message.content.split(' ').slice(2);
if ((mention.displayName + ' ' + args.join(' ')).length > 32) return message.channel.send('The nickname exceeds 32 characters');
if (mention.roles.cache.has('1234567890')) {
message.reply('User is already accepted.');
} else {
mention.roles
.add('1234567890')
.then(() => mention.setNickname(mention.displayName + ' ' + args.join(' ')))
.catch(e => {
console.log('handle error here: ', e.message);
});
}
}
}
}

Promise not waiting for return value in NodeJS

Hi as i am new to NodeJS as a follow-up to my previous question (Having problems getting new Array Value after looping in NodeJS) i have managed to get my code mostly working for parsing a list of email and querying them to the database, unable to get the return value in my promise when i get a response back from NodeJS API.
I am using MySQL 2.18.1 for my database and 4.17.1
Any idea i can solve it? Been trying it for a few hours.
Logs:
IM OUT HERE
Promise { { recipients: [] } }
{ recipients: [] }
retrieve_for_notification.js
async function processEmails(emails) {
var retrieveValues = {
recipients: []
};
// emails consist of those who were mentioned/notified, check condition whether they are eligible to be placed in receipients list
for (var i = 0; i < emails.length; i++) {
console.log(emails[i]);
// 1 - check for suspended
// 2 - check whether teacher and student pair is registered
var sql1 = 'SELECT COUNT(*) as count_value FROM school.schoolinformation WHERE email = ? AND user_status = ?';
var sql2 = 'SELECT COUNT(*) as count_value2 FROM school.registration_relationship WHERE teacher_email = ? AND student_email = ?';
var sql3 = 'SELECT COUNT(*) as count_value3 FROM school.schoolinformation WHERE email = ? AND user_type = ?';
var sqlvalues1 = [emails[i], 1];
var sqlvalues2 = [teacher, emails[i]];
var sqlvalues3 = [emails[i], 0];
// check for suspended
con.pool.query(sql1, sqlvalues1, async function (err1, result1) {
if (err1) throw err1;
var res1 = await getResult(sql1, sqlvalues1)
// console.log("(1) res value is %s", res1[0].count_value);
if (res1 > 0) return; // if result found skip to next email
// check whether teacher and student pair is registered
con.pool.query(sql2, sqlvalues2, async function (err2, result2) {
if (err2) throw err2;
var res2 = await getResult(sql2, sqlvalues2)
// teacher and student pair is not registered
if (res2 == 0) {
// check whether student mentioned is a valid student
con.pool.query(sql3, sqlvalues3, async function (err3, result3) {
if (err3) throw err3;
var res3 = await getResult(sql3, sqlvalues3)
// student is valid
if (res3 == 0) {
retrieveValues.recipients.push(sqlvalues3[0]);
}
});
}
else {
retrieveValues.recipients.push(sqlvalues2[0]);
}
});
});
};
return recipientsList;
}
var recipientsList = processEmails(emails);
console.log("IM OUT HERE");
console.log(recipientsList);
// Resolve promise and response send, not using helper for this
var p2 = Promise.resolve(recipientsList);
p2.then(function(v) {
console.log(v);
response.write(JSON.stringify(v, null, 3));
response.send.bind(response);
response.end();
}, function(e) {
console.error(e); // TypeError: Throwing
});
function getResult(sql, sqlvalues) {
// console.log("getResult SQL Query: %s", sql);
return new Promise(function (resolve, reject) {
con.pool.query(sql, sqlvalues, function (err, result) {
if (err) {
reject(err)
} else {
resolve(result)
}
})
})
}
May by use - "response.statusCode = responseCode" for old version express

Categories