Finding names of a channel array - discord.js

I want to create an array of strings by getting the names of the channels in a guild, but the methods I've tried haven't worked. This is my code, but the console.log doesn't send the array.
if (message.content.startsWith(`${prefix}command`)){
var channel_list = Array.from(message.guild.channels.name);
console.log(channel_list);
}

You're going to want to use Collection.prototype.map()
Discord.js v11.x
console.log(message.guild.channels.map((c) => c.name))
Discord.js v12.x
console.log(message.guild.channels.cache.map((c) => c.name))

Related

How can i make a guild-side variable using Discord.js

im trying to make a server/guild side variable for my bot (have a variable that has a different value in each server). I dont know how to make that so i really need help... How can i get a variable to have a different value in each server?
You should use a discord.js Collection, which is:
A Map with additional utility methods. This is used throughout discord.js rather than Arrays for anything that has an ID, for significantly improved performance and ease-of-use.
A Map object holds key-value pairs and remembers the original insertion order of the keys. Any value may be used as either a key or a value. Here's a quick demo:
// let's say we had two people: John and Sarah
const people = new Map();
// each of them were a different age
people.set('John', 25); // in this example, 'John' is the key, and 25 is the value
people.set('Sarah', 19); // in this example, 'Sarah' is the key, and 25 is the value
// each person has an individual age
// you can `get()` the key, and it will return the value
console.log(`Sarah is ${people.get('Sarah')} years old.`);
console.log(`John is ${people.get('John')} years old.`);
You can use this type of format to create a collection with each key being a different guild ID, and each value being... whatever you want. Here's an example:
// const { Collection } = require('discord.js');
const guilds = new Collection();
// put some data in an object as the key
guilds.set("Guild ID", {
name: "Guild Name",
welcomeMsg: "Welcome new person!",
welcomeChannel: "...",
blacklistedIDs: ["123456", "67890"],
});
client.on("guildMemberAdd", (member) => {
const guild = guilds.get(member.guild.id); // get the collection element via guild id
if (!guild) return;
// then access all its data!
console.log(`Somebody joined ${guild.name}`);
if (guild.blacklistedIDs.includes(member.id)) return member.kick();
guild.welcomeChannel.send(guild.welcomeMsg);
});
I believe Tin Nguyen posted this idea as a comment, I am just elaborating on that. To achieve what you want, you can use what is known as a "data dictionary" which is basically just a file storing a list of something.
For your specific use case, you can use a simple JSON file to store your variables. For each guild that your bot is in, you can add a new object to a list of objects in a local JSON file called variable.json for example.
Here is an idea of what it might look like:
[
{
"guild": "INSERT GUILD ID",
"value": "INSERT VARIABLE VALUE"
},
]
guild will store the id of the guild, so you can identify the correct value. To get the value stored in value for a certain guild, all you have to do is loop through the JSON file, and find the object with the correct guild ID:
const variables = require("variable.json"); //imports the JSON data
const value; //creates a new variable
for (i = 0; i < variables.length; i++) { //loops through the guilds
if (variables[i].guild === message.guild.id) { //if the IDs are the same...
value = variables[i].value; //...sets "value" to the retrieved value
}
}
This of course relies on the fact that your bot also adds each guild it joins to the list. To do this, you can use the guildCreate event. Documentation for this can be found here.

Find the first 300 members of the server

I want to create a bot that can tell me the list of the first 300 members of my server. Is this possible with Discord.js? Any help would be appreciated. I just don't know where to start
Assuming you want to get the first 300 members that joined the guild, you can use the GuildMember.joinedAt property. You would go through these steps:
Fetch all the members in the guild: you can use Guild.members.fetch() for that
Sort them by the date you get from the joinedAt property
Get the first 300
Here's how I would do it:
guild.members.fetch() // Fectch all the members in the guild
.then(members => {
let first300 = members
.sort((a, b) => a.joinedAt - b.joinedAt) // Order them by they date the joined the guild
.first(300) // Take the first 300
})
Like syntle asked it depends which kinda but, here's the first 300 to fetch:
Might not work since there might be an already set limit of members you can fetch
const members = await <Guild>.members.fetch({ limit: 300 });
//or if you are fine with cached
const members = <Guild>.members.cache.array();
members.length = 300;

Discord.JS Sharding Guild ID list problem

Im using Discord.JS Sharding and im trying to get all the guilds in from the 2 shards.
shard.broadcastEval("this.guilds.map(u => u.id).join('\\n')").then(result => {
console.log(result)
})
Note: Nodejs is not taking \n so it wants \\n to even work... and i think thats where my error is but idk how to fix
it gives me this
["389019673557073925","469387242767646730\n537085738509008896"]
i want it to give me this
["389019673557073925","469387242767646730", "537085738509008896"]
i tried forEach and many other ways... If you can help me that would be very helpful!
Try this it will give you an array of guild ids per shard
shard.broadcastEval("this.guilds.map(u => u.id)").then(result => {
for (var i = 0; i<result.length; i++){
console.log(result[i]);
}
});
Also it seems to return an array of arrays so I just gave it the index of the first array which is shard 0 and second is shard 1

Adding Nested Objects Arrays to Firestore

I have an array called Pages. My application allows users to add page objects to the page array. The data is then sent to Firestore. I've tried using a For Loop to iterate through each object in the array and send it to Firestore but it doesn't seem to be working. What am I doing wrong?
(I'm using Mobx instead of state to store info which is why I don't have this.state mentioned anywhere)
let id = Math.floor(Math.random() * 10000);
let docTitle = this.projectTitle.title;
for(let i = 0; i > this.pages.length; i++){
let pageT = this.pages[i].pageTitle;
let pageD = this.pages[i].pageDesc;
db.collection(docTitle + id).doc(pageT).set({
page: {pageTitle:pageT, pageDesc: pageD, blocks:['item', 'item'], id:'' }
})
.then(function() {
console.log("Document successfully written!");
})
.catch(function(error) {
console.error("Error writing document: ", error);
});
}
Accepted answer using forEach is inefficient creating a request for every array value, using n (array length) more write operations. (Not to mention the time it will take if using await on each write).
I'm using NodeJS/Javascript so this should work in React as well, but may need to be slightly modified, the key point is the ... (getSearchSubstrings returns an array):
db.collection(x).doc(y).update({
accountSearch: admin.firestore.FieldValue.arrayUnion(...getSearchSubstrings(username))
})
According to their Update elements in a array documentation, there are two ways of doing it:
// To add or remove multiple items, pass multiple arguments to arrayUnion/arrayRemove
const multipleUnionRes = await washingtonRef.update({
regions: admin.firestore.FieldValue.arrayUnion('south_carolina', 'texas')
// Alternatively, you can use spread operator in ES6 syntax
// const newRegions = ['south_carolina', 'texas']
// regions: admin.firestore.FieldValue.arrayUnion(...newRegions)
});
Use forEach (no need in i etc)
Key duplicated in bot doc I'd and inside object. Dont use title as key.
Flatten object that you gonna save.

Collection#find: pass a function instead

I'm fairly new to node.js and I'm working on a discord bot with discord.js, I'm am trying to do assigned roles with commands. When I do the code and type in the command it works successfully but pops up with "DeprecationWarning: Collection#find: pass a function instead" in the console, how can I get rid of this?
https://i.imgur.com/agKFNsF.png
This warning is caused by the following line:
var role = message.guild.roles.find('name', 'Epic Gamer');
On an earlier version of Discord.js, this would be valid, but they have now redone the find function. Instead of taking in a property and a value, you pass in a filtering function instead. This should work:
var role = message.guild.roles.find(role => role.name === "Epic Gamer")
Instead of passing in 'name' (the property), and 'Epic Gamer' (the value we want to search for/filter out), we pass in the arrow function role => role.name === 'Epic Gamer'. This is like mapping. find passes every role from message.guild.roles into the function as role, and then checks if the property we want equals the value we want.
If you would like to learn more about the find function, please check out the official documentation.
Pass a predicate function in find method, take a look at the discord.js document on the find function.
Change the find statement to
var role = message.guild.roles.find(role => role.name === 'Epic Gamer');
Hope this will help!

Resources