Trying to figure out the issue with my code - javascript

I have a problem with my code and try to find the error
I have already tried to use let instead of var but it still did not work. There is also no output in the console.
I believe the error to be within the if (tylerdel == true) of my code:
if (command === prefixfile.prefix + `active`) {
var tylerdel = true
message.channel.send (`test`)
if (tylerdel == true) {
if (message.author.id === ("")) {
message.delete (1)
}
}
}
It is supposed to delete a message if it comes from a certain person but I also need it to be toggleable.

As per your code boolean variable tylerdel will always be true so there is no need to use this variable in your if condition.
if(command === prefixfile.prefix + 'active') {
message.channel.send('test');
if (message.author.id === '') {
message.delete(1);
}
}

Be careful with == (Equality) and === (Identity).
More info about the operators
You should know what is "Debugging". You can try printing something in each if to see where is the problem.
Hope this helps you to solve your problem.

Try this:
if (command === prefixfile.prefix + 'active') {
var tylerdel = true;
message.channel.send ('test');
if (tylerdel) {
if (message.author.id === '') {
message.delete(1);
}
}
}

Related

Discord.js counting system

so I was trying to make my own version of a counting system for my server like how other bots such as countr do it, so I made the following:
if (message.channel.id === "794733520458612736") {
const numdb = db.get("numdb");
if (message.content === numdb) {
db.add("numdb", 1);
message.react("✅");
} else if (typeof message.content === "number") {
db.set("numdb", 1);
message.channel.send(`${message.author} ruined it at **${numdb}**! The next number is **1**.`);
message.react("❌");
};
};
Yet, when I try it, it doesn't seem to work. Does anyone know what I am doing wrong?
Alright, I solved it as shown below:
if (message.channel.id === "794733520458612736") {
const numdb = db.get("numdb");
if (message.content == `${numdb}`) {
db.add("numdb", 1);
message.react("✅");
} else if (!isNaN(message.content) && message.content != `${numdb}`) {
db.set("numdb", 1);
message.channel.send(`${message.author} ruined it at **${numdb-1}**! The next number is **1**.`);
message.react("❌");
};
};
I figured out that the reason was because === checks both value and type (credit to Zsolt) and the old method I used to check if it was a number didn't work, so I switched it to isNaN.

Bot plays same audio for joining and leaving the channel

my Bot is playing the same audio File for joining and leaving the Voice Channel and i dont know how to solve it:
client.on('voiceStateUpdate', (oldMember, newMember) => {
let newUserChannel = newMember.voiceChannel
let oldUserChannel = oldMember.voiceChannel
const voiceChannel = client.channels.cache.get('807305239941480543')
if(oldUserChannel === undefined && newUserChannel !== undefined && oldMember.member.user.bot === false && newMember.member.user.bot === false) {
voiceChannel.join().then(connection => { connection.play("./a.mp3").on("finish", () => connection.disconnect())
});
} else if(newUserChannel === undefined && oldMember.member.user.bot === false && newMember.member.user.bot === false){
voiceChannel.join().then(connection => { connection.play("./b.mp3").on("finish", () => connection.disconnect())
});
}
})
I dont get any error and the Bot works but the Bot is playing the audio file ./b.mp3 everytime and not the audio ./a.mp3.
Thanks!
You are already on the right track but you're overthinking the if statement.
First off, when the voiceStateUpdate event is triggered, the parameters available are voiceStates so we'll use oldState and newState in this code.
You have the right idea when you check if the user is a bot but you can do that in a separate check.
if (oldState.member.user.bot) return;
Now that we know a user is joining/leaving we can differentiate, however we need to check three cases:
a user joins a new channel, here case A
a user leaves a channel, here case B
a user switches channels, here case C
A joining is indicated if oldState.channelID is either null or undefined.
oldState.channelID === null || typeof oldState.channelID == 'undefined'
A leaving is indicated if newState.channelID is either null or undefined.
newState.channelID === null || typeof newState.channelID == 'undefined'
A switching is indicated if neither of the above fit which we simply cover with else.
Since I don't have your MP3 files I simply console.log() a "PLAYING (A/B/C)" which you need to switch out for your audiofiles.
The entire voiceStateUpdate looks like this:
client.on('voiceStateUpdate', (oldState, newState) => {
if (oldState.member.user.bot) return;
const voiceChannel = client.channels.cache.get('807305239941480543');
if (oldState.channelID === null || typeof oldState.channelID == 'undefined') {
voiceChannel.join().then(connection => {
console.log("PLAYING (A)");
connection.disconnect();
});
} else if (newState.channelID === null || typeof newState.channelID == 'undefined') {
voiceChannel.join().then(connection => {
console.log("PLAYING (B)");
connection.disconnect();
});
} else {
voiceChannel.join().then(connection => {
console.log("PLAYING (C)");
connection.disconnect();
});
}
})
;

Cypress test hangs with custom command but not if using function in PO file - what am I getting wrong?

I'm still kinda new to Cypress, so please forgive any noob ignorance - but...
I'm using page objects, and trying to use a custom command that I've written as a kind of wrapper around assertions. This custom command will be used across a number of tests, and a number of page object files, so I don't want to replicate the code for it in each page object file. But! If I put the exact same code into the page object definition it works fine, if I use it as a custom command, the test hangs (elapsed time just goes up and up, but nothing happens)... A rough illustration of what I'm doing:
myPage.myFirstElement.click()
myPage.mySecondElement.type('something')
myPage.want(myPage.ThirdElement, 'to equal', 'Fred') // want is the name of my custom command / function in the PO file
The above works. However, if I move 'want' to a custom command:
myPage.myFirstElement.click()
myPage.mySecondElement.type('something')
cy.want(myPage.ThirdElement, 'to equal', 'Fred') // want is the name of my custom command / function in the PO file
This hangs, as described above. I've tried setting prevSubject in my custom command definition, to no avail. I've also tried using .then(...), also to no avail.
What am I failing to spot / understand correctly?
Thank you :)
//EDIT : Code for 'want' function as requested. This is as it is when in my po file. When a custom command, it is identical in content, except of course the declaration reads "Cypress.Commands.Add('want', (val1, op, val2) => { " and so on...
want(val1, op, val2) {
function getContent(obj, op) {
if ((op.indexOf('exist') >= 0) || (op.indexOf('visible') >= 0) || (typeof obj != 'object')) {
return obj
}
return obj === null ? obj : obj.attr('value') === undefined ? obj.text() : obj.attr('value');
}
function compare(first, second) {
op = op.split(' ').join('.')
var cmp1 = getContent(first, op);
var cmp2 = getContent(second, op);
var assertFn = (op.indexOf('exist') >= 0) || (op.indexOf('visible') >= 0) ? 'expect' : 'softExpect'
if (cmp2 === undefined) {
var chaiAssertion = new Function('a', 'return chai.' + assertFn + '(a).' + op)
chaiAssertion(cmp1)
//.then({timeout: Cypress.config('responseTimeout')}, () => { return originalFn(cmp1)})
} else {
var chaiAssertion = new Function('a, b', 'return chai.' + assertFn + '(a).' + op + '(b)')
chaiAssertion(cmp1, cmp2)
}
}
if (typeof (val1) === 'object' && val1 != null) {
val1.should(($v1) => {
if (typeof (val2) === 'object' && val2 != null) {
val2.should(($v2) => {
compare($v1, $v2)
})
}
else {
compare($v1, val2)
}
})
}
else {
if (typeof (val2) === 'object' && val2 != null) {
val2.should(($v2) => {
compare(val1, $v2)
})
}
else {
compare(val1, val2)
}
}
}
If you created custom command, this means you have to use like any other command in cypress:
cy.[command]
so it should work with :
cy.want(myPage.ThirdElement, 'to equal', 'Fred') // want is the name of my custom command / function in the PO file

javascript how to fill a return from values of array

I don't know how to formule the question(title), so I'll just say it here, and maybe someone may help or provide a new point of view about it.
I'm working with discord.js and I want to check if user has a role/roles from a message
client.on('message', message => {
if (message.member.roles.find(r => r.name === 'ADMIN')) {
console.log('I am admin');
}
});
Now my idea is to make this a polymorphism functions, because if I want to check two roles I have to do this:
client.on('message', message => {
if (message.member.roles.find(r => r.name === 'ADMIN') || message.member.roles.find(r => r.name === 'Other')) {
console.log('I am admin');
}
});
And I would like to move this if condition to a function and it will check it even if I want to check one or more `permissions.
For now I have tried to deal with it, but nothing, and stopped here... Maybe someone can give me some advice or other point of view. The idea is to prevent duplicate code and an if as long as the width of my monitor.
function hasRole(msg, permissions, condition = 'or') {
if (Array.isArray(permission)) {
if (condition === 'or') {
permissions.forEach(function (element) {
});
// permission.join('||');
return msg.member.roles.find(r => r.name === permissions) ||
msg.member.roles.find(r => r.name === permissions);
} else if (condition === 'and') {
}
}
return msg.member.roles.find(r => r.name === permissions);
}
If you want to check DiscordJS DOCS.
Response:
function checkPermissions(msg, permissions, condition = 'or') {
if (condition === 'or') {
return msg.member.roles.some(r => permissions.includes(r.name));
} else if (condition === 'and') {
return msg.member.roles.every(r => permissions.includes(r.name));
}
}
Something like this?
function hasRole(msg, permissions, condition = 'or') {
//harmonise #permissions to array, if isn't already one
permissions = Array.isArray(permissions) ? permissions : [permissions];
//if or, at least 1 member role must be present in #permissions
if (condition === 'or')
return msg.member.roles.some(role => permissions.includes(role));
//if and, all member roles must be found in #permissions
else
return permissions.every(perm => msg.member.roles.includes(perm));
}
function checkPermissions(msg, permissions, condition = 'or') {
if (Array.isArray(permissions)) {
if (condition === 'or') {
return msg.member.roles.some(r => permissions.includes(r.name));
} else if (condition === 'and') {
let value = false;
permissions.forEach(permission => {
value = !!msg.member.roles.find(r => r.name === permission);
});
return value;
}
}
return !!msg.member.roles.find(r => r.name === permissions);
}

Else statement executes even if the If statement conditions are valid

I am using Google Cloud function to validate my OTP Authentication, and also using Firebase database to save code in the database.
My problem is, even when the If statements condition are satisfied, it always executes else statement. I am comparing code and codeValid from firebase database with the user input. Thus, my user input is satisfied with code and codevalid is also satisfied, but it always moves to else statement. I dont know why.
Here is my code
const admin = require('firebase-admin');
module.exports = function(req, res) {
if(!req.body.phone || !req.body.code) {
return res.status(422).send({error: 'Phone and Code Must be
Provided'});
}
const phone = String(req.body.phone).replace(/[^\d]/g, '');
const code = parseInt(req.body.code);
return admin.auth().getUser(phone)
.then(() => {
const ref = admin.database().ref('users/'+ phone);
return ref.on('value', snapshot => {
ref.off();
const user = snapshot.val();
if (user.code === code && user.codeValid === true) {
ref.update({ codeValid: false });
admin.auth().createCustomToken(phone)
.then(token => res.send({ token: token }))
.catch((err)=> res.status(422).send({ error:err }));
}
else {
return res.status(422).send({ error: 'Code Not Valid' });
}
});
})
.catch((err)=> res.status(422).send({ error:err }) )
}
So, I always get "code not valid" what ever the input i give. I cross checked all the values with firebase database also, everything matches. But couldn't find why its happening.
Add this above your if condition and check whether your statements are really true. I think it's possible that your datatypes are different for example for user.code and code. So you should also test it with == or with parsing your values.
// values and datatypes are equal
if (user.code === code) {
console.log('user.code === code');
}
// values and datatypes are equal
if (user.codeValid === true) {
console.log('user.codeValid === codeValid');
}
// values are equal
if (user.code == code) {
console.log('user.code == code');
}
// values are equal
if (user.codeValid == true) {
console.log('user.codeValid == codeValid');
}
For more information about the difference of == and === look at this answer:
Difference between == and === in JavaScript

Categories