#djs-help-v14

78874 messages · Page 7 of 79

foggy grove

Yeah then I'll fix it, back to the question of creating a category.

what can you say about it, that sometimes it creates strictly where it should and sometimes chaotically?

steel trail

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

foggy grove
steel trail

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

hushed mirage

is it currently possible to use slash commands in private messages? a friend of mine is making a bot in python and can normally

proud arrow

Yes, using user apps

sharp ginkgoBOT
proud arrow

You need to specify these two. Handling the interaction is same as you normally do

jolly bay

how to disable mentions in the new components v2

sharp ginkgoBOT

tag suggestion for @jolly bay:
You can control which entities receive notifications via the allowedMentions option. You can:

{ ..., allowedMentions: { parse: ["users", "roles"] } }
compact swan

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

polar karma

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

compact swan

aha thank you

sharp ginkgoBOT
polar karma

I think it may be possible to specify that during the fetch as well

keen junco

does anyone know if discord.js v14 supports js module????

steel trail

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

steel trail
keen junco
hasty osprey

are there any guides torwards v2 yet

im thinking about rewriting the whole "use embeds as """popups""" " thing in my bot

steel trail

not really sure how much more of a "guide" you expect

crimson thistle

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

hasty osprey

compare Date.now() with the message's timestamp

crimson thistle

ok thanks

burnt quartz

you also have client.ws.ping which is the websocket ping. if you are making a ping command i would add both

hasty osprey

whats a websocket

burnt quartz

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

fading girder
c.permissionsFor(guild.members.me!)                    ?.has([PermissionFlagsBits.ViewChannel, PermissionFlagsBits.SendMessages])```

Can I use arrays for .has()
sharp ginkgoBOT
shell ravine

Hey! What is the number for the ephemeral flag? How can I calculate it if necessary?

sharp ginkgoBOT
shell ravine

thx!

cobalt tree

Hi, is this Message _Preset: triggerType 4?

covert vine

anyway, i did actually end up implementing a system to check if i changed any of the commands' payloads

hot marten

Hello,
I am a bit confused:
console.log calls:

false
false

Edit: thread.setArchived returns archived: true

covert vine
hot marten
covert vine

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

hot marten
covert vine

mmmm

hot marten

this is some kind of bug isn't it?

mellow frigate

TypeError: container.addMediaComponents is not a function

what to import for this?

covert vine
hot marten
covert vine mmmm

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

sharp ginkgoBOT
fallen trellis

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

worthy hound

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

rose tangle
rose tangle
fallen trellis

thanks

worthy hound
balmy kraken

how can I check if a string is valid snowflake user ID before trying to fetch it?

halcyon bison

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}$/

gritty lily

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.

halcyon bison

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

opal river

Does any event get triggered when a server changes from a normal one into a community server?

sharp ginkgoBOT
primal edge

my bot was online. and. i randomly get this error???
what is it from???

steel trail

It literally tells you where it‘s from

primal edge

but im not using anything webhook

zenith violet

They expire after 15 minutes

editing them after 15 mins results in that error

primal edge

oh

toxic moat

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.

grave pond

We used 9 text display 4 separator and 10 buttons using builders but got error that expected >=10

leaden shuttle

with componentsv2 is it possible to align text next to eachother or is it just components?

topaz bluff
drowsy lark

can i fetch the full slash command if a message has interactionmetadata, like to get the options provided?

topaz bluff
toxic moat
topaz bluff
pseudo cloak

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
                    }
safe wigeon

Is it possible to send two components v2 in one message? If so, is that just done with an array? Like components: [container1, container2] ?

leaden shuttle

with componentsv2 is it possible to align text next to eachother or is it just components?

topaz bluff
topaz bluff
safe wigeon

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?

zenith violet

it errors

safe wigeon
toxic moat
worldly coyote

ive got a question :
guild.members.cache.filter
what do i have to type for people who are in voices?

uncut quest

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

red coral
stable sun

Could also guild.voiceStates.cache.filter

toxic moat
topaz bluff

that looks right

toxic moat
topaz bluff 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]
    }
  ]
}
topaz bluff

well looks like neither of those errors are from your separator

looks like theyre coming from ThumbnailBuilder and ButtonBuilder

toxic moat

I don't have either ButtonBuilder or ThumbnailBuilder

topaz bluff

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

toxic moat
topaz bluff

no...instead of wrapping your textdisplays in a section...simply pass them directly into the container

toxic moat
topaz bluff no...instead of wrapping your textdisplays in a section...simply pass them direc...

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>`)
    )
primal edge
south sigil

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

loud quartz

what specifically runs the shard doesn't really matter

south sigil

ah ok

loud quartz

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

south sigil

ok

loud quartz

onyl exception is interactions from DMs (and direct messages themselves) - these go to shard 0

south sigil

yeah ok then thanks for the reply

radiant epoch

can we revoke member's connection with linked role? is there any method for that?

balmy kraken

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?

little pebble
little pebble
balmy kraken

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`
clear garnet

Seems like you didn't import it

balmy kraken
toxic moat

how to kick member from vc channel

sharp ginkgoBOT
bleak owl
toxic moat

how to get vc state? I have voice channel

sharp ginkgoBOT
balmy kraken

can i remove components from action rows?

bleak owl

yes, just pass an empty array

balmy kraken

i mean like, from existing ones

bleak owl

by passing an empty array

balmy kraken

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?

bleak owl

the empty array goes where you send the message/interaction

balmy kraken

yeah but that removes the whole row and i only want to remove one button

bleak owl

then simply don’t add that button to the action row

when sending or editing

halcyon bison

<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

fathom warren

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?

tribal warren

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?

balmy kraken

can I listen for components with a collector after deferring an interaction and then editing it with the button row?

vast bloom

is there any way to stream videos with discordjs or another library

fathom warren
fathom warren
vast bloom
balmy kraken
fathom warren
fathom warren

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

silent elk

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.
clear garnet

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

sharp ginkgoBOT
silent elk

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?

clear garnet
silent elk

Ah, unfortunately. I cannot use editReply() as that does not edit the actual original message.

clear garnet

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

silent elk

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:

  1. A user sends a slash command and that creates a reply to that slash command with some buttons
  2. Another user hits one of those buttons which does some logic and than needs to update the reply in #1
clear garnet

Can you share the logic relating to the buttons?

sharp ginkgoBOT

To share long code snippets, use a service like gist, sourcebin, pastebin, or similar instead of posting them as large code blocks or files.

silent elk

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.

clear garnet

I'm referring to the actual code

silent elk

Ok

The relevant code starts on line 79

This is the code where I handle the original slash command and create the raid message

clear garnet

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)

silent elk

I had those swapped at first. However, on line 118 I don't want to be editing the reply from line 122.

stable sun

Could just use interaction.update then followUp

clear garnet
silent elk
clear garnet
silent elk

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?
silent elk
stable sun
silent elk
stable sun

No, view channel

silent elk

Thanks. Lemme try that.

stable sun

I always recommend doing it via the interaction to avoid perm issues

Interactions are intended to eliminate this issue

silent elk

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 😄

stable sun
silent elk

It is in response to a different button where I have not used update()

stable sun

Still has to be within the 15 min tho

silent elk
stable sun

You could try specifying the message in deleteReply. I’ve never tried this particular setup tbh

silent elk

I'll try that

stable sun

.deleteReply(message)

silent elk

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.

stable sun
serene crane

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)

unique shoal

That would help

Since it will tell us what's not validating

serene crane
    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]
    }
  ]
}
unique shoal
silent elk
serene crane
silent elk

I wish I could find a good page which explained what permissions are required for various actions in the API.

rose tangle

and if you try to delete before replying, what would you be deleting

silent elk

The current interaction is from a button. The message I need to delete is the original message the button was attached to.

tardy sable

Why does an thread deletion/creation event also triggers an messageupdate event. How do i ignore it in my messageupdate event

rose tangle
silent elk

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.

rose tangle

but do you want to update it and later delete or delete directly?

silent elk

In this case, delete

rose tangle

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

silent elk

I will try deferUpdate() and then deleteReply()

rose tangle

they do need to arrive in that exact order though so make sure to await

serene crane

is this the proper way to print out a containerbuilder or am i doing something wrong lol

        return message.reply({ components: [container] });
rose tangle

looks good

ah

no, it's missing the IsComponentsV2 flag

since containers are part of those

serene crane

wdym

rose tangle

{ ..., flags: MessageFlags.IsComponentsV2 } as part of your reply options

you need that flag to send v2 components

serene crane

Salute savior

silent elk

Thanks very much. The followUp is to a message, 'message could not be loaded', but that is ok.

rose tangle

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

serene crane

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)

rose tangle

number should also work

0xrrggbb

serene crane

ah yup
just realized when u said number haha

silent elk

Any quick tip on how to automatically delete ephemeral responses after a minute or two?

rose tangle

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

silent elk

Cool beans, thanks again

quartz oar

Is there a way to ask a user for additional input after the initial invocation of a slash command?

rose tangle

depends on the type of input you want, and how you want to ask for it

quartz oar

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.

rose tangle

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

quartz oar

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?

rose tangle

sure, whether on a modal or by awaiting messages

sharp ginkgoBOT

method 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.`));

quartz oar

I think that is going to end up being a better option. Appreciate the help!

toxic moat

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
rose tangle

are you sure it comes from that line? can you share the whole code and error in a bin

sharp ginkgoBOT

To share long code snippets, use a service like gist, sourcebin, pastebin, or similar instead of posting them as large code blocks or files.

toxic moat
rose tangle are you sure it comes from that line? can you share the whole code and error in ...
      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

rose tangle

I meant both the code and the error in the bin

but just the error now ig

toxic moat

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

rose tangle

you aren't sending the IsComponentsV2 flag

toxic moat

I think is related to interaction.reply

        return Interaction.reply({
          ...Container.toJSON(), 
          flags: MessageFlags.Ephemeral,
          allowedMentions: { parse: [] }
        });
rose tangle

and for the deprecation notice:

sharp ginkgoBOT

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
rose tangle

somewhere you're replying with ephemeral: true instead of the Ephemeral flag

rose tangle

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

blissful spoke

Since string select menus are no longer searchable, how do i add all available roles to a select menu

rose tangle

they were never searchable

and you could always use a role select menu for that

toxic moat
sharp ginkgoBOT
rose tangle
toxic moat
rose tangle well that codeblock is still wrong, in case you're trying to send a container li...

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: [] }
      });
rose tangle

yeah that looks good now

orchid latch

I'm getting tired of this error

It makes my bot not listening for DM messages when I replace with as TextChannel

stable sun

Ensure channel.isSendable() is true

orchid latch

Oooooh noooo la polizia, this library.... Thank you !!

Why the interaction.channel is null when the interaction is used in a DM channel ?

sharp ginkgoBOT

To receive direct message events on "messageCreate" with your bot, you will need:

steel trail

Missing Channel partial I guess

unique shoal

We should update that tag somewhat

steel trail

Nah, that tag is for receiving DMs. Not for receiving interactions in DMs

orchid latch

...

high oxide

can i use a regex for verifying the input entered by the user?

zenith violet

in a modal?

orchid latch

I have that intent enabled already, so the channel is partial by default in DMs ?

high oxide

like slashcommand options

zenith violet

sure, but only after they submitted

high oxide

okay

crude void

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 })
loud quartz
steel trail

Need withComponents: true in the send call for a webhook

crude void

Ok ty

cobalt tree

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

zenith violet

no need for any 3rd party packages

cobalt tree
cobalt tree
zenith violet djs supports it natively

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).

hushed mirage

is it possible to send a survey in components v2? because there is no survey here

zenith violet
hushed mirage

ugh

why?

zenith violet

Because discord didnt make it

unique shoal

Because it's not a V2 component

You're looking for poll

Which already exists as a separate thing

cobalt tree
leaden shuttle

with componentsv2 is it possible to align text next to eachother or is it just components?

proud arrow

Scroll a bit, it's attached with v2 announcement post

leaden shuttle

hmm alright

leaden shuttle

can i add an image to the top right of the container

proud arrow

Sure, using section components.

unique shoal

You can use a Section as the first component, and add a Thumbnail as its accessory

sharp ginkgoBOT

To share long code snippets, use a service like gist, sourcebin, pastebin, or similar instead of posting them as large code blocks or files.

half night

do sections support images as well or only thumbnails as accessory?

unique shoal

A thumbnail is an image

cobalt tree
unique shoal

Not sure I understand the question sorry

half night

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?

unique shoal

There is a MediaGalleryComponent

leaden shuttle
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?

proud arrow
unique shoal

Which supports multiple images

half night

Awesome, thank you! bloblove

and you can have multiple of these galleries also per message? or only one?

dam, v2 seems to be quite a huge improvement

proud arrow

There can be only one accessory

unique shoal

Uhh probably multiple galleries honestly but I dont know

half night

time for TIAS then 😄 thanks for the help!

proud arrow

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

reef flame

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?

sharp ginkgoBOT
unique shoal

its not possible to control button positions

Right-aligned buttons exists only as section accessories

toxic moat

Can you interact with buttons in containers or they are just link

unique shoal

You can interact

reef flame
unique shoal

yes

reef flame

Thanks

leaden shuttle

can you add a thumbnail for each section?

unique shoal

yes

leaden shuttle
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
proud arrow

Your second section doesn't have any accessory component

leaden shuttle
unique shoal

or a button

leaden shuttle

so if one section has an accessory then all of them do?

unique shoal

All sections must have an accessory, its required

If you dont want one, dont use a section, just add TextDisplayComponents to the container directly

leaden shuttle

ohhh okay

crisp finch

Am I able to defer a reply to a ModalSubmitInteraction?

leaden shuttle

so ig i can think of a section as a wrapper

crisp finch

Peak, thank you

half night
proud arrow

Not really a d.js question, but yeah make the bot private

tribal warren

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?

balmy kraken

how do I get emoji ID?

tribal warren
wary coral
crude void

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?

wary coral
tribal warren
sick arrow

hey, i was just wondering if bots being able to foward messages is possible yet?

stiff whale

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

sharp ginkgoBOT
sick arrow

perfect thank you!

balmy kraken

can I have custom emojis in autocomplete popups? Like this, but with a custom one

wary coral

@tribal warren sorry Sent the message with out what I meant

frosty epoch

forum threads can only be 'public'?

dense jackal

yes

rugged coyote

dose discord.js support v2component?

zenith violet
rugged coyote
untold fulcrum
stiff whale
wary coral could you give more context
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
rugged coyote

there is not much info

proud arrow
rugged coyote
zenith violet
snow fractal

Anyone know why <role>.color.toString(16) is sometimes giving me invalid color codes. E.g #9ff00 when it should have given #09FF00

spring frost

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

snow fractal
wary coral
dry valve

Hi

stiff whale
wary coral

I will try when I am in front of my pc

agile nest

do i need to fetch member after getting id from slash command option

zenith violet

if its a user option, use getMember

agile nest

K

half night

I suppose you cannot update a legacy message to one that uses components v2 with <interaction>.update?

sharp ginkgoBOT
wary coral

and add the flag property

proud arrow

You just can't go back to legacy once you do

half night
red coral

Rate limits time to reset and retry after both in ms?

wary coral
steel trail
stiff whale
wary coral

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))
proud arrow
merry hamlet

is jesting djs overkill (for fun and learning)

delicate pike

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

stiff whale
delicate pike
loud quartz

Quite big distinction

But

delicate pike
loud quartz

Not sure if accent or banner, plus there's no access to gradient (secondary color) if I'm not mistaken

delicate pike

The primary and secondary colors are the same, although maybe is the accent color just an estimated color from my avatar?

loud quartz

No idea, honestly. Someone in ddevs might have a better answer which color is sent under which property

winter vine
  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
proud arrow
crimson thistle

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

proud arrow

And i explained how you can fix it. If typecasting helps then sure, but it is generally not recommended

winter vine
stiff whale
fading girder

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

sharp ginkgoBOT

tag suggestion for @winter vine:
To share long code snippets, use a service like gist, sourcebin, pastebin, or similar instead of posting them as large code blocks or files.

proud arrow

Paste rhe relevant part

wary coral
crimson thistle

ah
thanks

stiff whale
steel trail
proud arrow
steel trail
wary coral
stiff whale and this does not help

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))
steel trail

id is a different property

wary coral

sorry your right my bad

stiff whale

yeas the property i am looking for is data.custom_id (if possible without type assertion)

winter vine
steel trail
proud arrow
stiff whale and this does not help

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

steel trail

put in some debugging effort yourself

winter vine
steel trail
stiff whale
proud arrow
steel trail

so you check the wrong object

stiff whale

but ButtonBuilder.customId === undefined

proud arrow

Also customId is not the same as custom_id

steel trail

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

stiff whale
steel trail

it actually is. in is a perfectly valid typeguard

wary coral

that is beter

steel trail

casting is less type safe than using typeguards though

stiff whale
wary coral
fading girder
steel trail
steel trail
stiff whale
steel trail

partly, yes

stiff whale
steel trail

don't write javascript in the first place if those numbers are concerning to you

stiff whale
proud arrow
winter vine

someone help me

fading girder
stiff whale
proud arrow
winter vine someone help me

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

winter vine
sharp ginkgoBOT

To share long code snippets, use a service like gist, sourcebin, pastebin, or similar instead of posting them as large code blocks or files.

zenith violet

not to mention there is no such thing as <Client>.messages (my reply got eaten)

winter vine
proud arrow

In a different gist

winter vine

ok wait

steel trail
steel trail

give us the code around that line. not a huge block of useless code

winter vine
steel trail 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();```
steel trail

value needs to be a string. not a number, not undefined

wary coral

this

steel trail

and | is bitwise or, definitely not what you want

winter vine
wary coral
winter vine

fixed?

sharp ginkgoBOT

documentation suggestion for @winter vine:
mdn 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.

steel trail
wary coral

I know, I was righting an explination but I am thingking is a wast of time after the "fixed?" message

wary coral

about the nullish I noticed that after I hit send

wary coral
winter vine sorry

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

steel trail
winter vine
crimson thistle

in a StringSelectMenuInteraction, to get the option that was pressed, do i just do StringSelectMenuInteraction.values[0]?

crimson thistle
wary coral
steel trail
wary coral
winter vine

can you give me a youtube video

sharp ginkgoBOT

guide suggestion for @winter vine:
guide Getting Started: Introduction
read more

crimson thistle
wary coral

ya it is just an array with only one element in that case

crimson thistle

thanks 👍

rugged coyote

i cant edit message with already have content via compoenent v2

tribal warren

After spending way too much time experimenting, I finally figured out how to recreate and edit the container.

rugged coyote
dense jackal

you can only edit the components when editing a components v2 message

steel trail
dense jackal

ah I misunderstood

burnt quartz

however you cannot edit it to downgrade it to not be components v2. once it is components v2 it must stay as that

dense jackal

content has to be null on the edit of upgrading the message to a cv2 flagged message

rugged coyote

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?

burnt quartz

in the edit just set content: ""

proud bay

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?

rugged coyote
dense jackal
message.edit({
  content: null,
  embeds: [],
  flags: MessageFlags.IsComponentsV2,
  components: [myComponents]
});
burnt quartz

i know empty string works as i do that

null probably works too i havent used that myself tho

sharp ginkgoBOT

documentation suggestion for @proud bay:
method 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);

steel trail
modern turret
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 😭

steel trail

Where do you import EmbedBuilder from?

npm ls discord-api-types

wise flower

how to make like a Select Menu That has Roles selection & users can search roles

sharp ginkgoBOT
wise flower

from when it is in discord.js ?

steep aspen

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?

burnt quartz
analog badger

only if the webhook is owned by the bot itself

burnt quartz

yes

steep aspen
wary coral

Sections can only have one text display component

shadow pier

Subcommandgroups can have description?

halcyon bison

@peak hare @wary coral you can have more than one text display in a section
however you can only have up to 3

halcyon bison
wary coral
halcyon bison

however you can only have up to 3

halcyon bison

ask discord mmLol

shadow pier

and can it be fetched?

halcyon bison

as part of the command data with <Client>.application.commands.fetch(), yes

uncut quest

in componentv2 , which one is for adding a thumbnail ?

halcyon bison

addSectionComponents
thumbnails can only be section accessories

(so <SectionBuilder>.setThumbnailAccessory() when adding a section)

rose tangle

and the section also requires text components, not just the accessory (thumbnail)

shadow pier

it has to be in container?

steel trail

No

shadow pier

what about dividers?

steel trail

Separators, same answer

Nothing needs to be in a container

uncut quest
steel trail

On SectionBuilder, not container

uncut quest
steel trail

That’s still the container. The section would be inside those ()

wild thunder

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:

delicate pike

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)

sharp ginkgoBOT
steel trail
delicate pike
steel trail

So the better question would be: what are you trying to do with them? Since all information they carry is contained in action already

steel trail

client.application.fetch()

delicate pike

No I didn't, my bad

wild thunder
hexed marsh

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
    });
}
steel trail

You shouldn’t i.message.reply and instead need to reply to the interaction i or do i.update and you did

hexed marsh

It also just hangs with i.update.

steel trail
hexed marsh

Executes all the way up to i.update and does nothing. i have nothing in the collector.on('end')

steel trail

Since this is a ButtonInteraction that starts all of this: how is that getting handled? Does the handler for that interfere with your collector?

steel trail
hexed marsh
const execute = async (interaction: ButtonInteraction) => {
    const { customId } = interaction;
    if (!interaction.isButton() || !customId) return;

    if(customId.includes('kiai')) {
        await handleKiaiImport(interaction);
        return;
    }
hearty pewter
hexed marsh

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.

hearty pewter
steel trail
steel trail
hexed marsh
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)
        );
};
steel trail
hearty pewter
steel trail
hexed marsh

Yes, but the questionId switches with each question.

steel trail

But still your other handler will try to reply to it as well as your collector

hexed marsh

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.

steel trail

No, your handling of the collector is fine. What isn’t is that your other handler matches the button‘s customIds too

hearty pewter
hexed marsh

You mean this? There is only one handler for these buttons.

    if(customId.includes('kiai')) {
        await handleKiaiImport(interaction);
        return;
    }
steel trail

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

hexed marsh

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.

hearty pewter
zenith violet

not from dapi types

hearty pewter

?

hexed marsh
zenith violet
hearty pewter ?

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

hexed marsh
  • I have a single buttonClickEvent that passes all interactions that have kiai in 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

steel trail
hexed marsh

Okay, so we only create a single collector instance. Do I need to maintain that collector reference anywhere or will it just work automagically?

steel trail

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

hexed marsh

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

hearty pewter

i'm back

thin cosmos

Is there no builder for ComponentV2 yet?

zenith violet

there is

thin cosmos

What is it called? Couldn't find anything searching v2 in docs

sharp ginkgoBOT

class ContainerBuilder discord.js@14.19.3
A builder that creates API-compatible JSON data for a container.

zenith violet

no components contain v2

thin cosmos

Container!

steel trail

Correct. Wouldn’t make much sense to have more than one reply to a vanished message

half night
steel trail

No. They can’t

Only one of them

half night

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 >.<

wary coral

Discord markdown just works in text displays

steel trail
half night

gotcha MenheraSalute3

versed current

If I want to combine two message flags, is that the way?

steel trail

No

That will cause flags: 0

versed current

oups
what should I do then? 😅

sharp ginkgoBOT

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
versed current

aaaah, thanks ^^

compact swan

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 peepo_shrug

zenith violet

what is the full error

compact swan
zenith violet

i'm assuming whatever your bot.translate is is giving the issue

compact swan

no that works, cause if I remove the logs part it translates properly "Admin commands", "DJ commands" etc. the field names

zenith violet

how have you determined those commands are the cause / where are those logs coming from

you might also just be over the character limit

compact swan

there is a character limit per field value

steel trail

Yes

sharp ginkgoBOT
compact swan

maybe it is the field character limit. ill have to check

i am over lol.. by 13 characters...

fallen trellis

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?

red coral

Try reloading the client your alt uses

cosmic grotto

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],
    });
  },
};
rose tangle

that looks ai made?

almost nothing makes sense

cosmic grotto

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

rose tangle
  • 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

cosmic grotto

The image can be a link, correct?

rose tangle

yes

loud quartz

the attachment:// itself is a url

rose tangle

but discord images expire so your image will no longer work eventually, you should use an actual cdn

loud quartz

like https://

cosmic grotto

My original code is gone, would've been better to come here with that... Starting from 0 ig

loud quartz

so technically it only accepts links

cosmic grotto

Do we need something like this:

      const response = await fetch(imageLink);
      const imageBuffer = await response.buffer();

      const attachment = new AttachmentBuilder(imageBuffer, { name: "image.png" });

loud quartz

"need"?

rose tangle

attachment builder also accepts an url

and it'll do something like that internally

cosmic grotto

I ment, is the buffer required

loud quartz

do you know what happens in those 3 lines you sent?

cosmic grotto

Not sure.

loud quartz

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://
cosmic grotto

So, to display image, I should have something like this:

      const mediaItem = new MediaGalleryItemBuilder()
        .setURL("attachment://image.png")
        .setDescription("Image");
loud quartz

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

cosmic grotto

Yes
const attachment = new AttachmentBuilder(imageBuffer, { name: "image.png" });

loud quartz

this is nothing new, it's exactly the same how it always worked for embeds

cosmic grotto

Do you recommend waiting for the full realise of components v2 and the guide?

I'm just experimenting :d

unique shoal

...full release?

It is fully released

No guide yet, sure

turbid mulch

my favorite part is containers

cosmic grotto
unique shoal

We're not aware of any major changes coming from Discord and discord.js fully supports the current implementation, no more work required

cosmic grotto

Cool!

open saddle

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.

manic axle
open saddle

That's the thing, im not entirely sure on how to actually detect that. Not yet at least

manic axle

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

open saddle

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

unique shoal

Thats the right event to listen to, yes

manic axle

That will detect if a message's text starts with test but that has nothing to do with images

unique shoal

But "content" refers to the text

open saddle

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

unique shoal

You'll also need to enable the right intents - Guilds, GuildMessages, MessageContent

open saddle

Already done 🙂

So, so that the detection for the image is completed, now to actually stress my brain to implement the image reading :v

versed current

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.

sharp ginkgoBOT
versed current

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.

open saddle

Trying to grab the image URL..

message.attachments.url doesn't work. Suggestions?

rose tangle

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

open saddle

Person post image > bot reads message (tesseract) > replies from certain words

rose tangle

doesn't answer the question

open saddle

I don't see question?

rose tangle
open saddle

The image URL of when a user posts an image.

that's like... the best i can describe it :v

rose tangle

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

open saddle

Then this is gonna be very difficult for me to implement it then :v

rose tangle

it really only depends on which image you want when the user sends many

or if you want to process all of them

open saddle

I guess i can have it trigger if a user sends more then one, it will ask to post em one at a time?

rose tangle

sure, you can do that, but at that point I'm not sure why you couldn't just process all of them at once

open saddle

and i wouldn't have a clue on how to actually properly do that with discords API

rose tangle

.attachments is a collection, which is a map

you can iterate over it

or call .filter() or .find()

leaden shuttle

is the char limit still 4k even with components v2?

rose tangle

yes

also for api questions you should ask in ddevs

leaden shuttle

does djs provide any utils to check the char length of your container

open saddle

Isn't the max like 2k in a message? Then it turns into a .txt?

leaden shuttle
rose tangle

you could make a feature request issue about that

it sounds very low priority though

open saddle

Huh... message.type gives me 0, is there a list of definitions of types?

unborn wagon

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.

unborn wagon

Ah alright cool ty

rose tangle

load limit?

oh, you mean file size limit?

yeah, it does

safe wigeon
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)
burnt quartz
safe wigeon
burnt quartz

because its faster since you dont attempt to upload it, and you can get the limit

polar karma

Can check the boost level and do an if statement. It's generally good practice to prevent unnecessary API requests

sharp ginkgoBOT
safe wigeon
burnt quartz

no idea how you actually access that

doesnt seem to be implemented into actual Interactions yet

unique shoal

You cannot control UI sizing, no

It will adjust to the content automatically

burnt pilot
unique shoal

You could shorten the lines of text

burnt pilot

okay

hexed marsh

Is there a collector for modals or do you have to use the Promisified pattern?

open saddle

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
burnt pilot

Can I switch from components v1 to v2 from a message that already exists?

open saddle

Most likely not...

sick ferry

is the duration for polls in seconds?

open saddle
sick ferry

ty

sick ferry
polar karma
sick ferry

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

hollow edge

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

unique shoal

That shouldnt have ever worked

The unicode is \🍕

clear garnet
sharp ginkgoBOT

discord Poll Resource - Poll Create Request Object
read more

hollow edge
open saddle

Can't i do links in Embeds? like on how we used (text)[url]

unique shoal

yes you can

But you got it backwards

[text](url)

open saddle

I just tried it in the .setDescription and it was failing to create the text a link

open saddle

.setDescription('[Main side](eternalhosting.cloud)') was the line i was using

unique shoal

You can test it yourself

Use the https protocol

So its a well-formed URL

vital raven

eternalhosting.cloud is not a link, did you mean to use template letiral?

open saddle
unique shoal

Use https

open saddle

fair

unique shoal

On its own, its not a well-formed URL

hexed marsh

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` });
vital raven

Warp your json string with buffer

sharp ginkgoBOT

node Buffer
Source Code: lib/buffer.jsBuffer objects are used to represent a fixed-length sequence of bytes.

hexed marsh
vital raven Warp your json string with buffer

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.

vital raven

You forgot the encoding, utf8 in your case

hexed marsh

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` });
vital raven
steel trail
hexed marsh

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]
    });
}
steel trail

And it fails at the buffer from?

hexed marsh

Nice catch.. apparently it fails on the reply.

No clue why. However xD

steel trail

Can you console.log(buffer.toString()) to confirm the json is correctly contained?

hexed marsh

Yes it's there.

steel trail
hexed marsh

Standby one.

steel trail

That’s… a completely different error now Thonk

hexed marsh

Hang on I was on a breakpoint for a hot minute might be messing it up sec

steel trail

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

hexed marsh

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)
steel trail

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

hexed marsh

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"
],
steel trail

Are you running the debugger? It seemed to me like you did, in which case you should see the callstack in the debugger itself

steel trail
hexed marsh

This is all it can give me. Unfortunately I can't see a way to export that call stack

steel trail
steel trail
hexed marsh

I did, the catch on the reply never gets hit, the console log before does hit the console.

steel trail

console.log(file) there then

hexed marsh

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

steel trail

I thought you had a console.log after that there? Did you try wiping node_modules and reinstalling?

hexed marsh

Is there a recommended version of node I should be running par-chance?

steel trail

Where did it import Buffer from? If at all

hexed marsh

Okay I'm much more recent than that lol

nuking node_modules did nothing.

steel trail
hexed marsh

Did not import. Seems it's standard.

steel trail

can you try importing it from node:buffer? should not make a difference but grasping straws here

hexed marsh

Negative ghost rider... same error. Did I inadvertently find a bug?

Wait a second...

It sat on the exception and eventually went through. TFUQ?

hexed marsh
steel trail

try running normally without debugger.

hexed marsh

Works fine w/o debugger

ripe topaz

Is it possible to hot reload commands as well as modify api commands (existing ones, new ones, deleting etc..)

zenith violet

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?

errant void

Is there a way to ge the connected social profils that are associated with a discord user account?
Just the names tho

zenith violet

No

errant void

Sad

loud quartz

But not everyone will be willing to share those with you

errant void
loud quartz

Yes, oauth2 flow with appropriate scope will allow you to request connections the user has from discord

errant void

kk

woeful kraken

did discord.js support HTTP command? those command with endpoint

sharp ginkgoBOT

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.

woeful kraken

ok thanks

lavish escarp

How to make the left side of ContainerBuilder have text and the right side buttons?

obtuse laurel
sharp ginkgoBOT

class SectionBuilder discord.js@14.19.3
A builder that creates API-compatible JSON data for a section.

ornate elk

Since v14.19.0, the APIMessageActionRowComponent import is no longer found, has it changed its name ?

grave pond

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)
ornate elk
dense jackal

oh lol

grave pond

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

limit have been removed still cant use

zenith violet

Not too sure if 19.3 even has those increased limits already

grave pond
grave pond
zenith violet Not too sure if 19.3 even has those increased limits already

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

sharp ginkgoBOT
thorn lion

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?

grave pond
heady vessel

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

crystal cargo

if i removed them, how to use:
const rest = new REST({ version: '9' }).setToken(process.env?.token);

grave pond
crystal cargo
heady vessel
heady vessel hi! currently working on a way to delete bot messages from a user app via a cont...
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

grave pond
crystal cargo

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

sharp ginkgoBOT

discord.js includes multiple sub-packages, installing these separately can mess with internal code:

npm uninstall discord-api-types @discordjs/rest @discordjs/builders
yarn remove discord-api-types @discordjs/rest @discordjs/builders
pnpm remove discord-api-types @discordjs/rest @discordjs/builders
zenith violet

and the latest api version is 10

zenith violet

The app needs to be a member of the guild to do so

heady vessel

oh huh that explains it
thanks 💜

grave pond
zenith violet
grave pond
{ 
                        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`}`)
                    },
obsidian rain

Is a set random value for setAccentColor available, or do I have to make a random color picker myself?

grave pond

i got from net that we have to use style

wary coral
grave pond

how did this button came if there is no inline thing?

wary coral
grave pond
zenith violet

thats a section with an accessory it looks like

topaz bluff
grave pond
topaz bluff

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

grave pond

ohk

obsidian rain

Get a random accent color.

function getRandomColor() {
  const allColors = Object.values(Colors);
  const randomColor = allColors[Math.floor(Math.random() * allColors.length)];
  return randomColor;
}
sharp ginkgoBOT
proud arrow

You can pass "Random" to it

obsidian rain

Awesome kekw

paper hound

Hi everyone! I got these 2 errors while trying to combine flipside with discordjs, does anyone know how to fix it?

  1. DiscordAPIError[10062]: Unknown interaction
    at handleErrors
  2. 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`);
    },
};
zenith violet

and also, you need to deferReply when doing stuff like that

leaden shuttle

whats the difference between a section and an action row?

paper hound
wheat stump

Is it possible to use message embeds/components v1 with v2 like the footer thing?

burnt quartz

no

polar karma

No, v1 is limited to just the 5 action rows

wary coral
paper hound
wheat stump
burnt quartz

v2 components can not be used in v1

wheat stump
polar karma

Yes, they can be used

burnt quartz

buttons, selects, and action rows can be used in v2 yes

wheat stump
polar karma

Your original message read as the other way, using the new methods with the old

burnt quartz

wdym by footer?

if you are asking how to put buttons last, you just put them last. nothing special

wheat stump
burnt quartz

what is the "Footer sort of thing" you are talking about?

wheat stump
burnt quartz wdym by footer?

Footer is the thing that usually is at the bottom? And you can have a unique icon next to it sometimes with a timestamp?

burnt quartz

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

wheat stump

So it can work with V2 and stuff

burnt quartz

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

wheat stump
zenith violet

you can use subtext to simulate it

wheat stump
rose eagle

Can I use StringSelectMenuBuilder() in ComponentV2?

shadow pier

in an action row, yes