How can I pick a random user from a server? - javascript
I tried making a bot command that replies with "(random user) is bot". I tried other solutions, but they didn't work. Here's my code:
if (msg.content === 'wb!bot') {
let userArray = Array.from(msg.member.guild.members);
let randomUser = userArray[Math.floor(Math.random() * msg.guild.memberCount)];
console.log(randomUser);
console.log(userArray);
msg.channel.send(randomUser + ' is bot');
}
Using math.random is pointless when the Collection class already has a .random() method
//msg.guild.members.cache if v12
const usersCollection = msg.guild.members;
const randomUser = usersCollection.random();
Your use of Math.random is incorrect.
// Generate the array for the snippet
const userArray = [];
for (let i = 0 ; i < 100 ; ++i) {
userArray.push(`user${i + 1}`);
}
// Function that returns you a random number
// https://www.w3schools.com/js/js_random.asp
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min) ) + min;
}
// Pick a random user
const user = userArray[getRndInteger(0, userArray.length)];
// Display it
console.log(`${user} is bot`);
Related
Compare an array with itself for duplicate and store in new array
I have a question, how do I compare values in an array with themselves without the value to be compared being shown as true? As an example, if the value EUW1_6011808396 occurs again, it should be stored in the array matchingMatches. The Values of the Array are: [EUW1_6011808396, EUW1_6011824351, EUW1_6011720277, EUW1_6010413995, EUW1_6010218048, EUW1_6010184913, EUW1_6010131700, EUW1_6009739853, EUW1_6008825456, EUW1_6008833322, EUW1_6008409245, EUW1_6008369887, EUW1_6008355242, EUW1_6007567238, EUW1_6007269146, EUW1_6007226284, EUW1_6007192332, EUW1_6005571988, EUW1_6005438941, EUW1_6005495312, EUW1_6013263286, EUW1_6013193252, EUW1_6012475324, EUW1_6012411610, EUW1_6012315128, EUW1_6012011561, EUW1_6011110477, EUW1_6011026046, EUW1_6009739853, EUW1_6006439870, EUW1_6006434580, EUW1_6005238786, EUW1_6005191249, EUW1_6005026992, EUW1_6005015187, EUW1_6004958241, EUW1_6003811368, EUW1_6002847479, EUW1_6002164371, EUW1_6002148723, EUW1_6015524685, EUW1_6015387328, EUW1_6015402003, EUW1_6014779337, EUW1_6014724668, EUW1_6014701498, EUW1_6014655368, EUW1_6014580839, EUW1_6014429620, EUW1_6014475971, EUW1_6014473252, EUW1_6013334881, EUW1_6013322375, EUW1_6012669749, EUW1_6012635347, EUW1_6012583396, EUW1_6010971941, EUW1_6006896961, EUW1_6006881165, EUW1_6006518887, EUW1_6015745842, EUW1_6015589872, EUW1_6014068520, EUW1_6014044304, EUW1_6007955310, EUW1_6003705297, EUW1_6003569783, EUW1_6002003834, EUW1_6000787500, EUW1_5994465297, EUW1_5993391050, EUW1_5992233473, EUW1_5992169601, EUW1_5984062877, EUW1_5984034743, EUW1_5983855739, EUW1_5983880569, EUW1_5983766086, EUW1_5982931745, EUW1_5982372929, EUW1_6005238786, EUW1_6005191249, EUW1_6005026992, EUW1_6005015187, EUW1_6004958241, EUW1_6002164371, EUW1_6002148723, EUW1_6002057259, EUW1_6002053660, EUW1_6002009239, EUW1_6002003834, EUW1_6001939719, EUW1_6001867883, EUW1_6001022392, EUW1_6000887143, EUW1_6000892356, EUW1_6000787500, EUW1_6000820954, EUW1_5996485374, EUW1_5994559073, EUW1_6010083174, EUW1_6010017420, EUW1_6006898776, EUW1_6006838293, EUW1_6005225782, EUW1_6005135031, EUW1_6003899867, EUW1_6003883079, EUW1_6003786523, EUW1_6002164371, EUW1_6002148723, EUW1_6002057259, EUW1_6002053660, EUW1_6002009239, EUW1_6001022392, EUW1_6000887143, EUW1_6000892356, EUW1_6000787500, EUW1_5999368247, EUW1_5999295110, EUW1_5989231240, EUW1_5989055249, EUW1_5987149834, EUW1_5978125118, EUW1_5969701977, EUW1_5969187233, EUW1_5956294382, EUW1_5955846040, EUW1_5949708234, EUW1_5934525960, EUW1_5916275391, EUW1_5916168691, EUW1_5916132470, EUW1_5907690529, EUW1_5897979620, EUW1_5897921186, EUW1_5896786548, EUW1_5880625543, EUW1_5880541891, EUW1_5878457213, EUW1_6015589872, EUW1_5969852994, EUW1_5969788713, EUW1_5940681289, EUW1_5940556247, EUW1_5937866203, EUW1_5937892773, EUW1_5937768916, EUW1_5937765393, EUW1_5934600651, EUW1_5934512860, EUW1_5934339533, EUW1_5932238516, EUW1_5932166008, EUW1_5932211862, EUW1_5929934534, EUW1_5930153889, EUW1_5931242804, EUW1_5919621815, EUW1_5918236611] The function which is used for getting the Id for the API call. /** * Getting the Team Members and their IDs * * #param {info_id|String} * #return Team Members IDs * #customfunction */ function getTeamMembersIDs(info_id) { try { startup(); var teamMembers = getTeamMembersSheet(); var riotIds = []; for (var counter = 0; counter != teamMembers.length; counter = counter + 1) { switch (info_id){ case "puuid": var data = buildURL("https://euw1.api.riotgames.com/lol/summoner/v4/summoners/by-name/"+teamMembers[counter]+"?api_key="+apiKey); var puuid = data["puuid"]; riotIds.push(puuid); break; case "id": var data = buildURL("https://euw1.api.riotgames.com/lol/summoner/v4/summoners/by-name/"+teamMembers[counter]+"?api_key="+apiKey); var id = data["id"]; riotIDs.push(id); break; case "accountId": var data = buildURL("https://euw1.api.riotgames.com/lol/summoner/v4/summoners/by-name/"+teamMembers[counter]+"?api_key="+apiKey); var accountId = data["accountId"]; riotIds.push(accountId); break; } } return riotIds } catch (err) { Logger.log('Failed with error %s', err.message); } } This Function is Used for Getting the Matches that got played per Team Member. /** * Getting the Data from the Api which matches got played * * #return the matches played * #customfunction */ function getMatchesPlayed() { try{ startup(); var puuids = getTeamMembersIDs("puuid"); var games = []; for (var counter = 0; counter != puuids.length; counter = counter + 1) { var data = buildURL("https://europe.api.riotgames.com/lol/match/v5/matches/by-puuid/"+puuids[counter]+"/ids?start=0&count=20&api_key="+apiKey) for(var counter2 = 0; counter2 != data.length; counter2 = counter2 + 1){ games.push(data[counter2]) } } return games }catch (err) { Logger.log('Failed with error %s', err.message); } } The function which should return the Matching Matches in the Array gets from the getMatchesPlayed function. /** * Checking the games for matches * * #return the matches which match * #customfunction */ function getMatchingMatches() { try{ var games = getMatchesPlayed(); var matchingMatches = []; Logger.log(games) const gettingGames = games.map(element => element) for (var counter = 0; counter != games.length; counter = counter + 1){ Logger.log(gettingGames[counter]) } }catch (err) { Logger.log('Failed with error %s', err.message); } }
As I understand, you need to get duplicate ids. Use the Set data structure for comparing the array values. // assume this should return an array [EUW1_6011808396, EUW1_6011824351] var games = getMatchesPlayed(); // var matched_games = [] // Initialise set data structure. var set = = new Set(); //Iterate over the games. Runtime complexity O(n) games.forEach((element) => { //the case when set does not contain the id we should add it to `set` if(!set.has(element)){ // O(1) set.add(element); // O(1) continue; } // if the set already contains the id, we should add it to the matching games array. matched_games.push(element); }) I hope this will help.
welcome to Stackoverflow! You have a lot of ways to store duplicate values In a new array, and this is one. // get duplicartes and store them in a array function getDuplicates(array) { let sorted = array.sort(); for (let i = 0; i < sorted.length - 1; i++) { if (sorted[i + 1] == sorted[i]) { duplicates.push(sorted[i]); } } }
Another way to get non-unique values const euws = ['EUW1_6011808396','EUW1_6011824351','EUW1_6011720277','EUW1_6010413995','EUW1_6010218048','EUW1_6010184913','EUW1_6010131700','EUW1_6009739853','EUW1_6008825456','EUW1_6008833322','EUW1_6008409245','EUW1_6008369887','EUW1_6008355242','EUW1_6007567238','EUW1_6007269146','EUW1_6007226284','EUW1_6007192332','EUW1_6005571988','EUW1_6005438941','EUW1_6005495312','EUW1_6013263286','EUW1_6013193252','EUW1_6012475324','EUW1_6012411610','EUW1_6012315128','EUW1_6012011561','EUW1_6011110477','EUW1_6011026046','EUW1_6009739853','EUW1_6006439870','EUW1_6006434580','EUW1_6005238786','EUW1_6005191249','EUW1_6005026992','EUW1_6005015187','EUW1_6004958241','EUW1_6003811368','EUW1_6002847479','EUW1_6002164371','EUW1_6002148723','EUW1_6015524685','EUW1_6015387328','EUW1_6015402003','EUW1_6014779337','EUW1_6014724668','EUW1_6014701498','EUW1_6014655368','EUW1_6014580839','EUW1_6014429620','EUW1_6014475971','EUW1_6014473252','EUW1_6013334881','EUW1_6013322375','EUW1_6012669749','EUW1_6012635347','EUW1_6012583396','EUW1_6010971941','EUW1_6006896961','EUW1_6006881165','EUW1_6006518887','EUW1_6015745842','EUW1_6015589872','EUW1_6014068520','EUW1_6014044304','EUW1_6007955310','EUW1_6003705297','EUW1_6003569783','EUW1_6002003834','EUW1_6000787500','EUW1_5994465297','EUW1_5993391050','EUW1_5992233473','EUW1_5992169601','EUW1_5984062877','EUW1_5984034743','EUW1_5983855739','EUW1_5983880569','EUW1_5983766086','EUW1_5982931745','EUW1_5982372929','EUW1_6005238786','EUW1_6005191249','EUW1_6005026992','EUW1_6005015187','EUW1_6004958241','EUW1_6002164371','EUW1_6002148723','EUW1_6002057259','EUW1_6002053660','EUW1_6002009239','EUW1_6002003834','EUW1_6001939719','EUW1_6001867883','EUW1_6001022392','EUW1_6000887143','EUW1_6000892356','EUW1_6000787500','EUW1_6000820954','EUW1_5996485374','EUW1_5994559073','EUW1_6010083174','EUW1_6010017420','EUW1_6006898776','EUW1_6006838293','EUW1_6005225782','EUW1_6005135031','EUW1_6003899867','EUW1_6003883079','EUW1_6003786523','EUW1_6002164371','EUW1_6002148723','EUW1_6002057259','EUW1_6002053660','EUW1_6002009239','EUW1_6001022392','EUW1_6000887143','EUW1_6000892356','EUW1_6000787500','EUW1_5999368247','EUW1_5999295110','EUW1_5989231240','EUW1_5989055249','EUW1_5987149834','EUW1_5978125118','EUW1_5969701977','EUW1_5969187233','EUW1_5956294382','EUW1_5955846040','EUW1_5949708234','EUW1_5934525960','EUW1_5916275391','EUW1_5916168691','EUW1_5916132470','EUW1_5907690529','EUW1_5897979620','EUW1_5897921186','EUW1_5896786548','EUW1_5880625543','EUW1_5880541891','EUW1_5878457213','EUW1_6015589872','EUW1_5969852994','EUW1_5969788713','EUW1_5940681289','EUW1_5940556247','EUW1_5937866203','EUW1_5937892773','EUW1_5937768916','EUW1_5937765393','EUW1_5934600651','EUW1_5934512860','EUW1_5934339533','EUW1_5932238516','EUW1_5932166008','EUW1_5932211862','EUW1_5929934534','EUW1_5930153889','EUW1_5931242804','EUW1_5919621815','EUW1_5918236611']; const nonUnique = euws.reduce((r, v, i, a) => { if (!r.includes(v) && a.indexOf(v) !== i) r.push(v); return r; }, []); console.log(nonUnique) .as-console-wrapper { max-height: 100% !important; top: 0 }
How to increment in forloop in random iterations?
I'm trying to add a random amount of "boulder" data into my "location" data. I want to use forloop to generate a random amount of boulders to put into each "location". I can't seem to get if I should use forEach or forLoop. In essence I want to know how to generate a forloop that increments in random iterations. (i.e. index=0, randomNum = 5 => nextIndex = 0+5, randomNum = 3, thirdIndex = 5+3 and so on) here's my randomNum generator const randomNum = (min, max) => { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min) + min) } and this is my boulder setting random forLoop (which doesnt work) const allBoulders = async() => {await Boulder.find().exec()} for (i=0, i < allBoulders.length; i+=upperCount;) { console.log(i) const area = location.area; const place = location.place; const latitude = location.latitude; const longitude = location.longitude; const boulderLocation = new Location({area: area, place: place, latitude: latitude, longitude: longitude}); const upperCount = indexCount + randomNum(1, 5) const boulderSet = allBoulders.slice(indexCount, upperCount); boulderLocation.boulders.push(...boulderSet); // await boulderLocation.save() console.log(boulderLocation) indexCount = upperCount; }; I'm getting the error: for (i=0, i < allBoulders.length; i+=upperCount;) { ^ ReferenceError: upperCount is not defined any help will be greatly appreciated!! thanks in advance! UPDATE[SOLVED]: I got it working thanks to answer from swift-lynx locations.forEach(async(location) => { const allBoulders = await Boulder.find().exec() // console.log(foundAllBoulders); for (let i = 0; i < allBoulders.length;) { const area = location.area; const place = location.place; const latitude = location.latitude; const longitude = location.longitude; const boulderLocation = new Location({area: area, place: place, latitude: latitude, longitude: longitude}); const random = randomNum(1, 5); const upperCount = i + random; const boulderSet = allBoulders.slice(i, upperCount); boulderLocation.boulders.push(...boulderSet); // await boulderLocation.save() console.log(boulderLocation); i += random; } }) i used a forEach so that i can call the async function, placed a forloop where the randomNum is generated in the loop with i, being iterated from the same randomNum set to const "random".
A loop incrementing randomly, using your randomNum function, can be done like this: const randomNum = (min, max) => { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min) + min); } // random increments for (let i = 0; i < 20; i += randomNum(1, 5)) { console.log(i); } If you want to use the random number inside of the for loop, you can do it like this: // random increments and use random number inside of for loop for (let i = 0; i < 20;) { // generate random number const random = randomNum(1, 5); // use it as you like console.log(random); // increment i manually at the end of the loop i += randomNum(1, 5); } The loop increments in random steps between 1 and 5, not including 5.
Trying to get the most inactive members from my guild
I'm using javascript and discord.js v12 n trying to make !inactive cmd, which get's the most inactive members from my server and then mute them. When I try to console.log(member) it says 'undefined' please help. Code: module.exports = { name: "inactive", description: "no", async execute(message, args, command, client, Discord) { if (!message.member.roles.cache.find(r => r.name === "Isäntä")) return message.channel.send("No perms") let userit = new Map() let time = ['21600000', '10800000', '7200000', '3600000', '14400000', '18000000']; //1-6h let muterole = message.guild.roles.cache.find(r => r.name === 'Muted') //mute role message.guild.members.cache.forEach(member => { if(member.roles.highest != message.guild.roles.cache.get("706922406257754132")) return; userit.set(member.id, member) }); if(userit.size == 0) return message.channel.send("None of users met requirements") const inactiveOnes = new Map() userit.forEach(member => { if (!member.lastMessage) return inactiveOnes.set(member.id, member) if (member.lastMessage.createdTimestamp <= Date.now() - 1209600000) return; inactiveOnes.set(member.id, member) }); if(inactiveOnes.size == 0) return message.channel.send("None of users met requirements") let random = Math.floor(Math.random() * 4)+1 let random_time = time[Math.floor(Math.random() * time.length)] for(let i = 0; i < random; i++ ){ const keys = inactiveOnes.keys(); let random2 = Math.floor(Math.random() * keys) const member = keys[random2]; console.log(member) console.log(keys) // member.roles.add(muterole.id) message.channel.send(`${member} you have been muted for being inactive! (Time: ${random_time}ms)`) setTimeout(() => { // member.roles.remove(muterole.id) message.channel.send(`${member} you have been unmuted!`) }, random_time) } } }
You missed a .length in the bottom for loop. const keys = inactiveOnes.keys(); let random2 = Math.floor(Math.random() * keys.length); const member = keys[random2]; console.log(member) console.log(keys) Without .length, random2 is set to NaN, causing the problem.
As theusaf mentioned, you missed a .length when getting a random number. const random2 = Math.floor(Math.random() * keys.length); However, even if you get a number, member will still be undefined. This is because inactiveOnes.keys() doesn't return an array, it returns a MapIterator. If you'd like to use array functionality, you could do one of two things. // 1: const keys = inactiveOnes.keyArray(); // 2: const keys = [...inactiveOnes.keys()];
(discord.js) How do I pick two different users from the guild?
So here's my command's code: module.exports = { name: 'test1', cooldown: '30', description: 'NaN', execute(message) { message.delete({ timeout: 10 }); const ranUser1 = message.guild.members.cache.random().user; const ranUser2 = message.guild.members.cache.random().user; const max = 100; const number = Math.floor(Math.random() * max) + 1; message.channel.send(`${ranUser1} ${ranUser2} ${number}%.`); console.log('\nExecuted command: !test'); }, }; And what I want to do is, when variable ranUser1 is equal to ranUser2 I want to "reroll" ranUser1 and then send the message with the changed variable. And I want to reroll this variable until it's not equal to ranUser2. The expected output would be to ensure two different users are selected instead of the same one twice.
A while loop should work. It will keep choosing a random user until it's not the same as the second user. You do have to dedine ranUser1 to a let instead of const since you will need to change it. module.exports = { name: 'test1', cooldown: '30', description: 'NaN', execute(message) { message.delete({ timeout: 10 }); let ranUser1 = message.guild.members.cache.random().user; // Converted to var so it can be changed const ranUser2 = message.guild.members.cache.random().user; while (ranUser1.id === ranUser2.id) { ranUser1 = message.guild.members.cache.random().user; } const max = 100; const number = Math.floor(Math.random() * max) + 1; message.channel.send(`${ranUser1} ${ranUser2} ${number}%.`); console.log('\nExecuted command: !test'); }, };
So I am not a complete expert on discord.js but I think I know the way to do so: module.exports = { name: 'test1', cooldown: '30', description: 'NaN', execute(message) { message.delete({ timeout: 10 }); function roll() { var ranUser1 = message.guild.members.cache.random().user; // constants aren't ideal if you want to be able to change them later var ranUser2 = message.guild.members.cache.random().user; if (ranUser1==ranUser2) { // you can do === for better accuracy roll() }; }; roll(); const max = 100; const number = Math.floor(Math.random() * max) + 1; message.channel.send(`${ranUser1} ${ranUser2} ${number}%.`); console.log('\nExecuted command: !test'); }, Not the best at making code beautiful but this should do.
A quick function that will reroll the variable until they aren't equal: var ranUser1; var ranUser2; function check() { ranUser1 = message.guild.members.cache.random().user; ranUser2 = message.guild.members.cache.random().user; if (ranUser1 === ranUser2) return check() const max = 100; const number = Math.floor(Math.random() * max) + 1; message.channel.send(`${ranUser1} ${ranUser2} ${number}%.`); console.log('\nExecuted command: !test'); } This way if they are the same it will attempt to pick two different users until it gets ones that are different. Here's an example with random number to show it in action: var ranUser1; var ranUser2; function check() { ranUser1 = Math.floor(Math.random() * (3 - 1 + 1)) + 1 ranUser2 = Math.floor(Math.random() * (3 - 1 + 1)) + 1 if (ranUser1 === ranUser2) return check() const max = 100; const number = Math.floor(Math.random() * max) + 1; console.log(`${ranUser1} ${ranUser2} ${number}%.`); console.log('\nExecuted command: !test'); } check()
Generate "Unique" 5 digits ID with javascript (99999 combinations) in random order
I want to generate an Unique 5 digits ID + 784 at the begining, the constraint, I can execute the script only one time, and I have to avoid the first 100 numbers so It can't be 00100 and lower. Since I use timestamp and I can execute only my script one time how I can handle this ? I did this it's maybe dumb but at least I tried. ConcatedID(); function ConcatedID() { var uniqID = checkProtectedRange(); if (checkProtectedRange()) { var BarcodeID = 784 + uniqID; return BarcodeID; } else checkProtectedRange(); } function checkProtectedRange() { var uniqueID = GenerateUniqueID(); var checkRange = uniqueID.substr(uniqueID.length - 3); var checkRangeINT = parseInt(checkRange); if (checkRangeINT <= 100) return (false); else return (true); } function GenerateUniqueID() { var lengthID = 5; var timestamp = + new Date(); var ts = timestamp.toString(); var parts = ts.split("").reverse(); var id = ""; var min = 0; var max = parts.length -1; for (var i = 0; i < lengthID; ++i) { var index = Math.floor(Math.random() * (max - min + 1)) + min; id += parts[index]; } gs.log('Generate ID ' + id); return id; }
Without being able to track previously used IDs, you're left with chance to prevent duplicates. Your shenanigans with Date doesn't really change that. See the birthday problem. Given that, just follow the most straight-forward method: Generate a random string consisting of five digits. function GenerateUniqueID() { return ('0000'+(Math.random() * (100000 - 101) + 101)|0).slice(-5); } Or, if you want just the final integer with constraints applied: function GenerateUniqueID() { return (Math.random() * (78500000 - 78400101) + 78400101)|0; }