Guild Member Update Log Channel With Nicknames and Avatar - javascript

I want to log when a member has been updated for example a new avatar or nickname. I can log it to a console but when I try to send it to a channel it fails. There are no errors in console. I have tried using multiple accounts and different channels but still no result or any errors in console.
client.on('guildMemberUpdate', async (oldMember, newMember) => {
const guild = newMember.guild;
var Changes = {
unknown: 0,
addedRole: 1,
removedRole: 2,
username: 3,
nickname: 4,
avatar: 5
}
var change = Changes.unknown
var removedRole = ''
oldMember.roles.every(function (value) {
if (newMember.roles.cache.find('id', value.id) == null) {
change = Changes.removedRole
removedRole = value.name
}
})
var addedRole = ''
newMember.roles.every(function (value) {
if (oldMember.roles.cache.find('id', value.id) == null) {
change = Changes.addedRole
addedRole = value.name
}
})
if (newMember.user.username != oldMember.user.username) {
change = Changes.username
}
if (newMember.nickname != oldMember.nickname) {
change = Changes.nickname
}
if (newMember.user.avatarURL() != oldMember.user.avatarURL()) {
change = Changes.avatar
}
var log = guild.channels.cache.get(`755216180603650059`)
if (log != null) {
switch (change) {
case Changes.unknown:
log.send('**[User Update]** ' + newMember)
break
case Changes.addedRole:
log.send('**[User Role Added]** ' + newMember + ': ' + addedRole)
break
case Changes.removedRole:
log.send('**[User Role Removed]** ' + newMember + ': ' + removedRole)
break
case Changes.username:
log.send('**[User Username Changed]** ' + newMember + ': Username changed from ' +
oldMember.user.username + '#' + oldMember.user.discriminator + ' to ' +
newMember.user.username + '#' + newMember.user.discriminator)
break
case Changes.nickname:
log.send('**[User Nickname Changed]** ' + newMember + ': ' +
(oldMember.nickname != null ? 'Changed nickname from ' + oldMember.nickname +
+newMember.nickname : 'Set nickname') + ' to ' +
(newMember.nickname != null ? newMember.nickname + '.' : 'original username.'))
break
case Changes.avatar:
log.send('**[User Avatar Changed]** ' + newMember)
break
}
}
})

Based off Levi_OP's comment
if (a != b) {
//...
}
needs to turn into:
if (a !== b) {
//...
}

Related

window.open(url) mailto adds a hashtag to end of my url. How do I stop it from doing that or forward my url/# to my url/?

Here is the simple function that gets called when a button is clicked:
// Contact form
function sendEmail(){
var name = document.getElementById("nameField").value;
var email = document.getElementById("emailField").value;
var subject = document.getElementById("subjectField").value;
var message = document.getElementById("messageField").value;
if(name != "" && email != "" && subject != "" && message != ""){
var url = 'mailto:email#emailprovider.com?subject=' + name + ' (' + email + ')' + ' ' + subject + '&body=' + message;
window.location.href = url;
} else {
console.log("SOMETHING WAS EMPTY");
}
};
But then it keeps redirecting me to http://127.0.0.1:5500/# instead of http://127.0.0.1:5500/ How do I prevent this?
I figured out what the issue was. I had action=“#” in the form html. I will mark this as answered.
Try something like this:
// Contact form
function sendEmail() {
const name = document.getElementById("nameField").value;
const email = document.getElementById("emailField").value;
const subject = document.getElementById("subjectField").value;
const message = document.getElementById("messageField").value;
if (name && email && subject && message) {
let url = window.location.origin;
let params = 'mailto:email#emailprovider.com?subject=' + name + ' (' + email + ')' + ' ' + subject + '&body=' + message;
window.location.href = url + params;
} else {
console.error("SOMETHING WAS EMPTY");
}
};

How to improve homemade SQL syntax from filter function?

I'm doing an API and the following code is used to retrieve users depending on filter. ( POST /users/search )
At the end of the function, I'm working with "LIMIT" and "OFFSET" in SQL because I want that nobody can retrieve more than 10 entries.
The code to generate the SQL query from WHERE is terrible. I am looking to improve it but I can't find a more effective way. Do you have any ideas?
function getSqlFilter(filter) {
var filterSql = '';
if (!util.isEmpty(filter)) {
var isFiltered = false;
if (filter.userId != null) {
if (!isFiltered) filterSql += ' WHERE ';
if (isFiltered) filterSql += ' AND ';
filterSql += 'pk_user in (' + filter.userId.toString() + ')';
isFiltered = true;
}
if (filter.username != null) {
if (!isFiltered) filterSql += ' WHERE ';
if (isFiltered) filterSql += ' AND ';
filterSql += 'username in (' + filter.username.toString() + ')';
isFiltered = true;
}
if (filter.email != null) {
if (!isFiltered) filterSql += ' WHERE ';
if (isFiltered) filterSql += ' AND ';
filterSql += 'email in (' + filter.email.toString() + ')';
isFiltered = true;
}
if (filter.society != null) {
if (!isFiltered) filterSql += ' WHERE ';
if (isFiltered) filterSql += ' AND ';
filterSql += 'society in (' + filter.society.toString() + ')';
isFiltered = true;
}
if (filter.firstname != null) {
if (!isFiltered) filterSql += ' WHERE ';
if (isFiltered) filterSql += ' AND ';
filterSql += 'firstname in (' + filter.firstname.toString() + ')';
isFiltered = true;
}
if ((filter.start != null) && (filter.end != null)) {
filter.start -= 1;
var limit = filter.end - filter.start;
if (limit <= 10) {
filterSql += 'LIMIT ' + limit + ' OFFSET ' + filter.start;
}
} else if (filter.start != null) {
filterSql += 'LIMIT 10 OFFSET ' + filter.start;
} else {
filterSql += 'LIMIT 10 OFFSET 0';
}
} else {
filterSql += 'LIMIT 10 OFFSET 0';
}
return filterSql;
}
Thanks for helping
You can simplify the redundant logic and utilize ES6 features for shorter syntax.
function getSqlFilter(filter = {}) {
const searches = Object.keys(filter);
const sLength = searches.length
let filterSql = sLength === 0 ? "LIMIT 10 OFFSET 0" : "WHERE ";
const map = {
userId: "pk_user",
username: "username",
email: "email",
society: "society"
}
const { start, end } = filter;
const hasOnlyStart = start !== undefined && end === undefined;
const hasStartAndEnd = start !== undefined && end !== undefined;
if (sLength) {
filterSql += searches.map(search => {
if(search === "start") {
return hasOnlyStart ? `LIMIT ${filter[search]} OFFSET 10` : "";
}
if(search === "end") {
return hasStartAndEnd ? `LIMIT ${filter[search]} OFFSET ${end - start}` : "";
}
return `${map[search]} in (${filter[search].toString()})`;
}).join(' AND ');
}
return filterSql;
}
I normally do this by starting with an always true condition
let filter= `...
WHERE 1 = 1`
Then you can simply append the filter
if (filter.username != null) {
filter += ' AND username in (' + filter.username.toString() + ')'
}
...
Hope this helps.
It is my anwser:
function getSqlFilter(filter) {
let sql = '';
let start = parseInt(filter.start);
let end = parseInt(filter.end);
delete filter.start;
delete filter.end;
const conditions = [];
const validKey = [...your key];
for (const key in filter){
if(validKey.indexOf(key) !== -1){
if(key === 'userId') conditions.push(`pk_user in (${filter[key].toString()})`);
else conditions.push(`${key} in (${filter[key].toString()})`);
}
}
if(conditions.length){
sql = ` WHERE ${conditions.join(' AND ')}`;
}
let limit = 10;
if (start) {
if(start < 0) start = 0;
if (end) {
let be_limit = start - end + 1;
if(be_limit <= 10 && be_limit >= 0) limit = be_limit;
}
} else {
start = 0;
}
sql += ` LIMIT ${limit} OFFSET ${start}`;
return sql;
}
If you don't want to change filter, please clone it before delete props.

Remove "null" from string in javascript

I have this code:
var returnValue = item.fname + " " + item.mname + " " + item.lname
returnValue.replace(null," ");
return returnValue ;
Sometimes one of the fields is null so returnValue is:
"John null Doe"
or
"John something null"
I want to get rid of the "null" but my code does not seem to work.
Can someone help me out here?
Rather than replacing null afterwards, only append the individual names if they are not null.
var returnValue = "";
if (item.fname !== null) {
returnValue += item.fname + " ";
}
if (item.mname !== null) {
returnValue += item.mname + " ";
}
if (item.lname !== null) {
returnValue += item.lname;
}
return returnValue;
Alternatively, use Array.prototype.filter to remove nulls:
// store the names in an array
var names = [ item.fname, item.mname, item.lname ];
// filter the array to values where they are `!== null`
var notNullNames = names.filter(x => x !== null);
// join them with spaces
var returnValue = notNullNames.join(" ");
var returnValue = (item.fname || " ") + " " + (item.mname || " ") + " " + (item.lname || " ");
return returnValue;
Be careful with mixing var types (string and null for example). Better make sure the variable is set or has a fallback.
I'd recommend you another technique: place your string parts to array, filter it and join it:
[item.fname, item.mname, item.lname].filter(v => !!v).join(' ')
try this
> return (item.fname ? item.fname : '') + " " + (item.mname ? item.mname : '') + " " + (item.lname ? item.lname : '');
var returnValue = item.fname
if(item.mname)returnValue += " " + item.mname
if(item.lname)returnValue += " " + item.lname
return returnValue
Try ternary operator for null avoiding:
var returnValue = item.fname + " " + item.mname ? item.mname : "" + " " + item.lname
In my opinion, the most elegant solution is:
[item.fname, item.lname, item.lname].join(' ');
For example:
const item = {}
item.fname = 'foo'
item.lname = 'bar'
console.log([item.fname, item.mname, item.lname].join(' '))
Otherwise you can use the or operator to skip falsy objects:
const item = {}
item.fname = 'foo'
item.lname = 'bar'
const joined = (item.fname || '') + " " + (item.mname || '') + " " + (item.lname || '')
console.log(joined)

Javascript error while concatenating values

I'm attempting a Javascript challenge on the 'codewars' website where the instructions are:
Implement a function likes :: [String] -> String, which must take in input array, containing the names of people who like an item. It must return the display text as shown in the examples:
likes [] // must be "no one likes this"
likes ["Peter"] // must be "Peter likes this"
likes ["Jacob", "Alex"] // must be "Jacob and Alex like this"
likes ["Max", "John", "Mark"] // must be "Max, John and Mark like this"
likes ["Alex", "Jacob", "Mark", "Max"] // must be "Alex, Jacob and 2 others like this"
For more than 4 names, the number in and 2 others simply increases.
My attempt is this:
function likes(names) {
var response = "a"
console.log(names[0]);
if (names.length === 0) {
response = 'no one likes this';
}
else if (names.length === 1) {
response = names[0] +' likes this';
}
else if (names.length === 2) {
response = names[0] + ' and' + names[1] ' like this';
}
else if (names.length === 3) {
response = names[0] + ',' + names[1] + ' and' + names[2] + ' like this';
}
else {
response = names[0] + ',' + names[1] + ' and' + (names.length-2).toString() + ' others like this';
}
return response;
}
and returns this error:
kata: Unexpected token:44 response = names[0] + ' and' + names[1] ' like this';
is it not possible to concatenate a string value inside an array with another string? Any help would be much appreciated.
You are missing + sign here
response = names[0] + ' and' + names[1] ' like this';
Try like this
response = names[0] + ' and' + names[1] +' like this';
You forgot a + on this line:
response = names[0] + ' and' + names[1] + ' like this';
Not critical but you also forgot a ; and the ' and' should be ' and '
function likes(names) {
var response = "a";
if (names.length === 0) {
response = 'no one likes this';
} else if (names.length === 1) {
response = names[0] + ' likes this';
} else if (names.length === 2) {
response = names[0] + ' and ' + names[1] + ' like this';
} else if (names.length === 3) {
response = names[0] + ', ' + names[1] + ' and ' + names[2] + ' like this';
} else {
response = names[0] + ', ' + names[1] + ' and ' + (names.length - 2).toString() + ' others like this';
}
return response;
}

Angular not working in IE8 document mode 7

Angular working well with IE7 document Mode 7. It's also working well with IE8 document Mode 8, but with IE8 document mode 7 not working.
This is the error:
{
description: "Member not found.
",
message: "Member not found.
",
name: "Error",
number: -2147352573
}
And this is the line where the error is throw:
this.$$element.attr(attrName, value);
Member not found
I'm using Angular 1.2.9. How can i fix it?
i have found the solution. Just check if (msie && msie <= 8) and it's work also in IE7.
I have also changed jqLiteRemoveClass and jqLiteAddClass
function jqLiteRemoveClass(element, cssClasses) {
if (msie && msie <= 8) {
if (cssClasses) {
forEach(cssClasses.split(' '), function(cssClass) {
element.className = trim(
(" " + element.className + " ")
.replace(/[\n\t]/g, " ")
.replace(" " + trim(cssClass) + " ", " ")
);
});
}
} else {
if (cssClasses && element.setAttribute) {
forEach(cssClasses.split(' '), function(cssClass) {
element.setAttribute('class', trim(
(" " + (element.getAttribute('class') || '') + " ")
.replace(/[\n\t]/g, " ")
.replace(" " + trim(cssClass) + " ", " "))
);
});
}
}
}
function jqLiteAddClass(element, cssClasses) {
if (msie && msie <= 8) {
if (cssClasses) {
forEach(cssClasses.split(' '), function(cssClass) {
if (!jqLiteHasClass(element, cssClass)) {
element.className = trim(element.className + ' ' + trim(cssClass));
}
});
}
} else {
if (cssClasses && element.setAttribute) {
var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
.replace(/[\n\t]/g, " ");
forEach(cssClasses.split(' '), function(cssClass) {
cssClass = trim(cssClass);
if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
existingClasses += cssClass + ' ';
}
});
element.setAttribute('class', trim(existingClasses));
}
}
}

Categories