#djs-help-v14

78874 messages · Page 27 of 79

hollow crag

that did not work

    discord = new Client({
        intents: [
            GatewayIntentBits.Guilds,
            GatewayIntentBits.GuildMembers,
            GatewayIntentBits.GuildMessages,
            GatewayIntentBits.MessageContent
        ],
        allowedMentions: { parse: ['roles', 'everyone'] }
    });
heady lintel

Are there any guides or in-depth examples for how exactly you can use all of the sweepers/cache settings? I'm struggling to understand it all from just the docs.

ah nevermind I found the guide page

shell grove
hollow crag

Can I see how you sent the message? The line of code

hollow crag

oh. lemme uhhhh write it in vanilla rq

shell grove
zenith violet

Embeds dont, containers do

shell grove

I see, thats that new container thing

hollow crag
shell grove Can I see how you sent the message? The line of code

same result

    async execute(interaction) {
        const message = `<@${interaction.user.id}> ran: /test\n\n[#1345071213885526026 message](/guild/600311056627269642/channel/1345071213885526026/)\n\n-# <t:1751688935:f>`;

        const container = new ContainerBuilder()
            .addTextDisplayComponents(text => text.setContent(message));

        await getChannel(config.logs.bot.channelID).send({ components: [container], flags: MessageFlags.IsComponentsV2 });
        await interaction.reply('e');
    }
polar karma

If you're talking about turning off the reply mention, there's a different one to see

sharp ginkgoBOT
shell grove
polar karma

Oh not the reply, mb

hollow crag
shell grove
hollow crag is something wrong?

Im not familiar with containers but the allowedMentions usage is correct, unsure why its still mentioning. Id assume it has something to do with containers

But you can test by sending a normal message that pings you

or any user, as it should block all user mentions

hollow crag

heh?

    async execute(interaction) {
        const message = new TextDisplayBuilder().setContent(`<@${interaction.user.id}>`);

        await getChannel(config.logs.bot.channelID).send({ components: [message], flags: MessageFlags.IsComponentsV2 });
        await interaction.reply('e');
    }
halcyon bison

what version of djs are you using?
could you show the output of npm ls discord.js?

hollow crag
zenith violet

Upgrade to latest

halcyon bison

to elaborate, there were a few issues regarding allowedMentions and components v2 when cv2 initially released
these were fixed in 14.19.3
latest being 14.21.0

hollow crag

OH THAT WORKED tysm lol <33

upper mica
sharp ginkgoBOT

user.usernamed.js docs
user.globalName global display name (users only)
user.discriminator0 | 1083 *
user.tagd.js docs | d.js docs#1083 *
* Note: The discriminator approach is mostly relevant to bots now, which are not currently transferred to the unique username system!

rigid ridgeBOT
halcyon bison

has yet to be merged
feel free to follow the pr

steel trail

What node version are you on?

void marsh

any documentation for gradients role added yet?

ah read up

obtuse nymph

how do we even start to read this shapeshift/builder error?

why go a custom validator route instead of just using zod?

unique shoal

zod sucked at the time

Then we tried ow, then shapeshift

Then somewhere along the line zod got good

obtuse nymph

i see

unique shoal

Admittedly this is a particularly bad logging of the error, are you using Node or something else?

obtuse nymph

Im currently using bun

unique shoal

It might log it differently, which doesn't help. I normally see which validator function failed

obtuse nymph

I'll snoop around, maybe it's included within the giant err log

unique shoal

At a guess it seems like a method that expected an anonymous function received undefined

So something like command.addStringOption()

With nothing in it

obtuse nymph

I isolated the issue to the containerBuilder, i'm reviewing the display components guide rn to find the correct syntax

unique shoal

If you share the container builder I can take a look

Section with no text or thumbnail maybe?

obtuse nymph
unique shoal If you share the container builder I can take a look

sure, thanks a lot by the way,

new ContainerBuilder().addSectionComponents(s => s.addTextDisplayComponents(s => s.setContent("Test!"))).addMediaGalleryComponents(
    new MediaGalleryBuilder().addItems(
        new MediaGalleryItemBuilder()
        .setURL(images.wizard_banner)
        .setDescription(
        "Test Description!"
    )
)
)

sry for messy syntax

unique shoal

Yep, sections require an accessory

obtuse nymph
obtuse nymph
unique shoal

If you only want text, add a text display component without putting it in a section

obtuse nymph

Understood, thanks 👌

unique shoal

And yeah I agree - terrible error output for that error. It's not great on Node by any means but seems we haven't even looked at bun

obtuse nymph

I am not sure how widely adopted bun is so I don't think it's that much of an issue

brave nimbus

is Manage Webhooks enough to create webhooks or the bot needs also manage channels?

novel mauve

you need manage webhooks and view channel

regal lion

Morning folks. Does Client.uset.setAvatar() have some kind of cooldown?

I've got code that sets the bot avatar when it's loaded/ready. Tested it with one file. Works great, but when trying to change it again, it doesn't change the avatar, no errors reported.

// This worked
module.exports = {
    name: Events.ClientReady,
    async execute(client) {
        client.user.setAvatar('/home/user/discord_bot_base/assets/avatar1.png')
        .then(user => logger.info('Avatar set.'))
        .catch(console.error);
    }
};

// Code 5 minutes later...
module.exports = {
    name: Events.ClientReady,
    async execute(client) {
        client.user.setAvatar('/home/user/discord_bot_base/assets/avatar2.png')
        .then(user => logger.info('Avatar set.'))
        .catch(console.error);
    }
};
steel trail

Possible. You really shouldn't change the bot's avatar that often

regal lion
steel trail Possible. You really shouldn't change the bot's avatar that often

Yeah I'm not planning on changing it every 5 seconds. Basically because this is bot is going in multiple servers. The avatar should be customisable. So I'm setting it in the ready event. Unless that's how I shouldn't be doing it?

Basically trying to make to the bot set its avatar, name, etc. based on a config file for the server its in.

dense stirrup

I believe that sets the avatar globally, not for a specific server. Guild profiles exist for bots? 🤔

regal lion
dense stirrup

Thats the App Icon, not the bot Avatar, what you're looking for is under the "Bot" tab

regal lion

Ah yeah, found it. So that explains why it's not changing. Any idea where I can find this guild profile or is that something not in the API?

Ah... hold on...

dense stirrup

from my knowledge, guild profiles don't exist for bots (I could be mistaken, perhaps double check with an expert), the only way I can think of to make a personalized bot avatar, is to make the user make their own bot, then give you the token, then you'd have to make some login logic and start the bot

regal lion
regal lion
zenith violet

Bots cannot set per server pfp's

And i'm pretty sure the endpoint has a very strict ratelimit

regal lion
granite lion

from an <Interaction>, which are all the type guards I should check to see if I can #showModal()?

zenith violet

they have separate limits

to know how they do it, ask them

regal lion

Not trying to compare, just trying to figure out how they implemented it. It's not urgent anyway, so I'll look at how to make my bot behave the way I need it. I think cal had the right idea though.

bitter nova

Its likely what cal said, mee6 and maki do it that way as well

regal lion
bitter nova
regal lion

Never been a fan of Postgres, but yeah might pop in there later if I've got anything further. Thanks.

bitter nova

Salute

polar karma

You could check if the role is present in the guild first

obtuse nymph

is there a way to know if an ephemeral interaction has been closed by the user?

loud quartz

No

rancid elbow

i would like to get the voice state of a button user.
ButtonInteraciton has
member : CacheTypeReducer<Cached, GuildMember, APIInteractionGuildMember>
but, I guess voice is not cached or something and therefore removed in the resulting type?
the functionality of the button assumes the user is in a channel-

polar karma

You need to use the inCachedGuild type guard so TS knows the member will be present

sharp ginkgoBOT
rancid elbow

ah, thank you. Is it reasonable to assume the guild is cached tho? are there cases when its not? im just curious.

also I remember you mark, you already helped me years ago when I started programming, thanks for your help in all times 😄

polar karma

The guild isn't cached if it's a user install app

rancid elbow

the command is supposed to be used in guild only-

polar karma

Otherwise, it should be present unless you're missing the intent or otherwise clear the cache data

rancid elbow

understood.

south sigil

if i'm not wrong i can send Compoents V2 with webhooks right?

zenith violet

yes

south sigil

ok then i'm so confused why i get an error with "empty message"

zenith violet

you need to specify withComponents: true

south sigil

ah true thanks
that was my bad

novel mauve
north cosmos

Can you put links in a title embed?

like if you do

I found it

brave nimbus

with components v2 i have a tree like this

container
|----section
     |----button

is it possible to change the button label when it's pressed?

crimson gale

sure, you have to pass in the new container into the update call

if you want to specifically swap one element you are best off giving it an id so you can identify it and iterate components recursively until you find it

or make it purposebound, if you know the structure you know where it is

if you have the full context you can also consider making a functiont hat spits out the component in its entirety based on some toggle parameter and use it in both the initial reply as well as the update

brave nimbus

wdym purposebound?
also ye, ik that the exact path would be
components[0].components[2].accessory

lapis plover

I'm trying to make a translate message context command. I'm currently encountering an issue where non of my logic of the command is triggered when the user does not have the SendMessage permission in that channel, weirdly they are allowed to use application commands but the context will just return "Missing Permissions" even if the context does not include any message being sent in that channel. As mentioned none of the command logic is triggered. I would appreciate some guidance and a possible solution on that issue (without giving everyone SendMessage permissions)

brave nimbus
zenith violet

Since its discord sending that error

verbal vine

i have a problem, i trying to use event interactionCraete for button , the customId is undefined

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

Show the full code instead of some very badly cropped screenshots

verbal vine

ok wait

sharp ginkgoBOT

The order of function parameters must match between definition and function call.

function execute(client, interaction) { ... };
execute(interaction, client);
  • mismatch! you pass an interaction where the client is expected
  • mismatch! you pass the client where an interaction is expected
verbal vine

same problem

Client imported from discord.js
async execute(client: Client, interaction: ButtonInteraction) {

zenith violet

you likely swapped your parameters

Look at your event handker

verbal vine
  async handleEvents(eventFiles: string[]) {
    info("Starting to load events...");
    try {
      for (const file of eventFiles) {
        const { default: event } = await import(`../events/${file}`);
        if (event.once) {
          this.once(event.name, (...args) => event.execute(...args, this));
        } else {
          this.on(event.name, (...args) => event.execute(...args, this));
        }
      }
      success("Successfully loaded all events!");
    } catch (err) {
      error(err as string);
    }
  }

this my event handler

verbal vine

ok thx

little elbow
CombinedPropertyError (1)
  Received one or more errors

  input[4]
  | CombinedPropertyError (1)
  |   Received one or more errors
  | 
  |   input.value
  |   | ValidationError > s.string()
  |   |   Expected a string primitive
  |   | 
  |   |   Received:
  |   |   | [Object]

    at _ArrayValidator.handle (/Users/lucas/Documents/LucasProject/starskybot/node_modules/@sapphire/shapeshift/dist/cjs/index.cjs:1254:70)
    at _ArrayValidator.parse (/Users/lucas/Documents/LucasProject/starskybot/node_modules/@sapphire/shapeshift/dist/cjs/index.cjs:972:90)
    at EmbedBuilder.addFields (/Users/lucas/Documents/LucasProject/starskybot/node_modules/@discordjs/builders/dist/index.js:235:31)
    at Object.execute (/Users/lucas/Documents/LucasProject/starskybot/Commands/Giveaway/giveaway.js:458:16)
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
    at async Object.execute (/Users/lucas/Documents/LucasProject/starskybot/Events/interactionCreate.js:81:7)
const logEmbed = new EmbedBuilder()
              .setColor(0x2f3136)
              .setTitle("🎉 Giveaway Created")
              .addFields(
                { name: "🎁 Prize", value: giveawayPrize, inline: true },
                {
                  name: "⏳ Duration",
                  value: formatDuration(ms(giveawayDuration)),
                  inline: true,
                },
                {
                  name: "🏆 Winners",
                  value: giveawayWinnerCount?.toString() || "1",
                  inline: true,
                },
                {
                  name: "📅 Ends At",
                  value: `<t:${Math.floor(endTime.getTime() / 1000)}:F>`,
                  inline: true,
                },
                {
                  name: "👤 Hosted By",
                  value: host || interaction.user || "N/A",
                  inline: true,
                },
                { name: "📌 Channel", value: giveawayChannel.toString(), inline: true },
                { name: "💎 Bonus Role", value: bonusText, inline: true },
                { name: "📎 Extra Data", value: extraDataText, inline: false },
                {
                  name: "🖼️ Image URL",
                  value: image || "None",
                  inline: false,
                },
                {
                  name: "🖼️ Thumbnail URL",
                  value: thumbnail || "None",
                  inline: false,
                }
              )
              .setFooter({ text: `Giveaway ID: ${interaction.id}` })
              .setTimestamp();

please help me fix

zenith violet

value needs to be a string

Its an object somewhere

ocean portal

Is using TypeScript with Discord.js very complicated?

steel trail

Depends if you think typescript is complicated

The "with discord.js" isn't

ocean portal

i see, thank you waveBoye

cedar kite

am i seeing correctly that user.primary_guild is merged to main but not released yet?

rigid ridgeBOT
cedar kite

ohh i was looking at a docs pr

right, thanks

steel yacht

Hi,
How can an awaitMessageComponent trigger an "interaction failed" error ?
Thanks

zenith violet

by you not responding to the collected interaction

steel yacht

The promise never resolves, actually

zenith violet

show your code

steel yacht
const [result] = await Promise.allSettled([
    message!.awaitMessageComponent({
        filter: interaction => interaction.user.id === userId,
        time: 5 * 60 * 1000
    })
]);
consoleLog(result);
if(result.status === 'fulfilled')
    resolve(result.value);
else
    remove!();

consoleLog is never reached

zenith violet

and how is message defined

how is userid defined

steel yacht
let message: Message, userId: string, remove;
if(parent instanceof Message){
    message = parent;
    userId = parent.interactionMetadata!.user.id;
    remove = () => interaction!.deleteReply();
}
if(parent instanceof MessageComponentInteraction){
    message = parent.message;
    userId = parent.user.id;
    remove = () => parent.deleteReply();
}
if(parent instanceof InteractionCallbackResponse){
    message = parent.resource!.message!;
    userId = parent.resource!.message!.interactionMetadata!.user.id;
    remove = () => interaction!.deleteReply();
}
if(parent instanceof InteractionResponse){
    message = await parent.fetch();
    userId = parent.interaction.user.id;
    remove = () => message.delete();
}
loud quartz

Did the collector collect anything?

steel yacht

Good question.
So I put a console.log inside filter, and no

steel yacht

Well, what happened is I passed the wrong interaction. 😅

analog oak

Do i need MessageContent and GuildMessages intent to access to emojis events and messageCreate event ?

rose tangle

GuildExpressions for emojis, GuildMessages for messages

and Guilds for any guild-related event

MessageContent, like the name says, is only required for message content

sharp ginkgoBOT
  • Websocket intents limit events and decrease memory usage: learn more
  • See what intents you need here
crystal cargo

message_reference[MESSAGE_REFERENCE_UNKNOWN_MESSAGE]: Unknown message js message.reply({ content: `GG`, allowedMentions: { users: [] } }).catch(console.error);
is it possible that the user deleted the message beffore the bot replies?

dapper oyster

allowedMentions: {users: ["USER_ID"]}

or remove that line

or use this instead of that

allowedMentions: {repliedUser:true}
analog oak
clear garnet
rose tangle
sharp ginkgoBOT

guide Miscellaneous: Cache customization - Limiting caches
read more

rose tangle
analog oak
rose tangle

the linked guide article explains it

if you want no caching at all you can simply use @discordjs/core

crystal cargo

TypeError: Cannot read properties of undefined (reading 'style')

const confirmButton = ({ style = ButtonStyle.Success, label = "gg", date = Date.now() }) => new ActionRowBuilder().addComponents(
    new ButtonBuilder().setCustomId(`gg-${date}`).setLabel(label).setStyle(style).setEmoji(Emojies.truee)
);```
polar karma

What's the full error including stack? I don't see how that code block could produce that error

polar karma

What's line 153/357 of logs.js? Assuming one is a part of a function and the other is calling that function?

crystal cargo
polar karma

Showing the actual code would be necessary. One of them is the source of the error

subtle girder

Is it normal that my bot takes up 1GB of memory?

polar karma

Maybe

bleak owl

please refrain from responding with AI to help others

subtle girder

but my bot is only in one server

If the bot's database is modified, it will send a message describing what was changed and the file

topaz bluff

How many members are in the server, are you listening to the messageCreate event? There's many factors into what could increase your memory usage

subtle girder

91 members(including bots)

I'm listening to almost all events

topaz bluff
weak ledge

I don't think that's unusual.

orchid radish
topaz bluff

No. 1GB is not unusual. Maybe a little for <100 members...but if you're listening to every event, then you're going to have to do some cache clearing to get under 1GB or just deal with it

subtle girder

So the solution is:
Clear cache every hour or stop listening to some unnecessary events?

topaz bluff

^

rose tangle

not listening is not enough though, you'd need to also remove their intents so djs doesn't cache their data

because it wouldn't receive their events at all

sharp ginkgoBOT

guide Miscellaneous: Cache customization
read more

covert vine

are there any premade functions to make unix timestamps like these? https://sesh.fyi/timestamp/
or should i just make them on my own (question is stability)

sharp ginkgoBOT
steel trail

They aren't Unix timestamps though

covert vine
unique shoal

Not really a djs question. JS doesn't really use Unix timestamps, it formats in ms instead of seconds. Dividing by 1000 is stable

steel trail

The website that got linked generates discord timestamps though, so they probably don't actually want Unix timestamps

radiant epoch

In which version of d.js app can read user's tag?

steel trail

In the next version

rigid ridgeBOT
dapper oyster

does anyone know why this code throws max callstack flatten?

export class CustomSlashBuilder extends SlashCommandBuilder {
  extraSettings: { allowDM: boolean; adminOnly: boolean };
  constructor(private bot: Client) {
    super();
    this.extraSettings = { allowDM: true, adminOnly: false };
  }

  setALlowDm(enabled?: boolean) {
    this.extraSettings.allowDM = enabled !== undefined ? enabled : !this.extraSettings.allowDM;
    return this;
  }
  setAdminOnly(enabled?: boolean) {
    this.extraSettings.adminOnly = enabled !== undefined ? enabled : !this.extraSettings.adminOnly;
    return this;
  }

  autoSet(...args: LocaleHeader) {
    this.setName(this.bot.localeHandler.getDefaultLocalization(...this.bot.localeHandler.addKey("name", ...args)));
    this.setDescription(this.bot.localeHandler.getDefaultLocalization(...this.bot.localeHandler.addKey("description", ...args)));
    this.setNameLocalizations(this.bot.localeHandler.generateLocalizationMap(...this.bot.localeHandler.addKey("name", ...args)));
    this.setDescriptionLocalizations(this.bot.localeHandler.generateLocalizationMap(...this.bot.localeHandler.addKey("description", ...args)));
    return this;
  }
  toJSON(): SlashCommandBody {
    const { allowDM, adminOnly } = this.extraSettings;
    const json = super.toJSON();
    console.log(json);
    return {
      ...json,
      allowDM,
      adminOnly
    };
  }
}
brave nimbus

when is the client.user null?

red coral

When the client isn’t logged in

steel trail
steel trail

By not extending SlashCommandBuilder like that, by not calling super.toJSON() or by not making your bot property enumerable

regal lion

Am I correct in thinking setAuthor() can take a local file for the iconUrl property?

const embed = new EmbedBuilder()
   .setTitle('Title')
   .setColor(0xABCDEF)
   .setAuthor({
       name: "Bob",
       iconURL: new AttachmentBuilder(...)
    ...
});
brave nimbus

(forgot to remove reply, wnated to add context but then was un-needed)

sharp ginkgoBOT

tag suggestion for @regal lion:
Files in embeds should be attached via the message option object and referenced in the embed:

const attachment = new AttachmentBuilder('./image.png', { name: 'image1.png' });
const embed = new EmbedBuilder()
  .setTitle('Attachments')
  .setImage(`attachment://${attachment.name}`);

channel.send({
  embeds: [embed],
  files: [attachment]
});
dense jackal
brave nimbus
steel trail

Yes

dapper oyster
steel trail

Probably need a declare in that first line

And you don't want it enumerable

regal lion

@steel trail, apologies for ping. I'm not trying to attach a file to the embed, that works already.

I'm basically trying to set the author icon URL to a local file rather than a hosted image.

// So instead of
.setAuthor({
    name: "Bob",
    iconURL: 'https://example/image.png'
})

// I want to do something like
.setAuthor({
    name: "Transit-X",
    iconURL: 'file:///some/dir/image.png'
})

Disregard that. Typo on my end.

dense jackal

you just put "attachment://image.png" for your icon url, as shown in the tag messages of the d.js app

regal lion

yeah I fixed it. accidentally typo'd something on my end so it was adding it as an image to the message instead.

dense jackal

ah didnt see that, mb

dapper oyster
regal lion

No worries pal. 🙂

lone eagle

if a bot doesnt have use external emojis permission it cant use application emojis or can it

crimson gale

it can

vocal willow

hello im new with this component v2 can anyone help, already installed latest packages

CombinedError (2)
  Received one or more errors

  1 ExpectedValidationError > s.instance(V)
  |   Expected
  |
  |   Expected:
  |   | [Function: ButtonBuilder]
  |
  |   Received:
  |   | undefined

  2 ExpectedValidationError > s.instance(V)
  |   Expected
  |
  |   Expected:
  |   | [Function: ThumbnailBuilder]
  |
  |   Received:
  |   | undefined

    at _UnionValidator.handle (D:\all_sb\savina_ticket\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:1965:23)
    at _UnionValidator.parse (D:\all_sb\savina_ticket\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:972:90)
    at SectionBuilder.toJSON (D:\all_sb\savina_ticket\node_modules\@discordjs\builders\dist\index.js:2169:37)
    at D:\all_sb\savina_ticket\node_modules\@discordjs\builders\dist\index.js:1870:64
    at Array.map (<anonymous>)
    at ContainerBuilder.toJSON (D:\all_sb\savina_ticket\node_modules\@discordjs\builders\dist\index.js:1870:35)
    at D:\all_sb\savina_ticket\node_modules\discord.js\src\structures\MessagePayload.js:151:46
    at Array.map (<anonymous>)
    at MessagePayload.resolveBody (D:\all_sb\savina_ticket\node_modules\discord.js\src\structures\MessagePayload.js:150:49)
    at TextChannel.send (D:\all_sb\savina_ticket\node_modules\discord.js\src\structures\interfaces\TextBasedChannel.js:189:32)
unique shoal

Your section has no accessory

dense jackal

use a text display component instead if you don't want a button or thumbnail on the right side

sharp ginkgoBOT

guide Popular Topics: Display Components
read more

vocal willow
unique shoal

Yes, sections need an accessory

If you dont need an accessory you dont need a section

vocal willow
const balanceButton = new ButtonBuilder()
            .setCustomId(`order_balance_${dealCode}_${targetUser.id}`)
            .setLabel('💰 Số Dư')
            .setStyle(ButtonStyle.Primary);

        const bankButton = new ButtonBuilder()
            .setCustomId(`order_bank_${dealCode}_${targetUser.id}`)
            .setLabel('🏦 Chuyển Khoản')
            .setStyle(ButtonStyle.Secondary);

        const confirmButton = new ButtonBuilder()
            .setCustomId(`order_confirm_${dealCode}_${targetUser.id}`)
            .setLabel('✅ Đã Xác Nhận')
            .setStyle(ButtonStyle.Success);

        const cancelButton = new ButtonBuilder()
            .setCustomId(`cancel_order_${dealCode}`)
            .setLabel('❌ Hủy')
            .setStyle(ButtonStyle.Danger);

        const titleSection = new SectionBuilder()
            .addTextDisplayComponents(
                new TextDisplayBuilder().setContent(`## ![cart2](https://cdn.discordapp.com/emojis/1391338523755413574.webp?size=128 "cart2") Xác Nhận Đơn Hàng\n`
                    + `**Mã đơn hàng:** \`${dealCode}\`\n`
                    + `**Khách hàng:** ${targetUser.username} (<@${targetUser.id}>)\n`
                    + `**Sản phẩm:** ${product}\n`
                    + `**Số lượng:** ${quantity}\n`
                    + `**Tổng tiền:** ${amount.toLocaleString('vi-VN')}đ\n`
                    + `**Số dư hiện tại:** ${parseInt(userBalance).toLocaleString('vi-VN')}đ\n`
                )
            )
            .setThumbnailAccessory(new ThumbnailBuilder().setURL('https://cdn-icons-png.flaticon.com/512/3081/3081840.png'));

        const paymentSection = new SectionBuilder()
            .addTextDisplayComponents(
                new TextDisplayBuilder().setContent('### ![AngelWings1](https://cdn.discordapp.com/emojis/1309051409773367306.webp?size=128 "AngelWings1") Phương Thức Thanh Toán ![AngelWings2](https://cdn.discordapp.com/emojis/1309051409555259402.webp?size=128 "AngelWings2")')
            )

        const balanceSection = new SectionBuilder()
            .addTextDisplayComponents(
                new TextDisplayBuilder().setContent('**Số Dư:** Thanh toán bằng số dư tài khoản')
            )
            .setButtonAccessory(balanceButton);

        const bankSection = new SectionBuilder()
            .addTextDisplayComponents(
                new TextDisplayBuilder().setContent('**Chuyển Khoản:** Thanh toán qua ngân hàng')
            )
            .setButtonAccessory(bankButton);

        const confirmSection = new SectionBuilder()
            .addTextDisplayComponents(
                new TextDisplayBuilder().setContent('**Đã Xác Nhận:** Admin xác nhận đã thanh toán')
            )
            .setButtonAccessory(confirmButton);

        const cancelSection = new SectionBuilder()
            .addTextDisplayComponents(
                new TextDisplayBuilder().setContent('**Hủy:** Hủy đơn hàng này')
            )
            .setButtonAccessory(cancelButton);

        const mainContainer = new ContainerBuilder()
            .setAccentColor(0x0099ff)
            .addSectionComponents(titleSection)
            .addSeparatorComponents(new SeparatorBuilder().setSpacing(SeparatorSpacingSize.Large))
            .addSectionComponents(paymentSection)
            .addSectionComponents(balanceSection)
            .addSectionComponents(bankSection)
            .addSectionComponents(confirmSection)
            .addSectionComponents(cancelSection);

        // Send order message
        const orderMessage = await message.reply({
            flags: MessageFlags.IsComponentsV2,
            components: [mainContainer]
        });
unique shoal

monbreyFacepalm

vocal willow
dense jackal
unique shoal

no, we told you what the error was

Check your own code pls

dense jackal

I think you have everything now to fix it yourself

vocal willow
dense jackal

you sure you imported it?

vocal willow
dense jackal

can you show

vocal willow
dense jackal can you show
const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, MessageFlags, SectionBuilder, SeparatorBuilder, SeparatorSpacingSize, TextDisplayBuilder, ThumbnailBuilder, ContainerBuilder } = require("discord.js");
dense jackal

hm then idk what happened

you can use .setSpacing(2) tho, that should work

but that shouldn't be needed, normally the enum would work too

dense jackal

but not in the code right?

vocal willow
red coral

What’s the nonce used for? Can you put random shit in there?

dense jackal
ivory valve

Hello, trying to log oldMessage.content with MessageUpdate, I need to fetch every channels of the guild when bot is starting to get the content? I have MessageContent/Message intents & Message Partial

red coral
zenith violet

fetching it is not gonna work either since you are fetching the updated message

steel trail
ivory valve

But if I fetch all messages in channel when bot is starting?

zenith violet

yeah no

steel trail

It's meant for deduplication mostly

vocal willow
red coral

So it’s not like something I can use to store something

zenith violet

you would have to store the content somewhere in a database

ivory valve

So if the bot restart, content is just null and there's no way to get the content

zenith violet

not natively, yes

dense jackal
red coral

Does it have other uses then deduplication?

ivory valve

thanks

steel trail
ivory valve

Yes, I will just display "Message not cached" if i don't have the content, that's all xd

No storing all messages or something else

dapper oyster

is it possible to use v2 components with v1 components?

zenith violet

no, or well, depends on what you consider 'v1 components'

you can use buttons and string selects etc yes

but no embeds etc

dapper oyster

ty

sharp vapor
zenith violet
steel trail
lone eagle
crimson gale it can

i have two bots that use same codebase . i wanna use same application emojis for both. but bots cant share application emojis . guild emojis have use external emoji permission drawback. is there another way?

crimson gale

upload them to both apps

mellow frigate

interaction.user.role.add('<roleID>') <--- what is wrong

obsidian dust

so js interaction.member.roles.add('<roleID>');

verbal plinth

When you query a user, Discord also has a field that displays the user's tag. Is it possible to query this directly in discord.js? Is it currently always done directly via the API?

coarse maple

hi, I want to check the usage of my server's stickers. I add a handler onMessageCreate event that detect if (message.stickers.size > 0) but the sticker does not have all info, like guildId (is null). Is there anyway to fetch this info without fetching all stickers of the server?

obsidian dust
coarse maple

sadge

thanks for the reply

obsidian dust

No worries

dapper oyster

does emojis.cache.get support with brackets (example:

client.emojis.cache.get("<:a:id>")
clear garnet

No, ID only

dapper oyster
zenith violet
verbal plinth

Okay thanks

sharp ginkgoBOT

documentation suggestion for @dapper oyster:
function parseEmoji discord.js@14.21.0
Parses emoji info out of a string. The string must be one of:* A UTF-8 emoji (no id)* A URL-encoded UTF-8 emoji (no id)* A Discord custom emoji (<:name:id> or <a:name:id>)

dapper oyster

thanks

verbal plinth
covert vine
C:\Users\Uzivatel\Desktop\Langs\js+ts\node.js\discord.js\savesbot\node_modules\@sapphire\shapeshift\src\validators\StringValidator.ts:108
                return (options as ValidatorOptions)?.message === undefined;
                                                                  ^


ValidationError: Expected a string primitive
    at _StringValidator.handle (C:\Users\Uzivatel\Desktop\Langs\js+ts\node.js\discord.js\savesbot\node_modules\@sapphire\shapeshift\src\validators\StringValidator.ts:108:53)
    at _StringValidator.parse (C:\Users\Uzivatel\Desktop\Langs\js+ts\node.js\discord.js\savesbot\node_modules\@sapphire\shapeshift\src\validators\BaseValidator.ts:126:2)
    at validateDescription (C:\Users\Uzivatel\Desktop\Langs\js+ts\node.js\discord.js\savesbot\node_modules\@discordjs\builders\src\interactions\slashCommands\Assertions.ts:33:23)        
    at validateRequiredParameters (C:\Users\Uzivatel\Desktop\Langs\js+ts\node.js\discord.js\savesbot\node_modules\@discordjs\builders\src\interactions\slashCommands\Assertions.ts:54:2)  
    at MixedClass.runRequiredValidations (C:\Users\...\node.js\discord.js\savesbot\node_modules\@discordjs\builders\src\interactions\slashCommands\mixins\ApplicationCommandOptionBase.ts:48:3)
    at MixedClass.toJSON (C:\...\js+ts\node.js\discord.js\savesbot\node_modules\@discordjs\builders\src\interactions\slashCommands\options\string.ts:61:8)       
    at <anonymous> (C:\Users\Uzivatel\Desktop\Langs\js+ts\node.js\discord.js\savesbot\node_modules\@discordjs\builders\src\interactions\slashCommands\mixins\SharedSlashCommand.ts:159:49)    at Array.map (<anonymous>)
    at MixedClass.toJSON (C:\Users\Uzivatel\Desktop\Langs\js+ts\node.js\discord.js\savesbot\node_modules\@discordjs\builders\src\interactions\slashCommands\mixins\SharedSlashCommand.ts:159:26)
    at <anonymous> (C:\Users\Uzivatel\Desktop\Langs\js+ts\node.js\discord.js\savesbot\index.ts:10:59) {
  validator: 's.string()',
  given: undefined
}

exception details my ass

polar karma

One of your slash command options has an undefined value instead of a string

covert vine
polar karma

You should read your error stacks more closely. That's all I did

covert vine
topaz bluff

Can you show a snippet of your code where you define your slash command?

covert vine

i assume its the boolean option somehow

topaz bluff

There's no description on either of those options

covert vine

there has to be??? i mean yeah
sorry i forgor thanks

topaz bluff
covert vine
topaz bluff

idk what a "string primitive" is (string or string subclass)

mellow frigate

if the message is sent on a thread channel inside a channel, how to get channel id of the channel where that thread is

sharp ginkgoBOT
nocturne moat

hi I need help with getting user profile data especially with avatar decoration
after I authorize my bot and redirect it to my backend callback link i have saved data showed on screenshot (i have covered it cause i do not know is it any secret data) and is it possible to get simple gif link directly to only avatar decoration like my pink cat ears

sharp ginkgoBOT
halcyon bison

oh and it's not really 'secret data'
asset hashes in particular are just public and the same for everyone with the same decoration
I don't believe any info can be gotten just from a sku id, but either way just the data you've shown is easily accessible from any app

steel trail
topaz bluff

There's validateDescription between the things you circled, that's even more helpful

shadow harness

This is probably me being a little psycho about security, but... I want to verify that an Attachment is either zip or rar, and I'm using the mime package on upload.contentType. Is there any way to fake that, which would then require me to check the download too, or is Attachment#contentType pulled from the file?

Now that I think about it that's kind of a stupid question innit. Discord isn't that dumb about security

dapper oyster

how to check a server is not activated community options?

halcyon bison

you'd want to check <Guild>.features

sharp ginkgoBOT
dapper oyster

ty

and how to disable throwing InteractionCollectorError

bleak owl

you can’t disable an error

outer plume

catch (e) {if (e instanceof InteractionCollectorError) return;}

#not recommended

bleak owl

if it’s not recommended then why suggest it?

outer plume

well... it does do what he wants it to do

outer plume
outer plume

then you're taking too long to reply to the interaction. if you don't defer it, you need to respond to it in under 3s

dapper oyster
bleak owl

still need to respond in under 3 seconds regardless of deferring or not

outer plume

technically. since deferring it is also replying to it. so yea. hm.

dapper oyster
outer plume
dapper oyster

best combo

halcyon bison
dapper oyster no, i mean collection timed out

are you using one of the promisified collectors?
some awaitX method?
if so, that's how you determine whether nothing was collected or not
if you want something more indefinite, consider just using a persistent event listener

dapper oyster
outer plume
halcyon bison

to elaborate, you can just increase the timeout if that's what you're looking for, but you'd still want to catch the error and handle it timing out

steel trail
steel trail

That was an "or" question

outer plume

how dyu reply to an or question with yeah AH_cryCat

waxen mirage

havent coded a discord bot in so long... how do i get the attachment from addAttachmentOption in SlashcommandBuilder

halcyon bison

<ChatInputCommandInteraction>.options.getAttachment()

sharp ginkgoBOT

guide suggestion for @waxen mirage:
guide Slash Commands: Parsing options
read more

waxen mirage
    data: new SlashCommandBuilder()
        .setName('upload-uniform')
        .setDescription('Uploads the uniform image to roblox')
        .setDefaultMemberPermissions(PermissionsBitField.Flags.Administrator)
        .addStringOption(o => o.setName('name').setDescription('The name of the image.').setRequired(true))
        .addAttachmentOption(a => a.setName('image').setDescription("Image to be uploaded").setRequired(true))
        .addStringOption(o => o.setName('description').setDescription('Description of the image').setRequired(false)),
        
    async execute(interaction, client){
        const name = interaction.options.getString('mame')
        const description = interaction.options.getString('description')
        const attachment = interaction.options.getAtttachment('image')```

*TypeError: interaction.options.getAtttachment is not a function*
halcyon bison

attachment has 3 Ts, not 4

waxen mirage

im so stupid

outer plume

||use typescript|| nah issok we've all been there

waxen mirage
shut musk

Is there a way to sync the perms of a voice channel to its parent?
I know you can via the client with the "Sync" option but does that exist for bots?

This one:

sharp ginkgoBOT
shut musk

ah its called lock, i was looking for sync

ty

lone eagle
crimson gale

correct

so handle that based on the application id

outer plume
lone eagle emoji id wont be same

run an 'injection' code when your app starts. make sure the names of the emojis in both applications are the same. make a const object, values being the emoji names. then find the emojis in applications.emojis.cache (after fetching once) and replace the value in the object

steel trail

fetch application emojis on login, find by name not by id whenever used

crimson gale

i personally prefer 2 name > emoji maps but true, that works

uneven lantern

Is changing nicknames, changing roles on a member, and moving members voice channels all under the same rate limit bucket? Or do they each have their own seperate ratelimits?

sharp ginkgoBOT

Ratelimits are dynamically assigned by the API based on current load and may change at any point.

  • The scale from okay to API-spam is sliding and depends heavily on the action you are taking
  • Rainbow roles, clock and counter channels, and DM'ing advertisements to all members are all examples of things that are not okay
zenith violet
small lotus

does djs already return the new discord badges and guild tags?

bleak owl

what new badges?

and guild tags has a PR that has not been merged yet

small lotus
bleak owl

that isn't documented, nor has a flag for the api to check

small lotus
bleak owl

when it's ready

you need to have patience

small lotus

no problem

rose tangle
sharp ginkgoBOT

We are not Discord, just some nerds who develop Discord bots!

rose tangle

djs can't support something discord hasn't added

bleak owl

i think they referred to the guild tags, which were documented recently. it’s just the d.js pr that hasn’t merged yet

rose tangle

ah, I misread that, thought it was about the flag, my bad then

bleak owl

nono it’s fine

drifting pecan

On button clicks:
What's the correct way to update components V2? e.g. remove buttons etc.
Also, is there a way to use interaction.update after an api call (in case that takes more than 3 seconds) based on the result since you can't defer interaction.update?

rose tangle

if you want to create builders based on the current data you can use djs' helper

sharp ginkgoBOT
rose tangle

as for the latter, you can defer an update

sharp ginkgoBOT

method ButtonInteraction#deferUpdate() discord.js@14.21.0
Defers an update to the message to which the component was attached.


// Defer updating and reset the component's loading state
interaction.deferUpdate()
  .then(console.log)
  .catch(console.error);

rose tangle

for any component interaction (including a modal shown from a component)

cyan spruce

how to set voice channel status

unique shoal

Not possible, the API is not documented

cyan spruce

well i was using the API but i wanted to use djs instead

unique shoal

We dont support undocumented features

You could use the REST module though

cyan spruce

how do i use REST on djs?

unique shoal

client.rest

cyan spruce

alright ty

plucky coral

Question! I see that role.members returns the cached guild members that have a role. If I don't want the cache, but instead the actual number, how should I approach this? Do I have to fetch all the guild members first so that they're all cached?
I'm doing a sorting algorithm at the moment for an opt-in team event, and it's become lopsided because one team's cached members are higher than the other by a bit haha

drifting pecan
unique shoal
calm maple

this isnt exactly djs related, but how do you send a file via a webhook?

i can use components v2 right?

stable sun
calm maple

i figured it out 🔥

stable sun

.send({ files: […] })

plucky coral
calm maple

are webhook files limited to 8mb or 10mb? whenever i tried to send a 8.41mb file it errored, but i can send it myself

crystal cargo

.setColor("Black")

snow onyx
calm maple

weird

crystal cargo
snow onyx

import it from discord.js and not from builders then

crystal cargo
snow onyx

the EmbedBuilder

crystal cargo

i do
const { EmbedBuilder } = require('discord.js');

snow onyx

okay yeah, I can see "Black" is indeed not valid

uneven wind

What are the default max lengths for Short and Paragraph text inputs in modals?

sharp ginkgoBOT
snow onyx

I dont think they have different limits, max length is 4000

livid sun

Supplied parameter is not a cached User or Role.
What is the reason of this problem ?

nvm i got it

hushed mirage

I have a question, I have greetings made in the bot, and everything works correctly but sometimes it happens that the message is sent twice, what could be the fault?

I have discord.js 14.21.0

sharp ginkgoBOT
golden smelt

i can make a select menu on a container ?

snow onyx

yes

the select menu needs to be in an action row, then you can add the action row to the container

white plank
Error: Received one or more errors
    at _UnionValidator.handle (E:\Github\Watcher-V14\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:1965:23)
    at _UnionValidator.parse (E:\Github\Watcher-V14\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:972:90)
    at SectionBuilder.toJSON (E:\Github\Watcher-V14\node_modules\@discordjs\builders\dist\index.js:2169:37)
    at E:\Github\Watcher-V14\node_modules\@discordjs\builders\dist\index.js:1870:64
    at Array.map (<anonymous>)
    at ContainerBuilder.toJSON (E:\Github\Watcher-V14\node_modules\@discordjs\builders\dist\index.js:1870:35)
    at E:\Github\Watcher-V14\node_modules\discord.js\src\structures\MessagePayload.js:151:46
    at Array.map (<anonymous>)
    at MessagePayload.resolveBody (E:\Github\Watcher-V14\node_modules\discord.js\src\structures\MessagePayload.js:150:49)
    at InteractionWebhook.editMessage (E:\Github\Watcher-V14\node_modules\discord.js\src\structures\Webhook.js:344:50)

Code:

const {
  SlashCommandBuilder,
  ContainerBuilder,
  SectionBuilder,
  SeparatorBuilder,
  TextDisplayBuilder,
  ActionRowBuilder,
  ButtonBuilder,
  ButtonStyle,
  MessageFlags,
} = require("discord.js");

module.exports = {
  data: new SlashCommandBuilder()
    .setName("help")
    .setDescription("Displays the help menu."),

  async execute(interaction) {
    await interaction.deferReply();

    const header = new SectionBuilder()
      .addTextDisplayComponents(
        new TextDisplayBuilder().setContent("### **Commands**"),
        new TextDisplayBuilder().setContent(
          "> Our [website](https://watcherbot.net/servers) contains lots of resources to get you going!"
        )
      )

    const commandsHeading = new SectionBuilder().addTextDisplayComponents(
      new TextDisplayBuilder().setContent("### **Bot Commands**")
    );

    const commands = [
      ["/add", "Track a bot"],
      ["/remove", "Un-track a bot"],
      ["/list", "Show clusters / services"],
      ["/channel", "Set the log channel"],
      ["/role", "Set ping role for outages"],
      ["/shard", "Display shard information"],
      ["/help", "Show this help menu"],
    ].map(
      ([cmd, desc]) =>
        new SectionBuilder().addTextDisplayComponents(
          new TextDisplayBuilder().setContent(`**${cmd}**`),
          new TextDisplayBuilder().setContent(`— ${desc}`)
        )
    );

    const links = new SectionBuilder().addTextDisplayComponents(
      new TextDisplayBuilder().setContent("### **Useful Links**")
    );

    const linksRow = new ActionRowBuilder().addComponents(
      new ButtonBuilder()
        .setLabel("Support Server")
        .setStyle(ButtonStyle.Link)
        .setURL("https://discord.gg/..."),
      new ButtonBuilder()
        .setLabel("Dashboard")
        .setStyle(ButtonStyle.Link)
        .setURL("https://watcherbot.net/servers"),
      new ButtonBuilder()
        .setLabel("Invite")
        .setStyle(ButtonStyle.Link)
        .setURL(
          "https://discord.com/oauth2/authorize...."
        )
    );

    const container = new ContainerBuilder()
      .setAccentColor(0xe4a726)
      .addSectionComponents(header)
      .addSectionComponents(commandsHeading)
      .addSectionComponents(...commands)
      .addSectionComponents(links)
      .addActionRowComponents(linksRow);

    await interaction.editReply({
      components: [container],
      flags: MessageFlags.IsComponentsV2,
    });
  },
};
loud quartz

Sections need accessory

If you don't need accessory, don't use sections

Just use text components directly

white plank

ohh ok ty

wise flower

how to remove that ping i doest want it to ping even if my mention is there

allowedMentions: {
        parse: ["roles", "users", "everyone"],
        repliedUser: false
      },
zenith violet
wise flower
wise flower
zenith violet

and the version returned by npm ls discord.js

wise flower
loud quartz

you don't really need to put the parse in at all if you're gonna tell it to parse everything

also, where is that allowedMentions located?

sharp ginkgoBOT

Despite sounding similar there is a distinct difference between users and members in Discord:

  • User: global Discord user data (global avatar, username, tag, id)
  • GuildMember: user data associated to a guild (guild, nickname, roles, voice, guild avatar, etc.)
  • Conversion: User ➞ GuildMember | GuildMember ➞ User
    * Note: Events received in cached guilds will often have both the member and user available, eg. interaction.user and interaction.member
polar karma
upper mica

thank you and sorry

I was looking for an update for the user guild tags

wise flower
polar karma

you can wait or use the dev version, your choice

upper mica

is it already in dev version?

simple wolf

Why I have to give the emoji object and not the emoji string ??

const container = new ContainerBuilder()
        .addSectionComponents((s) =>
          s
            .addTextDisplayComponents((t) =>
              t.setContent(
                "blabla"
              )
            )
            .setButtonAccessory((b) =>
              b
                .setCustomId("settings")
                .setEmoji({ id })  // if it's a string => bug
                .setStyle(ButtonStyle.Secondary)
            )
        )

With the buttonbuilder we can do that so i dont understand why not where

loud quartz

making a class in your code has no impact on any other code

unless you use it

wise flower
loud quartz

what are you extending?

wise flower

Discord Js client ??

loud quartz

are you extending Client? if so, you're passing it as options to super()?
in which case you extending makes no difference, really

it's set as default on a Client, which was what i was asking about - is it there or is it directly in the reply() call

rose tangle
simple wolf
obtuse nymph

Do interaction components on ephemeral interactions time out? I have a button in a ephemeral response that throws a 50027 Invalid webhook token error after a ~10-20 minutes time window

zenith violet

the intrraction webhook expires after 15 minutes yes

rose tangle

and why do you need to use an interaction from an ephemeral message after 15 mins?

it's unlikely any user will keep the message for that long

steel trail
cinder shale

are bots able to send voice messages with djs?

zenith violet

pretty sure those arent documented

daring cradle

i need help

steel trail

With what?

daring cradle
steel trail

You're in the wrong place then. Try fiverr. This channel and server is for helping you write your own, not find someone to do it for you

crystal glen

what version should i install to get v2 comps

rose tangle

latest

bitter nova

the newest, so 14.21.0

rose tangle

and you should always use latest in general, there's no other major version being maintained

crystal glen

npm i discord.js@latest?

rose tangle

just discord.js

steel trail

Both work

hoary rock

how do you edit a component v2 message for example let's say a user clicks a button and changes every data in that container?

sharp ginkgoBOT

method ButtonInteraction#update() discord.js@14.21.0
Updates the original message of the component on which the interaction was received on.


// Remove the components from the message
interaction.update({
  content: "A component interaction was received",
  components: []
})
  .then(console.log)
  .catch(console.error);

bitter nova

you can just update it how you used to update components and embeds with <ButtonInteraction>.update()

hoary rock

alr thanks

verbal plinth

Is it possible if I have a message and there is a button that opens a modal. That I can use this ModalSubmitInteraction to edit the first message of the button without fetching the messages or so because of the rate limit?

stable sun
bitter nova

yes, you can use <ModalSubmitInteraction>.update() just like you would on ButtonInteractions
but you should check beforehand with <ModalSubmitInteraction>.isFromMessage() if the modal interaction had a message as source

loud quartz

that last part isn't necessary if the modal can only happen from the button, and your custom ids are unique enough

bitter nova

thats true, i like using the type guard tho

steel trail

It is necessary if using typescript

verbal plinth
bitter nova

this is why i mentioned to type guard with <ModalSubmitInteraction>.isFromMessage()

verbal plinth

Oh check

steel trail

Why can it be both a ButtonInteraction or a ModalSubmitInteraction there?

verbal plinth

If you want to give a reason it is modal interaction and without a reason there is directly the button interaction.

steel trail

Then you should do the isFromMessage typeguard before passing to that scope where it can be both and accept MessageModalSubmitInteraction as type for that scope

Because there is no isFromMessage() on ButtonInteraction

bitter nova

or <interaction> instanceof ModalSubmitInteraction && <interaction>.isFromMessage()

verbal plinth

Currently, I have it like this:


if (interaction.isModalSubmit() && !interaction.isFromMessage()) return;
await InteractionHelper.update(interaction, [suggestionEditEmbed], true, []);
bitter nova

isModalSubmit is probably the intended way over instanceof

crystal glen

Can i do if someone Join Server embed also comps?

rose tangle

what?

gilded raven

Good afternoon, I'm experiencing an issue I've never had before. I have a system with a button, the button works for everyone, besides one user. When they press it, I get this error:

F:\Development\Zyron-Beta\backend\events\registration.js:23
    if (!interaction.isButton()) return;
                     ^

TypeError: interaction.isButton is not a function
    at Object.execute (F:\Development\Zyron-Beta\backend\events\registration.js:23:22)
    at InteractionCollector.<anonymous> (F:\Development\Zyron-Beta\backend\events\registration.js:254:28)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

Node.js v22.4.1
PS F:\Development\Zyron-Beta\backend>

Would anyone be able to assist?

rose tangle

show registration.js

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.

strong star
        const exampleSection = new ContainerBuilder()
            .setAccentColor(0x00CEFF)
            .addSectionComponents(section =>
                section
                    .addTextDisplayComponents(textDisplay =>
                        textDisplay.setContent(`# ${interaction.user.displayName}\n-# test\n-# test\n-# test`)
                    )
                    .setThumbnailAccessory(thumbnail =>
                        thumbnail.setURL(interaction.user.displayAvatarURL())
                    )
            )
            // Separator
            .addSeparatorComponents(separator =>
                separator.setSpacing(SeparatorSpacingSize.Large)
            )
            .addSectionComponents(section =>
                section.addTextDisplayComponents(textDisplay =>
                    textDisplay.setContent('Pick your main account from the list below. This will be the account you receive gifts on!')
                )
            )

can I not have 2 sections?

  • section
  • separator
  • another section
agile nest

You can have multiple sections

strong star

what is the correct way to do it?

rose tangle

you're doing it correctly

but a section needs an accessory

agile nest

There is no correct way, do it how you like

strong star

this is giving a validation error

rose tangle

your 2nd section doesn't have one

read my message

strong star

ah I see, what if I just want text on that section?

rose tangle

then just add text

agile nest

You cant

sharp ginkgoBOT
rose tangle

not an entire section

a section without an accessory is useless, hence why it errors

strong star

that sucks Sadge
and can you not have a drop down accessory?

rose tangle

that sucks Sadge
why? you're adding an unnecessary component
and can you not have a drop down accessory?
do you mean a select menu? if yes, then yeah, but like always it needs to go in an action row

strong star

oh wait I got it

if you want just plain text you can addTextDisplayComponents to ContainerBuilder on its own, otherwise if you want an accessory you do it in a section

rose tangle

yes

strong star

what does SeparatorSpacingSize increase? its y-spacing or how wide it spans on the x-axis?

bitter nova

its y-spacing

strong star

oh that's nice, thx

bitter nova

pepeCheers

strong star

time to port 100+ commands now weariest

bitter nova

good luck Kek i still need to do that

strong star

😂

gilded raven
rose tangle show registration.js

It's a very big file, I won't be sharing all of it. This is what's causing the error:


module.exports = {
  name: "interactionCreate",
  execute: async (interaction) => {
    if (!interaction.isButton()) return;

InteractionCreate:

client.on('interactionCreate', async interaction => {
    if (!interaction.isChatInputCommand()) return;

    const command = client.commands.get(interaction.commandName);

    if (!command) return;
  
    try {
        await command.execute(interaction);
    } catch (error) {
        console.error(error);
        await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
    }
});
rose tangle

that second code seems entirely unrelated

since it's handling commands

in your first code, "interaction" isn't an interaction, you can try logging it

maybe you're passing your client and it's actually that

crystal glen
node:events:495
      throw er; // Unhandled 'error' event

TypeError: media.addMediaItem is not a function
    at C:\Users\Leon\Desktop\Neuer Ordner (2)\index.js:51:15
    at resolveBuilder (C:\Users\Leon\node_modules\@discordjs\builders\dist\index.js:2224:12)
    at C:\Users\Leon\node_modules\@discordjs\builders\dist\index.js:1805:56
    at Array.map (<anonymous>)
    at ContainerBuilder.addMediaGalleryComponents (C:\Users\Leon\node_modules\@discordjs\builders\dist\index.js:1805:37)
    at Client.<anonymous> (C:\Users\Leon\Desktop\Neuer Ordner (2)\index.js:50:8)
    at Client.emit (node:events:517:28)
    at MessageCreateAction.handle (C:\Users\Leon\node_modules\discord.js\src\client\actions\MessageCreate.js:32:14)
    at module.exports [as MESSAGE_CREATE] (C:\Users\Leon\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
    at WebSocketManager.handlePacket (C:\Users\Leon\node_modules\discord.js\src\client\websocket\WebSocketManager.js:351:31)
Emitted 'error' event on Client instance at:
    at emitUnhandledRejectionOrErr (node:events:398:10)
    at process.processTicksAndRejections (node:internal/process/task_queues:84:21)

Node.js v18.18.0```
rose tangle

there's no addMediaItem method in any builder

if you're using ai-generated code you should expect issues

check the docs for actual usages

sharp ginkgoBOT

guide Popular Topics: Display Components - Media Gallery
read more

steel trail
bitter nova

Peepogiga

torn orchid

How do I get the update of @discordjs/core @ 2.2.0 & @discord.js @ 14.21.0?

bleak owl

what do you mean?

just install the version?

torn orchid

Yea, how do I do that?

gilded raven
bleak owl

npm i <package>

torn orchid

What would be the package?
npm i 14.21.0 & npm i 2.2.0

bleak owl

this is basic npm commands, not really d.js related

npm i discord.js@14.21.0, etc.

bitter nova
gilded raven Ah, that's here: ```js } else if (btnInteraction.customId === "new_ver...

...interaction serializes and spreads the object, so you lose a lot of properties
you should never modify discord.js provided classes
until you did a better implementation, you can use interaction.skipDuplicateCheck = true; before the execute() call

a better implementation would be passing a second parameter into your execute() function like execute(interaction, true)
and change the execute definition to async (interaction, skipDuplicateCheck)
making the skipDuplicateCheck an optional parameter

zenith violet
torn orchid
zenith violet

they're exclusive to eachother

torn orchid

Alright

zenith violet

core is djs but a skinned down version

hence 'core'

crystal glen

Could someone help me rq dm

zenith violet

no

paper crescent

Does the system message for starting threads (<User> started a thread: <name>. See all threads) trigger the messageCreate event?

regal lion

Anyone know whats causing this? Basically, any users, roles being mentioned come back as unknown or inaccessable. The user is me btw.

bitter nova
regal lion

I'll check my code, 1 sec

bitter nova

do interaction.update() or interaction.message.edit() if you already replied to the interaction

regal lion

Yep that fixed it @bitter nova. The typescript warning should have given me a clue, thanks 🙂

bitter nova

thats why i said you need to run .update on interaction, not on interaction.message
so interaction.update()

that should be interaction.deleteReply()
if that doesnt work try passing the message ID into it like so interaction.deleteReply(interaction.message.id)
if that also doesnt work you can still interaction.message.delete()

regal lion

Anyone know how to start to figure out what discord.js is complaining about here?

If I add any fields to the embed, it just fails.

.addFields(
                {name: 'Start Date', value: loaRequest.start, inline: true},
                {name: 'End Date', value: loaRequest.start, inline: true},
                {name: 'Reason', value: loaRequest.reason, inline: false},
            )
bitter nova

did you try all 3 of the options?

also note that you cant .update then .deleteReply
you need to pick one of the 2

that is correct, ephemeral messages cant be deleted with interaction.message.delete()

unique shoal

deleteReply works though

bitter nova

it should, try doing interaction.deleteReply("@original")

make sure you dont run .update() before it tho

regal lion
bitter nova

no worries pepeCheers

unique shoal

Not sure I understand why you can't update first, I missed that part

Yeah

Just pass the id of the ephemeral

bitter nova
unique shoal

No?

rose tangle

making what error? ah, deleteReply, no, it isn't an interaction reply, in fact deleteReply will error if you don't reply (defer, reply, or update) first (since there's no reply), maybe not if it's a component interaction but I wouldn't reply on it

bitter nova

ahh alright, my bad BowDown

unique shoal

update is an initial response method that updates the message an interaction came from.

You can then no longer use reply, update, defer(s) or showModal again, as it's already been sent

editReply and deleteReply would still work perfectly though

That's the whole point of those methods, to be used after

And followUp

bitter nova

AyakoNoted

bitter nova

I'm pretty sure its just new EmbedBuilder(<Message>.embeds[0].data)
<Message>.embeds[0] can be anything referencing a message embed

sharp ginkgoBOT
bitter nova

its the new markdown -# text here but not djs related

stray saffron

thank you

sand briar

Hello, I'm trying to enter the reason for deleting the channel, but Discord doesn't give me anything. Do you know why? I'm on Discord.js 14.21.0.

loud quartz

try fetching the audit log and see if there's a reason in the data you fetched

if it's there - unfortunately discord didn't add showing the reason in the ui, not much you (or anyone here) can do about that.
if it's not, someone would have to bonk discord people to either remove note that this supports reasons in api docs, or have them fix it. again not really something you can do much about

regal lion

Is there anyway to force which line you want the embed fields on?

Ideally want this in 3 rows, fields 1 and 2, fields 3 and 4 and then field 5.

loud quartz

inline fields will display next to each other

any non-inline field will not allow any other field to display next to it

and as such will have entire row to itself

regal lion

I need to find a nicer way of doing this then. Thanks though. ^_^

loud quartz

if you start inserting empty fields, you'll make this look bad in places that don't display inline fields at all

regal lion

Yeah, wasn't thinking empty fields. I'll come up with something.

Idea. setTimestamp on an Embed... will that take a regular javascript Date object?

loud quartz

you can check docs on what does it take

sharp ginkgoBOT
loud quartz

depends how you build them

regal lion

In theory, looks good, in practice, let's find out.

That timestamp will continue to update based on the current date/time, correct?

loud quartz

uhh

update how?

it's one single timestamp, that will always point to that time you passed in

regal lion

Yep, that works great then.

Appreciate the help. ^_^

sand briar
loud quartz

*UI

well

plush veldt

Hello! When the message component collector time ends, is its collect and end event also completely cleared or might it cause a memory leak if there are too many of them by sending new message?

stable sun
plush veldt
stable sun All listeners are stopped when the collector is stopped

Thanks! Does that mean the collect and end events are automatically removed from memory, without needing to explicitly call Collector.removeAllListener("collect") in the end event?

I checked the Discord.js source code, and I saw that it removes listeners for events like messageDelete and guildDelete, but I couldn’t find anything related to removing collector events like collect.

stable sun

That’s why d.js has to manually remove those listeners

plush veldt
stable sun That’s why d.js has to manually remove those listeners

Yeah I saw that some client events like messageDelete are automatically removed, but what about collector events when the collector time expires?
Do they get removed automatically, or do I need to explicitly call collector.removeAllListener("collect") in the end event of collector?

stable sun

You should’ve also seen in the code that the collector creates those listeners

stable sun

Collector event listeners are automatically stopped

Unless you mean "automatically" in the POV of ur codebase/project

Not d.js source code

You don’t need to manually remove listeners when the collector is stopped for any reason specified when creating the collector or when calling collector.stop

If ur collector isn’t ending, then you have a bigger issue at hand most likely

dense jackal

if you switch two things you are correct:

Yeah I saw that some client events like messageDelete collector events when the collector time expires are automatically removed, but what about collector events when the collector time expires client events like messageDelete ?

answer: you need client.removeAllListeners("messageDelete") as you said (partially)

stable sun

The collector needs to remove it because it created it and the client doesn’t get destroyed when the collector ends

client.removeAllListeners("messageDelete")
As a side-note, you should never use that specific line since is very problematic as it can mess up active collectors and anyone else using it. Prefer removing specific listeners instead

The only reason you would need to remove a listener from the collector is if you haven’t ended the collector (collector.end event doesn’t fire)

plush veldt

Is those collector events will remove like the client event? After the specificied collector is ended

dense jackal

I noticed that the client event—such as a messgeDelete—gets removed as expected

that should not be expected at all, that shouldn't happen in the first place

collector ends > corresponding collector event ends too

client events are not related to your collectors

stable sun

The collector will only remove its own listeners that it created on the client

To be honest, you wouldn’t have to worry about a memory leak as long as you aren’t making stuff global for no reason

plush veldt

Yeah I know I just want to know what about the collector events because i also listen tocollect event and it not useful when collector ends

stable sun

The collector would disconnect itself from the client and wouldn’t be reachable in the code

No line in the collector would be able to execute after ending

So it all gets garbage collected regardless of whether you removed all collector listeners or not

plush veldt
dapper oyster

how to extend collection lifetime?

stable sun
dapper oyster
stable sun

I don’t think any caches have a time by default

stable sun

You could use the idle option if you want the time to reset every time a component gets collected

dim tide

Hi, would Discord Wordle's "Your group is on a x day streak! 🔥 Here are yesterday's results:" trigger messageCreate? Thanks!

snow onyx

yes

raw veldt

How do I go about attaching files to messages? What I currently have is just causing this: TypeError [ReqResourceType]: The resource must be a string, Buffer or a valid file stream.

rose tangle

show your code

raw veldt
rose tangle show your code
 let file = new File([message], "records.txt", { type: "text/plain", })

file = new AttachmentBuilder()
.setFile(file)
.setName("records.txt")
.setDescription("The records of this AOS.")
.setSpoiler(false)

const fileComp = new FileBuilder()
.setURL('attachment://records.txt')

interaction.user.send({ content: header, files: [file], components: [fileComp], flags: MessageFlags.IsComponentsV2})

rose tangle

setFile accepts the path directly

raw veldt
rose tangle

ah, thought it was a weird attempt to try to attach it

you need the buffer in some way then

then pass the buffer to setFile

sharp ginkgoBOT
rose tangle

in case it's a string

dapper oyster

how to remove mentions in message (like aoi: $noMentionMessage)

sharp ginkgoBOT
dapper oyster
regal lion

Got an odd one today folks, got a slash command that's behaving as expected, but then throwing an 'Unknown interaction'. Any idea how to troubleshoot this?

I've checked the error message and it seems to link back to the component that's been sent in a reply.

Application log shows as follows:

[17:10:21.987] INFO (58092): Sending LOA component to channel 🚫︱request-loa (1374029652355711177)...
[17:10:22.198] ERROR (58092): Unknown interaction
[17:10:22.363] ERROR (58092): Interaction has already been acknowledged.
regal lion

Anyone got any ideas here? I'm just trying to trace whatever interaction is throwing this error.

steel trail

First step: log the full error (including stack) not just the message

Second step: look at the code where it gets thrown

regal lion

I've got the full error log, but it essentially just dumps the component twice. Even though it's only posted once.

sharp ginkgoBOT

Common causes of DiscordAPIError[10062]: Unknown interaction:

  • Initial response took more than 3 seconds ➞ defer the response *.
  • Wrong interaction object inside a collector.
  • Two processes handling the same command (the first consumes the interaction, so it won't be valid for the other instance)
    * Note: you cannot defer modal or autocomplete value responses
steel trail
regal lion

Let me try deferring it and see what happens. If it still throws an error, should I just upload the log here?

steel trail

And if you got the stacktrace then looking at the code that points to helps.

steel trail

Showing full error and code are advisable, yes

regal lion

Yeah deferring it causes it to fail completely. So gimme a moment.

steel trail

Huh? That sounds like you're doing something wrong in deferring... showing that code would also help to find that issue

regal lion

Which bit do you need? interactionCreate, the command, or both?

steel trail

... the one your error stack points at. Since you haven't posted that it's impossible for me to answer that

regal lion
//interactionCreate.js
const { Events, MessageFlags } = require('discord.js');
const { logger } = require('../../utilities/logger.js');

module.exports = {
    name: Events.InteractionCreate,
    async execute(interaction) {
        if (!interaction.isChatInputCommand()) return;

        const command = interaction.client.commands.get(interaction.commandName);

        if (!command) {
            logger.error(`No command matching ${interaction.commandName} was found.`);
            return;
        }

        try {
            const {displayName, id} = interaction.member;
            logger.info(`User ${displayName} (${id}) used /${interaction.commandName}`);
            await command.execute(interaction);
            console.log(interaction.commandName, interaction.id);
        }
        catch (error) {
            logger.error(error);
            if (interaction.replied || interaction.deferred) {
                await interaction.followUp({ content: 'There was an error while executing this command!', flags: MessageFlags.Ephemeral });
            }
            else {
                await interaction.reply({ content: 'There was an error while executing this command!', flags: MessageFlags.Ephemeral });
            }
        }
    },
};
//component.js
const { SlashCommandBuilder, MessageFlags } = require('discord.js');
const LOARequestComponent = require('../../components/loaRequest.js');
const { logger } = require('../../utilities/logger.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('loacomponent')
        .setDescription('Sends the LOA information component to the current channel.'),

    async execute(interaction) {
        const { name, id } = interaction.channel;
        logger.info(`Sending LOA component to channel ${name} (${id})...`);

        await interaction.reply({
            components: [new LOARequestComponent()],
            flags: MessageFlags.IsComponentsV2,
        });
        
        logger.info('Component sent.');
    }
}

This should do it then, let me know if you need anything else.

Log is a bit scuffed because it's going through pino.

steel trail

Neither of those code files are the one your error points at meguFace

regal lion

Yeah I've just seen that in the log. gimme a second. I think I might just found my really stupid mistake.

steel trail

Also seems weird that a file called Button_press seems to try to defer a ChatInputCommandInteraction

regal lion

Yeah I found out what I did...

module.exports = {
    name: Events.InteractionCreate,
    async execute(interaction) {
        if (!(interaction.isButton() && interaction.customId.startsWith("approveLoaButton"))) return;

        await interaction.deferReply({ flags: MessageFlags.Ephemeral });
...
}

I had the interaction.deferReply above the if statement.

So, typical PEBKAC. I wasn't watching what I was doing when I was copying and pasting. 😳

crystal glen
    SlashCommandBuilder,
    EmbedBuilder,
    TextDisplayBuilder,
    MessageFlags,
    SeparatorBuilder,
    SeparatorSpacingSize,
    SectionBuilder,
    ThumbnailBuilder,
    ButtonBuilder,
    ButtonStyle,
    MediaGalleryBuilder,
    ContainerBuilder,
    AttachmentBuilder,
    FileBuilder
} = require('discord.js');
const path = require('path');
const fs = require('fs');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('agb')
        .setDescription('This is components version 2.'),
    async execute(interaction, client) {
        const container = new ContainerBuilder();

        const textTop = new TextDisplayBuilder()
            .setContent(`## Willkommen auf Medusa | Design`);
            container.addTextDisplayComponents(textTop);


        const text1 = new TextDisplayBuilder().setContent('jjj);
        // const button1 = new ButtonBuilder().setLabel('Overview').setURL('https://youtube.com').setStyle(ButtonStyle.Link);

        container.addTextDisplayComponents(text1);


        const separator = new SeparatorBuilder();

        container.addSeparatorComponents(separator);

        const media = new MediaGalleryBuilder()
            .addItems([
                {
                    media: {
                        url: 'https://media.discordapp.net/attachments/1079015238730534923/1388934550465286164/richtlinien.png?ex=686dfe59&is=686cacd9&hm=0c0c8ab2b71bffbe5dfb63d3e60b884e4ce4b727c8414a34a2e76c951651b126&=&format=webp&quality=lossless&width=1178&height=303'
                    }
                }
            ]);
        container.addMediaGalleryComponents(media);

        

        const button1 = new ButtonBuilder()
            .setLabel('Discord Richtlinien')
            .setURL('https://discord.com/terms')
            .setStyle(ButtonStyle.Link);
        const button2 = new ButtonBuilder()
            .setLabel('Community Richtlinien')
            .setURL('https://discord.com/guidelines')
            .setStyle(ButtonStyle.Link);
        const button3 = new ButtonBuilder()
            .setLabel('Community Richtlinien')
            .setURL('https://discord.com/guidelines')
            .setStyle(ButtonStyle.Link);

    const section2 = new SectionBuilder()
        .setButtonAccessory(button1)
        .setButtonAccessory(button2)
        .setButtonAccessory(button3)

        container.addSectionComponents(section2);

        
        interaction.reply({
            flags: MessageFlags.IsComponentsV2,
            components: [container]
        });

    }
};```


The Command doesn't show up on my Server
topaz bluff
crystal glen

ERROR: Unhandled Rejection at: [object Promise]
Reason: Error: Invalid Array length

Cmd Error

topaz bluff

Is that coming from your deploy-commands.js (or whatever equivalent script you have)?

dull pike
        const exampleContainer = new ContainerBuilder()
            .setAccentColor(0x0099FF)
            .addTextDisplayComponents(
                textDisplay => textDisplay
                .setContent(`# Modelo de Pedir Música`),
            )
            .addSeparatorComponents(
                separator => separator,
            )
            .addSectionComponents(
                section => section
                .addTextDisplayComponents(
                    textDisplay => textDisplay
                    .setContent(`\`\`\`
- Nome: Se Depender de Mim - Zé Vaqueiro
- Link: https://www.youtube.com/watch?v=zKTlVopyqxA
- Categoria: Forró
- Estilo: Grave seco
\`\`\``),
                )
                .setButtonAccessory(
                    button => button
                    .setCustomId('copiar')
                    .setLabel('Copiar Modelo')
                    .setStyle(ButtonStyle.Primary),
                )
            )

I'm just starting out with v2 components, how can I put the button below the message, instead of appearing on the right?

sharp ginkgoBOT
topaz bluff

add the buttons to an action row, then pass the action row directly to the container

crystal glen
            .setAccentColor('#00ff00')
            .setContent(`## Willkommen auf Medusa | Design`);
        container.addTextDisplayComponents(textTop);```

Is it wrong to add color?
zenith violet

text displays dont have colors

containers do

crystal glen
steel trail

What would that even look like? Both of those can be inside a container. Which can have an accentColor

crystal glen

Aight

unique hornet
await interaction.deferReply();
let user1 = interaction.user;
let user2 = interaction.options.getUser("user");

const mainMessage = await interaction.editReply({
      content: `<@${user2.id}>, you have been challenged by ${user1}!`,
      embeds: [embedInfo],
      components: [rowBtn],
      allowedMentions: { parse: ["users"] },
    });

Any reason its not pinging user2?

steel trail

Edits don't notify. But it should show the yellowish mention around the message

Considering you don't do any async tasks in between you don't need to defer and edit, just reply

unique hornet
wary coral
bleak owl

or just reply without the defer and edit

steel trail
wary coral
crystal glen
                button.setLabel('hi')
                    .setURL('https://discord.com/guidelines')
                    .setStyle(ButtonStyle.Link)
            );```

Is this Correct ?
wary coral

you need a textdisplay for a section

crystal glen
wary coral

then you would need an action row

zenith violet

Also why ask if its correct, check the docs

sharp ginkgoBOT

guide suggestion for @crystal glen:
guide Popular Topics: Display Components
read more

pliant forge

i wanna create Emoji thread and sticker log system, which one gateway intent bits i should add?

bleak owl

what would be the purpose of that?

pliant forge

Like when emoji created or deleted or updated

same thig for sitcker and threads

sharp ginkgoBOT
bleak owl

whoops yeah GuildExpressions

pliant forge

tysm

worthy light

Since when can we make embeds like this? This looks crazyy

sharp ginkgoBOT

guide suggestion for @worthy light:
guide Popular Topics: Display Components
read more

worthy light

thanks, is this new?

worthy light

damn

short mulch

How can I make my button contain the message ID for the custom id? (Slash command)

zenith violet

by literally doing that

set the customId to your messageid

short mulch

(I'm kinda new, so sorry if im being dumb)

short mulch
steel trail

That's not the error you receive. Read the actual error, not paraphrase it

wary coral
short mulch

Would you kindly show us the code at and around line 158 in slash/giveaway.js

dense jackal

is the interaction an actual button interaction

short mulch
const send = new ButtonBuilder()
             .setLabel('Send')
             .setCustomId(`send-giveaway-${interaction.message.id}`)

             .setStyle(ButtonStyle.Success);

(Indents are caused by the panel)

dense jackal

yeah so your interaction is most likely of type ChatInputCommandInteraction, which does not include the message property

steel trail

What message do you expect that to be?

jagged rock

command name shows as /undefined

```js
const now = Date.now();
const timestamps = cooldowns.get(command.name);
const cooldownAmount = (command.cooldown || 0) * 1000;

if (timestamps.has(interaction.user.id)) {
  const expirationTime = timestamps.get(interaction.user.id) + cooldownAmount;
  if (now < expirationTime) {
    const timeLeft = Math.floor(expirationTime / 1000);
    const embed = new EmbedBuilder()
      .setColor(config.colour.warn)
      .setDescription(`You can use \`/${command.name}\` again <t:${timeLeft}:R>.`);

    return interaction.reply({
      embeds: [embed],
      flags: MessageFlags.Ephemeral
    });
  }
}
steel trail

And what is command defined as?

short mulch
jagged rock
steel trail
steel trail
dense jackal
jagged rock

my userinfo command

steel trail

They should know how they define their variable. Logging doesn't help

steel trail
jagged rock
dense jackal
jagged rock

i have instialized client.commands too in my index.js

did this

if (timestamps.has(interaction.user.id)) {
  const expirationTime = timestamps.get(interaction.user.id) + cooldownAmount;
  if (now < expirationTime) {
    const timeLeft = Math.floor(expirationTime / 1000);
    const embed = new EmbedBuilder()
      .setColor(config.colour.warn)
      .setDescription(`You can use \`/${interaction.commandName}\` again <t:${timeLeft}:R>.`);

    return interaction.reply({
      embeds: [embed],
      flags: MessageFlags.Ephemeral
    });
  }
}```

works now

steel trail

That... is completely unrelated to your issue, but okay

jagged rock

i fixed my issue so what do you even mean, it was my issue ?

steel trail

Oh, mb, you just changed your code... got confused since there was no mention of command anymore

ocean portal
ocean portal

oh

spiral cargo

hi, is the documentation for components v2 available yet?

bleak owl

yes

sharp ginkgoBOT

guide Popular Topics: Display Components
read more

spiral cargo

thanks ramenCat

quartz lodge

How do I check if a specific role in a channel has a permission ?

sharp ginkgoBOT
quartz lodge

what does this return ?

an array, an object?

sharp ginkgoBOT
wary coral

The above object is what it returns as per the documentation

unborn scarab

does djs have a func for verifying signature headers? using it in an interactions endpoint

red coral

I don’t believe so, check djs http-only

No. Not that i can see

kind brook

this chunk of code exists in one of my command files, unsure as to why nothing is being played.

async function execute(interaction) {
    const sound = interaction.options.getString("file");

    const player = createAudioPlayer();
    player.on(AudioPlayerStatus.Playing, () => {
        console.log('The audio player has started playing!');
    });
    player.on('error', error => {
        console.error(`Error: ${error.message} with resource`);
    });

    const resource = createAudioResource(`./resources/mp3/${sound}.mp3`)
    player.play(resource)

    let connection = getVoiceConnection(interaction.guild.id)
    if(!connection) {
        console.log("no connection found")
        connection = joinVoiceChannel({
            channelId: "xxx",
            guildId: "xxx",
            adapterCreator: interaction.guild.voiceAdapterCreator,
            selfDeaf: false
        })
    } else {console.log("connection found")}

    connection.subscribe(player);
    
}

any ideas?

I tried to follow the guide and examples in the repo as closely as possible, no errors or anything however

unborn scarab
loud quartz
unborn scarab

ah that's a shame

sharp ginkgoBOT

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.

unborn scarab

hmmm, just a quick followup, would I still be able to use @discordjs/rest for responding to interactions, or should I just hand roll fetch?

unique shoal

you can use it standalone, yeah

lean sail

why is there no .kickable? (as well as a bunch of other properties/methods?)

wary coral

GiuildMember does have GiuildMember#kickable

sharp ginkgoBOT
lean sail

well i know it exists but why is it not showing up in intellisense

is there some kind of typeguard i need or something else

wary coral

getMember could be APIInteractionDataResolvedGuildMember

sharp ginkgoBOT
wary coral

So you do need to type guard

lean sail

ok thanks

sharp ginkgoBOT
zealous bison

hello, i'm creating a channel through <GuildChannelManager>.create, i'm setting up permissions for multiple users and roles when creating, but in some cases I am getting this error: ```js
TypeError [InvalidType]: Supplied parameter is not a cached User or Role.
at PermissionOverwrites.resolve (/app/node_modules/discord.js/src/structures/PermissionOverwrites.js:185:13)
at /app/node_modules/discord.js/src/managers/GuildChannelManager.js:181:89
at Array.map (<anonymous>)
at GuildChannelManager.create (/app/node_modules/discord.js/src/managers/GuildChannelManager.js:181:51) {
code: 'InvalidType'
}

the error basically says that the user does not exist in cache, and it really is not in cache, but it actually exists, does anyone know how I can avoid this check?

I thought about using REST to create the channel, but I first wanted to know if there really isn't a way to skip this check through `<GuildChannelManager>.create`
rose tangle

you need to supply the overwrite type if you provide an id

otherwise djs will need to infer from the cache whether it's a user or a role

and if it's not cached and you don't provide the type there's no way for it to know which one it is

zealous bison

oh well thanks angelo, i didn't even look at the api documentation and i ended up not realizing that it required the type

i put the type and everything worked out, thank you

lone eagle

for existing channels bot needs manage_roles for editing permission overwrites, and when creating channels (when bot has manage_channels) it can set overwrites without manage_roles right?

steel trail

Yes, but only allow/deny permissions the bot itself has, unless it had ManageRoles

plush veldt

Hello I deleted a message from the bot but the <Message>.editable returns me true but why?

steel trail

Because that checks permissions, not if the message still exists

plush veldt
steel trail

That's what you did. Finding out what actually exists on API side needs an API request. The edit request is the best one to do so as otherwise it's still possible that the message gets deleted between your check and the edit request

plush veldt
steel trail

Well, if you yourself delete the message you should be able to know that in your code. That's not something djs can do for you though

plush veldt
steel trail

Those still both check permissions, neither can check whether the message still exists

plush veldt

Thank you

safe axle

Hi,
Can someone tell me the PermissionFlagsBits for Create Posts permission of the guild forum ?
Thank you

steel trail

CreatePublicThreads is the correct permission

lone eagle
sharp ginkgoBOT

method GuildChannelManager#create() discord.js@14.21.0
Creates a new channel in the guild.


// Create a new text channel
guild.channels.create({ name: 'new-general', reason: 'Needed a cool new channel' })
  .then(console.log)
  .catch(console.error);

lone eagle

thinKappa

safe axle
steel trail CreatePublicThreads is the correct permission

Thank you for your reply but it didn't work. I tried with other permissions like CreateInstantInvite and it worked.
I'm using discord.js 14.21.0
This is my sample code

if (!forumChannel) {
        forumChannel = await interaction.guild.channels.create({
          name: "Private",
          type: ChannelType.GuildForum,
          topic: "Private Forum",
          reason: "Auto setup",
          permissionOverwrites: [
            {
              id: interaction.guild.id,
              deny: [
                PermissionFlagsBits.ViewChannel,
                PermissionFlagsBits.CreatePublicThreads,
              ],
            },
          ],
        });
      }```
Did I make a mistake ?
Thank you
steel trail

Yes, you deny everyone to view the channel and to make posts so your bot won't be able to do it either. But it needs to be able to do it to be able to deny others to do so

lone eagle
steel trail
sharp ginkgoBOT
steel trail

Maybe this answers all your questions better

Or rather the following page

sharp ginkgoBOT

guide Popular Topics: Permissions (extended)
read more

lone eagle

exception manage_roles overwrite

neat

so i dont need to remind user of every permission when creating channel as long bot has manage_channels

safe axle
dense jackal
safe axle

I want to hide it when creating then set the ViewChannel for everyone later.

dense jackal

allow your bot the ViewChannel permission

safe axle

Even it has the admin permission ? Lemme try

dense jackal

admin !== server owner

safe axle
dapper oyster

how can i fix this typing error, should i install @discordjs/rest module?

Module '"discord.js"' declares 'REST' locally, but it is exported as 'Collection'.ts(2460)
index.d.ts(40, 57): 'REST' is declared here.
steel trail

No, where do you get that error? Because it makes no sense

dapper oyster
steel trail

Is it your IDE or tsc that errors? Or something completely different?

dapper oyster

tsc, maybe mt tsconfig.json is wrong

steel trail

What version of typescript and discord.js are you on?

dapper oyster

dependencies:
discord.js 14.21.0

devDependencies:
ts-node 10.9.2
typescript 5.8.3

golden laurel

Nuke node_modules, install again, and see if it persists

dapper oyster

yep, thats tsconfig fault

"preserveSymlinks": true, //faulty c
raven cedar

does anyone know if there is a way to disable the display of user tags on one's server?

topaz bluff

Not DJS related. But no

raven cedar

ok, I thought there perhaps might be some hacky way to do it server-side with DJS by nulling the property for the server-member's tag, or just overwriting it with some blank tag

topaz bluff

DJS doesn't have a "hacky way" to do anything because it only supports documented features of the API

But server tags also are User attributes and can't be set on a per-server basis, meaning you can't modify them by a bot anyways. You can filter for them but the update for DJS for server tags is still a PR, so you'll have to use raw REST requests until then

(or use AutoMod)

tired bone

Alright so i'm on the edge of losing my sanity.
i already made a specific client.ready code to enforce caching all members once bot's up
Yet when a listener is fired to detect if a user's roles changed before/after it never works the first time only the second and from so on.
How do i put an end to this

unique shoal

Can you show the code you're referring to and your intents?

tired bone

Sure, One second

The listener Code is in the message.txt
My intents :

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.GuildPresences,
    GatewayIntentBits.MessageContent,
    GatewayIntentBits.GuildMembers,
    GatewayIntentBits.GuildModeration,
    GatewayIntentBits.GuildBans
  ]
});

The script inside client.ready to cache all members

 try {
    // 👥 Fetch and cache all members in each guild
    for (const [guildId, guild] of client.guilds.cache) {
      try {
        await guild.members.fetch();
        logger.info(`✅ Cached ${guild.members.cache.size} members in ${guild.name}`);
      } catch (err) {
        logger.warn(`⚠️ Failed to fetch members for ${guild.name}: ${err.message}`);
      }
    }
  } catch (fetchError) {
    logger.error('❌ Failed while fetching members in all guilds:', fetchError);
  }

i also want to note that i've used an eval command

-eval return message.guild.members.cache.map(m => m.user.username)

To see if a specific member is indeed cached or not and they were! So i tried adding manually a role to their roles, Nothing happend
Removed it and added it again
The bot removed it.
So i'm so lost.
And it seems SOMEHOW that even when i hard-restart the bot it still remembers the members i already added roles to before but the ones i never did (even before restart) i have to interact with them even once
Which makes me even more lost cause if it was a normal cache issue then it should happen to same members each time i hard-restart

nocturne flint

Is there a method to run or something before running anything that implies using cached user to avoid such an error:
TypeError [InvalidType]: Supplied parameter is not a cached User or Role.?

outer plume
nocturne flint

Which one is expected: id: guild.roles.everyone, or id: guild.roles.everyone.id,

nocturne flint
outer plume
nocturne flint

I am referring to permission channel overwrites.

outer plume
nocturne flint

Thanks!

outer plume

i assume you're using permissionsFor?

lean sail

is the .kickable on the GuildMember going to return for if the person who actually USED the command can kick them or the client itself

nocturne flint

Nope, creating a channel... guild.channels.create({})...

zenith violet

Roles are cached by the Guilds intent

and even then, the everyone role id is the same as the guild id

You might have to specify an OverwriteType

sharp ginkgoBOT
lean sail
zenith violet

No

outer plume
zenith violet

You have to manually check it

lean sail
zenith violet

Or just check their permissions in general

lean sail

how so

sharp ginkgoBOT
zenith violet

1 less api request

Though if you have the fetch the role you might have a bigger issue

outer plume

that's what I was wondering. since they should already be cached

lean sail
lean sail
zenith violet

Probably yes, only one way to check.
Also name your variables properly

A member is not a user

Also those 2 isGuildMember checks are redundant

If the user isnt in the server there would be no interaction.member, and getMember would return null if the specified user isnt in the server

lean sail

ok

lean sail

do i just check if it exists instead?

outer plume

you still need to check if .member exists in the first place. since slash commands can be used in DMs, TS can't be sure about 'member' existing

null check ≠ guild member check. If you've made sure the command can't be used in DMs, add a ! after interaction.member

sharp ginkgoBOT
lean sail

is the generic not enough?

outer plume

i always forget inCachedGuild exists Thonk

lean sail

and also with my logic the server owner passes the permissions check but not the role check and thus is told they cant kick the member, do i have to add an additional check for guild owners?

outer plume

check for owner first. if owner, skip role and permission check

tiny condor

Heya is it against the API to get all my guild members and select like 100 random ones ?

snow onyx

no

tiny condor

And I would use fetch for that right?

<guild>.members

Or wait I can't fetch from that

snow onyx

guild.members.fetch() -> returns a promise with a collection of all members
collection.random(100) gives you 100 random members

tiny condor

Ah okay perfect thanks

And I can cache the full members right since I need to re-use it every like hour

Around 2,000~ members, just only specific to this guild

loud quartz

This is a really small amount

tiny condor

Okay perfect 😄

I just need their avatar and username that's all it's for a game

sharp ginkgoBOT
viral cave

ty

kind plume

Is there way to clone container component like buttons? Buttons have ButtonBuilder#from method and looks like ContainerBuilder don't have one

sharp ginkgoBOT
kind plume

❤️

tiny condor
cobalt valley

How to set this? In bot's about me

ocean portal
bleak owl

that is only available when discord has enough data on your bot and when it's verified

cobalt valley
bleak owl

that is only available when discord has enough data on your bot

thorny lily

Hello, I've got this setup:

```const collector = await reply.createMessageComponentCollector({ componentType: ComponentType.Button });`

collector.on('collect', async i => {
i.reply("Aaaaaaaa");
})```

(this is a little bit simplified version, but the point is this)
aaand no matter what, if I do i.reply() or i.deferUpdate(), it always gives me Unknown Interaction error

tardy sable

whats the MessageType for forwards?

also if i fetch a message thats a reply to someone, will that message that was replied to be in cache?

sharp ginkgoBOT
hallow mesa
hallow mesa

A type for the message reference, not for the message itself

outer plume

ah. Pray

hallow mesa
tardy sable

ty

boreal olive

what's the best tsconfig for an application that includes express and discord.js?

steel trail

That depends on where/how you intend to run it. And if it includes frontend too

boreal olive
boreal olive

oke.. let me see

boreal olive
steel trail Then <https://github.com/discordjs/discord.js/blob/main/packages/create-discord-...
📄 Reason: Error: Cannot find module 'file:///C:/Users/e03o/Desktop/bot/aethel/dist/commands/fun/8ball.js'
Require stack:
- C:\Users\e03o\Desktop\bot\aethel\dist\handlers\initialzeCommands.js
- C:\Users\e03o\Desktop\bot\aethel\dist\services\Client.js
- C:\Users\e03o\Desktop\bot\aethel\dist\index.js
    at Function._resolveFilename (node:internal/modules/cjs/loader:1401:15)
    at defaultResolveImpl (node:internal/modules/cjs/loader:1057:19)
    at resolveForCJSWithHooks (node:internal/modules/cjs/loader:1062:22)
    at Function._load (node:internal/modules/cjs/loader:1211:37)
    at TracingChannel.traceSync (node:diagnostics_channel:322:14)
    at wrapModuleLoad (node:internal/modules/cjs/loader:235:24)
    at Module.require (node:internal/modules/cjs/loader:1487:12)
    at require (node:internal/modules/helpers:135:16)
    at C:\Users\e03o\Desktop\bot\aethel\dist\handlers\initialzeCommands.js:64:98
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    'C:\\Users\\e03o\\Desktop\\bot\\aethel\\dist\\handlers\\initialzeCommands.js',
    'C:\\Users\\e03o\\Desktop\\bot\\aethel\\dist\\services\\Client.js',
    'C:\\Users\\e03o\\Desktop\\bot\\aethel\\dist\\index.js'
  ]
}

this is the main problem I'm trying to overcome..

steel trail

that's unrelated to your tsconfig though

boreal olive

no problem on dev environment

steel trail

Does a file by that name exist?

boreal olive

yeah

steel trail

node16 is probably not what you want. your path alias points to ./src .
But node doesn't know how to handle that alias

boreal olive
steel trail

Ah, I see... and did you check if the .js file actually exists?

steel trail

Can you show me? Because the error clearly disagrees

boreal olive

i deleted the dist and tried building again.. now with imports errors

steel trail

dist/src/commands is not dist/commands

boreal olive

but there's something i need to show you

you can see here that I'm logging the default value from the command https://github.com/9is-z/aethel/blob/6aee94a10b82c6caf5ab28fba28e14136f7ee050/src/handlers/initialzeCommands.ts#L22
in dev, the log of 8ball looks like this

{
  data: SlashCommandBuilder {
    options: [ [SlashCommandStringOption] ],
    name: '8ball',
    name_localizations: { 'es-ES': 'bola8', 'es-419': 'bola8', 'en-US': '8ball' },
    description: 'Ask the magic 8-ball a question',
    description_localizations: {
      'es-ES': 'Haz una pregunta a la bola 8 mágica',
      'es-419': 'Haz una pregunta a la bola 8 mágica',
      'en-US': 'Ask the magic 8-ball a question'
    },
    contexts: [ 1, 0, 2 ],
    default_permission: undefined,
    default_member_permissions: undefined,
    dm_permission: undefined,
    integration_types: [ 1 ],
    nsfw: undefined
  },
  execute: [AsyncFunction: execute],
  category: 'fun'
}

but in the build,

{
  default: {
    data: SlashCommandBuilder {
      options: [Array],
      name: '8ball',
      name_localizations: [Object],
      description: 'Ask the magic 8-ball a question',
      description_localizations: [Object],
      contexts: [Array],
      default_permission: undefined,
      default_member_permissions: undefined,
      dm_permission: undefined,
      integration_types: [Array],
      nsfw: undefined
    },
    execute: [AsyncFunction: execute]
  },
  category: 'fun'
}

error that doesn't exist on dev

tried using copilot but no success

steel trail

Is that with the tsconfig I linked you to? Or the one in the repo?

boreal olive
steel trail

... with additions/changes you made I assume, since it won't work with path aliases otherwise for example

boreal olive
proud otter

Hi guys, was wondering how do i get the colors of the gradient role?

steel trail