Discord - showing member join position with specified number - javascript

I want to show you which number of users I entered in the argument is the order of joining the server. Like = when i use .join 1 I want to show the 1st member join in to the server. I use
let arr = message.guild.members.filter(a => !a.user.bot).array().sort((b, a) => b.joinedTimestamp - a.joinedTimestamp)
let map = arr.indexOf(sesmi) + 1
this command for showing joing position but im so confused how can i do as i said?

Try this:
// if the first argument is not a number (this message is kind of bad so you can change it)
if (isNaN(args[0])) return message.reply('you must specify what number user you want to get!')
const members = message.guild.members.cache
.filter(member => !member.user.bot)
// sorted is a member on Discord's utility class Collection that doesn't modify the original collection
.sorted((a, b) => a.joinedTimestamp - b.joinedTimestamp)
.array()
// the number user to get
const n = Number(args[0])
// if there are not enough members
if (n > members.length) {
// You only really need this if there is ever going to be only 1 member in the server
// and if you care about grammar. You could also just do
// return message.reply(`there are only ${members.length} members!`)
const plural = members.length !== 1
return message.reply(`there ${plural ? 'are' : 'is'} only ${members.length} member${plural ? 's' : ''}!`)
}
message.channel.send(members[n - 1].user.tag)
I'm assuming args will be an array of strings with the arguments passed into the command (e.g. .join 1 will have the args ['1'].

Related

taking one element of each type from a list and only taking the first occurrence not working as expected

So this function is supposed to pars an array of object and only take the first occurrence of each type of object there is like 4 different ones and each ones has a dozen of entries.
LastReadingOfEach(measurements){
let devicesList = []
devicesList.push(measurements.map((device) => {if (!devicesList.includes(device.Type) ) { return device} else console.log("removed :")}))
console.log("devicesList : ", devicesList)
}
I created an array and thought I could just push in a device of each type, but I think it doesn't compare against the array as it fill up because it at the end I find the devicesList has all elements on measurements
I believe what you're looking for can be done with a reducer and findIndex. If find index fails to match the device type it will return -1, we know that we don't have that type yet so it gets pushed into the aggregation.
LastReadingOfEach(measurements){
const devicesList = measurements.reduce((agg, device) => {
if (agg.findIndex(x => x.type === device.type) === -1) {
agg.push(device)
}
return agg
}, [])
console.log("devicesList : ", devicesList)
}

Multiple Filter Methods

I'm trying to solve this problem.
I'm creating a filter method, that has to return me a filtered array based on my preference.
The array is containing some sports bet info, like the odd quote, the starting date, the name of the bookmaker, etc, and I'm trying (for the moment) to just filter based on the min and max odds
First of all, into my "Parent" react component, I receive some info from his child, and those info are stored in an object.
The object is like that:
filters = {minOdd: "", maxOdds:"", ecc...}
And the filter method is like:
setFilters = () => {
const odds = this.state.odds
const filters = this.state.filters
const newOdds = odds.filter((odd) => odd.quota > filters.quotaMin)
.filter((odd) => odd.quota < filters.quotaMax)
}
Where "quota" means "odd", quotaMin means "min odd" and "quotaMax" means max odd
Now, if I set the min and the max odd into my child component, the function returns me an array containing all the right odds. But if I set just one of the 2 filters, this function returns me back an empty object.
I'n my opinion, the problem is that if i don't set one of the 2 value, the filter method compares the odd this a value that is like modd.quota < filters.quotaMax, where filters.quotaMax could be = to "".
Soo i have to not allow the filter method to filter value that are = to "".
If someone can give my an advice!
Thanks in advice!
Use fallback values for the undefined filters.
If either quotaMax or quotaMin is not defined, you are (most likely, haven't seen the structure of a bet) comparing a Number against undefined, which always results in false:
1 < undefined; // -> false
1 > undefined; // -> false
As fallback values, you can use negative and positive infinity. To be honest, it doesn't matter which values you use as long as the fallback for quotaMin is guaranteed to be smaller than the lowest quota and the fallback for quotaMax is guaranteed to be higher than the highest quota.
const newOdds = odds
.filter(odd => odd.quota > (filters.quotaMin || -Infinity))
.filter(odd => odd.quota < (filters.quotaMax || Infinity));
Side note:
You can make your code run faster by merging both predicates into one with AND && (saves one iteraton/filtering).
const newOdds = odds
.filter(odd => odd.quota > (filters.quotaMin || -Infinity) &&
odd.quota < (filters.quotaMax || Infinity));
I guess you just need to handle that case then where quotaMax is undefined/"":
const newOdds = odds.filter((odd) => odd.quota > filters.quotaMin)
.filter((odd) => {
if (filters.quotaMax) {
return odd.quota < filters.quotaMax
} else {
// you decide what should happen in this case..
// return true/false
})

How do I use javascript includes to filter out text that does not include specific text

I have a method that gets a list of saved photos and determines the number of photos listed. What I wish to do is return the number of photos that contain the text "Biological Hazards" in the name. Here is my code so far
getPhotoNumber(): void {
this.storage.get(this.formID+"_photos").then((val) => {
this.photoResults = JSON.parse(val);
console.log("photoResults", this.photoResults);
// photoResults returns 3 photos
// Hazardscamera_11576868238023.jpg,
// Biological Hazardscamera_11576868238023.jpg,
// Biological Hazardscamera_11576868351915.jpg
this.photoList = this.photoResults.length;
console.log("photoList", this.photoList); // returns 3
this.photoListTwo = this.photoResults.includes('Biological Hazards').length; // I wish to return 2
}).catch(err => {
this.photoList = 0;
});
}
Any help would be greatly appreciated.
Xcode log
[
One way to do this is to .filter() the array, and then calculate the length of that array.
this.photoListTwo = this.photoResults.filter(photoString => {
return photoString === 'Biological Hazards' //or whatever comparison makes sense for your data
}).length;
Quick solution for this (sorry for the lack of better formating, posting from mobile):
const array = ["Hazardscamera_11576868238023.jpg", "Biological Hazardscamera_11576868238023.jpg", "Biological Hazardscamera_11576868351915.jpg"];
const filterBioHazards = (str) => /Biological Hazards/.test(str);
console.log(array.filter(filterBioHazards).length);
// Prints 2
The method includes returns boolean to indicate whether the array contains a value or not. What you need is to filter your array and return its length after.
You need to replace the line:
this.photoListTwo = this.photoResults.includes('Biological Hazards').length;
By this:
this.photoListTwo = this.photoResults.filter(function(result) {return result.contains("Biological Hazards");}).length;

Discord bot delete command

My main goal is for someone with message managing permissions to type a command for deleting a message but be able to specify how many messages they'd like to delete.
I have tried messing with variables but I don't have much knowledge on them, usually ending in some errors. I've tried replacing the value of messages deleted (the 2) with the variable with success but I'm clueless when it comes to changing the variable with a message.
if(message.member.hasPermission('MANAGE_MESSAGES')) {
if(message.content.startsWith(`${prefix}delete`)) {
message.channel.bulkDelete(2)
}
}
I will suppose you have it on message event.
This is one of many ways you can do it:
if(message.content.startsWith(`${prefix}delete`)) {
const user = message.mentions.users.first();
// Parse Amount
const amount = !!parseInt(message.content.split(' ')[1]) ? parseInt(message.content.split(' ')[1]) : parseInt(message.content.split(' ')[2])
//Check if it the amount for message to delete where declared
if (!amount) return message.reply('Must specify an amount to delete!').then(msg => msg.delete(15000));
// Fetch 100 messages (will be filtered and lowered up to max amount requested)
message.channel.fetchMessages({
limit: 100,
}).then((messages) => {
//I declare the messages like that with amount + 1 to delete the command itself
messages = messages.array().slice(0, amount + 1);
//And finally buldDelete deletes the desired amount
message.channel.bulkDelete(messages).then(messages => console.log(`Bulk deleted ${args[0]} messages`))
.catch(console.error);
});
You would need to split message.content, which will return an array that I'll name args for this example. Then, args[1] should be the number you are looking for.
const prefix = '#'
const args = message.content.split(' ')
if(message.member.hasPermission('MANAGE_MESSAGES')) {
if(message.content.startsWith(`${prefix}delete`)) {
message.channel.bulkDelete(args[1])
}
}
Et voilĂ  ! You just need to make sure that args[1] is a number now.

Recursicely call data in a mongodb with node

I am creating a login system and i want to implement a username system automatically after registration with the user first-name and last-name. Everything is working fine but in the case if the registered user with the same first-name and last-name is already in the system i want to concatenate a incrmental number to it.
Example if : firstname:Badmus Lastname:Kabiru is in the system as badmus.kabiru and the newly registered user is also named so the new user username will be badmus.kabiru.1 the next will be badmus.kabiru.2.
My code sample are.
assignUserTrendname: function(req_username, callback){
let userNewname = fetchUserName(req_username);
let inc = 1, newlyAssignUsername;
userNewname.then((usernames) => {
console.log(req_username+" ...................... "+usernames); //The data from the database is loging out
if (usernames.atusername == null || usernames.atusername == undefined) {
newlyAssignUsername = req_username;
console.log("Assign automaticaly "+ newlyAssignUsername);
} else {
newlyAssignUsername = req_username;
console.log(`Username Result is DB: ${usernames.atusername} Req: ${newlyAssignUsername} Search ${inc}`);
if(usernames.atusername.toString() == newlyAssignUsername.toString()){
console.log("User name exit and inc is "+ inc);
inc++;
newlyAssignUsername = `${req_username}.${inc}`;
console.log("New search..."+ newlyAssignUsername);
fetchusernames(newlyAssignUsername); // These is not fetching from the database
}
newlyAssignUsername = `${req_username}.${inc}`;
}
console.log("Assigned is ......"+ newTrendname);
callback(null, newTrendname);
})
.catch((err)=> {console.log(err); throw err;});
}
function fetchUserName(trendname){
return Trender.getUserByTrendname(trendname);
}
If i am taking the wrong route please let me know.
Thanks.
In the scenario that your.username already exists you can search your Users with a regex pattern: ((?:your\.username)\d+$). This will get all records that match: your.username{num} where {num} is any number. If your username's are formatted as your.username.123 the pattern would be: ((?:your\.username\.)\d+$).
Assuming this returns an array, existing_users, you can count the records, since you'll always be incrementing by one, which will give you your next incremented number. Pseudo code:
let inc = existing_users.length + 1;
However, in the scenario that you delete a user your count is going to be off. You would need to loop over your existing_users and extract the number at the end and only keep the largest number.
let largest_num = 0;
existing_users.forEach(user => {
let num = user.match(/\d+$/);
if ( num != null && parseInt(num[0]) > largest_num ) {
largest_num = num[0];
}
});
Then you could do the same as above: let inc = largest_num + 1 and add that to your your.username string.
I do not know what library/framework you're using to search your MongoDB so I cannot write a query and function snippet.
We cannot write your code for you. A general regex has already been given that could be a potential way to solve your problem. If you go that route you can make use of the $regex operator. If you were to store the increment of the username as a separate field you could also sort by that to get the max value as well.
Here is an example of that:
db.users.find({
username: {
$regex: < Your Regex Here >
}
}).sort({
usernameIncrement: -1
}).limit(1);
Please see:
http://mongoosejs.com/docs/queries.html
https://docs.mongodb.com/manual/reference/operator/query/regex/
https://docs.mongodb.com/manual/reference/method/cursor.sort/

Categories