#djs-help-v14
78874 messages · Page 7 of 79
what can you say about it, that sometimes it creates strictly where it should and sometimes chaotically?
you never stated that before. So please describe your issue a bit more. it sometimes works as you expect and sometimes not? did you determine when which case happens? for "random" issues like these you're the only one that can do the primary debugging. once you have a reproducable issue we can help with fixing that
slightly different, when creating a channel the position parameter doesn't work automatically and there are critical shifts in position, would it be better to use the asynchronous method channel.setPosition() after channel registration, or to use the same when creating position.
are you creating several channels/categories at the same time?
if so you should make sure to await all calls and only start the calls for the next when the first finished so that they use the correct positions
is it currently possible to use slash commands in private messages? a friend of mine is making a bot in python and can normally
Yes, using user apps
SlashCommandBuilder#setContexts() discord.js@14.19.3
Sets the contexts of this command.
SlashCommandBuilder#setIntegrationTypes() discord.js@14.19.3
Sets the integration types of this command.
You need to specify these two. Handling the interaction is same as you normally do
how to disable mentions in the new components v2
tag suggestion for @jolly bay:
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"] } }
in the channelDelete event, how do I get the person who deleted that channel?
i have to fetch audit logs.
how do I filter by channel delete
The question of who did something will always be answered by "get the audit log" if it's available
You can filter by the action type
aha thank you
GuildAuditLogsEntry#action discord.js@14.19.3
The type of action that occurred.
I think it may be possible to specify that during the fetch as well
does anyone know if discord.js v14 supports js module????
You should fetch. The cache only has those you either fetched before or that got sent as guildBanAdd to your bot during its runtime if you have GuildModeration intent
It supports cjs modules, esm and typescript. So yes. And has for a long time
okie dokie, i saw the docs and i though that maybe it don't has any support. Thnks for the support! :D
are there any guides torwards v2 yet
im thinking about rewriting the whole "use embeds as """popups""" " thing in my bot
#announcements exists, https://discord.builders/ exists and discord.js docs exist
not really sure how much more of a "guide" you expect
how can i make a command that replies with the amout of milliseconds it took to send that reply?
kind of like Dyno's ping command
compare Date.now() with the message's timestamp
ok thanks
you also have client.ws.ping which is the websocket ping. if you are making a ping command i would add both
whats a websocket
how your bot recieves things like commands and events from discord
if the websocket ping is slow, then your bot will take longer to receive that info from discord, and will therefore take longer to reply to commands and events
c.permissionsFor(guild.members.me!) ?.has([PermissionFlagsBits.ViewChannel, PermissionFlagsBits.SendMessages])```
Can I use arrays for .has()
PermissionsBitField#has() discord.js@14.19.3
Checks whether the bitfield has a permission, or multiple permissions.
Hey! What is the number for the ephemeral flag? How can I calculate it if necessary?
Use the MessageFlags enum
thx!
Hi, is this Message _Preset: triggerType 4?
anyway, i did actually end up implementing a system to check if i changed any of the commands' payloads
Hello,
I am a bit confused:
console.log calls:
false
false
Edit: thread.setArchived returns archived: true
maybe it doesnt mutate itself based on the calls
returns the same and fetch uses the api and not the cache or am I wrong?
im pretty sure accessing something then storing it and mutating it wont change it
if you assign .channel to thread
and then access .channel i dont know if it will mutate that way
I mean I was expecting it (the fetch call in screenshot 2) to change to true after archiving the thread
mmmm
this is some kind of bug isn't it?
TypeError: container.addMediaComponents is not a function
what to import for this?
id check the docs
Okay I made a little oopsie
forgot await for thread.setArchived, after adding await it returns true on the fetch call, but if I run this a second time interaction.channel returns archived: false
documentation suggestion for @mellow frigate:
ContainerBuilder#addMediaGalleryComponents() discord.js@14.19.3
Adds media gallery components to this container.
i am facing this discord api error when i try to send my container:
https://sourceb.in/zUrs139PmB
can anybody explain to me what does this mean? i don't really understand it
Anyone know why I would get the error Cannot find module ‘.client/BaseClient’. this only happened when I tried to put it on my server
you aren't sending the IsComponentsV2 flag
try reinstalling just in case (delete node_modules, npm i)
like npm install discord.js cause i think i tried that and it didnt work. just saw the edit
how can I check if a string is valid snowflake user ID before trying to fetch it?
you can't check if it actually belongs to a user without fetching
but if you're just trying to check that it's a snowflake, you can use some regex like /^\d{17,20}$/
Have a scenario where I need a lot of text on something I'm converting to use the Components v2 and wanting a container with sections - what is the max characters of a Text Display, is it something similar to Embed descriptions? Can't seem to find it on Discord API so wondered if anyone knew before I ended up running into problems.
I'm not totally sure there is a character limit on text display specifically, but rather just the overall character limit of 4000 across all components
Does any event get triggered when a server changes from a normal one into a community server?
documentation suggestion for @opal river:
(event) Client#guildUpdate discord.js@14.19.3
Emitted whenever a guild is updated - e.g. name change.
my bot was online. and. i randomly get this error???
what is it from???
It literally tells you where it‘s from
but im not using anything webhook
interaction replies are webhooks
They expire after 15 minutes
editing them after 15 mins results in that error
oh
I keep getting an issue with SectionBuilder
// Section 1: Combined info
const Section1 = new SectionBuilder().addTextDisplayComponents(
new TextDisplayBuilder().setContent(
`**Channel:** \`${channel.name}\`\n` +
`**Type:** \`${type}\`\n` +
`**Deleted By:** ${Executor}`
)
);
// Section 2: Separator
const Section2 = new SectionBuilder().addTextDisplayComponents(
new SeparatorBuilder().setDivider(true).setSpacing(SeparatorSpacingSize.Small)
);
// Section 3: Timestamp
const Section3 = new SectionBuilder().addTextDisplayComponents(
new TextDisplayBuilder().setContent(`**Timestamp:** <t:${TimeStamp}:F>`)
);
// Container setup
const Container = new ContainerBuilder()
.setAccentColor(0xED4245)
.addSectionComponents(Section1, Section2, Section3);
I believe the issue is related to Section2 with SeparatorBuilder, I am unsure If I supposed to use the addTextDisplayComponents if displaying the separator betweeen display text.
We used 9 text display 4 separator and 10 buttons using builders but got error that expected >=10
with componentsv2 is it possible to align text next to eachother or is it just components?
a separator is a separate component, you aren't supposed to put it inside of a text component
container.addSeparatorComponents((separator) => separator.setSpacing(SeparatorSpacingSize.Small))`
can i fetch the full slash command if a message has interactionmetadata, like to get the options provided?
DiscordJS has yet to release an update for the increased component limit...if you want to exceed 10 components, youll have to use raw api requests/data
TypeError: (intermediate value).addSeparatorComponents is not a function
sorry typo on my part...the method is supposed to be invoked on a ContainerBuilder
Oh ok
Hi, I have a question. Is it possible to "disable" an option without having to disable the entire Select menu using djs or the API?
Something similar to what can be done at https://discord.builders/#JTVCJTVE
...
"components": [
{
"type": 3,
"custom_id": "8d6563ec466148d5bee56b069927f9b7",
"options": [
{
"label": "Aggressive Boar",
"value": "b1ca8319b9e54083f827ec071a2093d8",
"description": null,
"emoji": null,
"default": false,
"disabled": true //this
}
],
"placeholder": "",
"min_values": 1,
"max_values": 1,
"disabled": false
}
Is it possible to send two components v2 in one message? If so, is that just done with an array? Like components: [container1, container2] ?
with componentsv2 is it possible to align text next to eachother or is it just components?
yes, you should be able to send it exactly like that
you have to create the const container = new ContainerBuilder() prior to calling .addSeparatorComponents
With components v2 when creating a "section", does it throw an error if you only add text display components without a thumbnail accessory / button accessory, or will it work fine?
it errors
No if there's not thumbnail or button accessory, should just use normal text display?
Like this?
const Container = new ContainerBuilder()
.setAccentColor(0xED4245)
.addSectionComponents(Section)
.addSeparatorComponents(separator =>
separator.setDivider(true).setSpacing(SeparatorSpacingSize.Small)
)
.addSectionComponents(Section2)
ive got a question :
guild.members.cache.filter
what do i have to type for people who are in voices?
is there a way to make the component container bigger based on a options like we can do in embeds ? in embed we would be able to join 2 fields together , can we do that with containers ? Nevermind i might have found a way
.filter((mem) => mem.voice.channelId)
Could also guild.voiceStates.cache.filter
@stable sun Could you help me with this?
that looks right
It's still outputting an error:
node:events:485
throw er; // Unhandled 'error' event
^
CombinedError: Received one or more errors
Emitted 'error' event on Client instance at:
at emitUnhandledRejectionOrErr (node:events:390:10)
at process.processTicksAndRejections (node:internal/process/task_queues:92:21) {
errors: [
ExpectedValidationError: Expected
at Array.map (<anonymous>) {
validator: 's.instance(V)',
given: undefined,
expected: [class ButtonBuilder extends ComponentBuilder]
},
ExpectedValidationError: Expected
at Array.map (<anonymous>) {
validator: 's.instance(V)',
given: undefined,
expected: [class ThumbnailBuilder extends ComponentBuilder]
}
]
}
well looks like neither of those errors are from your separator
looks like theyre coming from ThumbnailBuilder and ButtonBuilder
I don't have either ButtonBuilder or ThumbnailBuilder
oh...ya that makes sense
youre using Sections...a section is required to have a TextDisplay and either a Button or Thumbnail...that's the point of a section
if you just want text, use .addTextDisplayComponents
Oh, so instead of building the TextDisplay in the Section, I'll build it in the ContainerBuilder?
no...instead of wrapping your textdisplays in a section...simply pass them directly into the container
Ahhh thank you! I fixed it.
const Container = new ContainerBuilder()
.setAccentColor(0xED4245)
.addTextDisplayComponents(
new TextDisplayBuilder().setContent(
`**Channel:** \`${channel.name}\`\n` +
`**Type:** \`${type}\`\n` +
`**Deleted By:** ${Executor}`
),
)
.addSeparatorComponents(separator =>
separator.setDivider(true).setSpacing(SeparatorSpacingSize.Small)
)
.addTextDisplayComponents(
new TextDisplayBuilder().setContent(`**Timestamp:** <t:${TimeStamp}:F>`)
)
ohhhhhh. i know what it was.
If I run my bot on a server with 2 shards then I have 2 shards, but if I run the bot on 2 servers via docker and both create 2 shards. Is this handled or is it required to handle my interaction
what specifically runs the shard doesn't really matter
ah ok
shard id is shard id. a guild will always be on the same shard if you never change the total shard count
all events relating to that guild will go to the shard that is handling it, including interaction create
ok
onyl exception is interactions from DMs (and direct messages themselves) - these go to shard 0
yeah ok then thanks for the reply
can we revoke member's connection with linked role? is there any method for that?
what does responding to an interaction with withResponse: true in properties actually change?
also what is response.resource.message supposed to be here? Is the tutoral up to date?
It tells the API to respond with the interaction callback object
The interaction response message?
nvm i was using editReply so it was undefined
const menu = await interaction.reply({
embeds: [embeds[index]],
components: [row],
ephemeral: true,
withResponse: true,
})
const collector = menu.resource.message.createMessageComponentCollector({
componentType: ComponentType.StringSelect,
time: 3_600_000,
})```
`ReferenceError: ComponentType is not defined`
why? my row is made of buttons so i suspect i have to put something else in `componentType`
Seems like you didn't import it
that fixed it
the import part is missing from the tutorial on https://discordjs.guide/message-components/interactions.html#component-collectors, would be more clear if it was there
how to kick member from vc channel
VoiceState#disconnect() discord.js@14.19.3
Disconnects the member from the channel.
you can easily look at the docs to find the answer next time
how to get vc state? I have voice channel
GuildMember#voice discord.js@14.19.3
The voice state of this member
can i remove components from action rows?
yes, just pass an empty array
i mean like, from existing ones
by passing an empty array
const row = new ActionRowBuilder().addComponents(button_a, button_b)
i cant picture it. Where would i pass an empty array if i wanted to remove button_b from the row?
the empty array goes where you send the message/interaction
yeah but that removes the whole row and i only want to remove one button
then simply don’t add that button to the action row
when sending or editing
<ActionRowBuilder>.setComponents() also exists and replaces all components in the row
but there's no spliceComponents-type method, so you'd need to just set the components to the ones you want to keep
Thank you
Hello, I have a problem with localized responses
Basically I want to access properties like shown on screen below 'pl', 'en-US', etc. but i SOMEHOW can't index language object, because PROPERTY from Locale doesn't exist in object that contains ( and probably will contain for a bit ) only 2 languages ( locale codes ), so whenever I run command it either errors or failsafe to option after nullcheck
export default class extends Command {
constructor() {
super({
name: 'ping',
description: 'Check the bot\'s latency',
category: 'utils',
})
}
async run(client: any, interaction: ChatInputCommandInteraction) {
// don't ask why any, I just don't want to show type, that's all.
await interaction.reply({
embeds: [
{
color: colors.normal,
description: replacePlaceholders(lang[interaction.guildLocale!].ping ?? lang['en-US'].ping, [emotes.ping, client.ws.ping])
}
]
});
}
}
error: screen below
meanwhile just logging interaction.guildLocale returns value that I'd use in lang, but I don't want to add all languages at once
how can I solve that?
Hey! Am I the only one having a really hard time editing the ContainerBuilder from Component V2?
I can't seem to find a practical way to identify and update only a specific part of the container. Any tips?
can I listen for components with a collector after deferring an interaction and then editing it with the button row?
is there any way to stream videos with discordjs or another library
it will always throw that interaction has been deffered or replied to
there is not, because selfbots are against ToS
is there no api based way to stream
Ive noticed, it bothers me because id prefer to defer it first, then edit and listen for buttons
nope
well, think of another way, because both api and djs will just say nuh uh
u might try .then() on .editReply() so it'd look like so
.editReply().then() and u pass in .then() everything u need for collector
but im not 100% sure if it will work as intended
Hi. I am having an issue with the following code statement:
await client.channels.fetch(interaction.message.channelId);
Unless I grant administrator permission for the bot on the discord, I get the following error:
at handleErrors (/home/captbunzo/src/rotom-bot/node_modules/@discordjs/rest/dist/index.js:748:13)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
at async SequentialHandler.runRequest (/home/captbunzo/src/rotom-bot/node_modules/@discordjs/rest/dist/index.js:1149:23)
at async SequentialHandler.queueRequest (/home/captbunzo/src/rotom-bot/node_modules/@discordjs/rest/dist/index.js:980:14)
at async _REST.request (/home/captbunzo/src/rotom-bot/node_modules/@discordjs/rest/dist/index.js:1293:22)
at async ChannelManager.fetch (/home/captbunzo/src/rotom-bot/node_modules/discord.js/src/managers/ChannelManager.js:123:18)
at async Object.handleJoin (file:///home/captbunzo/src/rotom-bot/src/buttons/BattleActionButtons.js:131:9)```
Is there some specific permission I need to be granting the bot to be able to fetch a channel?
Also, I am having trouble understanding the different between `Default Install Settings` on the bot Installation page and the `Bot Permissions` part on the Bot page.
I don't know if I am doing things in a dumb way. I am trying to run edit an interaction message:
embeds: [battleEmbed]
});```
However, if I don't fetch the channel first, I get an error that the channel is not cached.
You might want to consider using editReply() instead which uses the interaction webhook to edit the message rather than the more standard channel messages route which adds additional permission requirements and such
MessageComponentInteraction#editReply() discord.js@14.19.3
Edits a reply to this interaction.
// Edit the initial reply to this interaction
interaction.editReply('New content')
.then(console.log)
.catch(console.error);
Will this work if I am editing a reply after the initial interaction has been completed, in the interaction from a button being pressed?
I am also wondering if maybe I needed to add the Guilds intent to my bot on startup. Perhaps this is why the channel was not being cached?
It should, yes
That would very likely fix your issue, yes. d.js relies on the Guilds intent for a lot of things, this being one of them
Ah, unfortunately. I cannot use editReply() as that does not edit the actual original message.
You'd want to specify the message option for it and pass the Message instance of the original message
editReply({ message: interaction.message, ... })
As this'll tell Discord which message you intend to edit with respect to the interaction
So adding the Guilds intent fixed the issue with the channel not being cached. Let me try that next suggestion.
When I try that I get the following error:
at ButtonInteraction.editReply (/home/captbunzo/src/rotom-bot/node_modules/discord.js/src/structures/interfaces/InteractionResponses.js:247:48)
at Object.handleLeave (file:///home/captbunzo/src/rotom-bot/src/buttons/BattleActionButtons.js:175:27)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)```
So to make sure I am being clear about the workflow:
- A user sends a slash command and that creates a reply to that slash command with some buttons
- Another user hits one of those buttons which does some logic and than needs to update the reply in #1
Can you share the logic relating to the buttons?
This is a Discord bot for coordinating remote raids in Pokemon Go.
The first user creates a raid via a slash command (which does stuff in the database and then replys to the slash command interaction with the raid activity and buttons.
Another user then hits a button to join the raid. That does more database stuff and then updates the original reply from the slash command of the first user.
I'm referring to the actual code
Ok
The relevant code starts on line 79
This is the code where I handle the original slash command and create the raid message
You want to swap the placement of these two statements
So that the initial reply happens first, and then the edit comes immediately after
(This is assuming you're doing the editReply() method)
I had those swapped at first. However, on line 118 I don't want to be editing the reply from line 122.
Could just use interaction.update then followUp
Yes, that's why I made this suggestion #djs-help-v14 message
I want to be editing the original message from line 116 of https://pastebin.com/SUYaaArh
Good point, that'd probably be a bit easier
My code;
embeds: [battleEmbed]
});```
Is working to update the message I want to update. However, if I don't give the bot Administrator permission, I am getting `DiscordAPIError[50001]: Missing Access`. Is there maybe a more granular permission I can give the bot rather then full admin to do this?
I'll give this a try and see how this works.
Editing a message (outside of interactions) requires the bot to have access to the channel
Is this the Manage Channels permission?
No, view channel
Thanks. Lemme try that.
I always recommend doing it via the interaction to avoid perm issues
Interactions are intended to eliminate this issue
Beautiful. Doing interaction.update() and then interaction.followup() does exactly what I need.
Thanks everyone! No View Channel permission required!
Now I just need to figure out how to delete the original message 😄
You can use interaction.deleteReply() (without extra params) since you used update() earlier
It is in response to a different button where I have not used update()
Still has to be within the 15 min tho
Line 228 of https://pastebin.com/CskwHLr5
You could try specifying the message in deleteReply. I’ve never tried this particular setup tbh
I'll try that
.deleteReply(message)
Alas, with that I get:
Error [InteractionNotReplied]: The reply to this interaction has not been sent or deferred.
I think I may have to use await interaction.message.delete(). Do you know what permission the bot needs to be able to delete that message? Once again, Administrator will do it, but I want to be as granular as possible.
You can’t use deleteReply before you use update or reply
what am i doing wrong here x_x
const section = new SectionBuilder().addTextDisplayComponents(
new TextDisplayBuilder()
.setContent('Choose an Option Below:')
);
const container = new ContainerBuilder().addSectionComponents(section);
return message.reply({ components: [container] });
can grab errors if it's not a dumb thing im doing wrong (they're validation errors)
That would help
Since it will tell us what's not validating
ExpectedValidationError: Expected
at _InstanceValidator.handle (E:\Discord Bots\Nuclei\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:1531:75)
at _InstanceValidator.run (E:\Discord Bots\Nuclei\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:958:23)
at _UnionValidator.handle (E:\Discord Bots\Nuclei\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:1960:32)
at _UnionValidator.parse (E:\Discord Bots\Nuclei\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:972:90)
at SectionBuilder.toJSON (E:\Discord Bots\Nuclei\node_modules\@discordjs\builders\dist\index.js:2169:37)
at E:\Discord Bots\Nuclei\node_modules\@discordjs\builders\dist\index.js:1870:64
at Array.map (<anonymous>)
at ContainerBuilder.toJSON (E:\Discord Bots\Nuclei\node_modules\@discordjs\builders\dist\index.js:1870:35)
at E:\Discord Bots\Nuclei\node_modules\discord.js\src\structures\MessagePayload.js:151:46
at Array.map (<anonymous>) {
validator: 's.instance(V)',
given: undefined,
expected: [class ButtonBuilder extends ComponentBuilder]
},
ExpectedValidationError: Expected
at _InstanceValidator.handle (E:\Discord Bots\Nuclei\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:1531:75)
at _InstanceValidator.run (E:\Discord Bots\Nuclei\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:958:23)
at _UnionValidator.handle (E:\Discord Bots\Nuclei\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:1960:32)
at _UnionValidator.parse (E:\Discord Bots\Nuclei\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:972:90)
at SectionBuilder.toJSON (E:\Discord Bots\Nuclei\node_modules\@discordjs\builders\dist\index.js:2169:37)
at E:\Discord Bots\Nuclei\node_modules\@discordjs\builders\dist\index.js:1870:64
at Array.map (<anonymous>)
at ContainerBuilder.toJSON (E:\Discord Bots\Nuclei\node_modules\@discordjs\builders\dist\index.js:1870:35)
at E:\Discord Bots\Nuclei\node_modules\discord.js\src\structures\MessagePayload.js:151:46
at Array.map (<anonymous>) {
validator: 's.instance(V)',
given: undefined,
expected: [class ThumbnailBuilder extends ComponentBuilder]
}
]
}
Sections need an accessory
Yep, so I have to use interaction.message.delete(). Do you know what permission this requires?
thanks
I wish I could find a good page which explained what permissions are required for various actions in the API.
but if you delete before you update, what would you be updating later?
and if you try to delete before replying, what would you be deleting
The current interaction is from a button. The message I need to delete is the original message the button was attached to.
Why does an thread deletion/creation event also triggers an messageupdate event. How do i ignore it in my messageupdate event
try deferUpdate, deleteReply and followUp
That original message is the reply to a slash command.
From what I can see in the docs, ButtonInteraction allows me to update the original message with update(). Access it with message. However, there is no direct access to delete the original message. That requires message.delete(), which I can't figure out how to avoid an access error without giving the bot full Administrator permission.
but do you want to update it and later delete or delete directly?
In this case, delete
then this
defers are replies, and if you deferUpdate, it makes the "reply target" the message itself
which is why deferUpdate and editReply works
if you deferUpdate and deleteReply it'll delete the message
and then you followUp to reply with the other message you want
I will try deferUpdate() and then deleteReply()
they do need to arrive in that exact order though so make sure to await
is this the proper way to print out a containerbuilder or am i doing something wrong lol
return message.reply({ components: [container] });
looks good
ah
no, it's missing the IsComponentsV2 flag
since containers are part of those
wdym
{ ..., flags: MessageFlags.IsComponentsV2 } as part of your reply options
you need that flag to send v2 components
savior
Holy moly, this and then followUp() worked
Thanks very much. The followUp is to a message, 'message could not be loaded', but that is ok.
yeah unfortunately there's no way around that since it doesn't exist anymore
other than sending a regular message but then you need to handle permissions and whatnot
is there an easier way to set accent color than a tuple 😂
const container = new ContainerBuilder().addSectionComponents(section).setAccentColor([255, 0, 0]);
(eg. hex code)
number should also work
0xrrggbb
ah yup
just realized when u said number haha
Any quick tip on how to automatically delete ephemeral responses after a minute or two?
just a regular setTimeout
but I'd say it's really unlikely someone will still have the ephemeral reply around after a minute
most people just close it after reading it
Cool beans, thanks again
Is there a way to ask a user for additional input after the initial invocation of a slash command?
depends on the type of input you want, and how you want to ask for it
I have a command that needs two different strings provided to do its job. I would like to ask them for the first of those two, get their response and validate it, and then ask for the second after the first is validated.
I know I can just make them both string options for the command, but that requires that the user input both on execution, and the server owners have asked if it can be split into two steps.
well you could use a modal for the second one
if it doesn't pass, reply instead
but the check should be sync and fast
because you can't defer the modal response
so you'll need to reply within 3s
Hmm... Okay. Perhaps a better strategy would be to get the first string on execution, validate it, and then reply with a DM asking the user for the second? Would that be possible?
sure, whether on a modal or by awaiting messages
DMChannel#awaitMessages() discord.js@14.19.3
Similar to createMessageCollector but in promise form. Resolves with a collection of messages that pass the specified filter.
// Await !vote messages
const filter = m => m.content.startsWith('!vote');
// Errors: ['time'] treats ending because of the time limit as an error
channel.awaitMessages({ filter, max: 4, time: 60_000, errors: ['time'] })
.then(collected => console.log(collected.size))
.catch(collected => console.log(`After a minute, only ${collected.size} out of 4 voted.`));
I think that is going to end up being a better option. Appreciate the help!
I am trying to attach a Button to my .addSectionComponents, but I seem to get continuous errors.
.addSectionComponents(
new SectionBuilder().addTextDisplayComponents(
new TextDisplayBuilder().setContent(
`**Guild ID:** \`${GuildID}\`\n` +
`**Duration:** \`${Duration} days\`\n` +
`**Reason:** ${Reason}\n` +
`**Granted By:** <@${Interaction.user.id}>`
)
)
.setButtonAccessory(
new ButtonBuilder()
.setCustomId('some_button')
.setLabel('Click Me')
.setStyle(ButtonStyle.Primary)
)
);
Errors:
[SLASH COMMAND ERROR]: trial-premium 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
are you sure it comes from that line? can you share the whole code and error in a bin
const Container = new ContainerBuilder()
.setAccentColor(0x57F287)
.addTextDisplayComponents(
new TextDisplayBuilder().setContent(`# Trial Premium Granted`)
)
.addSectionComponents(
new SectionBuilder().addTextDisplayComponents(
new TextDisplayBuilder().setContent(
`**Guild ID:** \`${GuildID}\`\n` +
`**Duration:** \`${Duration} days\`\n` +
`**Reason:** ${Reason}\n` +
`**Granted By:** <@${Interaction.user.id}>`
)
)
.setButtonAccessory(
new ButtonBuilder()
.setCustomId('some_button')
.setLabel('Click Me')
.setStyle(ButtonStyle.Primary)
)
);
This is the ContainerBuilder
I meant both the code and the error in the bin
but just the error now ig
I think I was able to fixed it, but I am getting another error:
[SLASH COMMAND ERROR]: trial-premium DiscordAPIError[50035]: Invalid Form Body
data.components[0][UNION_TYPE_CHOICES]: Value of field "type" must be one of (1,).
data.components[1][UNION_TYPE_CHOICES]: Value of field "type" must be one of (1,).
data.components[2][UNION_TYPE_CHOICES]: Value of field "type" must be one of (1,).
at handleErrors (C:\Users\va495\Desktop\Bot\node_modules\@discordjs\rest\dist\index.js:748:13)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
at async BurstHandler.runRequest (C:\Users\va495\Desktop\Bot\node_modules\@discordjs\rest\dist\index.js:852:23)
at async _REST.request (C:\Users\va495\Desktop\Bot\node_modules\@discordjs\rest\dist\index.js:1293:22)
at async ChatInputCommandInteraction.reply (C:\Users\va495\Desktop\Bot\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:194:22)
at async Object.execute (C:\Users\va495\Desktop\Bot\Events\Interaction\interactionCreate.js:87:9) {
requestBody: { files: [], json: { type: 4, data: [Object] } },
rawError: {
message: 'Invalid Form Body',
code: 50035,
errors: { data: [Object] }
},
code: 50035,
status: 400,
method: 'POST',
url: 'https://discord.com/api/v10/interactions/1368471328490917920/aW50ZXJhY3Rpb246MTM2ODQ3MTMyODQ5MDkxNzkyMDpNY0lJYmVzakFSYUNJWmRxYTg4VWZrSG5WU1BJOFkzc1UwcmFodnc0bGhWbG1zZ3ZkZGMxRVVKUk8zRjVJc051VXdaMFhlMzRaWFNGODBIV3Y3OXJ3UWRVMGkyVTczWXc3S0U0Q3hORzdSZnBzZ1d3d1FuaTJzUDdQUTF4Y1FjRA/callback?with_response=false'
}
(node:120652) Warning: Supplying "ephemeral" for interaction response options is deprecated. Utilize flags instead.
(Use `node --trace-warnings ...` to show where the warning was created)
@rose tangle
you aren't sending the IsComponentsV2 flag
I think is related to interaction.reply
return Interaction.reply({
...Container.toJSON(),
flags: MessageFlags.Ephemeral,
allowedMentions: { parse: [] }
});
and for the deprecation notice:
The ephemeral option when replying to an interaction will be removed in v15
- {..., ephemeral: true}
+ {..., flags: MessageFlags.Ephemeral}
``` Read [here](<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_OR>) on how to specify multiple flags
somewhere you're replying with ephemeral: true instead of the Ephemeral flag
the container is a component
it's not meant to be destructured that way
how you'd send multiple containers otherwise
just send it as part of the components array
Since string select menus are no longer searchable, how do i add all available roles to a select menu
they were never searchable
and you could always use a role select menu for that
I found where the error is coming from, and it's from my other sub command interaction.reply
RoleSelectMenuBuilder discord.js@14.19.3
Class used to build select menu components to be sent through the API
well that codeblock is still wrong, in case you're trying to send a container like that
No, I changed the ContainerBuilder
const Container = new ContainerBuilder()
.setAccentColor(0x57F287)
.addTextDisplayComponents(
new TextDisplayBuilder().setContent(`# Trial Premium Granted`)
)
.addSeparatorComponents(
new SeparatorBuilder().setDivider(true).setSpacing(SeparatorSpacingSize.Small)
)
.addSectionComponents(
new SectionBuilder()
.addTextDisplayComponents(
new TextDisplayBuilder().setContent(
`**Guild ID:** \`${GuildID}\`\n` +
`**Duration:** \`${Duration} days\`\n` +
`**Reason:** ${Reason}\n` +
`**Granted By:** <@${Interaction.user.id}>`
)
)
.setButtonAccessory(
new ButtonBuilder()
.setCustomId('trial_extend')
.setLabel('Extend')
.setStyle(ButtonStyle.Primary)
)
);
return Interaction.reply({
components: [Container],
flags: [
MessageFlags.IsComponentsV2,
MessageFlags.Ephemeral
],
allowedMentions: { parse: [] }
});
yeah that looks good now
I'm getting tired of this error
It makes my bot not listening for DM messages when I replace with as TextChannel
Ensure channel.isSendable() is true
Oooooh noooo la polizia, this library.... Thank you !!
Why the interaction.channel is null when the interaction is used in a DM channel ?
To receive direct message events on "messageCreate" with your bot, you will need:
- The
DirectMessagesgateway intent - The
Channelpartial setting
Missing Channel partial I guess
We should update that tag somewhat
Nah, that tag is for receiving DMs. Not for receiving interactions in DMs
...
can i use a regex for verifying the input entered by the user?
in a modal?
I have that intent enabled already, so the channel is partial by default in DMs ?
like slashcommand options
sure, but only after they submitted
Yes
okay
Hi, is it possible to send containers with webhook? I can send content or embed normally.
const webhookClient = new Discord.WebhookClient({ url: webhookUrl })
await webhookClient.send({ components: [container], flags: 1 << 15 })
#announcements is a webhook
Need withComponents: true in the send call for a webhook
Ok ty
Error loading command test.js: Error: Cannot find module 'v2componentsbuilder'
Require stack:
Hi can anyone help? i want to try new componentsV2 but i got this error
op mb i havent installed the package v2 huhu sorry guys
djs supports it natively
no need for any 3rd party packages
so no need to use v2componentbuilder? just i need to update to latest?
i got this
Error in interactionCreate: DiscordAPIError[50035]: Invalid Form Body
data.components[0][UNION_TYPE_CHOICES]: Value of field "type" must be one of (1, 9, 10, 12, 13, 14, 17).
is it possible to send a survey in components v2? because there is no survey here
Start by using the enum or just builders so you dont have to remember the types, which are incorrect
No
ugh
why?
Because discord didnt make it
Because it's not a V2 component
You're looking for poll
Which already exists as a separate thing
i still got error, im updated to discord.js, can u give me a sample code that show v2? like a container components
with componentsv2 is it possible to align text next to eachother or is it just components?
#announcements has example code
Scroll a bit, it's attached with v2 announcement post
Do you mean like fields? No
hmm alright
can i add an image to the top right of the container
Sure, using section components.
You can use a Section as the first component, and add a Thumbnail as its accessory
do sections support images as well or only thumbnails as accessory?
A thumbnail is an image
can you help me to correct my test code?
https://srcb.in/NobdX6DydG
Not sure I understand the question sorry
Nah, I asked in a stupid way sorry. With components v2 can you add a big image as well as you could in legacy / embeds? if yes, how many or how? only one, or one per section?
There is a MediaGalleryComponent
const container = new ContainerBuilder()
.addSectionComponents([
new SectionBuilder()
.setThumbnailAccessory([
new ThumbnailBuilder()
.setURL(interaction.client.user.displayAvatarURL(iconConfig))
])
])
.addTextDisplayComponents(
new TextDisplayBuilder()
.setContent([
"test",
"test",
].join("\n"))
);
whats wrong with this?
Please use enum, no one remembers component types. And your issue is you are missing v2 flag, if not more
Which supports multiple images
Awesome, thank you! 
and you can have multiple of these galleries also per message? or only one?
dam, v2 seems to be quite a huge improvement
Probably the array you pass in the accessory
There can be only one accessory
Uhh probably multiple galleries honestly but I dont know
time for TIAS then 😄 thanks for the help!
like this? https://srcb.in/zsD0omgtHc
Umm, why are you second guessing stuff? And creating your own enum, d.js exports them, and use it. The v2 flag is still wrong
Hey guys I have a quick question about interactive buttons in components v2. I want to shift a single button to the right, surely I shouldn't be doing .addSeparatorComponents()to achieve this?
its not possible to control button positions
Right-aligned buttons exists only as section accessories
Can you interact with buttons in containers or they are just link
You can interact
If you look at the example in #announcements message you can see the link buttons are positioned to the right? so these are section accessories?
yes
Thanks
can you add a thumbnail for each section?
yes
const container = new ContainerBuilder()
.addSectionComponents([
new SectionBuilder()
.setThumbnailAccessory(
new ThumbnailBuilder()
.setURL(interaction.client.user.displayAvatarURL(iconConfig))
)
.addTextDisplayComponents(
new TextDisplayBuilder()
.setContent([
"test1."
].join("\n"))
),
new SectionBuilder()
.addTextDisplayComponents(
new TextDisplayBuilder()
.setContent([
"test2."
].join("\n"))
)
]);
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
Your second section doesn't have any accessory component
what's an accessory? just a thumbnail?
or a button
so if one section has an accessory then all of them do?
All sections must have an accessory, its required
If you dont want one, dont use a section, just add TextDisplayComponents to the container directly
ohhh okay
Am I able to defer a reply to a ModalSubmitInteraction?
so ig i can think of a section as a wrapper
Peak, thank you
just tried, seems to work fine
Not really a d.js question, but yeah make the bot private
my bad
Hey!
I can't seem to find a practical way to identify and update only a specific part of a ContainerComponent.
const existingContainer = interaction.message.components[0] as ContainerComponent;
I'm trying to use IDs to target a specific section, but even when I find it, I don't understand how to recreate the container and update just that part.
Any advice?
how do I get emoji ID?
!kek
backslash before emoji
First you shouldn't need to use as in this case second are you using a container
When creating an autoposter system with top-gg/sdk, I get an error like this and when I try it in a different place, it works. What is this error exactly?
Ask over in #1081585952654360687 this error is not related to d.js
sorry ok
I'm sending a ContainerBuilder that contains two select menus, and on interaction with one of them, I'm trying to edit a specific part of the container. What should I use if I shouldn't rely on as?
hey, i was just wondering if bots being able to foward messages is possible yet?
How do i map over all components from an ActionJRowBuilder to get their customIds? it seems the button type is only holding disabled style and type
Message#forward() discord.js@14.19.3
Forwards this message
perfect thank you!
can I have custom emojis in autocomplete popups? Like this, but with a custom one
to get the elements in inside the container
const c = message.components[0]
if (c.type === ComponentType.Container){
const cc = (c as ContainerComponent).components
}
you need to access the components in the container
@tribal warren sorry Sent the message with out what I meant
could you give more context
No
forum threads can only be 'public'?
yes
dose discord.js support v2component?
yes
docs?
const comps = [
new ActionRowBuilder<ButtonBuilder>().addComponents(
new ButtonBuilder()
.setLabel("Play it now")
.setStyle(ButtonStyle.Secondary)
.setCustomId("inline_skip_song"),
new ButtonBuilder()
.setLabel("Move it to top of Queue")
.setStyle(ButtonStyle.Secondary)
.setCustomId("inline_top_queue")
),
]
const validIds = comps.map(v => v.components.map(x => x.data.customId)); // data.customId does not exist
const validIds2 = comps.map(v => v.components.map(x => x.toJSON().customId)); // toJSON().customId does not exist
there is not much info
For starting point, checkout the #announcements that has the example code attached. You can also use https://discord.builders which is easier
its not in discordjs.guide?
Not yet no
Anyone know why <role>.color.toString(16) is sometimes giving me invalid color codes. E.g #9ff00 when it should have given #09FF00
you'd have to do color.toString(16).padStart(6, "0") because there's no leading zero normally
or just skip all this and use role.hexColor
forgot about that 😂 , thanks
I am not at my PC so forgive that syntax. Try Comps.components.map()
Hi
again the TYPESCRIPT TYPE is saying custom_id nor customId exists on a Buttonbuilder
const validCustomIds = components.map(x => x.components.map(y => (y.data as APIButtonComponentWithCustomId).custom_id))
this would work
but its ugly
I will try when I am in front of my pc
do i need to fetch member after getting id from slash command option
if its a string option yes
if its a user option, use getMember
K
I suppose you cannot update a legacy message to one that uses components v2 with <interaction>.update?
documentation suggestion for @half night:
ChatInputCommandInteraction#editReply() discord.js@14.19.3
Edits a reply to this interaction.
// Edit the initial reply to this interaction
interaction.editReply('New content')
.then(console.log)
.catch(console.error);
You can
and add the flag property
You just can't go back to legacy once you do
I got an error message, but figured out that the legacy message I wanted to update had a content field. Or if I explicitly set that to an empty string then it may work? edit: ye, seems so 😄
Rate limits time to reset and retry after both in ms?
got it
const a = [new ActionRowBuilder<ButtonBuilder>()]
a[0].components.map(c => c.data.id)
what's the type of that array insferred as here?
doesnt work
ActionRowBuilder<ButtonBuilder>
is does you are missing that the actionrow is in an array
sorry is read you origonal code. will fix but customId does not exsit on data
here you go
const ars = [new ActionRowBuilder<MessageActionRowComponentBuilder>()]
const customIds: (number | undefined)[][] = ars.map( ar => ar.components.map( c => c.data.id))
CustomId doesn't exist on link buttons (and premium?) So if you rule out those, you should have it
is jesting djs overkill (for fun and learning)
A user bot can't get the accent color? User#accentColor and User#hexAccentColor return undefined
upd: Fetching forcefully helped, but it's completly the wrong color. My profile color is #256091, but it is returning #232428
i have it if i assert the type for withCustomId as you can see above
User bot?
User-installed bot
Can't get used to it
Not sure if accent or banner, plus there's no access to gradient (secondary color) if I'm not mistaken
The primary and secondary colors are the same, although maybe is the accent color just an estimated color from my avatar?
No idea, honestly. Someone in ddevs might have a better answer which color is sent under which property
Received one or more errors
input[0]
| CombinedPropertyError (1)
| Received one or more errors
|
| input.value
| | ValidationError > s.string()
| | Expected a string primitive
| |
| | Received:
| | | 0
input[1]
| CombinedPropertyError (1)
| Received one or more errors
|
| input.value
| | ValidationError > s.string()
| | Expected a string primitive
| |
| | Received:
| | | 0
input[3]
| CombinedPropertyError (1)
| Received one or more errors
|
| input.value
| | ValidationError > s.string()
| | Expected a string primitive
| |
| | Received:
| | | 0
input[4]
| CombinedPropertyError (1)
| Received one or more errors
|
| input.value
| | ValidationError > s.string()
| | Expected a string primitive
| |
| | Received:
| | | 0
input[5]
| CombinedPropertyError (1)
| Received one or more errors
|
| input.value
| | ValidationError > s.string()
| | Expected a string primitive
| |
| | Received:
| | | 0
input[6]
| CombinedPropertyError (1)
| Received one or more errors
|
| input.value
| | ValidationError > s.string()
| | Expected a string primitive
| |
| | Received:
| | | 0
input[7]
| CombinedPropertyError (1)
| Received one or more errors
|
| input.value
| | ValidationError > s.string()
| | Expected a string primitive
| |
| | Received:
| | | 0
type casting and explicitly checking are two different things. It is generally not recommended to typecast unless you are absolutely sure that it is what you are asserting it as
Code? #how-to-get-help
hello,
i'm trying to use String Menus, but i'm encountering an issue
this is my code:
const exploitReport = new StringSelectMenuOptionBuilder()
.setLabel("Exploit Report")
.setDescription("A ticket that will be made for reporting exploiters.")
.setValue("exploit_report")
const appealReport = new StringSelectMenuOptionBuilder()
.setLabel("Appeal Report")
.setDescription("A ticket that will be made to appear for, what you think, a false ban.")
.setValue("appeal_report")
const stringSelect = new StringSelectMenuBuilder()
.addOptions([
exploitReport,
appealReport
])
.setCustomId("ticket_support")
.setPlaceholder("placeholder")
await interaction.reply({
components: [stringSelect],
flags: [
MessageFlags.Ephemeral,
MessageFlags.IsComponentsV2
]
})
and this is the issue i'm getting : https://pastebin.com/BUu6ag1r
well the issue is this
And i explained how you can fix it. If typecasting helps then sure, but it is generally not recommended
code is big and only intrection code is in 600 lines or more
i dont have the link set and its not a premium button
does client.channels.fetch() work for a channel id even if the guild is not part of the shard the client is in? I hope you get what I mean
Paste rhe relevant part
you need to put the menu in an action row
ah
thanks
and this does not help
the error will tell you where it happened though...
It does, but it is not recommended. You should broadcastEval to get the channel from the cache from the shard that handles it. Because as for fetching you'll be handling a channel in a shard that potentially doesn't handles it
we don't care for all of that. show us where the error happened
Here is what I found to work
const ars = [new ActionRowBuilder<MessageActionRowComponentBuilder>()]
const customIds: (number | undefined)[][] = ars.map( ar => ar.components.map( c => c.data.id))
Okay
that's not customIds though
id is a different property
sorry your right my bad
yeas the property i am looking for is data.custom_id (if possible without type assertion)
in most of the slash command i got this error so i shared full create-intrection code
show us full error and the code lines it references
You may potentially need to check it in the same scope of the .filter() though if typescript still doesn't narrow it, then ig typecast should be the solution
put in some debugging effort yourself
where should i share the full error
'customId' in button ? button.customId : null
nop sadly not
the Button does not have customId as a property
Then what Qjuh said
because it is in y.data in your case
so you check the wrong object
but ButtonBuilder.customId === undefined
Also customId is not the same as custom_id
you check if it exists in y but then try to access it on y.data. you need to check in y.data for that to work
yes i know but this isnt really a type safe way of developing
const validCustomIds = components
.flatMap(x => x.components.flatMap(y => "custom_id" in y.data ? y.data.custom_id : null))
.filter(x => x !== null);
why cant you make somehow the class type that it has customId in there infereded and when you call setLink or smt then it removes that type
it actually is. in is a perfectly valid typeguard
that is beter
casting is less type safe than using typeguards though
yes but i dont want to check all the time wehter it's custom_id or customId, etc. in the past it was for e.g. customID (v12)
like this
const ars = [new ActionRowBuilder<ButtonBuilder>()]
const customIds = ars.map( ar => ar.components.map(b =>{
if ('custom_id' in b.data) {
return b.data.custom_id
}}
))
I am trying to edit a message which might be in a different shard. Can I use client.messages.fetch() in a broadcastEval() ? or would that not be necessary
we do. the issue is you having an ActionRowBuilder containing possibly any type of button and then try to get buttons from it that are interactive. so you need to check for them having a customId (or filter by type, but that needs ts actually being able to infer a typeguard from a .filter call)
that looks perfectly typesafe to me btw
so you are basically saying the problem with type checking lays into ts?
partly, yes
but it removes performance on 10000 checks about 2.84ms
🤡
don't write javascript in the first place if those numbers are concerning to you
you can have performant products in js/ts
e.g. buffer handling faster than in rust
Why use fetch? Just check cache, if it doesn't return a channel then return, if it does then perform your operation. If you use fetch it will return the channel in every shard as it directly queries the api causing it to duplicate whatever you initially wanted to do with the channel
someone help me
Okay I understand it now thanks
ofc. you can, the question is if you should.you can always fetch a message on any shard. you should hwoever fetch it on the CORRECT SHARD else you will get caching issues. if you need to edit a message which is not cached, you need to figure out a way to figure out on which shard it was (e.g. through guildId)
You were asked to share the full error, you haven't done that yet. You can't expect us to read through 1000s line of code to find issues for you
The error will show you where it is coming from
i also asked where to share full error
not to mention there is no such thing as <Client>.messages (my reply got eaten)
should i put error also in same gist ?
In a different gist
error is from index.js line 932. your code gist has less lines than 932
i provided block
give us the code around that line. not a huge block of useless code
addfeild is on 932
const embed = new EmbedBuilder()
.setTitle(`🤖 Your Bot Control Panel`)
.setColor(0x00ffff)
.addFields(
{ name: 'Server', value: `${botData.ip}:${botData.port}` | undefined, inline: true },
{ name: 'Username', value: botData.username | undefined, inline: true },
{ name: 'Status', value: isConnected ? '🟢 Connected' : '🔴 Disconnected' , inline: true },
{ name: 'Status', value: isConnected ? '🟢 Connected' : '🔴 Disconnected' | undefined, inline: true },
{ name: 'Auto-Respawn', value: botData.autoRespawn ? '✅ Enabled' : '❌ Disabled' | undefined, inline: true },
{ name: 'Auto-Reconnect', value: botData.autoReconnect ? '✅ Enabled' : '❌ Disabled' | undefined, inline: true },
{ name: 'Random Movement', value: botData.moveRandomly ? '✅ Enabled' : '❌ Disabled' | undefined, inline: true },
{ name: '24/7 SRV Rotation', value: botData.srv247 ? '✅ Enabled' : '❌ Disabled' | undefined, inline: true },
{ name: 'Chat Promotion', value: botData.showPromo ? '✅ Enabled' : '❌ Disabled' | undefined, inline: true }
)
.setTimestamp();```
value needs to be a string. not a number, not undefined

and | is bitwise or, definitely not what you want
can you give me example as im new
value: (botData.srv247 ? '✅ Enabled' : '❌ Disabled') ?? 'undefined'
fixed?
documentation suggestion for @winter vine:
Bitwise OR (|)
The bitwise OR (|) operator returns a number or BigInt whose binary representation has a 1 in each bit position for which the corresponding bits of either or both operands are 1.
spoonfeeding won't help them. not to mention that that () can never be nullish, so the ?? is useless
I know, I was righting an explination but I am thingking is a wast of time after the "fixed?" message
sorry
about the nullish I noticed that after I hit send
Look is just is a basic error about you giving the builder the wrong type is the bitwise or. and is a js error related to js not d.js
next time just write the explanation how they can fix it instead. spoonfeeding won't help anyone, even less when it's not guaranteed to be correct
oh but it was writen by chatgpt
in a StringSelectMenuInteraction, to get the option that was pressed, do i just do StringSelectMenuInteraction.values[0]?
don't use AI to make code

that explains a lot. AI can't code if you don't understand it enough to correct the halucinations of the AI in it.
That is right. I believe. just checking that you only are allowing one option to be selected
thanks now ill code self
can you give me a youtube video
guide suggestion for @winter vine:
Getting Started: Introduction
read more
cool
cause on the docs it says "The values selected", altho it's only possible to select one
ya it is just an array with only one element in that case
thanks 👍
i cant edit message with already have content via compoenent v2
After spending way too much time experimenting, I finally figured out how to recreate and edit the container.
thats intended
how to resolve?
you can only edit the components when editing a components v2 message
you can, but then you need to remove the content while editing
ah I misunderstood
however you cannot edit it to downgrade it to not be components v2. once it is components v2 it must stay as that
content has to be null on the edit of upgrading the message to a cv2 flagged message
i already have old embed and my bot just update embed every time, so I need to update my embed to component v2 but its have content.. so i need to remove content then update it?
in the edit just set content: ""
can someone tell me how to set it so that after you have selected an option in the select menu, it automatically remains unselected. no new message should be sent in or the message should be set as edited?
not working you cannot pass content when using component v2
message.edit({
content: null,
embeds: [],
flags: MessageFlags.IsComponentsV2,
components: [myComponents]
});
you can as long as its empty
i know empty string works as i do that
null probably works too i havent used that myself tho
documentation suggestion for @proud bay:
StringSelectMenuInteraction#deferUpdate() discord.js@14.19.3
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);

keep off-topic to #archive-offtopic or in case of a shitpost not even there
src/plugins/utils/JpTranslation.ts:67:13 - error TS2322: Type 'EmbedBuilder' is not assignable to type 'APIEmbed | JSONEncodable<APIEmbed>'.
Type 'EmbedBuilder' is not assignable to type 'JSONEncodable<APIEmbed>'.
The types of 'toJSON().type' are incompatible between these types.
how to fix this?
everything just dyin after i updated djs 😭
Where do you import EmbedBuilder from?
npm ls discord-api-types
how to make like a Select Menu That has Roles selection & users can search roles
RoleSelectMenuBuilder discord.js@14.19.3
Class used to build select menu components to be sent through the API
oh thanks
from when it is in discord.js ?
hey, i'm using formatEmoji to display an emoji by id, but it doesn't appear in my webhook embeds. i tried inviting the bot to the server, as well as logging and pasting the emoji into the channel, which shows the correct emoji.
am i not able to use app emojis in webhooks?
i just tested it myself and webhooks can send app owned emojis. works fine for me
only if the webhook is owned by the bot itself
yes
ahh, you're right. thank you
Sections can only have one text display component
Subcommandgroups can have description?
@peak hare @wary coral you can have more than one text display in a section
however you can only have up to 3
all options are required to have descriptions, regardless of whether they're viewable or not
Oh so it is only one accessory and up to 4 text display
however you can only have up to 3
where does the data go lmao
ask discord 
and can it be fetched?
as part of the command data with <Client>.application.commands.fetch(), yes
in componentv2 , which one is for adding a thumbnail ?
addSectionComponents
thumbnails can only be section accessories
(so <SectionBuilder>.setThumbnailAccessory() when adding a section)
and the section also requires text components, not just the accessory (thumbnail)
it has to be in container?
No
what about dividers?
Separators, same answer
Nothing needs to be in a container
i dont have the setThumbail accessory ? is it normal ?
On SectionBuilder, not container
That’s still the container. The section would be inside those ()
Question (AuditLogs) how do I make use of actionType and targetType they seem to be enums but GuildAuditLogsTypes doesn't seem to be a thing and using AuditLogEvent gives me a TS error:
ah ok got it now
What is the correct way to get the count of how many users installed the user-installable app? ( client.users.cache.size tells me a different number)
documentation suggestion for @delicate pike:
ClientApplication#approximateUserInstallCount discord.js@14.19.3
An approximate amount of users that have installed this application.
You don‘t need that at all. They already are strings
Is it a very approximated count? Because right now, it's just null
So the better question would be: what are you trying to do with them? Since all information they carry is contained in action already
Did you fetch the ClientApplication?
client.application.fetch()
No I didn't, my bad
ah fantastic, thanks
Can anyone help me understand what I'm doing wrong with this collector? I can't seem to do a "Quiz" style interaction. I can get the first question to start, but any successive questions don't seem to actually update/edit the response.
export const handleKiaiImport = async (interaction: ButtonInteraction) => {
const { guild, guildId } = interaction;
if (!guild || !guildId) {
const errorEmbed = new ErrorEmbed('Invalid Guild', 'The guild ID is invalid');
await interaction.reply({ embeds: [errorEmbed], flags: MessageFlags.Ephemeral });
return;
}
const questions = new Map([
// Removed for brevity
]);
const questionEmbed = new EmbedBuilder()
.setColor(Colors.Blue)
.setTitle(questions.get('overwriteXp')!)
.setDescription(questions.get('overwriteXp')!);
let questionRow = createQuestionButtons('overwriteXp');
let message = interaction.message
if (interaction.customId.includes("kiaiStartOver") || interaction.customId.includes("kiaiImportYes")) {
await interaction.reply({
embeds: [questionEmbed],
components: [questionRow],
flags: MessageFlags.Ephemeral
});
}
const collectorFilter = (i: MessageComponentInteraction) => i.user.id === interaction.user.id;
const collector = message.createMessageComponentCollector({ filter: collectorFilter, time: 15000, max: 6 });
collector?.on('collect', async (i: MessageComponentInteraction) => {
if (i.customId.includes("kiaiStartOver")) {
collector.stop();
return;
}
const [_key, questionId, _answer] = i.customId.split('_');
switch (questionId) {
case 'overwriteXp': // Ask the next question
questionEmbed.setTitle("Overwrite XP");
questionEmbed.setDescription(questions.get('weighXp')!);
questionRow = createQuestionButtons('weighXp');
break;
case 'weighXp': // Ask the next question
questionEmbed.setTitle("Import Cooldowns");
questionEmbed.setDescription(questions.get('importCooldowns')!);
questionRow = createQuestionButtons('importCooldowns');
break;
case 'importCooldowns': // Ask the next question
questionEmbed.setTitle("Import Role Rewards");
questionEmbed.setDescription(questions.get('importRoleRewards')!);
questionRow = createQuestionButtons('importRoleRewards');
break;
case 'importRoleRewards': // Ask the next question
questionEmbed.setTitle("Stack Role Rewards");
questionEmbed.setDescription(questions.get('stackRoleRewards')!);
questionRow = createQuestionButtons('stackRoleRewards');
break;
case 'stackRoleRewards': // End of questions, review the answers..
break;
}
await i.update({ embeds: [questionEmbed], components: [questionRow] });
});
collector?.on('end', (_) => {
// Removed for brevity
});
}
You shouldn’t i.message.reply and instead need to reply to the interaction i or do i.update and you did
It also just hangs with i.update.
Hang where?
Executes all the way up to i.update and does nothing. i have nothing in the collector.on('end')
Since this is a ButtonInteraction that starts all of this: how is that getting handled? Does the handler for that interfere with your collector?
How did you verify that to be the case?
const execute = async (interaction: ButtonInteraction) => {
const { customId } = interaction;
if (!interaction.isButton() || !customId) return;
if(customId.includes('kiai')) {
await handleKiaiImport(interaction);
return;
}
I straight up skip any other handling whenever the customId includes 'kiai'. I verified by setting a breakpoint on that line, and I reach it each time.
can anyone help me
And what do the customIds of your questions look like? Since you hid that away in another function
Do you have a handler for unhandledRejection and/or uncaughtException? If so does that log anywhere?
const createQuestionButtons = (questionId: string): ActionRowBuilder<ButtonBuilder> => {
return new ActionRowBuilder<ButtonBuilder>()
.addComponents(
new ButtonBuilder()
.setCustomId(`kiai_${questionId}_yes`)
.setLabel('Yes')
.setStyle(ButtonStyle.Success),
new ButtonBuilder()
.setCustomId(`kiai_${questionId}_no`)
.setLabel('No')
.setStyle(ButtonStyle.Danger),
new ButtonBuilder()
.setCustomId(`kiaiStartOver`)
.setLabel('Start Over')
.setStyle(ButtonStyle.Secondary)
);
};
Without code there’s not much we can tell you
oh i gone sent it
So they all include kiai. There’s your issue
Yes, but the questionId switches with each question.
But still your other handler will try to reply to it as well as your collector
This one
Okay so when we construct a collector, do we only want to do it once and every button interaction thereafter should not pass through and recreate the collector? So only handle it once, then every continuous interaction simply skip? I figured that'd result in a non-existent memory reference
I was under the impression we needed to pass every button interaction into it.
No, your handling of the collector is fine. What isn’t is that your other handler matches the button‘s customIds too
Here is the command code
You mean this? There is only one handler for these buttons.
if(customId.includes('kiai')) {
await handleKiaiImport(interaction);
return;
}
No. That calls your handleKiaiImport which will reply with the questions. And your collector also tries to respond to each of your question buttons. Hence two places trying to respond
Or rather you start another collector
I think I see what you're saying now. So the first question fires, which then causes the collector to attempt to collect it because it matches, thus following up with an additional reply, despite not being intended.
So we want the collector to ignore the first interaction.
can anyone help me with this error
https://sourceb.in/CJvmUG3dP5
https://srcb.in/bEqm8lZ5jg
you have to import from djs
not from dapi types
?
Looks like you're attempting to create an object from a static reference.
const FirstContainer = new Builders.ContainerBuilder()
you defined your Builders as dapi types. Not too sure as to why you imported it twice under a different name too
just import from djs directly
you even have the import for ContainerBuilder there
I cannot find this "Two places" trying to respond. I have one that responds only for the first question, right before constructing the collector, and then the collector then takes every question thereafter updating.
- I have a single
buttonClickEventthat passes all interactions that havekiaiin it's custom ID directly to `handleKiaiImport. - I have an "Initial Reply" that verifies that the customId is
kiaiImportYes<- Eg entry point for the questions. - We create a collector which filters out all customID's that do not match the KVP.
- We update once there, for each new interaction.
- Never make it past the first question, the bot simply times-out. No errors.
- The buttons created are uniquely identifiable when creating the action rows.
Might need to explain it to me like I'm 5, and I'm probably going to kick myself whenever I see the problem xD
You create a collector immediately after your first reply. Then when you use a button on that you create another collector. On the second reply you would create your third collector. All of them trying to respond
Okay, so we only create a single collector instance. Do I need to maintain that collector reference anywhere or will it just work automagically?
Just don’t let the buttons on your quiz go through the outer check calling handleKiaiImport, only handle them in your collector. Or don’t use a collector at all and handle all the buttons in the handleKiaiImport directly. Don’t mix both approaches
The collector exists as long as no end condition applies and it will emit the collect event on each interaction passing the filter
No need to maintain it
Okay that explains a lot of my confusion. I got it to progress through the questions after ensuring only one instance existed. ❤️ Thanks a ton, also thanks for the additional explanation that'll help me tremendously going forward
i'm back
Is there no builder for ComponentV2 yet?
there is
What is it called? Couldn't find anything searching v2 in docs
ContainerBuilder discord.js@14.19.3
A builder that creates API-compatible JSON data for a container.
no components contain v2
Container!
Correct. Wouldn’t make much sense to have more than one reply to a vanished message
Sorry, I deleted it cause I realized I asked a dumb thing. I wanted to know if you can only have either a thumbnail or a button accessory, but I guess if they have seperate setter functions then they can be both present.
No. They can’t
Only one of them
Oh, okay. Thanks!
And is there a way to use links in a TextDisplayComponent or Section? Not in a form of a link button but text based / masked links / whatever they are called, I don't know sorry >.<
are you talking about hyperlinks ?
Discord markdown just works in text displays
Any markdown is available in them, yes
gotcha 
If I want to combine two message flags, is that the way?
No
That will cause flags: 0
oups
what should I do then? 😅
The ephemeral option when replying to an interaction will be removed in v15
- {..., ephemeral: true}
+ {..., flags: MessageFlags.Ephemeral}
``` Read [here](<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_OR>) on how to specify multiple flags
aaaah, thanks ^^
i might be tripping but if I get my commands using
const commands = await client.application.commands.fetch();
Then store each of them as object like this in an array [{ category: category.name, name: command.name, id: command.id }] same for subcommands
.push({ category: category.name, name: ${commandName} ${cutName}, id: command.id });
for example this: { category: 'Admin', name: 'ban', id: '1368671138879639685' },
and in an embed field I do this:
const AdminCommandsArray = [];
AdminCommands.forEach((cmd) => {
AdminCommandsArray.push(`</${cmd.name}:${cmd.id}>`);
});
embed.addFields([
{ name: bot.translate(settings.Language, `translation:help.CATEGORY.Admin`), value: AdminCommandsArray.join(', ') },
{ name: bot.translate(settings.Language, `translation:help.CATEGORY.DJ`), value: DJCommandsArray.join(', ') },
{ name: bot.translate(settings.Language, `translation:help.CATEGORY.Everyone`), value: EveryoneCommandsArray.join(', ') },
{ name: bot.translate(settings.Language, `translation:help.CATEGORY.Premium`), value: PremiumCommandsArray.join(', ') },
]);
I get an error: "Error: Received one or more errors" in the embed.addFields()
if I remove the AdminCommandsArray field, it works.
I tested each command individually and the problem is this command:
</logs channel-show:1368671139341275192>,
</logs channel-set:1368671139341275192>,
</logs channel-remove:1368671139341275192>,
what is different about that, why doesnt it work?
why does this work though:
</language list:1368671139341275189>,
</language set:1368671139341275189>,
idk I am confused af
this is what it currently looks like:
each command is "clickable" and it instantly gets inserted into the chatbox.
but it throws an error for my logs command 
what is the full error
i'm assuming whatever your bot.translate is is giving the issue
no that works, cause if I remove the logs part it translates properly "Admin commands", "DJ commands" etc. the field names
how have you determined those commands are the cause / where are those logs coming from
you might also just be over the character limit
there is a character limit per field value
Yes
Learn more about embed limits at the Discord Developer Documentation
maybe it is the field character limit. ill have to check
i am over lol.. by 13 characters...
does anybody know why I am getting this error when I try to run a command on my alt which has admin permissions and no specific required permissions to run the command were set?
Try reloading the client your alt uses
Hello, I'm trying to put an image with components v2, but im getting error:
TypeError: (intermediate value).setType is not a function
my code:
const { SlashCommandBuilder, ActionRowBuilder, MediaGalleryItemBuilder, ComponentType } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('preview')
.setDescription('Displays an image using the new media gallery component.'),
async execute(interaction) {
const imageUrl = 'https://media.discordapp.net/attachments/1011355084514394164/1181676508436246578/META_B_DINOWORLD.png?ex=68190f82&is=6817be02&hm=c14859a249fe1dbce498b32c6d5f19eab97863c946cfaea819fc6a55c6a3e664&=&format=webp&quality=lossless&width=2351&height=613';
const mediaItem = new MediaGalleryItemBuilder()
.setType(ComponentType.Image)
.setURL(imageUrl)
.setAltText('Meta B Dinoworld Preview');
const row = new ActionRowBuilder().addComponents(mediaItem);
await interaction.reply({
content: 'Here is your image in a media gallery:',
components: [row],
});
},
};
that looks ai made?
almost nothing makes sense
Yes, I've used AI because my original work didn't work, so the last couple of days I've been dealing with GPT, but he doesn't know either :d
Not everything there is AI. The logic is, but coded by me still :d
- you can't send a media gallery item directly, they go under a media gallery component (not under a row)
- if you use cv2 you need to send the IsComponentsV2 flag, and you can't send anything except components and files (that are referred to with attachment:// inside the components you send)
- there isn't a setType for media gallery items, and there isn't an Image ComponentType
expanding on the second point, if you want to send text you'll need a TextDisplay component
The image can be a link, correct?
yes
the attachment:// itself is a url
but discord images expire so your image will no longer work eventually, you should use an actual cdn
like https://
My original code is gone, would've been better to come here with that... Starting from 0 ig
so technically it only accepts links
just for testing
Do we need something like this:
const response = await fetch(imageLink);
const imageBuffer = await response.buffer();
const attachment = new AttachmentBuilder(imageBuffer, { name: "image.png" });
"need"?
attachment builder also accepts an url
and it'll do something like that internally
I ment, is the buffer required
do you know what happens in those 3 lines you sent?
Not sure.
first line fetches the url, second turns it into a buffer, which due to the url pointing to an image ends up as the image data.
and third line makes an attachment out of the buffer you made
but as said
- you can give the link to the builder, it will fetch the link on its own
- you can put the link as file in the reply, exactly the same thing will happen, but you won't have the uniform control over the file name to use for referencing it with
attachment://
So, to display image, I should have something like this:
const mediaItem = new MediaGalleryItemBuilder()
.setURL("attachment://image.png")
.setDescription("Image");
if you have attached a file named image.png to the message this is on, yes, it will put that image file into that gallery
Yes
const attachment = new AttachmentBuilder(imageBuffer, { name: "image.png" });
this is nothing new, it's exactly the same how it always worked for embeds
Do you recommend waiting for the full realise of components v2 and the guide?
I'm just experimenting :d
...full release?
It is fully released
No guide yet, sure
my favorite part is containers
Oh, for some reaosn I remember somone saying here that this is being worked on still.
We're not aware of any major changes coming from Discord and discord.js fully supports the current implementation, no more work required
Cool!
I'm trying to implement a code into my bot (which is hard for me) and it's basically going to be
person post image > bot reads image > replies with appropiate message (tesseract)
and im not sure on how to actually detect if message is an image.
Messages cannot be images, but they can have images
Check whether <Message>.attachments has a size > 0 to know if it has at least one attachment, for example
That's the thing, im not entirely sure on how to actually detect that. Not yet at least
You can detect if a message is sent via the 'messageCreate' event, which emits with the Message instance that was created (sent)
or if you mean you're not sure whether an attachment is an image, check <Attachment>.contentType
So basically
client.on('messageCreate', async message => {
if (message.content.startsWith('test')) {
message.reply('yes?')
}
});
``` or or no will suffice or a better explination o .o
just whipping that in the top of my head really
Thats the right event to listen to, yes
That will detect if a message's text starts with test but that has nothing to do with images
But "content" refers to the text
Correct, i'll be changing that. that's just a basic messageCreate to get me started
cause i'll be trying to implement tesseract to it so the bot can read the image and reply with certain words it detects :v
You'll also need to enable the right intents - Guilds, GuildMessages, MessageContent
Already done 🙂
So, so that the detection for the image is completed, now to actually stress my brain to implement the image reading :v
When creating an invite, can I set another user with the targetUser field? Or for what is this field exactly? I remember it was possible before that you could provide a user id and the invite was then created for this user.
InviteCreateOptions#targetUser discord.js@14.19.3
The user whose stream to display for this invite, required if targetType is InviteTargetType.Stream, the user must be streaming in the channel
so it's only possible for a specific user in a voice channel when he's streaming? yes
-# Didn't read the third part of the sentence...
"required if..." - when I send it and no target type is set, then discord returns an error... So I guess it's only usable then.
Trying to grab the image URL..
message.attachments.url doesn't work. Suggestions?
attachments is a collection
because a message can have multiple attachments (hence the plural)
it'd depend on which image you want
once you get it then you can get #url on it
Person post image > bot reads message (tesseract) > replies from certain words
doesn't answer the question
I don't see question?
^^
The image URL of when a user posts an image.
that's like... the best i can describe it :v
the point is that a user can send many images
eg
and not only images but any attachment in general
so I can send an image, then a .docx and another image, in a single message
Then this is gonna be very difficult for me to implement it then :v
it really only depends on which image you want when the user sends many
or if you want to process all of them
I guess i can have it trigger if a user sends more then one, it will ask to post em one at a time?
sure, you can do that, but at that point I'm not sure why you couldn't just process all of them at once
and i wouldn't have a clue on how to actually properly do that with discords API
.attachments is a collection, which is a map
you can iterate over it
or call .filter() or .find()
is the char limit still 4k even with components v2?
does djs provide any utils to check the char length of your container
Isn't the max like 2k in a message? Then it turns into a .txt?
bots have nitro technically
there isn't, though it sounds like a good idea considering there's an embedLength() and EmbedBuilder#length
you could make a feature request issue about that
it sounds very low priority though
Huh... message.type gives me 0, is there a list of definitions of types?
Wait found it on the doc https://discord.js.org/docs/packages/discord.js/14.19.3/MessageType:Enum
Heyo just wondering if this is intended or not. The height and width properties on Thumbnail and MediaGallery don't seem to do anything once sent.
This is in a section component for further context.
Ah alright cool ty
load limit?
oh, you mean file size limit?
yeah, it does
await editReply({
content: `[Not loading?](<${sd}>)`,
files: [attachment]
}).catch(async (err) => {
if (
err.code == RESTJSONErrorCodes.RequestEntityTooLarge ||
err.status == 413
) {
await editReply({
content: `-# [Media](${url})`
}).catch(() => { });
}
});
```Is there a better way of doing this? (the way I handle if the file is too large to send)
check the size BEFORE you send it?
Why’s that a better solution? The limit isn’t fixed as it can be different depending on boost level
because its faster since you dont attempt to upload it, and you can get the limit
Can check the boost level and do an if statement. It's generally good practice to prevent unnecessary API requests
APIBaseInteraction#attachment_size_limit discord.js@14.19.3
Attachment size limit in bytes
Oh I see. Will make use of this, thnx
no idea how you actually access that
doesnt seem to be implemented into actual Interactions yet
You cannot control UI sizing, no
It will adjust to the content automatically
I can't do this in any way?
You could shorten the lines of text
okay
Is there a collector for modals or do you have to use the Promisified pattern?
WHELP, got it to finally work. that took me a few hours to figure out.
client.on('messageCreate', async message => {
const worker = await createWorker('eng');
const image = message.attachments.first();
if (!image) {
return;
}
try {
const {
data: { text },
} = await worker.recognize(image.url);
await worker.terminate();
console.log(text.includes('transfer'));
if (text.includes('transfer') === true) {
message.reply('Your service is currently in the process to transfer. Please wait until that message goes away to use your service.');
}
}
catch (e) {
console.log(e);
}
});
``` BUT im wondering if i can have it use the sentence instead of just one word... can't figure out the style of method for it :v
Can I switch from components v1 to v2 from a message that already exists?
Most likely not...
is the duration for polls in seconds?
i think it's milliseconds
ty
https://gist.github.com/SkullGaming31/271aecf2c172f3fff81d79a902856c15
having a bit of trouble, everything works besides for the poll, its posts the embed with the buttons but will not post the poll, the bot has the permission to create polls and it has the intent for polls
Iirc yes, someone else asked this earlier
for polls if i use 60 for duration it gives me 2 days, i use 1 and it gives me an error
poll.duration[NUMBER_TYPE_MIN]: int32 value should be greater than or equal to 1.
duration is set to 1
Hey, I just updated from Discord v14.14.1 to v14.19.3 and now I'm getting:
DiscordAPIError[50035]: Invalid Form Body
components[0].components[0].emoji[MODEL_TYPE_CONVERT]: Expected an object/dictionary.
from the following code:
[{
type: 1,
components: [
{
customId: 'cooldowns_bake',
type: 2,
label: 'Bake',
style: timeleftBake.includes(':white_check_mark:') ? ButtonStyle.Success : ButtonStyle.Danger,
emoji: ':pizza:',
},
}]
Did emojis in components change? All the docs point towards the new components and not the old ones on discord.dev and before, unicode emoijs worked as well, but currently, I'm getting the same error. I searched for a solution here, but couldn't find it.
To confirm as well, trying:
emoji: {
name: ':pizza:',
}
didn't work as well
That shouldnt have ever worked
The unicode is \🍕
Because a poll's duration is in hours. 60 hours is two and a half days
Poll Resource - Poll Create Request Object
read more
Well, that's fun. I have to go change all my unicode emojis to use this new format (name: '🍕' worked). But, thanks for the help!
Can't i do links in Embeds? like on how we used (text)[url]
yes you can
But you got it backwards
[text](url)
I just tried it in the .setDescription and it was failing to create the text a link
Show how you did then
.setDescription('[Main side](eternalhosting.cloud)') was the line i was using
You can test it yourself
Use the https protocol
So its a well-formed URL
eternalhosting.cloud is not a link, did you mean to use template letiral?
Use https
fair
On its own, its not a well-formed URL
What is the process to actually attach a file? I need to create a JSON file and attach it to a reply. This gives me all sorts of fun "EONAME Too Long" type errors and the docs are questionable asf on this xD. Like what's a BufferResolvable?
const json = JSON.stringify(data, null, 2);
const date = new Date().toISOString().split('T')[0]; // Get just the YYYY-MM-DD part
const file = new AttachmentBuilder(json, { name: `infinitea-export-${date}.json` });
Warp your json string with buffer
Buffer
Source Code: lib/buffer.jsBuffer objects are used to represent a fixed-length sequence of bytes.
So like this?
const json = JSON.stringify(data, null, 2);
const date = new Date().toISOString().split('T')[0]; // Get just the YYYY-MM-DD part
const buffer = Buffer.from(json);
const file = new AttachmentBuilder(buffer, { name: `infinitea-export-${date}.json` });
Doing it that way results in an error like this.
You forgot the encoding, utf8 in your case
Theres more to it than that. I added the utf-8 and still fails with the same error.
const json = JSON.stringify(data);
const date = new Date().toISOString().split('T')[0]; // Get just the YYYY-MM-DD part
const buffer = Buffer.from(json, 'utf-8');
const file = new AttachmentBuilder(buffer, { name: `infinitea-export-${date}.json` });
It should be without the dash, and con you show how do you send it?
Why is that using webstreams? 
Here you go. I verified the data does exist too for sanity. Additionally I verified valid json.
const data = {
leaderboardConfig,
voiceActivityData,
messageActivityData
};
const json = JSON.stringify(data);
const date = new Date().toISOString().split('T')[0]; // Get just the YYYY-MM-DD part
const buffer = Buffer.from(json, 'utf8');
const file = new AttachmentBuilder(buffer, { name: `infinitea-export-${date}.json` });
await interaction.reply({
embeds: [
new EmbedBuilder()
.setColor('#2ecc71')
.setTitle('Thank you for using InfiniTea!')
.setDescription('We appreciate the time you spent with us. We hope you find a bot that perfectly suits your community\'s needs. Your data export is attached below.')
],
files: [file]
});
}
And it fails at the buffer from?
Nice catch.. apparently it fails on the reply.
No clue why. However xD
Can you console.log(buffer.toString()) to confirm the json is correctly contained?
Yes it's there.
Got a full stacktrace? Considering you seem to use a debugger you should be able to get a full one, not just what it showed in that popup
Standby one.
That’s… a completely different error now 
Hang on I was on a breakpoint for a hot minute might be messing it up sec
But it seems it errors in one of your own internal functions
Which means this is not a djs issue at all. You‘re hooking into undici with async hooks for some reason and that’s where it fails
Here's the corrected error.
Exception has occurred: TypeError: Invalid state: Reader released
at lazyReadableReleasedError (node:internal/webstreams/readablestream:157:19)
at readableStreamReaderGenericRelease (node:internal/webstreams/readablestream:2220:30)
at [kClose] (node:internal/webstreams/readablestream:776:5)
at readableStreamClose (node:internal/webstreams/readablestream:2037:45)
at readableByteStreamControllerClose (node:internal/webstreams/readablestream:2532:3)
at ReadableByteStreamController.close (node:internal/webstreams/readablestream:1163:5)
at BlobReader.<anonymous> (node:internal/blob:456:15)
at BlobReader.callbackTrampoline (node:internal/async_hooks:130:17)
at readNext (node:internal/blob:447:16)
at Immediate._onImmediate (node:internal/blob:493:13)
That’s just the regular stacktrace. I was asking for a full one. State that your debugger should track since it stopped at a breakpoint there
Ummm I am not sure how to get VSCode to provide an entire stacktrace. I have the flags turned on in my configuration and that's all it gives me xD
"runtimeArgs": [
"--require",
"dotenv/config",
"--enable-source-maps",
"--trace-warnings",
"--trace-uncaught"
],
Are you running the debugger? It seemed to me like you did, in which case you should see the callstack in the debugger itself
Add a .catch(console.error) to that reply() as well as a console.log before and after to further debug this
This is all it can give me. Unfortunately I can't see a way to export that call stack
That’s undici fetch. Which reply would only use if you passed a string or a URL to it. Not an AttachmentBuilder
So please do this and run without debugger
I did, the catch on the reply never gets hit, the console log before does hit the console.
console.log(file) there then
For sanity just checked the version of that package. It's up to date.
Lol
Wonder what happens if I reply, then immediately update/followup
I thought you had a console.log after that there? Did you try wiping node_modules and reinstalling?
Is there a recommended version of node I should be running par-chance?
Where did it import Buffer from? If at all
At least v18
Okay I'm much more recent than that lol
nuking node_modules did nothing.
👆 ?
Did not import. Seems it's standard.
can you try importing it from node:buffer? should not make a difference but grasping straws here
Negative ghost rider... same error. Did I inadvertently find a bug?
Wait a second...
It sat on the exception and eventually went through. TFUQ?
So how bout this. If I disable the "uncaught exceptions" in my settings, works just fine. The moment I turn that on, even if I skip faster than the 3 second limit, it will fail every time.
try running normally without debugger.
Works fine w/o debugger
Is it possible to hot reload commands as well as modify api commands (existing ones, new ones, deleting etc..)
your deploy script is, or well, should be separate
allowing you to redeploy while your bot is running
as for your code logic, you can hot reload them yes, but why not restart?
Is there a way to ge the connected social profils that are associated with a discord user account?
Just the names tho
No
Sad
Only via oauth2
But not everyone will be willing to share those with you
so with the access token when the user signsin/accepts via oauth2?
Yes, oauth2 flow with appropriate scope will allow you to request connections the user has from discord
kk
did discord.js support HTTP command? those command with endpoint
tag suggestion for @woeful kraken:
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.
ok thanks
How to make the left side of ContainerBuilder have text and the right side buttons?
using section components
Create a new section using SectionBuilder, add the text display component to that section with .addTextDisplayComponent() function, and then use .setButtonAccessory() to add the button
SectionBuilder discord.js@14.19.3
A builder that creates API-compatible JSON data for a section.
Since v14.19.0, the APIMessageActionRowComponent import is no longer found, has it changed its name ?
seems like its APIActionRowComponent now
uhh
Error in interactionCreate event: Error: Cannot properly serialize component type: undefined
at createComponentBuilder (C:\Users\LENOVO T460\Desktop\ Beta\node_modules\@discordjs\builders\dist\index.js:2212:13)
at C:\Users\LENOVO T460\Desktop\zayan\Aucto Beta\node_modules\@discordjs\builders\dist\index.js:1754:54
at Array.map (<anonymous>)
at new ContainerBuilder (C:\Users\LENOVO T460\Desktop\ Beta\node_modules\@discordjs\builders\dist\index.js:1754:35)
at handleAuctionSettings (C:\Users\LENOVO T460\Desktop\ Beta\commands\slash\auctionv2.js:24:34)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async Object.execute (C:\Users\LENOVO T460\Desktop\ Beta\commands\slash\auctionv2.js:1035:17)
at async Client.<anonymous> (C:\Users\LENOVO T460\Desktop\ Beta\index.js:135:17)
APIActionRowComponent<APIMessageActionRowComponent> -> APIActionRowComponent<APIComponentInMessageActionRow> xD
oh lol
anyone here to help me?
Invalid Array length
Expected: expected.length <= 10
Received:
| [ { data: [Object] },
| { data: [Object] },
| { data: [Object] },
| { data: [Object] },
| { data: [Object] },
| { data: [Object] },
| { data: [Object] },
| { data: [Object] },
| { data: [Object] },
| { data: [Object] },
| { data: [Object] },
| { data: [Object] },
| { data: [Object], components: [Object] },
| { data: [Object], components: [Object] } ]
at Object.run (C:\Users\LENOVO T460\Desktop\Beta\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:1045:79)
at C:\Users\LENOVO T460\Desktop\ Beta\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:972:67
at Array.reduce (<anonymous>)
at _ArrayValidator.parse (C:\Users\LENOVO T460\Desktop\ Beta\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:972:29)
at validateComponentArray (C:\Users\LENOVO T460\Desktop\Beta\node_modules\@discordjs\builders\dist\index.js:1532:191)
at ContainerBuilder.toJSON (C:\Users\LENOVO T460\Desktop\Beta\node_modules\@discordjs\builders\dist\index.js:1868:5)
at C:\Users\LENOVO T460\Desktop\ Beta\node_modules\discord.js\src\structures\MessagePayload.js:151:46
at Array.map (<anonymous>)
at MessagePayload.resolveBody (C:\Users\LENOVO T460\Desktop\zayan\Aucto Beta\node_modules\discord.js\src\structures\MessagePayload.js:150:49)
at ChatInputCommandInteraction.reply (C:\Users\LENOVO T460\Desktop\Beta\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:192:56)```
📦 Raised Component Limits 📦
We're removing the top level component limit and raising the limit on number of components in a message to 40 when using the IS_COMPONENTS_V2 message flag! We're also removing the limit on the number of components in a Container Component. Legacy messages have not changed and continue to allow up to 5 action rows.
What Changed
- Total components: The limit for total components in a message has been increased to 40.
- Top-level components: There is no longer a limit on top level components in a message (previously it was 10).
- Container Component: There is no longer a limit on the number of components in a Container Component (previously it was 10).
Resources
- Get started with Using Message Components
- Check out the changelog for more details
limit have been removed still cant use
what is your djs version
Not too sure if 19.3 even has those increased limits already
just updated to 19.3 it worked
can we inline text in container?
{
type: ComponentType.TextDisplay,
content: (`Auction Role: ${settings.auctionRole ? `:paidrepend: <@&${settings.auctionRole}>` : `:paidrepend: Not set`}`)
},
{
type: ComponentType.TextDisplay,
content: (`Blacklist Role: ${settings.blacklistRole ? `:paidrepend: <@&${settings.blacklistRole}>` : `:paidrepend: Not set`}`)
},
{
type: ComponentType.TextDisplay,
content: (`Manager Role: ${settings.managerRole ? `:paidrepend: <@&${settings.managerRole}>` : `:paidrepend: Not set`}`)
},
i wanna inline these
inlineCode discord.js@14.19.3
Wraps the content inside backticks, which formats it as inline code.
(static) Formatters#inlineCode discord.js@14.19.3
[DEPRECATED] Import this method directly from discord.js instead.
does anyone have good recommendations for node modules that can help with scheduling messages? like:
/command DATE
-> parses DATE into a timestamp, and sends a message at that time, like a reminder?
or would it be better to use discord.py for that?
you can use SetIntervals and maps/database
moment as well
hi! currently working on a way to delete bot messages from a user app via a context menu regardless of whether the bot is present in the server, and i think i'm stuck
from what i recall trying, using Message.delete() doesn't seem to work because it hasn't cached the channel yet and maybe cannot because it isn't there in the server itself (but only called through my commands), and interaction.client.rest.delete(`/channels/${interaction.channelId}/messages/${interaction.targetMessage.id}`) doesn't seem to work without me also providing the guild id which i do not think i can get
i'm working out of a context menu, so i get interaction stuff from ApplicationContextType.Message
Thank you!
if i removed them, how to use:
const rest = new REST({ version: '9' }).setToken(process.env?.token);
install the latest ones
npm i discord.js@latest @discordjs/builders@latest discord-api-types@latest @discordjs/rest@latest
module.exports = {
data: new ContextMenuCommandBuilder()
.setName("Delete this message")
.setContexts([0])
.setType(ApplicationCommandType.Message),
async execute(interaction) {
// send initial response
await interaction.deferReply({flags: MessageFlags.Ephemeral});
try {
console.log(interaction.targetMessage)
// Can I delete this message? Quickfail interactions
console.log(interaction.user.id)
let message = interaction.targetMessage;
if (APPLICATION_ID != message.author.id) { interaction.editReply("..."); return; }
else if (interaction.user.id != message.interactionMetadata.user.id) { interaction.editReply("..."); return }
// delete post
// message.delete()
await interaction.client.rest.delete(`/channels/${interaction.channelId}/messages/${interaction.targetMessage.id}`)
await interaction.editReply("...")
} catch(e) {
console.log(e)
await interaction.editReply("...");
}
},
};
this code block currently outputs a 50001 missing access error
npm i discord.js@latest @discordjs/builders@latest discord-api-types@latest @discordjs/rest@latest
run this in your terminal it will work then fine
No
discord.js includes multiple sub-packages, installing these separately can mess with internal code:
[0;31mnpm [0;0muninstall discord-api-types @discordjs/rest @discordjs/builders
[0;34myarn [0;0mremove discord-api-types @discordjs/rest @discordjs/builders
[0;33mpnpm [0;0mremove discord-api-types @discordjs/rest @discordjs/builders
Import directly from djs
and the latest api version is 10
a user app cannot delete messages
The app needs to be a member of the guild to do so
oh huh that explains it
thanks 💜
uhh how can i inline 3 text displays in container?
dont think thats possible
{
type: ComponentType.TextDisplay,
style: 1,
content: (`Auction Role: \n${settings.auctionRole ? `:paidrepend: <@&${settings.auctionRole}>` : `:paidrepend: Not set`}`)
},
{
type: ComponentType.TextDisplay,
style: 1,
content: (`Blacklist Role: \n${settings.blacklistRole ? `:paidrepend: <@&${settings.blacklistRole}>` : `:paidrepend: Not set`}`)
},
{
type: ComponentType.TextDisplay,
style: 1,
content: (`Manager Role: \n${settings.managerRole ? `:paidrepend: <@&${settings.managerRole}>` : `:paidrepend: Not set`}`)
},
Is a set random value for setAccentColor available, or do I have to make a random color picker myself?
i got from net that we have to use style
I believe you would have to make the "random color picker"
how did this button came if there is no inline thing?
I dont believe that text display has a style field
the thumbs up one
thats a section with an accessory it looks like
It's called a Section. It is a TextDisplay with an inline Button or Thumbnail
You cannot inline multiple TextDisplays
section doesnt have separator
i was told here only
You're right. It doesn't. But you can put a separator before the section
- text
- separator
- section
- separator
- action row
That's how that container is made
ohk
Get a random accent color.
function getRandomColor() {
const allColors = Object.values(Colors);
const randomColor = allColors[Math.floor(Math.random() * allColors.length)];
return randomColor;
}
documentation suggestion for @obsidian rain:
resolveColor discord.js@14.19.3
Resolves a ColorResolvable into a color number.
You can pass "Random" to it
Awesome 
Hi everyone! I got these 2 errors while trying to combine flipside with discordjs, does anyone know how to fix it?
- DiscordAPIError[10062]: Unknown interaction
at handleErrors - throw er; // Unhandled 'error' event
^
ReferenceError: MessageFlags is not defined
at Client.
code:
const { SlashCommandBuilder, MessageFlags } = require('discord.js');
const { Flipside } = require("@flipsidecrypto/sdk");
const flipside = new Flipside(
"{myapi}",
"https://api-v2.flipsidecrypto.xyz"
);
module.exports = {
data: new SlashCommandBuilder()
.setName('user')
.setDescription('provides info.'),
async execute(interaction) {
const sql = `
SELECT
date_trunc('day', block_timestamp) as day,
count(distinct tx_id) as tx_count
FROM eclipse.core.fact_transactions
WHERE block_timestamp >= GETDATE() - interval'1 day'
GROUP BY 1
`
const queryResultSet = await flipside.query.run({sql: sql});
await interaction.reply(`Success`);
},
};
what is your djs version
and also, you need to deferReply when doing stuff like that
whats the difference between a section and an action row?
14.19.2
Is it possible to use message embeds/components v1 with v2 like the footer thing?
no
No, v1 is limited to just the 5 action rows
Action row can have multiple buttons or a select menu
Sections can have 1-3 text displays and an accessory ie thumbnail or a button
thanks, everything worked
ty
Wdym 😭 I didn't say anything about action rows
v2 components can not be used in v1
No I am saying v1 components in v2
Yes, they can be used
buttons, selects, and action rows can be used in v2 yes
So how can I use a footer or is there no support for it anymore🤔
Your original message read as the other way, using the new methods with the old
wdym by footer?
if you are asking how to put buttons last, you just put them last. nothing special
No like Message
Button
Footer sort of thing
what is the "Footer sort of thing" you are talking about?
Footer is the thing that usually is at the bottom? And you can have a unique icon next to it sometimes with a timestamp?
thats part of an embed. that is not a component
you cannot use embeds in components v2.
you can instead use containers and text displays. you can use markdown in a text display to make the text small like in the footer
-# like this
Sad 😔 I hope they bring it back someday
So it can work with V2 and stuff
do you need the icon. if you dont need the icon then you can just use small markdown text
if you need the icon, and the icon is not dynamic, you can use a custom emoji instead
I just use it for branding and pages tbf
you can use subtext to simulate it
Ok 👍
'-# small footer'
Can I use StringSelectMenuBuilder() in ComponentV2?
in an action row, yes
v10: MessageFlags