Bot's Cache and Fetching

Hey everyone, I'm looking to understand how the cache works and what would be the most efficient way to ensure that the I get the channel I need (similar thing goes for members/etc.) To get a channel from cache, I understand I need to run
const cachedChannel = client.channels.cache.get(channelId);
const cachedChannel = client.channels.cache.get(channelId);
Now, I'm aware that in case the bot does not have this in cache, even if channel is existent I won't get it To fetch the channel from discord, I need to
const channel = await client.channels.fetch(channelId)
const channel = await client.channels.fetch(channelId)
Now, does fetch first check whether the channel is existent in cache, or how does that part work exactly? What I'm looking to get is simply a way to edit it's name and potentially send a message there, here's my solution so far, but I'm not sure if it's ideal, and in the case fetch already checks cache it's likely unnecessary. (Example with getting a user, but would likely be similar for channels)
export default async function setChannelName(channelId: string, newName: string) {
const channel = (client.channels.cache.get(channelId) ||
(await client.channels.fetch(channelId))) as TextChannel | null;
if (!channel) {
throw new Error(`Channel with ID ${channelId} not found`);
}
await channel.setName(newName);
}
export default async function setChannelName(channelId: string, newName: string) {
const channel = (client.channels.cache.get(channelId) ||
(await client.channels.fetch(channelId))) as TextChannel | null;
if (!channel) {
throw new Error(`Channel with ID ${channelId} not found`);
}
await channel.setName(newName);
}
I simplified the example to assume the provided channelId will be a text channel, but of course that will be checked upon in a better way in the final version, cheers.
3 Replies
d.js toolkit
d.js toolkit2mo ago
- What's your exact discord.js npm list discord.js and node node -v version? - Not a discord.js issue? Check out #other-js-ts. - Consider reading #how-to-get-help to improve your question! - Explain what exactly your issue is. - Post the full error stack trace, not just the top part! - Show your code! - Issue solved? Press the button! - Marked as resolved by OP
treble/luna
treble/luna2mo ago
Fetch checks cache first And all guilds, roles and channels are cached by the Guilds intent So fetching isnt needed when you have it
imalfect
imalfectOP2mo ago
amazing, makes sense. Thank you for the help!

Did you find this page helpful?