#djs-help-v14
78874 messages · Page 27 of 79
Are there any guides or in-depth examples for how exactly you can use all of the sweepers/cache settings? I'm struggling to understand it all from just the docs.
ah nevermind I found the guide page
Can I see how you sent the message? The line of code
oh. lemme uhhhh write it in vanilla rq
Embeds dont mention users iirc
Embeds dont, containers do
I see, thats that new container thing
same result
async execute(interaction) {
const message = `<@${interaction.user.id}> ran: /test\n\n[#1345071213885526026 message](/guild/600311056627269642/channel/1345071213885526026/)\n\n-# <t:1751688935:f>`;
const container = new ContainerBuilder()
.addTextDisplayComponents(text => text.setContent(message));
await getChannel(config.logs.bot.channelID).send({ components: [container], flags: MessageFlags.IsComponentsV2 });
await interaction.reply('e');
}
If you're talking about turning off the reply mention, there's a different one to see
MessageMentionOptions#repliedUser discord.js@14.21.0
Whether the author of the Message being replied to should be pinged
Default value: true
Its a diff msg unfortunately, sent in another channel
Oh not the reply, mb
is something wrong?
Im not familiar with containers but the allowedMentions usage is correct, unsure why its still mentioning. Id assume it has something to do with containers
But you can test by sending a normal message that pings you
or any user, as it should block all user mentions
heh?
async execute(interaction) {
const message = new TextDisplayBuilder().setContent(`<@${interaction.user.id}>`);
await getChannel(config.logs.bot.channelID).send({ components: [message], flags: MessageFlags.IsComponentsV2 });
await interaction.reply('e');
}
what version of djs are you using?
could you show the output of npm ls discord.js?
Upgrade to latest
to elaborate, there were a few issues regarding allowedMentions and components v2 when cv2 initially released
these were fixed in 14.19.3
latest being 14.21.0
OH THAT WORKED tysm lol <33
hi, is there already docs for the guild tags?
I've seen that the guild tags is finally merged to the discord api
user.username ➞ d.js docs
user.globalName global display name (users only)
user.discriminator ➞ 0 | 1083 *
user.tag ➞ d.js docs | d.js docs#1083 *
* Note: The discriminator approach is mostly relevant to bots now, which are not currently transferred to the unique username system!
nope :((
#10962 in discordjs/discord.js by sdanialraza opened <t:1751492353:R> (changes requested)
feat: support user guilds
has yet to be merged
feel free to follow the pr
What node version are you on?
any documentation for gradients role added yet?
ah read up
how do we even start to read this shapeshift/builder error?
why go a custom validator route instead of just using zod?
zod sucked at the time
Then we tried ow, then shapeshift
Then somewhere along the line zod got good
i see
Admittedly this is a particularly bad logging of the error, are you using Node or something else?
Im currently using bun
It might log it differently, which doesn't help. I normally see which validator function failed
I'll snoop around, maybe it's included within the giant err log
At a guess it seems like a method that expected an anonymous function received undefined
So something like command.addStringOption()
With nothing in it
I isolated the issue to the containerBuilder, i'm reviewing the display components guide rn to find the correct syntax
If you share the container builder I can take a look
Section with no text or thumbnail maybe?
sure, thanks a lot by the way,
new ContainerBuilder().addSectionComponents(s => s.addTextDisplayComponents(s => s.setContent("Test!"))).addMediaGalleryComponents(
new MediaGalleryBuilder().addItems(
new MediaGalleryItemBuilder()
.setURL(images.wizard_banner)
.setDescription(
"Test Description!"
)
)
)
sry for messy syntax
Yep, sections require an accessory
It's definately in th sectionComponents part
ah okay, didn't think they'd be required
If you only want text, add a text display component without putting it in a section
Understood, thanks 👌
And yeah I agree - terrible error output for that error. It's not great on Node by any means but seems we haven't even looked at bun
I am not sure how widely adopted bun is so I don't think it's that much of an issue
is Manage Webhooks enough to create webhooks or the bot needs also manage channels?
you need manage webhooks and view channel
Morning folks. Does Client.uset.setAvatar() have some kind of cooldown?
I've got code that sets the bot avatar when it's loaded/ready. Tested it with one file. Works great, but when trying to change it again, it doesn't change the avatar, no errors reported.
// This worked
module.exports = {
name: Events.ClientReady,
async execute(client) {
client.user.setAvatar('/home/user/discord_bot_base/assets/avatar1.png')
.then(user => logger.info('Avatar set.'))
.catch(console.error);
}
};
// Code 5 minutes later...
module.exports = {
name: Events.ClientReady,
async execute(client) {
client.user.setAvatar('/home/user/discord_bot_base/assets/avatar2.png')
.then(user => logger.info('Avatar set.'))
.catch(console.error);
}
};
Possible. You really shouldn't change the bot's avatar that often
Yeah I'm not planning on changing it every 5 seconds. Basically because this is bot is going in multiple servers. The avatar should be customisable. So I'm setting it in the ready event. Unless that's how I shouldn't be doing it?
Basically trying to make to the bot set its avatar, name, etc. based on a config file for the server its in.
I believe that sets the avatar globally, not for a specific server. Guild profiles exist for bots? 🤔
Picture hasn't changed on the developer portal.
I'll have to check for a guild profile then. Any idea if there's docs for it?
Thats the App Icon, not the bot Avatar, what you're looking for is under the "Bot" tab
Ah yeah, found it. So that explains why it's not changing. Any idea where I can find this guild profile or is that something not in the API?
Ah... hold on...
from my knowledge, guild profiles don't exist for bots (I could be mistaken, perhaps double check with an expert), the only way I can think of to make a personalized bot avatar, is to make the user make their own bot, then give you the token, then you'd have to make some login logic and start the bot
https://stackoverflow.com/questions/73014930/change-bot-avatar-only-in-specific-guilds
I'f I'm reading that correctly, if I want different avatars I need to send interaction replies via a webhook?
That could work too... More reading for me. 😮💨
Bots cannot set per server pfp's
And i'm pretty sure the endpoint has a very strict ratelimit
So how do bots like Dyno accomplish it? Sending responses via a webhook, or...?
from an <Interaction>, which are all the type guards I should check to see if I can #showModal()?
you cant compare your bot to a bot like dyno
they have separate limits
to know how they do it, ask them
Not trying to compare, just trying to figure out how they implemented it. It's not urgent anyway, so I'll look at how to make my bot behave the way I need it. I think cal had the right idea though.
Its likely what cal said, mee6 and maki do it that way as well
Mystery solved then. Now to decide whether or not my bot needs a SQL or NoSQL database. Unless anyone wants to impart some wisdom? ^_^
personally i use pSQL but that would be a topic for #1081585952654360687 cuz its not djs related
Never been a fan of Postgres, but yeah might pop in there later if I've got anything further. Thanks.

You could check if the role is present in the guild first
is there a way to know if an ephemeral interaction has been closed by the user?
No
i would like to get the voice state of a button user.
ButtonInteraciton has
member : CacheTypeReducer<Cached, GuildMember, APIInteractionGuildMember>
but, I guess voice is not cached or something and therefore removed in the resulting type?
the functionality of the button assumes the user is in a channel-
You need to use the inCachedGuild type guard so TS knows the member will be present
ButtonInteraction#inCachedGuild() discord.js@14.21.0
Indicates whether this interaction is received from a cached guild.
ah, thank you. Is it reasonable to assume the guild is cached tho? are there cases when its not? im just curious.
also I remember you mark, you already helped me years ago when I started programming, thanks for your help in all times 😄
The guild isn't cached if it's a user install app
the command is supposed to be used in guild only-
Otherwise, it should be present unless you're missing the intent or otherwise clear the cache data
understood.
if i'm not wrong i can send Compoents V2 with webhooks right?
yes
ok then i'm so confused why i get an error with "empty message"
you need to specify withComponents: true
ah true thanks
that was my bad
this message should be updated now that the guide is live #1370478227872551032 message
with components v2 i have a tree like this
container
|----section
|----button
is it possible to change the button label when it's pressed?
sure, you have to pass in the new container into the update call
if you want to specifically swap one element you are best off giving it an id so you can identify it and iterate components recursively until you find it
or make it purposebound, if you know the structure you know where it is
if you have the full context you can also consider making a functiont hat spits out the component in its entirety based on some toggle parameter and use it in both the initial reply as well as the update
wdym purposebound?
also ye, ik that the exact path would be
components[0].components[2].accessory
I'm trying to make a translate message context command. I'm currently encountering an issue where non of my logic of the command is triggered when the user does not have the SendMessage permission in that channel, weirdly they are allowed to use application commands but the context will just return "Missing Permissions" even if the context does not include any message being sent in that channel. As mentioned none of the command logic is triggered. I would appreciate some guidance and a possible solution on that issue (without giving everyone SendMessage permissions)
if i edit a message with components v2, i have to keep or remove the flag in the edit function?
Thats nothing djs can do about
Since its discord sending that error
i have a problem, i trying to use event interactionCraete for button , the customId is undefined
Show the full code instead of some very badly cropped screenshots
The order of function parameters must match between definition and function call.
function execute(client, interaction) { ... };
execute(interaction, client);
- mismatch! you pass an interaction where the client is expected
- mismatch! you pass the client where an interaction is expected
same problem
Client imported from discord.js
async execute(client: Client, interaction: ButtonInteraction) {
thats not your issue though
you likely swapped your parameters
Look at your event handker
async handleEvents(eventFiles: string[]) {
info("Starting to load events...");
try {
for (const file of eventFiles) {
const { default: event } = await import(`../events/${file}`);
if (event.once) {
this.once(event.name, (...args) => event.execute(...args, this));
} else {
this.on(event.name, (...args) => event.execute(...args, this));
}
}
success("Successfully loaded all events!");
} catch (err) {
error(err as string);
}
}
this my event handler
so exactly this
ok thx
CombinedPropertyError (1)
Received one or more errors
input[4]
| CombinedPropertyError (1)
| Received one or more errors
|
| input.value
| | ValidationError > s.string()
| | Expected a string primitive
| |
| | Received:
| | | [Object]
at _ArrayValidator.handle (/Users/lucas/Documents/LucasProject/starskybot/node_modules/@sapphire/shapeshift/dist/cjs/index.cjs:1254:70)
at _ArrayValidator.parse (/Users/lucas/Documents/LucasProject/starskybot/node_modules/@sapphire/shapeshift/dist/cjs/index.cjs:972:90)
at EmbedBuilder.addFields (/Users/lucas/Documents/LucasProject/starskybot/node_modules/@discordjs/builders/dist/index.js:235:31)
at Object.execute (/Users/lucas/Documents/LucasProject/starskybot/Commands/Giveaway/giveaway.js:458:16)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
at async Object.execute (/Users/lucas/Documents/LucasProject/starskybot/Events/interactionCreate.js:81:7)
const logEmbed = new EmbedBuilder()
.setColor(0x2f3136)
.setTitle("🎉 Giveaway Created")
.addFields(
{ name: "🎁 Prize", value: giveawayPrize, inline: true },
{
name: "⏳ Duration",
value: formatDuration(ms(giveawayDuration)),
inline: true,
},
{
name: "🏆 Winners",
value: giveawayWinnerCount?.toString() || "1",
inline: true,
},
{
name: "📅 Ends At",
value: `<t:${Math.floor(endTime.getTime() / 1000)}:F>`,
inline: true,
},
{
name: "👤 Hosted By",
value: host || interaction.user || "N/A",
inline: true,
},
{ name: "📌 Channel", value: giveawayChannel.toString(), inline: true },
{ name: "💎 Bonus Role", value: bonusText, inline: true },
{ name: "📎 Extra Data", value: extraDataText, inline: false },
{
name: "🖼️ Image URL",
value: image || "None",
inline: false,
},
{
name: "🖼️ Thumbnail URL",
value: thumbnail || "None",
inline: false,
}
)
.setFooter({ text: `Giveaway ID: ${interaction.id}` })
.setTimestamp();
please help me fix
value needs to be a string
Its an object somewhere
Is using TypeScript with Discord.js very complicated?
Depends if you think typescript is complicated
The "with discord.js" isn't
i see, thank you 
am i seeing correctly that user.primary_guild is merged to main but not released yet?
It hasn't been merged yet
#10962 in discordjs/discord.js by sdanialraza created <t:1751492353:R> (changes requested)
feat: support user guilds
ohh i was looking at a docs pr
right, thanks
Hi,
How can an awaitMessageComponent trigger an "interaction failed" error ?
Thanks
by you not responding to the collected interaction
The promise never resolves, actually
show your code
const [result] = await Promise.allSettled([
message!.awaitMessageComponent({
filter: interaction => interaction.user.id === userId,
time: 5 * 60 * 1000
})
]);
consoleLog(result);
if(result.status === 'fulfilled')
resolve(result.value);
else
remove!();
consoleLog is never reached
and how is message defined
how is userid defined
let message: Message, userId: string, remove;
if(parent instanceof Message){
message = parent;
userId = parent.interactionMetadata!.user.id;
remove = () => interaction!.deleteReply();
}
if(parent instanceof MessageComponentInteraction){
message = parent.message;
userId = parent.user.id;
remove = () => parent.deleteReply();
}
if(parent instanceof InteractionCallbackResponse){
message = parent.resource!.message!;
userId = parent.resource!.message!.interactionMetadata!.user.id;
remove = () => interaction!.deleteReply();
}
if(parent instanceof InteractionResponse){
message = await parent.fetch();
userId = parent.interaction.user.id;
remove = () => message.delete();
}
Did the collector collect anything?
Good question.
So I put a console.log inside filter, and no
Well, what happened is I passed the wrong interaction. 😅
Do i need MessageContent and GuildMessages intent to access to emojis events and messageCreate event ?
GuildExpressions for emojis, GuildMessages for messages
and Guilds for any guild-related event
MessageContent, like the name says, is only required for message content
- Websocket intents limit events and decrease memory usage: learn more
- See what intents you need here
message_reference[MESSAGE_REFERENCE_UNKNOWN_MESSAGE]: Unknown message js message.reply({ content: `GG`, allowedMentions: { users: [] } }).catch(console.error);
is it possible that the user deleted the message beffore the bot replies?
you need add user ids
allowedMentions: {users: ["USER_ID"]}
or remove that line
or use this instead of that
allowedMentions: {repliedUser:true}
yeah it possible
Is there a way to have the Message Create event without having the intent, because i don't want to have all messages cached?
That depends on what's supposed to happen before the attempted reply and whether a human can realistically delete the message beforehand, but yes, it's possible to have a Message instance for a message that no longer exists on Discord
If message is for an ephemeral interaction response, that would be another reason for the error you're getting
no for the first part, but you can limit the message cache to 0
Miscellaneous: Cache customization - Limiting caches
read more
no, you can send an empty array perfectly fine, the error also has nothing to do with allowed mentions
oh, really?
Is disabling all of them can cause a problem?
the linked guide article explains it
if you want no caching at all you can simply use @discordjs/core
TypeError: Cannot read properties of undefined (reading 'style')
const confirmButton = ({ style = ButtonStyle.Success, label = "gg", date = Date.now() }) => new ActionRowBuilder().addComponents(
new ButtonBuilder().setCustomId(`gg-${date}`).setLabel(label).setStyle(style).setEmoji(Emojies.truee)
);```
What's the full error including stack? I don't see how that code block could produce that error
What's line 153/357 of logs.js? Assuming one is a part of a function and the other is calling that function?
yes, in logs.js, x will be called (153), then x will call confirmButton (357)
Showing the actual code would be necessary. One of them is the source of the error
Is it normal that my bot takes up 1GB of memory?
Maybe
please refrain from responding with AI to help others
oh sorry
but my bot is only in one server
If the bot's database is modified, it will send a message describing what was changed and the file
How many members are in the server, are you listening to the messageCreate event? There's many factors into what could increase your memory usage
91 members(including bots)
I'm listening to almost all events
Well that would do it. You might need to set up some sweeper settings for your caches
I don't think that's unusual.
if it helps at all, mine takes up a little more than that with about five times the members. im listening to a fair amount of events and i do cache quite a bit of data locally for some things, so i cant say its unusual
No. 1GB is not unusual. Maybe a little for <100 members...but if you're listening to every event, then you're going to have to do some cache clearing to get under 1GB or just deal with it
So the solution is:
Clear cache every hour or stop listening to some unnecessary events?
^
not listening is not enough though, you'd need to also remove their intents so djs doesn't cache their data
because it wouldn't receive their events at all
Miscellaneous: Cache customization
read more
are there any premade functions to make unix timestamps like these? https://sesh.fyi/timestamp/
or should i just make them on my own (question is stability)
time discord.js@14.21.0
Formats a date into a short date-time string.
They aren't Unix timestamps though
well thats only what i want
Not really a djs question. JS doesn't really use Unix timestamps, it formats in ms instead of seconds. Dividing by 1000 is stable
The website that got linked generates discord timestamps though, so they probably don't actually want Unix timestamps
In which version of d.js app can read user's tag?
In the next version
#10962 in discordjs/discord.js by sdanialraza created <t:1751492353:R> (changes requested)
feat: support user guilds
does anyone know why this code throws max callstack flatten?
export class CustomSlashBuilder extends SlashCommandBuilder {
extraSettings: { allowDM: boolean; adminOnly: boolean };
constructor(private bot: Client) {
super();
this.extraSettings = { allowDM: true, adminOnly: false };
}
setALlowDm(enabled?: boolean) {
this.extraSettings.allowDM = enabled !== undefined ? enabled : !this.extraSettings.allowDM;
return this;
}
setAdminOnly(enabled?: boolean) {
this.extraSettings.adminOnly = enabled !== undefined ? enabled : !this.extraSettings.adminOnly;
return this;
}
autoSet(...args: LocaleHeader) {
this.setName(this.bot.localeHandler.getDefaultLocalization(...this.bot.localeHandler.addKey("name", ...args)));
this.setDescription(this.bot.localeHandler.getDefaultLocalization(...this.bot.localeHandler.addKey("description", ...args)));
this.setNameLocalizations(this.bot.localeHandler.generateLocalizationMap(...this.bot.localeHandler.addKey("name", ...args)));
this.setDescriptionLocalizations(this.bot.localeHandler.generateLocalizationMap(...this.bot.localeHandler.addKey("description", ...args)));
return this;
}
toJSON(): SlashCommandBody {
const { allowDM, adminOnly } = this.extraSettings;
const json = super.toJSON();
console.log(json);
return {
...json,
allowDM,
adminOnly
};
}
}
when is the client.user null?
When the client isn’t logged in
Because SlashCommandBuilder#toJSON() serializes all properties. you added an enumerable .bot: Client property but that fails to be JSONified
so, how can i fix it?
By not extending SlashCommandBuilder like that, by not calling super.toJSON() or by not making your bot property enumerable
Am I correct in thinking setAuthor() can take a local file for the iconUrl property?
const embed = new EmbedBuilder()
.setTitle('Title')
.setColor(0xABCDEF)
.setAuthor({
name: "Bob",
iconURL: new AttachmentBuilder(...)
...
});
what is the max length of a text display content? is it 2000 or 4000?
(forgot to remove reply, wnated to add context but then was un-needed)
tag suggestion for @regal lion:
Files in embeds should be attached via the message option object and referenced in the embed:
const attachment = new AttachmentBuilder('./image.png', { name: 'image1.png' });
const embed = new EmbedBuilder()
.setTitle('Attachments')
.setImage(`attachment://${attachment.name}`);
channel.send({
embeds: [embed],
files: [attachment]
});
all text across all text display components cannot exceed 4000 characters
so 4k if i just use a text display and 1 action row with 2 buttons?
Yes
like that?
bot: Client | undefined;
constructor(_bot: Client) {
super();
Object.defineProperty(this, "bot", {
value: _bot,
writable: false,
configurable: false,
enumerable: true
});
this.extraSettings = { allowDM: true, adminOnly: false };
}
Probably need a declare in that first line
And you don't want it enumerable
@steel trail, apologies for ping. I'm not trying to attach a file to the embed, that works already.
I'm basically trying to set the author icon URL to a local file rather than a hosted image.
// So instead of
.setAuthor({
name: "Bob",
iconURL: 'https://example/image.png'
})
// I want to do something like
.setAuthor({
name: "Transit-X",
iconURL: 'file:///some/dir/image.png'
})
Disregard that. Typo on my end.
you just put "attachment://image.png" for your icon url, as shown in the tag messages of the d.js app
^ this one
yeah I fixed it. accidentally typo'd something on my end so it was adding it as an image to the message instead.
ah didnt see that, mb
i use typescript and thank you
No worries pal. 🙂
if a bot doesnt have use external emojis permission it cant use application emojis or can it
it can
hello im new with this component v2 can anyone help, already installed latest packages
CombinedError (2)
Received one or more errors
1 ExpectedValidationError > s.instance(V)
| Expected
|
| Expected:
| | [Function: ButtonBuilder]
|
| Received:
| | undefined
2 ExpectedValidationError > s.instance(V)
| Expected
|
| Expected:
| | [Function: ThumbnailBuilder]
|
| Received:
| | undefined
at _UnionValidator.handle (D:\all_sb\savina_ticket\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:1965:23)
at _UnionValidator.parse (D:\all_sb\savina_ticket\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:972:90)
at SectionBuilder.toJSON (D:\all_sb\savina_ticket\node_modules\@discordjs\builders\dist\index.js:2169:37)
at D:\all_sb\savina_ticket\node_modules\@discordjs\builders\dist\index.js:1870:64
at Array.map (<anonymous>)
at ContainerBuilder.toJSON (D:\all_sb\savina_ticket\node_modules\@discordjs\builders\dist\index.js:1870:35)
at D:\all_sb\savina_ticket\node_modules\discord.js\src\structures\MessagePayload.js:151:46
at Array.map (<anonymous>)
at MessagePayload.resolveBody (D:\all_sb\savina_ticket\node_modules\discord.js\src\structures\MessagePayload.js:150:49)
at TextChannel.send (D:\all_sb\savina_ticket\node_modules\discord.js\src\structures\interfaces\TextBasedChannel.js:189:32)
Your section has no accessory
use a text display component instead if you don't want a button or thumbnail on the right side
Popular Topics: Display Components
read more
i need it
Yes, sections need an accessory
If you dont need an accessory you dont need a section
const balanceButton = new ButtonBuilder()
.setCustomId(`order_balance_${dealCode}_${targetUser.id}`)
.setLabel('💰 Số Dư')
.setStyle(ButtonStyle.Primary);
const bankButton = new ButtonBuilder()
.setCustomId(`order_bank_${dealCode}_${targetUser.id}`)
.setLabel('🏦 Chuyển Khoản')
.setStyle(ButtonStyle.Secondary);
const confirmButton = new ButtonBuilder()
.setCustomId(`order_confirm_${dealCode}_${targetUser.id}`)
.setLabel('✅ Đã Xác Nhận')
.setStyle(ButtonStyle.Success);
const cancelButton = new ButtonBuilder()
.setCustomId(`cancel_order_${dealCode}`)
.setLabel('❌ Hủy')
.setStyle(ButtonStyle.Danger);
const titleSection = new SectionBuilder()
.addTextDisplayComponents(
new TextDisplayBuilder().setContent(`##  Xác Nhận Đơn Hàng\n`
+ `**Mã đơn hàng:** \`${dealCode}\`\n`
+ `**Khách hàng:** ${targetUser.username} (<@${targetUser.id}>)\n`
+ `**Sản phẩm:** ${product}\n`
+ `**Số lượng:** ${quantity}\n`
+ `**Tổng tiền:** ${amount.toLocaleString('vi-VN')}đ\n`
+ `**Số dư hiện tại:** ${parseInt(userBalance).toLocaleString('vi-VN')}đ\n`
)
)
.setThumbnailAccessory(new ThumbnailBuilder().setURL('https://cdn-icons-png.flaticon.com/512/3081/3081840.png'));
const paymentSection = new SectionBuilder()
.addTextDisplayComponents(
new TextDisplayBuilder().setContent('###  Phương Thức Thanh Toán ')
)
const balanceSection = new SectionBuilder()
.addTextDisplayComponents(
new TextDisplayBuilder().setContent('**Số Dư:** Thanh toán bằng số dư tài khoản')
)
.setButtonAccessory(balanceButton);
const bankSection = new SectionBuilder()
.addTextDisplayComponents(
new TextDisplayBuilder().setContent('**Chuyển Khoản:** Thanh toán qua ngân hàng')
)
.setButtonAccessory(bankButton);
const confirmSection = new SectionBuilder()
.addTextDisplayComponents(
new TextDisplayBuilder().setContent('**Đã Xác Nhận:** Admin xác nhận đã thanh toán')
)
.setButtonAccessory(confirmButton);
const cancelSection = new SectionBuilder()
.addTextDisplayComponents(
new TextDisplayBuilder().setContent('**Hủy:** Hủy đơn hàng này')
)
.setButtonAccessory(cancelButton);
const mainContainer = new ContainerBuilder()
.setAccentColor(0x0099ff)
.addSectionComponents(titleSection)
.addSeparatorComponents(new SeparatorBuilder().setSpacing(SeparatorSpacingSize.Large))
.addSectionComponents(paymentSection)
.addSectionComponents(balanceSection)
.addSectionComponents(bankSection)
.addSectionComponents(confirmSection)
.addSectionComponents(cancelSection);
// Send order message
const orderMessage = await message.reply({
flags: MessageFlags.IsComponentsV2,
components: [mainContainer]
});

this is my codes check it pls
check your payment section..
no, we told you what the error was
Check your own code pls
I think you have everything now to fix it yourself
fixed thanks, and one more error is Large is not defined of SeparotorSpacingSize
you sure you imported it?
yes i did
can you show
const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, MessageFlags, SectionBuilder, SeparatorBuilder, SeparatorSpacingSize, TextDisplayBuilder, ThumbnailBuilder, ContainerBuilder } = require("discord.js");
hm then idk what happened
you can use .setSpacing(2) tho, that should work
but that shouldn't be needed, normally the enum would work too
You spelt that wrong
but not in the code right?
got thanks !
What’s the nonce used for? Can you put random shit in there?
what is your d.js version? run npm ls discord.js in your terminal
Hello, trying to log oldMessage.content with MessageUpdate, I need to fetch every channels of the guild when bot is starting to get the content? I have MessageContent/Message intents & Message Partial
Like can I encode some stuff in the nonce, then that message will have buttons on it then when the interaction is pressed I can check the interaction.message.nonce
no. if the oldMessage isnt cached before, you wont have its content since its a partial
fetching it is not gonna work either since you are fetching the updated message
Not sure if nonce will be present on any other event than messageCreate
But if I fetch all messages in channel when bot is starting?
yeah no
It's meant for deduplication mostly
PS D:\all_sb\savina_ticket> npm ls discord.js
plextickets@2.0.4 D:\all_sb\savina_ticket
├─┬ discord-html-transcripts@3.2.0
│ └── discord.js@14.21.0 deduped
└── discord.js@14.21.0
So it’s not like something I can use to store something
you would have to store the content somewhere in a database
So if the bot restart, content is just null and there's no way to get the content
not natively, yes
okay then I have no clue why you cannot use the SeparatorSpacingSize enums
Does it have other uses then deduplication?
thanks
You really shouldn't. Storing it outside of discord means you now need to include it in your privacy policy and take care of data retention
Yes, I will just display "Message not cached" if i don't have the content, that's all xd
No storing all messages or something else
is it possible to use v2 components with v1 components?
no, or well, depends on what you consider 'v1 components'
you can use buttons and string selects etc yes
but no embeds etc
ty
hello everyone
https://cdn.discordapp.com/nameplate-presets/nameplates/nameplates_v3/bonsai.png?size=128
who's know the url to get nameplate image ?
this is a question for #useful-servers ddevs
components v2 is a superset of the legacy components. so they are included in it
i have two bots that use same codebase . i wanna use same application emojis for both. but bots cant share application emojis . guild emojis have use external emoji permission drawback. is there another way?
upload them to both apps
interaction.user.role.add('<roleID>') <--- what is wrong
you have to use .member object, not .user object
so js interaction.member.roles.add('<roleID>');
When you query a user, Discord also has a field that displays the user's tag. Is it possible to query this directly in discord.js? Is it currently always done directly via the API?
hi, I want to check the usage of my server's stickers. I add a handler onMessageCreate event that detect if (message.stickers.size > 0) but the sticker does not have all info, like guildId (is null). Is there anyway to fetch this info without fetching all stickers of the server?
Unfortunately, Discord doesn’t provide full sticker info like the guild ID when a sticker is used in a message, so there’s no direct way to get that without caching or fetching all stickers manually.
sadge
thanks for the reply
No worries
does emojis.cache.get support with brackets (example:
client.emojis.cache.get("<:a:id>")
No, ID only

not yet, it will be in the next release
Okay thanks
documentation suggestion for @dapper oyster:
parseEmoji discord.js@14.21.0
Parses emoji info out of a string. The string must be one of:* A UTF-8 emoji (no id)* A URL-encoded UTF-8 emoji (no id)* A Discord custom emoji (<:name:id> or <a:name:id>)
thanks
Is there an approximate time when this will be released?
C:\Users\Uzivatel\Desktop\Langs\js+ts\node.js\discord.js\savesbot\node_modules\@sapphire\shapeshift\src\validators\StringValidator.ts:108
return (options as ValidatorOptions)?.message === undefined;
^
ValidationError: Expected a string primitive
at _StringValidator.handle (C:\Users\Uzivatel\Desktop\Langs\js+ts\node.js\discord.js\savesbot\node_modules\@sapphire\shapeshift\src\validators\StringValidator.ts:108:53)
at _StringValidator.parse (C:\Users\Uzivatel\Desktop\Langs\js+ts\node.js\discord.js\savesbot\node_modules\@sapphire\shapeshift\src\validators\BaseValidator.ts:126:2)
at validateDescription (C:\Users\Uzivatel\Desktop\Langs\js+ts\node.js\discord.js\savesbot\node_modules\@discordjs\builders\src\interactions\slashCommands\Assertions.ts:33:23)
at validateRequiredParameters (C:\Users\Uzivatel\Desktop\Langs\js+ts\node.js\discord.js\savesbot\node_modules\@discordjs\builders\src\interactions\slashCommands\Assertions.ts:54:2)
at MixedClass.runRequiredValidations (C:\Users\...\node.js\discord.js\savesbot\node_modules\@discordjs\builders\src\interactions\slashCommands\mixins\ApplicationCommandOptionBase.ts:48:3)
at MixedClass.toJSON (C:\...\js+ts\node.js\discord.js\savesbot\node_modules\@discordjs\builders\src\interactions\slashCommands\options\string.ts:61:8)
at <anonymous> (C:\Users\Uzivatel\Desktop\Langs\js+ts\node.js\discord.js\savesbot\node_modules\@discordjs\builders\src\interactions\slashCommands\mixins\SharedSlashCommand.ts:159:49) at Array.map (<anonymous>)
at MixedClass.toJSON (C:\Users\Uzivatel\Desktop\Langs\js+ts\node.js\discord.js\savesbot\node_modules\@discordjs\builders\src\interactions\slashCommands\mixins\SharedSlashCommand.ts:159:26)
at <anonymous> (C:\Users\Uzivatel\Desktop\Langs\js+ts\node.js\discord.js\savesbot\index.ts:10:59) {
validator: 's.string()',
given: undefined
}
exception details my ass
One of your slash command options has an undefined value instead of a string
thank you
method to add default?
You should read your error stacks more closely. That's all I did
i did it just that i didnt really understand it, i mean i saw that its something wrong with my options but this explaining is so hard to understand
i am currently looking at https://discord.js.org/docs/packages/discord.js/14.21.0/SlashCommandBooleanOption:Class i have no idea how to fix this
Can you show a snippet of your code where you define your slash command?
payload: new SlashCommandBuilder()
.setName("analyze")
.setDescription("Analyze a code and return it readable and parsed.")
.addStringOption(option => option
.setName("code")
.setRequired(true)
)
.addBooleanOption(option => option
.setName("blur_token")
.setRequired(false)
)
``` heres the command payload (i expect is causing the issue)
i assume its the boolean option somehow
There's no description on either of those options
there has to be??? i mean yeah
sorry i forgor thanks
idk what a "string primitive" is (string or string subclass)
if the message is sent on a thread channel inside a channel, how to get channel id of the channel where that thread is
ThreadChannel#parentId discord.js@14.21.0
The id of the parent channel of this thread
i am literally blind lol
hi I need help with getting user profile data especially with avatar decoration
after I authorize my bot and redirect it to my backend callback link i have saved data showed on screenshot (i have covered it cause i do not know is it any secret data) and is it possible to get simple gif link directly to only avatar decoration like my pink cat ears
User#avatarDecorationURL() discord.js@14.21.0
A link to the user's avatar decoration.
if you're using @discordjs/rest, you can use <REST>.cdn.avatarDecoration()
if not, since it sounds like you're implementing oauth2, it doesn't sound like you're using discord.js
therefore further questions would probably be better suited to the discord developers server in #useful-servers
oh and it's not really 'secret data'
asset hashes in particular are just public and the same for everyone with the same decoration
I don't believe any info can be gotten just from a sku id, but either way just the data you've shown is easily accessible from any app
There's validateDescription between the things you circled, that's even more helpful
This is probably me being a little psycho about security, but... I want to verify that an Attachment is either zip or rar, and I'm using the mime package on upload.contentType. Is there any way to fake that, which would then require me to check the download too, or is Attachment#contentType pulled from the file?
Now that I think about it that's kind of a stupid question innit. Discord isn't that dumb about security
how to check a server is not activated community options?
you'd want to check <Guild>.features
Guild#features discord.js@14.21.0
An array of features available to this guild
v10: GuildFeature - Community
read more
ty
and how to disable throwing InteractionCollectorError
you can’t disable an error
catch (e) {if (e instanceof InteractionCollectorError) return;}
#not recommended
if it’s not recommended then why suggest it?
well... it does do what he wants it to do
recommended: use stack trace to figure out why you're getting that specific error. best to send some code to if you need help debugging
timeout error ._.
then you're taking too long to reply to the interaction. if you don't defer it, you need to respond to it in under 3s
no, i mean collection timed out
still need to respond in under 3 seconds regardless of deferring or not
technically. since deferring it is also replying to it. so yea. hm.
deferreply().editReply
there's a parameter when you make a collector to change the timeout duration
best combo
are you using one of the promisified collectors?
some awaitX method?
if so, that's how you determine whether nothing was collected or not
if you want something more indefinite, consider just using a persistent event listener
like that?
const collector = await msg
.awaitMessageComponent({
componentType: ComponentType.Button,
time: ms("5m"),
filter: (int) => {
if (int.user.id == user.id) return true;
else {
return false;
}
}
})
if you're having it wait for 5m, it's best that you use an event listener. like duck said
to elaborate, you can just increase the timeout if that's what you're looking for, but you'd still want to catch the error and handle it timing out
Do you want it to not time out or just catch the error of when it does instead of it being logged uncaught?
yeah
That was an "or" question
how dyu reply to an or question with yeah 
havent coded a discord bot in so long... how do i get the attachment from addAttachmentOption in SlashcommandBuilder
<ChatInputCommandInteraction>.options.getAttachment()
guide suggestion for @waxen mirage:
Slash Commands: Parsing options
read more
data: new SlashCommandBuilder()
.setName('upload-uniform')
.setDescription('Uploads the uniform image to roblox')
.setDefaultMemberPermissions(PermissionsBitField.Flags.Administrator)
.addStringOption(o => o.setName('name').setDescription('The name of the image.').setRequired(true))
.addAttachmentOption(a => a.setName('image').setDescription("Image to be uploaded").setRequired(true))
.addStringOption(o => o.setName('description').setDescription('Description of the image').setRequired(false)),
async execute(interaction, client){
const name = interaction.options.getString('mame')
const description = interaction.options.getString('description')
const attachment = interaction.options.getAtttachment('image')```
*TypeError: interaction.options.getAtttachment is not a function*
triple t
attachment has 3 Ts, not 4
im so stupid
||use typescript|| nah issok we've all been there
nope, typescript scares me
Is there a way to sync the perms of a voice channel to its parent?
I know you can via the client with the "Sync" option but does that exist for bots?
This one:
documentation suggestion for @shut musk:
GuildChannel#lockPermissions() discord.js@14.21.0
Locks in the permission overwrites from the parent channel.
ah its called lock, i was looking for sync
ty
emoji id wont be same
correct
so handle that based on the application id
run an 'injection' code when your app starts. make sure the names of the emojis in both applications are the same. make a const object, values being the emoji names. then find the emojis in applications.emojis.cache (after fetching once) and replace the value in the object
fetch application emojis on login, find by name not by id whenever used
i personally prefer 2 name > emoji maps but true, that works
Is changing nicknames, changing roles on a member, and moving members voice channels all under the same rate limit bucket? Or do they each have their own seperate ratelimits?
Ratelimits are dynamically assigned by the API based on current load and may change at any point.
- The scale from okay to API-spam is sliding and depends heavily on the action you are taking
- Rainbow roles, clock and counter channels, and DM'ing advertisements to all members are all examples of things that are not okay
also not really a question for djs, more for #useful-servers ddevs
does djs already return the new discord badges and guild tags?
what new badges?
and guild tags has a PR that has not been merged yet
for example quest badge
that isn't documented, nor has a flag for the api to check
any eta? its about time
when it's ready
you need to have patience
no problem
you'll have to ask discord for that either way, not here
We are not Discord, just some nerds who develop Discord bots!
- /report appeals and age updates
- /howtoreport reports (harassment/hacking/spam/abuse)
- /support anything Discord related
- /billing payment/nitro
- /feedback feedback/feature requests
djs can't support something discord hasn't added
i think they referred to the guild tags, which were documented recently. it’s just the d.js pr that hasn’t merged yet
ah, I misread that, thought it was about the flag, my bad then
nono it’s fine
On button clicks:
What's the correct way to update components V2? e.g. remove buttons etc.
Also, is there a way to use interaction.update after an api call (in case that takes more than 3 seconds) based on the result since you can't defer interaction.update?
the correct way is the only way, to edit the message sending the new components
if you want to create builders based on the current data you can use djs' helper
createComponentBuilder discord.js@14.21.0
Factory for creating components from API data.
as for the latter, you can defer an update
ButtonInteraction#deferUpdate() discord.js@14.21.0
Defers an update to the message to which the component was attached.
// Defer updating and reset the component's loading state
interaction.deferUpdate()
.then(console.log)
.catch(console.error);
for any component interaction (including a modal shown from a component)
how to set voice channel status
Not possible, the API is not documented
well i was using the API but i wanted to use djs instead
We dont support undocumented features
You could use the REST module though
how do i use REST on djs?
client.rest
alright ty
Question! I see that role.members returns the cached guild members that have a role. If I don't want the cache, but instead the actual number, how should I approach this? Do I have to fetch all the guild members first so that they're all cached?
I'm doing a sorting algorithm at the moment for an opt-in team event, and it's become lopsided because one team's cached members are higher than the other by a bit haha
Ty :D is there a way to do client side restrictions on who can click on button? E.g specific roles/people, or does it have to be from server side
Yes, you must first do a fetch
Server-side only, buttons do not have restrictions
this isnt exactly djs related, but how do you send a file via a webhook?
i can use components v2 right?
Same way you would as if it were a channel
i figured it out 🔥
.send({ files: […] })
👍 Will do, I'll just add a message before the fetch for the user to be aware that stuff is happening in the background.
are webhook files limited to 8mb or 10mb? whenever i tried to send a 8.41mb file it errored, but i can send it myself
.setColor("Black")
what are you trying to use setColor on
10 according to the docs https://discord.com/developers/docs/reference#uploading-files
weird
EmbedBuilder
import it from discord.js and not from builders then
import what? colors?
the EmbedBuilder
i do
const { EmbedBuilder } = require('discord.js');
okay yeah, I can see "Black" is indeed not valid
What are the default max lengths for Short and Paragraph text inputs in modals?
Learn more about modal limits at the Discord Developer Documentation
I dont think they have different limits, max length is 4000
Supplied parameter is not a cached User or Role.
What is the reason of this problem ?
nvm i got it
I have a question, I have greetings made in the bot, and everything works correctly but sometimes it happens that the message is sent twice, what could be the fault?
I have discord.js 14.21.0
i can make a select menu on a container ?
yes
the select menu needs to be in an action row, then you can add the action row to the container
Error: Received one or more errors
at _UnionValidator.handle (E:\Github\Watcher-V14\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:1965:23)
at _UnionValidator.parse (E:\Github\Watcher-V14\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:972:90)
at SectionBuilder.toJSON (E:\Github\Watcher-V14\node_modules\@discordjs\builders\dist\index.js:2169:37)
at E:\Github\Watcher-V14\node_modules\@discordjs\builders\dist\index.js:1870:64
at Array.map (<anonymous>)
at ContainerBuilder.toJSON (E:\Github\Watcher-V14\node_modules\@discordjs\builders\dist\index.js:1870:35)
at E:\Github\Watcher-V14\node_modules\discord.js\src\structures\MessagePayload.js:151:46
at Array.map (<anonymous>)
at MessagePayload.resolveBody (E:\Github\Watcher-V14\node_modules\discord.js\src\structures\MessagePayload.js:150:49)
at InteractionWebhook.editMessage (E:\Github\Watcher-V14\node_modules\discord.js\src\structures\Webhook.js:344:50)
Code:
const {
SlashCommandBuilder,
ContainerBuilder,
SectionBuilder,
SeparatorBuilder,
TextDisplayBuilder,
ActionRowBuilder,
ButtonBuilder,
ButtonStyle,
MessageFlags,
} = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName("help")
.setDescription("Displays the help menu."),
async execute(interaction) {
await interaction.deferReply();
const header = new SectionBuilder()
.addTextDisplayComponents(
new TextDisplayBuilder().setContent("### **Commands**"),
new TextDisplayBuilder().setContent(
"> Our [website](https://watcherbot.net/servers) contains lots of resources to get you going!"
)
)
const commandsHeading = new SectionBuilder().addTextDisplayComponents(
new TextDisplayBuilder().setContent("### **Bot Commands**")
);
const commands = [
["/add", "Track a bot"],
["/remove", "Un-track a bot"],
["/list", "Show clusters / services"],
["/channel", "Set the log channel"],
["/role", "Set ping role for outages"],
["/shard", "Display shard information"],
["/help", "Show this help menu"],
].map(
([cmd, desc]) =>
new SectionBuilder().addTextDisplayComponents(
new TextDisplayBuilder().setContent(`**${cmd}**`),
new TextDisplayBuilder().setContent(`— ${desc}`)
)
);
const links = new SectionBuilder().addTextDisplayComponents(
new TextDisplayBuilder().setContent("### **Useful Links**")
);
const linksRow = new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setLabel("Support Server")
.setStyle(ButtonStyle.Link)
.setURL("https://discord.gg/..."),
new ButtonBuilder()
.setLabel("Dashboard")
.setStyle(ButtonStyle.Link)
.setURL("https://watcherbot.net/servers"),
new ButtonBuilder()
.setLabel("Invite")
.setStyle(ButtonStyle.Link)
.setURL(
"https://discord.com/oauth2/authorize...."
)
);
const container = new ContainerBuilder()
.setAccentColor(0xe4a726)
.addSectionComponents(header)
.addSectionComponents(commandsHeading)
.addSectionComponents(...commands)
.addSectionComponents(links)
.addActionRowComponents(linksRow);
await interaction.editReply({
components: [container],
flags: MessageFlags.IsComponentsV2,
});
},
};
Sections need accessory
If you don't need accessory, don't use sections
Just use text components directly
ohh ok ty
how to remove that ping i doest want it to ping even if my mention is there
allowedMentions: {
parse: ["roles", "users", "everyone"],
repliedUser: false
},
what is your djs version
"discord.js": "^14.21.0",
kyxen@archlinux: ( ~/Projects/Axiom )
% node -v
v22.16.0
and also node version
and the version returned by npm ls discord.js
kyxen@archlinux: ( ~/Projects/Axiom )
% npm ls discord.js
axiom@1.0.0 /home/kyxen/Projects/Axiom
└── discord.js@14.21.0```
you don't really need to put the parse in at all if you're gonna tell it to parse everything
also, where is that allowedMentions located?
Despite sounding similar there is a distinct difference between users and members in Discord:
- User: global Discord user data (global avatar, username, tag, id)
- GuildMember: user data associated to a guild (guild, nickname, roles, voice, guild avatar, etc.)
- Conversion: User ➞ GuildMember | GuildMember ➞ User
* Note: Events received in cached guilds will often have both the member and user available, eg.interaction.userandinteraction.member
@upper mica #app-commands for personal use please
thank you and sorry
I was looking for an update for the user guild tags
custom class ?
pr has been merged but no new release yet, it will be in 14.22, no ETA
you can wait or use the dev version, your choice
is it already in dev version?
Why I have to give the emoji object and not the emoji string ??
const container = new ContainerBuilder()
.addSectionComponents((s) =>
s
.addTextDisplayComponents((t) =>
t.setContent(
"blabla"
)
)
.setButtonAccessory((b) =>
b
.setCustomId("settings")
.setEmoji({ id }) // if it's a string => bug
.setStyle(ButtonStyle.Secondary)
)
)
With the buttonbuilder we can do that so i dont understand why not where
what custom class
making a class in your code has no impact on any other code
unless you use it
*Extended Class
-# nvm i fixed it
what are you extending?
Discord Js client ??
are you extending Client? if so, you're passing it as options to super()?
in which case you extending makes no difference, really
it's set as default on a Client, which was what i was asking about - is it there or is it directly in the reply() call
only the ButtonBuilder from djs accepts emoji strings, not the ButtonBuilder from @discordjs/builders, which is the one setButtonAccessory uses for its callback. you can create the builder in a separate variable and pass that to setButtonAccessory and it should work, it probably won't be "fixed" since only accepting full objects is how builders v2 will work
I see, thank you for your answer !
Do interaction components on ephemeral interactions time out? I have a button in a ephemeral response that throws a 50027 Invalid webhook token error after a ~10-20 minutes time window
the intrraction webhook expires after 15 minutes yes
and why do you need to use an interaction from an ephemeral message after 15 mins?
it's unlikely any user will keep the message for that long
They don't. But if you use the original interaction instead of the new one caused by the interactive component you'll face that issue
are bots able to send voice messages with djs?
pretty sure those arent documented
i need help
With what?
I need someone who can make a simple bot for me
You're in the wrong place then. Try fiverr. This channel and server is for helping you write your own, not find someone to do it for you
oo alrr
what version should i install to get v2 comps
latest
the newest, so 14.21.0
and you should always use latest in general, there's no other major version being maintained
npm i discord.js@latest?
just discord.js
Both work
how do you edit a component v2 message for example let's say a user clicks a button and changes every data in that container?
ButtonInteraction#update() discord.js@14.21.0
Updates the original message of the component on which the interaction was received on.
// Remove the components from the message
interaction.update({
content: "A component interaction was received",
components: []
})
.then(console.log)
.catch(console.error);
you can just update it how you used to update components and embeds with <ButtonInteraction>.update()
alr thanks
Is it possible if I have a message and there is a button that opens a modal. That I can use this ModalSubmitInteraction to edit the first message of the button without fetching the messages or so because of the rate limit?
interaction.update will still edit that message
yes, you can use <ModalSubmitInteraction>.update() just like you would on ButtonInteractions
but you should check beforehand with <ModalSubmitInteraction>.isFromMessage() if the modal interaction had a message as source
that last part isn't necessary if the modal can only happen from the button, and your custom ids are unique enough
thats true, i like using the type guard tho
It is necessary if using typescript
But it tells me that .update doesn't work.
this is why i mentioned to type guard with <ModalSubmitInteraction>.isFromMessage()
Oh check
Why can it be both a ButtonInteraction or a ModalSubmitInteraction there?
If you want to give a reason it is modal interaction and without a reason there is directly the button interaction.
Then you should do the isFromMessage typeguard before passing to that scope where it can be both and accept MessageModalSubmitInteraction as type for that scope
Because there is no isFromMessage() on ButtonInteraction
or <interaction> instanceof ModalSubmitInteraction && <interaction>.isFromMessage()
Currently, I have it like this:
if (interaction.isModalSubmit() && !interaction.isFromMessage()) return;
await InteractionHelper.update(interaction, [suggestionEditEmbed], true, []);
isModalSubmit is probably the intended way over instanceof
Can i do if someone Join Server embed also comps?
what?
Good afternoon, I'm experiencing an issue I've never had before. I have a system with a button, the button works for everyone, besides one user. When they press it, I get this error:
F:\Development\Zyron-Beta\backend\events\registration.js:23
if (!interaction.isButton()) return;
^
TypeError: interaction.isButton is not a function
at Object.execute (F:\Development\Zyron-Beta\backend\events\registration.js:23:22)
at InteractionCollector.<anonymous> (F:\Development\Zyron-Beta\backend\events\registration.js:254:28)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
Node.js v22.4.1
PS F:\Development\Zyron-Beta\backend>
Would anyone be able to assist?
show registration.js
const exampleSection = new ContainerBuilder()
.setAccentColor(0x00CEFF)
.addSectionComponents(section =>
section
.addTextDisplayComponents(textDisplay =>
textDisplay.setContent(`# ${interaction.user.displayName}\n-# test\n-# test\n-# test`)
)
.setThumbnailAccessory(thumbnail =>
thumbnail.setURL(interaction.user.displayAvatarURL())
)
)
// Separator
.addSeparatorComponents(separator =>
separator.setSpacing(SeparatorSpacingSize.Large)
)
.addSectionComponents(section =>
section.addTextDisplayComponents(textDisplay =>
textDisplay.setContent('Pick your main account from the list below. This will be the account you receive gifts on!')
)
)
can I not have 2 sections?
- section
- separator
- another section
You can have multiple sections
what is the correct way to do it?
you're doing it correctly
but a section needs an accessory
There is no correct way, do it how you like
this is giving a validation error
your 2nd section doesn't have one
read my message
ah I see, what if I just want text on that section?
then just add text
You cant
ContainerBuilder#addTextDisplayComponents() discord.js@14.21.0
Adds text display components to this container.
not an entire section
a section without an accessory is useless, hence why it errors
that sucks 
and can you not have a drop down accessory?
that sucks
why? you're adding an unnecessary component
and can you not have a drop down accessory?
do you mean a select menu? if yes, then yeah, but like always it needs to go in an action row
oh wait I got it
if you want just plain text you can addTextDisplayComponents to ContainerBuilder on its own, otherwise if you want an accessory you do it in a section
yes
what does SeparatorSpacingSize increase? its y-spacing or how wide it spans on the x-axis?
oh that's nice, thx

time to port 100+ commands now 
good luck
i still need to do that
😂
It's a very big file, I won't be sharing all of it. This is what's causing the error:
module.exports = {
name: "interactionCreate",
execute: async (interaction) => {
if (!interaction.isButton()) return;
InteractionCreate:
client.on('interactionCreate', async interaction => {
if (!interaction.isChatInputCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
that second code seems entirely unrelated
since it's handling commands
in your first code, "interaction" isn't an interaction, you can try logging it
maybe you're passing your client and it's actually that
node:events:495
throw er; // Unhandled 'error' event
TypeError: media.addMediaItem is not a function
at C:\Users\Leon\Desktop\Neuer Ordner (2)\index.js:51:15
at resolveBuilder (C:\Users\Leon\node_modules\@discordjs\builders\dist\index.js:2224:12)
at C:\Users\Leon\node_modules\@discordjs\builders\dist\index.js:1805:56
at Array.map (<anonymous>)
at ContainerBuilder.addMediaGalleryComponents (C:\Users\Leon\node_modules\@discordjs\builders\dist\index.js:1805:37)
at Client.<anonymous> (C:\Users\Leon\Desktop\Neuer Ordner (2)\index.js:50:8)
at Client.emit (node:events:517:28)
at MessageCreateAction.handle (C:\Users\Leon\node_modules\discord.js\src\client\actions\MessageCreate.js:32:14)
at module.exports [as MESSAGE_CREATE] (C:\Users\Leon\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\Leon\node_modules\discord.js\src\client\websocket\WebSocketManager.js:351:31)
Emitted 'error' event on Client instance at:
at emitUnhandledRejectionOrErr (node:events:398:10)
at process.processTicksAndRejections (node:internal/process/task_queues:84:21)
Node.js v18.18.0```
there's no addMediaItem method in any builder
if you're using ai-generated code you should expect issues
check the docs for actual usages
Popular Topics: Display Components - Media Gallery
read more
Line 254 of your registration.js you seem to call your execute() again from a collector but don't pass an interaction

How do I get the update of @discordjs/core @ 2.2.0 & @discord.js @ 14.21.0?
what do you mean?
just install the version?
Yea, how do I do that?
Ah, that's here:
} else if (btnInteraction.customId === "new_verification") {
module.exports.execute({
...interaction,
skipDuplicateCheck: true,
});
}
How would I change it so it actually pass the interaction?
npm i <package>
What would be the package?
npm i 14.21.0 & npm i 2.2.0
this is basic npm commands, not really d.js related
npm i discord.js@14.21.0, etc.
...interaction serializes and spreads the object, so you lose a lot of properties
you should never modify discord.js provided classes
until you did a better implementation, you can use interaction.skipDuplicateCheck = true; before the execute() call
a better implementation would be passing a second parameter into your execute() function like execute(interaction, true)
and change the execute definition to async (interaction, skipDuplicateCheck)
making the skipDuplicateCheck an optional parameter
why are you using both core and djs at the same time
Do I need both?
Alright
core is djs but a skinned down version
hence 'core'
Could someone help me rq dm
Does the system message for starting threads (<User> started a thread: <name>. See all threads) trigger the messageCreate event?
yes, im not sure which one you want but there are these 2 message types
https://discord-api-types.dev/api/discord-api-types-v10/enum/MessageType#ThreadStarterMessage
https://discord-api-types.dev/api/discord-api-types-v10/enum/MessageType#ThreadCreated
thanks
Anyone know whats causing this? Basically, any users, roles being mentioned come back as unknown or inaccessable. The user is me btw.
from the looks of the ID compared to your actual ID it seems like you're converting the IDs into numbers
Discord snowflakes are too large to be numbers, which basically rounds them down. If you need to perform calculations on them (unlikely) convert them to BigInts, otherwise just leave them as string
I'll check my code, 1 sec
do interaction.update() or interaction.message.edit() if you already replied to the interaction
Yep that fixed it @bitter nova. The typescript warning should have given me a clue, thanks 🙂

if you're actually dealing with a UserSelectMenuInteraction then .update() should be a thing
see https://discord.js.org/docs/packages/discord.js/14.21.0/UserSelectMenuInteraction:Class#update
otherwise show me your code and any error you're experiencing
thats why i said you need to run .update on interaction, not on interaction.message
so interaction.update()
that should be interaction.deleteReply()
if that doesnt work try passing the message ID into it like so interaction.deleteReply(interaction.message.id)
if that also doesnt work you can still interaction.message.delete()
Anyone know how to start to figure out what discord.js is complaining about here?
If I add any fields to the embed, it just fails.
.addFields(
{name: 'Start Date', value: loaRequest.start, inline: true},
{name: 'End Date', value: loaRequest.start, inline: true},
{name: 'Reason', value: loaRequest.reason, inline: false},
)
im not sure what loaRequest.start is but try wrapping it in String() (String(loadRequest.start))
otherwise just remove all but one fields and see the error it gives you then
did you try all 3 of the options?
also note that you cant .update then .deleteReply
you need to pick one of the 2
that is correct, ephemeral messages cant be deleted with interaction.message.delete()
deleteReply works though
it should, try doing interaction.deleteReply("@original")
make sure you dont run .update() before it tho
Yep, it was storing it as a Date rather than a string. Just need to format it now. Thanks again Lars. ^_^
no worries 
Not sure I understand why you can't update first, I missed that part
Yeah
Just pass the id of the ephemeral
doesnt update invalidate the interaction, making it error with interaction already sent or deferred?
No?
making what error? ah, deleteReply, no, it isn't an interaction reply, in fact deleteReply will error if you don't reply (defer, reply, or update) first (since there's no reply), maybe not if it's a component interaction but I wouldn't reply on it
ahh alright, my bad 
update is an initial response method that updates the message an interaction came from.
You can then no longer use reply, update, defer(s) or showModal again, as it's already been sent
editReply and deleteReply would still work perfectly though
That's the whole point of those methods, to be used after
And followUp

I'm pretty sure its just new EmbedBuilder(<Message>.embeds[0].data)
<Message>.embeds[0] can be anything referencing a message embed
(static) EmbedBuilder#from() discord.js@14.21.0
Creates a new embed builder from JSON data
its the new markdown -# text here but not djs related
thank you
Hello, I'm trying to enter the reason for deleting the channel, but Discord doesn't give me anything. Do you know why? I'm on Discord.js 14.21.0.
try fetching the audit log and see if there's a reason in the data you fetched
if it's there - unfortunately discord didn't add showing the reason in the ui, not much you (or anyone here) can do about that.
if it's not, someone would have to bonk discord people to either remove note that this supports reasons in api docs, or have them fix it. again not really something you can do much about
Is there anyway to force which line you want the embed fields on?
Ideally want this in 3 rows, fields 1 and 2, fields 3 and 4 and then field 5.
inline fields will display next to each other
any non-inline field will not allow any other field to display next to it
and as such will have entire row to itself
I need to find a nicer way of doing this then. Thanks though. ^_^
if you start inserting empty fields, you'll make this look bad in places that don't display inline fields at all
Yeah, wasn't thinking empty fields. I'll come up with something.
Idea. setTimestamp on an Embed... will that take a regular javascript Date object?
you can check docs on what does it take
EmbedBuilder#setTimestamp() builders@1.11.2
Sets the timestamp of this embed.
Messages Resource - Embed Object
read more
depends how you build them
In theory, looks good, in practice, let's find out.
That timestamp will continue to update based on the current date/time, correct?
uhh
update how?
it's one single timestamp, that will always point to that time you passed in
Yep, that works great then.
Appreciate the help. ^_^
I just saw, yes it's in UX that doesn't display it
thanks
*UI
well
Hello! When the message component collector time ends, is its collect and end event also completely cleared or might it cause a memory leak if there are too many of them by sending new message?
All listeners are stopped when the collector is stopped
Thanks! Does that mean the collect and end events are automatically removed from memory, without needing to explicitly call Collector.removeAllListener("collect") in the end event?
I checked the Discord.js source code, and I saw that it removes listeners for events like messageDelete and guildDelete, but I couldn’t find anything related to removing collector events like collect.
messageDelete and guildDelete are client events, not collector
That’s why d.js has to manually remove those listeners
Yeah I saw that some client events like messageDelete are automatically removed, but what about collector events when the collector time expires?
Do they get removed automatically, or do I need to explicitly call collector.removeAllListener("collect") in the end event of collector?
You should’ve also seen in the code that the collector creates those listeners
client events are automatically removed
No they aren’t
Collector event listeners are automatically stopped
Unless you mean "automatically" in the POV of ur codebase/project
Not d.js source code
You don’t need to manually remove listeners when the collector is stopped for any reason specified when creating the collector or when calling collector.stop
If ur collector isn’t ending, then you have a bigger issue at hand most likely
if you switch two things you are correct:
Yeah I saw that some
client events likecollector events when the collector time expires are automatically removed, but what aboutmessageDeletecollector events when the collector time expiresclient events likemessageDelete?
answer: you need client.removeAllListeners("messageDelete") as you said (partially)
The collector needs to remove it because it created it and the client doesn’t get destroyed when the collector ends
client.removeAllListeners("messageDelete")
As a side-note, you should never use that specific line since is very problematic as it can mess up active collectors and anyone else using it. Prefer removing specific listeners instead
The only reason you would need to remove a listener from the collector is if you haven’t ended the collector (collector.end event doesn’t fire)
Thanks! For example, when the collector ends, I noticed that the client event—such as a messgeDelete—gets removed as expected. However, something seems to happen to the corresponding collector event, like collect event.
Is those collector events will remove like the client event? After the specificied collector is ended
I noticed that the client event—such as a
messgeDelete—gets removed as expected
that should not be expected at all, that shouldn't happen in the first place
collector ends > corresponding collector event ends too
client events are not related to your collectors
The collector will only remove its own listeners that it created on the client
To be honest, you wouldn’t have to worry about a memory leak as long as you aren’t making stuff global for no reason
Yeah I know I just want to know what about the collector events because i also listen tocollect event and it not useful when collector ends
The collector would disconnect itself from the client and wouldn’t be reachable in the code
No line in the collector would be able to execute after ending
So it all gets garbage collected regardless of whether you removed all collector listeners or not
Yeah finally I found the answer! Thank you
how to extend collection lifetime?
Which collection?
ComponentCollector
I don’t think any caches have a time by default
Don’t provide a time option and use your own timer
You could use the idle option if you want the time to reset every time a component gets collected
ty
Hi, would Discord Wordle's "Your group is on a x day streak! 🔥 Here are yesterday's results:" trigger messageCreate? Thanks!
yes
How do I go about attaching files to messages? What I currently have is just causing this: TypeError [ReqResourceType]: The resource must be a string, Buffer or a valid file stream.
show your code
let file = new File([message], "records.txt", { type: "text/plain", })
file = new AttachmentBuilder()
.setFile(file)
.setName("records.txt")
.setDescription("The records of this AOS.")
.setSpoiler(false)
const fileComp = new FileBuilder()
.setURL('attachment://records.txt')
interaction.user.send({ content: header, files: [file], components: [fileComp], flags: MessageFlags.IsComponentsV2})
setFile accepts the path directly
i dont have a path to the file because i create the file above ?
ah, thought it was a weird attempt to try to attach it
you need the buffer in some way then
then pass the buffer to setFile
Buffer.from(string[, encoding])
Creates a new Buffer containing string.
in case it's a string
how to remove mentions in message (like aoi: $noMentionMessage)
You can control which entities receive notifications via the allowedMentions option. You can:
- Set a default on the client
- Set for a specific message
- Use the
repliedUserkey to disable in-line reply mentions
{ ..., allowedMentions: { parse: ["users", "roles"] } }
I don't want to add data to the client, I listen messageCreate event and I want to remove the mentions in the content
nvm, i found it ty
Got an odd one today folks, got a slash command that's behaving as expected, but then throwing an 'Unknown interaction'. Any idea how to troubleshoot this?
I've checked the error message and it seems to link back to the component that's been sent in a reply.
Application log shows as follows:
[17:10:21.987] INFO (58092): Sending LOA component to channel 🚫︱request-loa (1374029652355711177)...
[17:10:22.198] ERROR (58092): Unknown interaction
[17:10:22.363] ERROR (58092): Interaction has already been acknowledged.
Anyone got any ideas here? I'm just trying to trace whatever interaction is throwing this error.
First step: log the full error (including stack) not just the message
Second step: look at the code where it gets thrown
I've got the full error log, but it essentially just dumps the component twice. Even though it's only posted once.
Common causes of DiscordAPIError[10062]: Unknown interaction:
- Initial response took more than 3 seconds ➞ defer the response *.
- Wrong interaction object inside a collector.
- Two processes handling the same command (the first consumes the interaction, so it won't be valid for the other instance)
* Note: you cannot defer modal or autocomplete value responses
The last bulletpoint probably. Or two collectors/event handlers
Let me try deferring it and see what happens. If it still throws an error, should I just upload the log here?
And if you got the stacktrace then looking at the code that points to helps.
The first bulletpoint is not your issue!
Showing full error and code are advisable, yes
Yeah deferring it causes it to fail completely. So gimme a moment.
Huh? That sounds like you're doing something wrong in deferring... showing that code would also help to find that issue
Which bit do you need? interactionCreate, the command, or both?
... the one your error stack points at. Since you haven't posted that it's impossible for me to answer that
//interactionCreate.js
const { Events, MessageFlags } = require('discord.js');
const { logger } = require('../../utilities/logger.js');
module.exports = {
name: Events.InteractionCreate,
async execute(interaction) {
if (!interaction.isChatInputCommand()) return;
const command = interaction.client.commands.get(interaction.commandName);
if (!command) {
logger.error(`No command matching ${interaction.commandName} was found.`);
return;
}
try {
const {displayName, id} = interaction.member;
logger.info(`User ${displayName} (${id}) used /${interaction.commandName}`);
await command.execute(interaction);
console.log(interaction.commandName, interaction.id);
}
catch (error) {
logger.error(error);
if (interaction.replied || interaction.deferred) {
await interaction.followUp({ content: 'There was an error while executing this command!', flags: MessageFlags.Ephemeral });
}
else {
await interaction.reply({ content: 'There was an error while executing this command!', flags: MessageFlags.Ephemeral });
}
}
},
};
//component.js
const { SlashCommandBuilder, MessageFlags } = require('discord.js');
const LOARequestComponent = require('../../components/loaRequest.js');
const { logger } = require('../../utilities/logger.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('loacomponent')
.setDescription('Sends the LOA information component to the current channel.'),
async execute(interaction) {
const { name, id } = interaction.channel;
logger.info(`Sending LOA component to channel ${name} (${id})...`);
await interaction.reply({
components: [new LOARequestComponent()],
flags: MessageFlags.IsComponentsV2,
});
logger.info('Component sent.');
}
}
This should do it then, let me know if you need anything else.
Log is a bit scuffed because it's going through pino.
Neither of those code files are the one your error points at 
Yeah I've just seen that in the log. gimme a second. I think I might just found my really stupid mistake.
Also seems weird that a file called Button_press seems to try to defer a ChatInputCommandInteraction
So probably second bulletpoint
Yeah I found out what I did...
module.exports = {
name: Events.InteractionCreate,
async execute(interaction) {
if (!(interaction.isButton() && interaction.customId.startsWith("approveLoaButton"))) return;
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
...
}
I had the interaction.deferReply above the if statement.
So, typical PEBKAC. I wasn't watching what I was doing when I was copying and pasting. 😳
SlashCommandBuilder,
EmbedBuilder,
TextDisplayBuilder,
MessageFlags,
SeparatorBuilder,
SeparatorSpacingSize,
SectionBuilder,
ThumbnailBuilder,
ButtonBuilder,
ButtonStyle,
MediaGalleryBuilder,
ContainerBuilder,
AttachmentBuilder,
FileBuilder
} = require('discord.js');
const path = require('path');
const fs = require('fs');
module.exports = {
data: new SlashCommandBuilder()
.setName('agb')
.setDescription('This is components version 2.'),
async execute(interaction, client) {
const container = new ContainerBuilder();
const textTop = new TextDisplayBuilder()
.setContent(`## Willkommen auf Medusa | Design`);
container.addTextDisplayComponents(textTop);
const text1 = new TextDisplayBuilder().setContent('jjj);
// const button1 = new ButtonBuilder().setLabel('Overview').setURL('https://youtube.com').setStyle(ButtonStyle.Link);
container.addTextDisplayComponents(text1);
const separator = new SeparatorBuilder();
container.addSeparatorComponents(separator);
const media = new MediaGalleryBuilder()
.addItems([
{
media: {
url: 'https://media.discordapp.net/attachments/1079015238730534923/1388934550465286164/richtlinien.png?ex=686dfe59&is=686cacd9&hm=0c0c8ab2b71bffbe5dfb63d3e60b884e4ce4b727c8414a34a2e76c951651b126&=&format=webp&quality=lossless&width=1178&height=303'
}
}
]);
container.addMediaGalleryComponents(media);
const button1 = new ButtonBuilder()
.setLabel('Discord Richtlinien')
.setURL('https://discord.com/terms')
.setStyle(ButtonStyle.Link);
const button2 = new ButtonBuilder()
.setLabel('Community Richtlinien')
.setURL('https://discord.com/guidelines')
.setStyle(ButtonStyle.Link);
const button3 = new ButtonBuilder()
.setLabel('Community Richtlinien')
.setURL('https://discord.com/guidelines')
.setStyle(ButtonStyle.Link);
const section2 = new SectionBuilder()
.setButtonAccessory(button1)
.setButtonAccessory(button2)
.setButtonAccessory(button3)
container.addSectionComponents(section2);
interaction.reply({
flags: MessageFlags.IsComponentsV2,
components: [container]
});
}
};```
The Command doesn't show up on my Server
Are you registering slash commands to Discord? Have you reloading your client after registering?
Yes, from the Structure of the Code is nothing wrong?
ERROR: Unhandled Rejection at: [object Promise]
Reason: Error: Invalid Array length
Cmd Error
Is that coming from your deploy-commands.js (or whatever equivalent script you have)?
const exampleContainer = new ContainerBuilder()
.setAccentColor(0x0099FF)
.addTextDisplayComponents(
textDisplay => textDisplay
.setContent(`# Modelo de Pedir Música`),
)
.addSeparatorComponents(
separator => separator,
)
.addSectionComponents(
section => section
.addTextDisplayComponents(
textDisplay => textDisplay
.setContent(`\`\`\`
- Nome: Se Depender de Mim - Zé Vaqueiro
- Link: https://www.youtube.com/watch?v=zKTlVopyqxA
- Categoria: Forró
- Estilo: Grave seco
\`\`\``),
)
.setButtonAccessory(
button => button
.setCustomId('copiar')
.setLabel('Copiar Modelo')
.setStyle(ButtonStyle.Primary),
)
)
I'm just starting out with v2 components, how can I put the button below the message, instead of appearing on the right?
documentation suggestion for @dull pike:
ContainerBuilder#addActionRowComponents() discord.js@14.21.0
Adds action row components to this container.
add the buttons to an action row, then pass the action row directly to the container
thanks 😄
.setAccentColor('#00ff00')
.setContent(`## Willkommen auf Medusa | Design`);
container.addTextDisplayComponents(textTop);```
Is it wrong to add color?
text displays dont have colors
containers do
so also not actionrowcomponents?
What would that even look like? Both of those can be inside a container. Which can have an accentColor
Aight
await interaction.deferReply();
let user1 = interaction.user;
let user2 = interaction.options.getUser("user");
const mainMessage = await interaction.editReply({
content: `<@${user2.id}>, you have been challenged by ${user1}!`,
embeds: [embedInfo],
components: [rowBtn],
allowedMentions: { parse: ["users"] },
});
Any reason its not pinging user2?
Edits don't notify. But it should show the yellowish mention around the message
Considering you don't do any async tasks in between you don't need to defer and edit, just reply
oh. Any alternative that can I can use?
No I do have other codes in between those.
You could ghost ping(I dislike). or just send a new message
ic ok thx
or just reply without the defer and edit
You seem to know the two users up front though. So reply with that content directly, then editReply the embed and button row (assuming those need the extra work being done in between)
that is def the better option
button.setLabel('hi')
.setURL('https://discord.com/guidelines')
.setStyle(ButtonStyle.Link)
);```
Is this Correct ?
you need a textdisplay for a section
addActionRowComponents
then you would need an action row
Also why ask if its correct, check the docs
guide suggestion for @crystal glen:
Popular Topics: Display Components
read more
i wanna create Emoji thread and sticker log system, which one gateway intent bits i should add?
what would be the purpose of that?
Like when emoji created or deleted or updated
same thig for sitcker and threads
GatewayIntentBits#GuildEmojisAndStickers discord.js@14.21.0
[DEPRECATED] This is the old name for GuildExpressions
whoops yeah GuildExpressions
tysm
Since when can we make embeds like this? This looks crazyy
guide suggestion for @worthy light:
Popular Topics: Display Components
read more
thanks, is this new?
damn
How can I make my button contain the message ID for the custom id? (Slash command)
by literally doing that
set the customId to your messageid
(I'm kinda new, so sorry if im being dumb)
I do this and I get an error saying something about
cannot read "id"
That's not the error you receive. Read the actual error, not paraphrase it
Would you kindly show us the code at and around line 158 in slash/giveaway.js
is the interaction an actual button interaction
const send = new ButtonBuilder()
.setLabel('Send')
.setCustomId(`send-giveaway-${interaction.message.id}`)
.setStyle(ButtonStyle.Success);
(Indents are caused by the panel)
yeah so your interaction is most likely of type ChatInputCommandInteraction, which does not include the message property
What message do you expect that to be?
command name shows as /undefined
```js
const now = Date.now();
const timestamps = cooldowns.get(command.name);
const cooldownAmount = (command.cooldown || 0) * 1000;
if (timestamps.has(interaction.user.id)) {
const expirationTime = timestamps.get(interaction.user.id) + cooldownAmount;
if (now < expirationTime) {
const timeLeft = Math.floor(expirationTime / 1000);
const embed = new EmbedBuilder()
.setColor(config.colour.warn)
.setDescription(`You can use \`/${command.name}\` again <t:${timeLeft}:R>.`);
return interaction.reply({
embeds: [embed],
flags: MessageFlags.Ephemeral
});
}
}
And what is command defined as?
The embed message that is getting sent with the button.
eh
That message doesn't exist yet at the point you define the button. And what is your use case here? Considering the ButtonInteraction would include the messageId either way
Yes?
console.log(command) if you aren't sure
my userinfo command
They should know how they define their variable. Logging doesn't help
Show the code where you define the variable command
const command = client.commands.get(interaction.commandName);
if (!command) return;
well it should tell if the name property is present or not right
i have instialized client.commands too in my index.js
did this
if (timestamps.has(interaction.user.id)) {
const expirationTime = timestamps.get(interaction.user.id) + cooldownAmount;
if (now < expirationTime) {
const timeLeft = Math.floor(expirationTime / 1000);
const embed = new EmbedBuilder()
.setColor(config.colour.warn)
.setDescription(`You can use \`/${interaction.commandName}\` again <t:${timeLeft}:R>.`);
return interaction.reply({
embeds: [embed],
flags: MessageFlags.Ephemeral
});
}
}```
works now
That... is completely unrelated to your issue, but okay
it aint
i fixed my issue so what do you even mean, it was my issue ?
Oh, mb, you just changed your code... got confused since there was no mention of command anymore
its fine
Try row.components[0].setCustomId(id_${interaction.message.id})
takes the id from the msg object you just got and puts it into the id of your button 
oh
hi, is the documentation for components v2 available yet?
yes
Popular Topics: Display Components
read more
thanks 
How do I check if a specific role in a channel has a permission ?
GuildChannel#permissionsFor() discord.js@14.21.0
Gets the overall set of permissions for a member or role in this channel, taking into account channel overwrites.
what does this return ?
an array, an object?
documentation suggestion for @quartz lodge:
PermissionsBitField discord.js@14.21.0
Data structure that makes it easy to interact with a permission bitfield. All GuildMembers have a set of permissions in their guild, and each channel in the guild may also have PermissionOverwrites for the member that override their default permissions.
The above object is what it returns as per the documentation
does djs have a func for verifying signature headers? using it in an interactions endpoint
I don’t believe so, check djs http-only
No. Not that i can see
this chunk of code exists in one of my command files, unsure as to why nothing is being played.
async function execute(interaction) {
const sound = interaction.options.getString("file");
const player = createAudioPlayer();
player.on(AudioPlayerStatus.Playing, () => {
console.log('The audio player has started playing!');
});
player.on('error', error => {
console.error(`Error: ${error.message} with resource`);
});
const resource = createAudioResource(`./resources/mp3/${sound}.mp3`)
player.play(resource)
let connection = getVoiceConnection(interaction.guild.id)
if(!connection) {
console.log("no connection found")
connection = joinVoiceChannel({
channelId: "xxx",
guildId: "xxx",
adapterCreator: interaction.guild.voiceAdapterCreator,
selfDeaf: false
})
} else {console.log("connection found")}
connection.subscribe(player);
}
any ideas?
I tried to follow the guide and examples in the repo as closely as possible, no errors or anything however
Are you using websocket?
nope
Then you have no way to use discord.js
ah that's a shame
HTTP-only applications receive interactions through HTTP webhooks instead of the Discord Gateway. Bots that are not connected to the Gateway, but use HTTP interactions appear as online without a status. Discord.js does not support HTTP interactions. Use discord-interactions instead.
hmmm, just a quick followup, would I still be able to use @discordjs/rest for responding to interactions, or should I just hand roll fetch?
you can use it standalone, yeah
why is there no .kickable? (as well as a bunch of other properties/methods?)
GiuildMember does have GiuildMember#kickable
documentation suggestion for @lean sail:
GuildMember#kickable discord.js@14.21.0
Whether this member is kickable by the client user
well i know it exists but why is it not showing up in intellisense
is there some kind of typeguard i need or something else
getMember could be APIInteractionDataResolvedGuildMember
So you do need to type guard
ok thanks
documentation suggestion for @lean sail:
BaseInteraction#inCachedGuild() discord.js@14.21.0
Indicates whether this interaction is received from a cached guild.
hello, i'm creating a channel through <GuildChannelManager>.create, i'm setting up permissions for multiple users and roles when creating, but in some cases I am getting this error: ```js
TypeError [InvalidType]: Supplied parameter is not a cached User or Role.
at PermissionOverwrites.resolve (/app/node_modules/discord.js/src/structures/PermissionOverwrites.js:185:13)
at /app/node_modules/discord.js/src/managers/GuildChannelManager.js:181:89
at Array.map (<anonymous>)
at GuildChannelManager.create (/app/node_modules/discord.js/src/managers/GuildChannelManager.js:181:51) {
code: 'InvalidType'
}
the error basically says that the user does not exist in cache, and it really is not in cache, but it actually exists, does anyone know how I can avoid this check?
I thought about using REST to create the channel, but I first wanted to know if there really isn't a way to skip this check through `<GuildChannelManager>.create`
you need to supply the overwrite type if you provide an id
otherwise djs will need to infer from the cache whether it's a user or a role
and if it's not cached and you don't provide the type there's no way for it to know which one it is
oh well thanks angelo, i didn't even look at the api documentation and i ended up not realizing that it required the type
i put the type and everything worked out, thank you
for existing channels bot needs manage_roles for editing permission overwrites, and when creating channels (when bot has manage_channels) it can set overwrites without manage_roles right?
Yes, but only allow/deny permissions the bot itself has, unless it had ManageRoles
Hello I deleted a message from the bot but the <Message>.editable returns me true but why?
Because that checks permissions, not if the message still exists
Is it possible to check that a message is fully editable before sending an edit request to the API?
That's what you did. Finding out what actually exists on API side needs an API request. The edit request is the best one to do so as otherwise it's still possible that the message gets deleted between your check and the edit request
Thanks! So for bot message the best way is to do like this?
message.edit("Some text").catch(()=>{})
and it sends a request to API and if error occurred do nothing
Because I don't want to send a request to the API that will definitely result in an error response, but there seems to be no way around this.
Well, if you yourself delete the message you should be able to know that in your code. That's not something djs can do for you though
No i just did it for test and also the members with MessageDelete permission can also delete these messages
Also how about checking for both deletable and editable for the messages is that will work?
Those still both check permissions, neither can check whether the message still exists
Thank you
Hi,
Can someone tell me the PermissionFlagsBits for Create Posts permission of the guild forum ?
Thank you
CreatePublicThreads is the correct permission
will the method throw error or just overwrite permissions which bot has for users/everyone/bot
GuildChannelManager#create() discord.js@14.21.0
Creates a new channel in the guild.
// Create a new text channel
guild.channels.create({ name: 'new-general', reason: 'Needed a cool new channel' })
.then(console.log)
.catch(console.error);
It'll error

Thank you for your reply but it didn't work. I tried with other permissions like CreateInstantInvite and it worked.
I'm using discord.js 14.21.0
This is my sample code
if (!forumChannel) {
forumChannel = await interaction.guild.channels.create({
name: "Private",
type: ChannelType.GuildForum,
topic: "Private Forum",
reason: "Auto setup",
permissionOverwrites: [
{
id: interaction.guild.id,
deny: [
PermissionFlagsBits.ViewChannel,
PermissionFlagsBits.CreatePublicThreads,
],
},
],
});
}```
Did I make a mistake ?
Thank you
Yes, you deny everyone to view the channel and to make posts so your bot won't be able to do it either. But it needs to be able to do it to be able to deny others to do so
if bot has manage_roles i can assign any permission during chsnnel creation?
If it has that permission globally and you create a top level channel, yes. Or if it has an explicit overwrite allowing it on the category you create the channel in
Popular Topics: Permissions
read more
Maybe this answers all your questions better
Or rather the following page
Popular Topics: Permissions (extended)
read more
It can manage overwrites for roles or users with higher roles than its own highest role.
It can manage overwrites for permissions it doesn't have.
exception manage_roles overwrite
neat
so i dont need to remind user of every permission when creating channel as long bot has manage_channels
My bot has admin permission so I guess it'll be able to deny everyone's "Create Posts" permission right ?
It did deny other permissions (like ManageChannels, ManageMessages) except the "Create Posts" (CreatePublicThreads)
whats the point of denying CreatePublicThreads if you denied ViewChannel anyway
I want to hide it when creating then set the ViewChannel for everyone later.
allow your bot the ViewChannel permission
Even it has the admin permission ? Lemme try
admin !== server owner
So the right permission is PermissionFlagsBits.SendMessages not PermissionFlagsBits.CreatePublicThreads 
Thank you guys for your helps.
how can i fix this typing error, should i install @discordjs/rest module?
Module '"discord.js"' declares 'REST' locally, but it is exported as 'Collection'.ts(2460)
index.d.ts(40, 57): 'REST' is declared here.
No, where do you get that error? Because it makes no sense
import { REST } from "discord.js";
Is it your IDE or tsc that errors? Or something completely different?
tsc, maybe mt tsconfig.json is wrong
What version of typescript and discord.js are you on?
dependencies:
discord.js 14.21.0
devDependencies:
ts-node 10.9.2
typescript 5.8.3
Nuke node_modules, install again, and see if it persists
i dont think so, maybe it was my tsconfig.json fault
yep, thats tsconfig fault
"preserveSymlinks": true, //faulty c
does anyone know if there is a way to disable the display of user tags on one's server?
Not DJS related. But no
ok, I thought there perhaps might be some hacky way to do it server-side with DJS by nulling the property for the server-member's tag, or just overwriting it with some blank tag
DJS doesn't have a "hacky way" to do anything because it only supports documented features of the API
But server tags also are User attributes and can't be set on a per-server basis, meaning you can't modify them by a bot anyways. You can filter for them but the update for DJS for server tags is still a PR, so you'll have to use raw REST requests until then
(or use AutoMod)
Alright so i'm on the edge of losing my sanity.
i already made a specific client.ready code to enforce caching all members once bot's up
Yet when a listener is fired to detect if a user's roles changed before/after it never works the first time only the second and from so on.
How do i put an end to this
Can you show the code you're referring to and your intents?
Sure, One second
The listener Code is in the message.txt
My intents :
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildPresences,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildModeration,
GatewayIntentBits.GuildBans
]
});
The script inside client.ready to cache all members
try {
// 👥 Fetch and cache all members in each guild
for (const [guildId, guild] of client.guilds.cache) {
try {
await guild.members.fetch();
logger.info(`✅ Cached ${guild.members.cache.size} members in ${guild.name}`);
} catch (err) {
logger.warn(`⚠️ Failed to fetch members for ${guild.name}: ${err.message}`);
}
}
} catch (fetchError) {
logger.error('❌ Failed while fetching members in all guilds:', fetchError);
}
i also want to note that i've used an eval command
-eval return message.guild.members.cache.map(m => m.user.username)
To see if a specific member is indeed cached or not and they were! So i tried adding manually a role to their roles, Nothing happend
Removed it and added it again
The bot removed it.
So i'm so lost.
And it seems SOMEHOW that even when i hard-restart the bot it still remembers the members i already added roles to before but the ones i never did (even before restart) i have to interact with them even once
Which makes me even more lost cause if it was a normal cache issue then it should happen to same members each time i hard-restart
Is there a method to run or something before running anything that implies using cached user to avoid such an error:
TypeError [InvalidType]: Supplied parameter is not a cached User or Role.?
if I understand correctly, fetching the User or Role first should solve the "not a cached User or Role" issue. If that's not it, looking at some of your code will give more context
Which one is expected: id: guild.roles.everyone, or id: guild.roles.everyone.id,
Okay! What's the quick syntax to fetch for a user or role? if you know it by any chance?
depends on what type is expected. .everyone if a Role is expected. .everyone.id if a Snowflae is expected
I am referring to permission channel overwrites.
client.users.fetch() for fetching a User. and guild.roles.fetch() for a Role
Thanks!
the full Role object in that case
i assume you're using permissionsFor?
is the .kickable on the GuildMember going to return for if the person who actually USED the command can kick them or the client itself
Nope, creating a channel... guild.channels.create({})...
Roles are cached by the Guilds intent
and even then, the everyone role id is the same as the guild id
You might have to specify an OverwriteType
v10: OverwriteType
read more
The client user
is there any property on the guildmember that is applicable to the person who used the command?
No
check out that type wolvinny linked. also check OverwriteData and CategoryCreateChannelOptions
You have to manually check it
as in check their role positions and if they have the kick permission and if the person is the guild owner?
Or just check their permissions in general
how so
That fixed it, thanks!
GuildMember#permissions discord.js@14.21.0
The overall set of permissions for this member, taking only roles and owner status into account
Would be better to specify a type instead of fetching though
1 less api request
Though if you have the fetch the role you might have a bigger issue
- compare role positions
that's what I was wondering. since they should already be cached
ah ok
so would this be enough to check?
Probably yes, only one way to check.
Also name your variables properly
A member is not a user
Also those 2 isGuildMember checks are redundant
If the user isnt in the server there would be no interaction.member, and getMember would return null if the specified user isnt in the server
ok
but if i remove them then it says that member is possibly null
do i just check if it exists instead?
you still need to check if .member exists in the first place. since slash commands can be used in DMs, TS can't be sure about 'member' existing
null check ≠ guild member check. If you've made sure the command can't be used in DMs, add a ! after interaction.member
documentation suggestion for @lean sail:
BaseInteraction#inCachedGuild() discord.js@14.21.0
Indicates whether this interaction is received from a cached guild.
is the generic not enough?
i always forget inCachedGuild exists 
and also with my logic the server owner passes the permissions check but not the role check and thus is told they cant kick the member, do i have to add an additional check for guild owners?
check for owner first. if owner, skip role and permission check
Heya is it against the API to get all my guild members and select like 100 random ones ?
no
And I would use fetch for that right?
<guild>.members
Or wait I can't fetch from that
guild.members.fetch() -> returns a promise with a collection of all members
collection.random(100) gives you 100 random members
Ah okay perfect thanks
And I can cache the full members right since I need to re-use it every like hour
Around 2,000~ members, just only specific to this guild
This is a really small amount
Okay perfect 😄
I just need their avatar and username that's all it's for a game
ContainerBuilder#addMediaGalleryComponents() discord.js@14.21.0
Adds media gallery components to this container.
ty
Is there way to clone container component like buttons? Buttons have ButtonBuilder#from method and looks like ContainerBuilder don't have one
createComponentBuilder discord.js@14.21.0
Factory for creating components from API data.
❤️
Thanks a lot that worked perfect 
How to set this? In bot's about me
you don't, it's for verified bots
that is only available when discord has enough data on your bot and when it's verified
my bot is verified bruh 
that is only available when discord has enough data on your bot
alright
Hello, I've got this setup:
```const collector = await reply.createMessageComponentCollector({ componentType: ComponentType.Button });`
collector.on('collect', async i => {
i.reply("Aaaaaaaa");
})```
(this is a little bit simplified version, but the point is this)
aaand no matter what, if I do i.reply() or i.deferUpdate(), it always gives me Unknown Interaction error
whats the MessageType for forwards?
also if i fetch a message thats a reply to someone, will that message that was replied to be in cache?
MessageReferenceType#Forward discord.js@14.21.0
Reference used to point to a message at a point in time
Default, typically. But they have the HasSnapshot flag and you can check their messageSnapshots or reference
what is Forward then?
A type for the message reference, not for the message itself
ah. 
And no, you'll have the MessageReference but would need to fetch the message separately with <Message>.fetchReference()
ty
what's the best tsconfig for an application that includes express and discord.js?
That depends on where/how you intend to run it. And if it includes frontend too
no frontend, express is to expose the current status of the bot as json.
oke.. let me see
📄 Reason: Error: Cannot find module 'file:///C:/Users/e03o/Desktop/bot/aethel/dist/commands/fun/8ball.js'
Require stack:
- C:\Users\e03o\Desktop\bot\aethel\dist\handlers\initialzeCommands.js
- C:\Users\e03o\Desktop\bot\aethel\dist\services\Client.js
- C:\Users\e03o\Desktop\bot\aethel\dist\index.js
at Function._resolveFilename (node:internal/modules/cjs/loader:1401:15)
at defaultResolveImpl (node:internal/modules/cjs/loader:1057:19)
at resolveForCJSWithHooks (node:internal/modules/cjs/loader:1062:22)
at Function._load (node:internal/modules/cjs/loader:1211:37)
at TracingChannel.traceSync (node:diagnostics_channel:322:14)
at wrapModuleLoad (node:internal/modules/cjs/loader:235:24)
at Module.require (node:internal/modules/cjs/loader:1487:12)
at require (node:internal/modules/helpers:135:16)
at C:\Users\e03o\Desktop\bot\aethel\dist\handlers\initialzeCommands.js:64:98
at process.processTicksAndRejections (node:internal/process/task_queues:105:5) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'C:\\Users\\e03o\\Desktop\\bot\\aethel\\dist\\handlers\\initialzeCommands.js',
'C:\\Users\\e03o\\Desktop\\bot\\aethel\\dist\\services\\Client.js',
'C:\\Users\\e03o\\Desktop\\bot\\aethel\\dist\\index.js'
]
}
this is the main problem I'm trying to overcome..
that's unrelated to your tsconfig though
no problem on dev environment
Does a file by that name exist?
node16 is probably not what you want. your path alias points to ./src .
But node doesn't know how to handle that alias
that handles after the build using tsc-alias
Ah, I see... and did you check if the .js file actually exists?
Yeah. It exists
Can you show me? Because the error clearly disagrees
i deleted the dist and tried building again.. now with imports errors
dist/src/commands is not dist/commands
yeah.. i cleared that..
but there's something i need to show you
you can see here that I'm logging the default value from the command https://github.com/9is-z/aethel/blob/6aee94a10b82c6caf5ab28fba28e14136f7ee050/src/handlers/initialzeCommands.ts#L22
in dev, the log of 8ball looks like this
{
data: SlashCommandBuilder {
options: [ [SlashCommandStringOption] ],
name: '8ball',
name_localizations: { 'es-ES': 'bola8', 'es-419': 'bola8', 'en-US': '8ball' },
description: 'Ask the magic 8-ball a question',
description_localizations: {
'es-ES': 'Haz una pregunta a la bola 8 mágica',
'es-419': 'Haz una pregunta a la bola 8 mágica',
'en-US': 'Ask the magic 8-ball a question'
},
contexts: [ 1, 0, 2 ],
default_permission: undefined,
default_member_permissions: undefined,
dm_permission: undefined,
integration_types: [ 1 ],
nsfw: undefined
},
execute: [AsyncFunction: execute],
category: 'fun'
}
but in the build,
{
default: {
data: SlashCommandBuilder {
options: [Array],
name: '8ball',
name_localizations: [Object],
description: 'Ask the magic 8-ball a question',
description_localizations: [Object],
contexts: [Array],
default_permission: undefined,
default_member_permissions: undefined,
dm_permission: undefined,
integration_types: [Array],
nsfw: undefined
},
execute: [AsyncFunction: execute]
},
category: 'fun'
}
error that doesn't exist on dev
tried using copilot but no success
Is that with the tsconfig I linked you to? Or the one in the repo?
the one you gave me,
... with additions/changes you made I assume, since it won't work with path aliases otherwise for example
path is being used only in dev, tsc-alias is helping to convert the path after the build, so it's not a problem i hope. now, it's with imports,
Hi guys, was wondering how do i get the colors of the gradient role?
But tsc still needs to know about it. So yes it is needed
