#djs-help-v14

78874 messages · Page 19 of 79

rose tangle
keen jungle

I can't see the chat

rose tangle

just click the link

it's not a private channel

woven portal

so .setContexts(BotDM, Guild, PrivateChannel)

keen jungle

Do you have the doc?: How are you learning to create this? I see a lot of people already using it, but I have difficulty

rose tangle
rose tangle

if you meant a guide doc/entry then as I said it's still in the works

woven portal
rose tangle

but there's a preview

rose tangle

^^

steel trail

InteractionConextType.BotDM for example

woven portal

i see, so either i write that full into the parameters or i can shorten them by defining them first

what about setIntegrationTypes, could you provide what that method takes in

rose tangle

^^

keen jungle

loss for opening the topic there, I was finishing reading

uncut fable

anyone why i need to fetch all guild members for the guildMemberRemove event to work?

clear garnet

Because without partials, the event relies on cache for the old member data since Discord only provides the new member data

keen jungle

I was reading and was in doubt, we can only use the CV2 with class containerbuilder?

steel trail

No

You can use them without a container too

keen jungle

Do you have a reference link? I was reading all about the topic #1365720579977511083 but I was still in doubt. It was not so clear, and then it could not solve it

I tried to send a containerbuilder, and the API rejected

It seems only is accepting the action -type action

steel trail

Missing the IsComponentsV2 flag then probably

keen jungle
keen jungle
steel trail

By passing that flag in your message payload. Showing your code helps also to help you fix it

keen jungle

Hello! I'm trying to use the new flexible components (CV2), specifically ContainerBuilder and TextDisplayBuilder, in an interaction reply.

However, any attempt to send a ContainerBuilder directly in the components array results in a DiscordAPIError[50035]: Invalid Form Body error, where the API expects a type: 1 (ActionRow) component.

Based on a conversation I saw (and this PR: https://github.com/discordjs/guide/pull/1620), I suspect I need to pass a specific flag to enable CV2 rendering. Someone mentioned I might be missing isComponentsV2: true in the message payload, but I couldn't find this in the official docs.

Is this correct? If so, how should I structure my reply payload? Here is the code that is failing:

import { SlashCommandBuilder, ChatInputCommandInteraction, ContainerBuilder, TextDisplayBuilder } from 'discord.js';

// ... (inside the command's execute function)

const imageText = new TextDisplayBuilder()
    .setContent('![banner](https://i.imgur.com/kS5A4ND.png)');

const container = new ContainerBuilder()
    .addTextDisplayComponents(imageText);

// This reply fails with error 50035
await interaction.reply({
    components: [container],
    ephemeral: true
});

Thank you for any guidance!

steel trail

Use flags: MessageFlags.IsComponentsV2 | MessageFlags.Ephemeral instead of your ephemeral: true

rustic vector

is there anyway to show countdown per sec without sending api call every sec?

bleak owl

you could use a unix timestamp, but otherwise no

fallen trellis

does anybody have a link to a resource presenting the limits of the api? by this i meant character limits for containers (or text displays), embeds, messages...

rose tangle

it's split in the docs

each resource documents its limits

sharp ginkgoBOT
rose tangle

text display limit is undocumented afaik but 4k characters per message

fallen trellis
cunning gazelle

Ok I have basically no clue how to get the bot to listen to the vc

bleak owl

discord.js doesn't have a way of doing that. you need to find your own way of doing so

steel trail
keen jungle
steel trail Use `flags: MessageFlags.IsComponentsV2 | MessageFlags.Ephemeral` instead of you...

perfeito, aprendi a usar um pouco
I'm exploring the new Flexible Components (V2) and trying to build a character sheet for an RPG bot. My goal is to replicate this layout, with a small image next to the character's name:

(Attach the desired layout image here)

I've already managed to create most of the structure using ContainerBuilder, TextDisplayBuilder, and StringSelectMenuBuilder, and the result looks great.

The code that generates the text layout below is this:

import {
    SlashCommandBuilder,
    ChatInputCommandInteraction,
    ContainerBuilder,
    TextDisplayBuilder,
    MessageFlags,
    ActionRowBuilder,
    StringSelectMenuBuilder
} from 'discord.js';

// ... (inside the command)

// 1. The Dropdown Menu
const selectMenu = new StringSelectMenuBuilder()
    .setCustomId('sheet-menu')
    .setPlaceholder("Hero's Nexus")
    .addOptions([
        { label: 'Inventory', value: 'inventory' },
        { label: 'Skills', value: 'skills' },
    ]);
const menuRow = new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(selectMenu);

// 2. The Text Components
const header = new TextDisplayBuilder()
    .setContent(`### Atlas Romanov's sheet\nPlayer: @user`);
const status = new TextDisplayBuilder()
    .setContent('**Status**\n🎯 Proficiency bonus 1\n🛡️ Armor class 5...');
const attributes = new TextDisplayBuilder()
    .setContent('**Attributes**\n```\nStrength: 7\n...```');

// 3. The Main Container
const container = new ContainerBuilder()
    .addActionRowComponents(menuRow)
    .addTextDisplayComponents(header, status, attributes);

// 4. The Final Reply
await interaction.reply({
    components: [container],
    flags: MessageFlags.IsComponentsV2 | MessageFlags.Ephemeral
});

My main challenge is positioning the image. I've already tried:

  1. Sending an Embed with .setThumbnail() alongside the V2 components. The Discord API rejects this, returning the error: Invalid Form Body: The 'embeds' field cannot be used when using MessageFlags.IS_COMPONENTS_V2.
  2. Sending the image in the files field. This works, but the image is attached to the message, completely outside the component layout.

My question is: Is there a way, using only V2 Components, to include an image from a URL so that it renders as a thumbnail next to a TextDisplayComponent, like in the example? Is there an ImageBuilder or a property that I'm missing?

sharp ginkgoBOT

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

steel trail

A section is what you want: text next to an accessory, which can be a button or (in your case) a thumbnail

keen jungle
steel trail

non-thumbnail images would be a MediaGallery instead

sharp ginkgoBOT

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

steel trail

And that JSDoc is wrong 🤦‍♂️

keen jungle

It seems a lot that you used an embed

steel trail

Huh? Can you rephrase that?

keen jungle

I meant that it seems that the person is using a normal embeds instead of CV2, in this first image I sent

steel trail

No, that's a container from components v2. Embeds can't have buttons in them

sharp ginkgoBOT
steel trail

You're probably confused because of the color

keen jungle

Yes, it really made it look like Embeds, but because of the button and other components, I realized it was a CV2

topaz bluff
potent gorge

of predefinied text?

what exacly i can isnert there

steel trail

You defined the text

potent gorge

damn nice, i thought only roles and members are possible

steel trail

Role, Member, Channel, or String

potent gorge

thats awesome, but search not possible or

going to implement this to my app thanks

zenith violet

you can search all except string selects

cunning gazelle
potent gorge
steel trail
rose tangle

but if you want all roles to be selectable, just use a role select

potent gorge

to bad it doesnt work with the strings

steel trail
potent gorge

ah fk

steel trail

StringSelectMenu is what you want

potent gorge

can i trigger with buttons to open slash commands ?

steel trail

The search feature only exists for menus that can have more than the 25 options able to show at once

steel trail
steel trail

A SelectMenu also triggers an interaction, if that's what you're asking, yes

potent gorge

can i put a selectmenu inside a components?

steel trail

Yes. A SelectMenu is a component

keen jungle
harsh kernel

does a function exist to auto transformate a date to discord timestamp

sharp ginkgoBOT

documentation suggestion for @harsh kernel:
function time discord.js@14.19.3
Formats a date into a short date-time string.

zenith perch

Are there any utility methods for resolving user ids out of UserResolveable objects?

For instance, I want to get the user id of a passed member:

function foo(user: UserResolvable) {
    const id = typeof user=== 'string'
        ? user
        : 'author' in user // message
            ? user.author.id
            : user.id;
    // ...
}

For now, I've just been manually extracting the id, but the docs promise that a UserResolveable will resolve to a user object. Is there some function in the library that does this?

sharp ginkgoBOT
proud arrow

UserManager is , client.users

zenith perch

Thanks, appreciate it

zealous bison

how can i watch this data on ws connection?

[WS => Shard 0] Shard not recoverable: 4004 (AuthenticationFailed)

is there any native event (other than debug) that triggers this data upon reconnection?

pliant forge

i send an ephemerael message with deferReply then i editReply but how can edit again?

pliant forge

oh can i use it again and again?

Tysm

zenith violet

up until 15 minutes after the interaction yes

pliant forge
zenith violet
pliant forge

thanks again

thin reef

I need GuildMembers intent to assign someone a role?

zenith violet

no

intents are for receiving data

you do need to have the Guilds intent

thin reef
zenith violet

a single member yes

thin reef
zenith violet

yes

thin reef

ok thx

night kindle

does GuildMember inherit User in everything like createdAt property for example?

bleak owl

you can access the User object from GuildMember#user to access those properties

bleak owl

im so glad

orchid radish

inside of modals are there any options to include images

topaz bluff

no, only text input

unique shoal

no

orchid radish

sad :(

rose tangle
sharp ginkgoBOT
analog oak

Is it a bad practice to use defer reply in all commands as they all use databases actions and it can take more then 3 seconds in a large-scale bot?

bleak owl

no not really

rose tangle

I mean, I doubt all of them use db actions

and you're also missing out on modals on commands

and you'll also have to code some way to include the ephemeral state you want in the defer

pliant forge

If i asked before sorry but will we get builders for components v2?

rose tangle

but if none of that matters then you're free to do what you feel is best

rose tangle
analog oak
pliant forge
bleak owl
analog oak
rose tangle
sharp ginkgoBOT

documentation suggestion for @pliant forge:
class ContainerBuilder discord.js@14.19.3
A builder that creates API-compatible JSON data for a container.

topaz bluff

start here

pliant forge

tysm @rose tangle @bleak owl and @topaz bluff

topaz bluff

yakuza_kiryuThumbsup

snow violet

So I was checking this server (yes, I know it's a scam) but I saw that they had buttons inside an embed. I cant figure out how this person has managed to do that. Does anyone know?

bleak owl

that's a container, which is a part of the new componentsv2

if you want to know how, i can send the docs for that, just let me know

snow violet
snow violet

Thank you! You guys really helped me

topaz bluff

it's what we do o7

orchid radish

can i show a new modal on a modal submission interaction

topaz bluff

no. a modal cannot trigger a modal

orchid radish

sadness why limited to only 5

topaz bluff

no idea...but if you need more data, you can ask the user to trigger another modal with a button...or you can do something like ask your questions in a DM chain

fathom sand

I was wondering if someone would know if someone made a framework / module to handle interactive chat questionaire with a user?
I'm writing a medical assistance request bot for a game and was wondering if I need to manually code all the questions and their related code, or if someone had built something we can only provide our text, option and flow.

sharp ginkgoBOT
rose tangle

maybe that?

fathom sand

Thanks, I'll take a look

red coral

For allowed mentions, is the default do nothing? Pass nothing? Or do you have to parse: []

unique shoal

By default all mentions are parsed

dawn dagger
const { Client, GatewayIntentBits } = require("discord.js");
const {
  ComponentBuilder,
  ContainerBuilder,
  TextDisplayBuilder,
  MediaGalleryBuilder,
  MediaGalleryItemBuilder,
  ActionRowBuilder,
  StringSelectMenuBuilder,
  SelectMenuOptionBuilder,
} = require("v2componentsbuilder");


// === CONFIGURATION ===
const TOKEN = "token"; // Selfbot token (your real user token)
const CHANNEL_ID = "1179555083323707434"; // Target channel

const client = new Client({
  intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages],
});

client.once("ready", async () => {
  console.log(`✅ Logged in as ${client.user.tag}`);

  // Build V2 Components using v2componentsbuilder
  const components = new ComponentBuilder().setComponents([
    new ContainerBuilder()
      .setAccentColor(0xffe741)
      .addTextDisplayComponents(
        new TextDisplayBuilder().setContent("# **Semi-Automatic Sniper Rifle** - Legendary**")
      )
      .addMediaGalleryComponents(
        new MediaGalleryBuilder().addItems(
          new MediaGalleryItemBuilder().setURL(
            "https://cdn.discordapp.com/attachments/1233225714258677781/1380441457353166909/glow.png"
          )
        )
      )
      .addActionRowComponents(
        new ActionRowBuilder().addComponents(
          new StringSelectMenuBuilder()
            .setCustomId("rarity_menu")
            .addOptions(
              new SelectMenuOptionBuilder().setLabel("None").setValue("none").setEmoji({ name: "❌" }),
              new SelectMenuOptionBuilder().setLabel("Common").setValue("common").setEmoji({ name: "⚪" }),
              new SelectMenuOptionBuilder().setLabel("Uncommon").setValue("uncommon").setEmoji({ name: "🟢" }),
              new SelectMenuOptionBuilder().setLabel("Rare").setValue("rare").setEmoji({ name: "🔵" }),
              new SelectMenuOptionBuilder().setLabel("Epic").setValue("epic").setEmoji({ name: "🟣" }),
              new SelectMenuOptionBuilder().setLabel("Legendary").setValue("legendary").setEmoji({ name: "🟠" }),
              new SelectMenuOptionBuilder().setLabel("Mythic").setValue("mythic").setEmoji({ name: "🟡" }),
              new SelectMenuOptionBuilder().setLabel("Exotic").setValue("exotic").setEmoji({ name: "🔵" })
            )
        )
      ),
  ]);

  // Send raw component payload
  const channel = await client.channels.fetch(CHANNEL_ID);
  await channel.send({
    content: "", // or your caption
    components: components.toJSON(), // V2 components
  });

  console.log("✅ Message sent!");
});

client.login(TOKEN);

Why am I getting this error? I legit copied this code straight from a video so this makes no sense

just trynna figure out how discord components v2 works 😭

unique shoal

ContainerBuilder?

ComponentBuilder is not a thing

rose tangle

v2componentsbuilder is not a package made by djs

unique shoal

Either the video sucks or your copying does

Oh I didnt even see that

dawn dagger
unique shoal

yes lmao

dawn dagger
red coral
unique shoal

I mean, the video is promoting a third party package that isnt necessary, which makes it a crap video

rose tangle
dawn dagger

ahh the video is 2 months old

rose tangle

and even then, if you know it's not a djs package, then it wouldn't make sense to ask for djs support Thonk

unique shoal

We've supported them pretty much since release, since Discord worked with lib devs for some time prior to make sure everyone was ready

rose tangle
dawn dagger

im not that advanced top g

rose tangle

well anyways, you'll have to adapt your code to actual djs code

dawn dagger
// index.js
import {
  Client,
  GatewayIntentBits,
  TextDisplayBuilder,
  MediaGalleryBuilder,
  MediaGalleryItemBuilder,
  StringSelectMenuBuilder,
  SelectMenuOptionBuilder,
  ActionRowBuilder,
  ContainerBuilder,
} from 'discord.js';

const TOKEN = 'token';
const CHANNEL_ID = 'id';

const client = new Client({
  intents: [GatewayIntentBits.Guilds],
});

client.once('ready', async () => {
  console.log(`✅ Logged in as ${client.user.tag}`);

  const components = [
    new ContainerBuilder()
      .setAccentColor(0xFFE741)
      .addTextDisplayComponents(
        new TextDisplayBuilder().setContent("# **Semi-Automatic Sniper Rifle** - Legendary**")
      )
      .addMediaGalleryComponents(
        new MediaGalleryBuilder().addItems(
          new MediaGalleryItemBuilder().setURL(
            'https://cdn.discordapp.com/attachments/1233225714258677781/1380441457353166909/glow.png?ex=6845de0a&is=68448c8a&hm=95eab0c2a93c5ad9dcc4da4fa6f848a5bbe8f508438272cef2a710cec004d1fe&'
          )
        )
      )
      .addActionRowComponents(
        new ActionRowBuilder().addComponents(
          new StringSelectMenuBuilder()
            .setCustomId('ae10aeb8d2b94be6a0431b91cb67d21d')
            .addOptions(
              new SelectMenuOptionBuilder().setLabel('None').setValue('72b52ae0991b479abe533ae7e459eef5').setEmoji({ name: '❌' }),
              new SelectMenuOptionBuilder().setLabel('Common').setValue('35f2b0e514f04660931cd352a8e3de3e').setEmoji({ name: '⚪' }),
              new SelectMenuOptionBuilder().setLabel('Uncommon').setValue('e8f8d101849c4393cab6cf28484b079b').setEmoji({ name: '🟢' }),
              new SelectMenuOptionBuilder().setLabel('Rare').setValue('654cc29392cb4424bbfa9478f5971772').setEmoji({ name: '🔵' }),
              new SelectMenuOptionBuilder().setLabel('Epic').setValue('cc3ba9781ff843929ce9b72283fef452').setEmoji({ name: '🟣' }),
              new SelectMenuOptionBuilder().setLabel('Legendary').setValue('104e9aba500d4270d6d621f41409f628').setEmoji({ name: '🟠' }),
              new SelectMenuOptionBuilder().setLabel('Mythic').setValue('ea429e6cccb84f69cd384dd175a0de3b').setEmoji({ name: '🟡' }),
              new SelectMenuOptionBuilder().setLabel('Exotic').setValue('e40c73f16e8c4383cafa1ce37e7666cc').setEmoji({ name: '🔵' })
            )
        )
      )
  ];

  const channel = await client.channels.fetch(CHANNEL_ID);
  await channel.send({ components });
});

client.login(TOKEN);
rose tangle

not that package

unique shoal

All good - you should be able to import basically all of those from discord.js, but with ContainerBuilder instead of ComponentBuilder

rose tangle

you're missing the IsComponentsV2 flag

dawn dagger

even with this script i tried using djs (i tried this before that other one) i got an api error

sharp ginkgoBOT

dtypes v10: MessageFlags - IsComponentsV2
read more

unique shoal

That send line doesnt look correct though, you'd need to set the IsComponentsV2 message flag

rose tangle

in general it's a better idea to ask/search here instead of using unsupported packages

and if you tried unsupported packages you should ask their support, or ask here but with your djs code

dawn dagger
rose tangle
dawn dagger

yeah idk im not a good discord dev im just trynna learn ty tho

unique shoal

The sample code in our accouncement should have it

dawn dagger

Is SelectMenuOptionBuilder depracted

rose tangle

yes

should use StringSelectMenuOptionBuilder

torn orchid

can someone give me the doc to make your bot go invisible, idle, dnd, online etc

sharp ginkgoBOT

typealias PresenceStatus discord.js@14.19.3
The status of this presence:* online * - user is online idle * - user is AFK offline * - user is offline or invisible *dnd * - user is in Do Not Disturb

dawn dagger
rose tangle
wet hull

Is there a rate limit for bot to edit a permissions for a channel? I have a category and I want the bot to edit almost every channel (VC) (around 20 channels) permissions, my bot is verified, is there a way to check how frequent I should have my intervals as well as check if I got rate limited?

rose tangle

does each channel have its own different set of permissions?

if they're equal you could just use a category and sync the channels

wet hull

yes each one is different

its for a temp voice thing, where you can block, hide, etc... members with a bot

torn orchid
rose tangle

yeah that's not how === works

and even then you'll also have to actually define Dnd, Idle

torn orchid
rose tangle

yep but you then modified that code, I assume to include Dnd and Idle as well

but that's not how equality (===) works

torn orchid

oh alr

rose tangle

Foo == Bar, Baz does not check if Foo equals Bar or Baz

it's mostly invalid syntax

but it's not there because it's being passed as arguments to .filter

torn orchid

how would i fix it?

rose tangle

but you don't have a Dnd or Idle variables, hence, error

rose tangle
sharp ginkgoBOT

mdn Logical OR (|​|)
The logical OR (|​|) (logical disjunction) operator for a set of operands is true if and only if one or more of its operands is true. It is typically used with boolean (logical) values. When it is, it returns a Boolean value. However, the |​| operator actually returns the value of one of the specified operands, so if this operator is used with non-Boolean values, it will return a non-Boolean value.

torn orchid
rose tangle

that's a basic js issue, I'd recommend you brush up js essentials, there's some resources on #resources

rose tangle
inland pawn

when a client fetches a guild, are members with a specific role cached by default or do we also need to fetch the role?

vital barn
stable sun

I don’t think members are included when fetching a guild

That’s only provided in the guild create event, which only runs when logging in before ready and when the bot is added to a guild

sharp ginkgoBOT

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

vital barn

also this isn't a discord.js issue so this isn't the right place to post this

fathom kettle

how can i edit button label after interaction..

topaz bluff

by editing the message the button is part of

fathom kettle

lets try

polar sun

Maybe dumb question but can a bot forward a message?

sharp ginkgoBOT
polar sun

💜

rigid crest

Is this a known issue? Or intentional? #unknown when linking channel and roles in a message (on desktop it shows as channels and roles and is clickable but on mobile it’s unknown)

west parrot
rigid crest

Is there another way to get the channels and roles to be both linked on mobile and desktop without one being unknown or?

clear garnet

🤷 Just Discord client behavior

rigid crest

Oh

west parrot

yuh

steel trail
rose tangle

nope

hot fjord

can ephemeral messages not be edited?

pearl venture

via interaction.editReply

sharp ginkgoBOT

node Convenience methods
All of these take a <Buffer>, <TypedArray>, <DataView>, <ArrayBuffer>, or string as the first argument, an optional second argument to supply options to the zlib classes and will call the supplied callback with callback(error, result).Every method has a *Sync counterpart, which accept the same arguments, but without a callback.

steel trail
hot fjord

is there a way to have hidden values in a message for my bot to read

pearl venture

not through discord but if you just use a variable you can set the message id as the key and store whatever you want as the value

cosmic glacier

every time I use a button my log spits out this whole mess of a list, does anyone know what that is? I can't seem to find any kind of console.log that would result in this anywhere in my code brown_think

rose tangle

looks like a console.log(Events)

cosmic glacier
verbal iris

Hello,
Am I at risk of directly calling GET https://discord.com/api/v9/users/608985661319413760 ?
And would I be at risk of spamming the API and getting banned if I call the API on guildMemberUpdate to check if the user has a specific guild tag or not to grant/remove a role on the server?

snow onyx

no, if the api doesnt like what you are doing you would just get ratelimited

@verbal iris

steel trail
icy hazel

Is there a way to have per-server slash commands?
like my bot is in three servers and I want to make some unique commands for each server.

steel trail

Yes, deploy them to the guild route instead of as global commands

sharp ginkgoBOT
verbal iris
verbal iris
steel trail

Yes. Ratelimits exist for GET too... but if you used client.rest to make the requests djs would take care of those for you

steel trail
verbal iris
verbal iris
steel trail

"You" as in your discord? Because that's the API version the app Discord still uses. v10 is only used by bots atm

verbal iris

Ohh ok
Yes I was talking about my user, I checked the payload to see what API I should use for my bot

Thanks

crimson gale

no

kindred sparrow

How can I use the bot to import my discord channels and role.

kindred sparrow
crimson gale

one of them is a yes/no question, one is not

kindred sparrow

Oh okay.

crimson gale

lol

what's your mission with that?

  • asks questions
  • gets no immediate answer
  • tries to post slurs
  • annoyed that we automod that
  • leaves
    10/10 interaction
dense jackal

reply with a button to the modal submit interaction, reply with a modal to the button interaction

waxen night

Hi! I have a problem with the new components v2 and I don't know why I get an error

My code:

import {
  Client,
  ContainerBuilder,
  Message,
  MessageFlags,
  SectionBuilder,
  SeparatorBuilder,
  TextDisplayBuilder,
  ThumbnailBuilder,
} from 'discord.js';

export const command: Command = {
  run: async (_client: Client<true>, message: Message) => {
    const characterPic = new ThumbnailBuilder().setURL(
      'https://i.pinimg.com/736x/e7/92/47/e7924777722fb9cb09259fa34a5e9ff5.jpg',
    );
    const descripion = new TextDisplayBuilder().setContent(
      `# ${'Yoichi Isagi'}\n` + `**Général: \`76\`**\n` + `**Position: \`Attaquant\`**\n`,
    );
    const statistics = new TextDisplayBuilder().setContent(
      `\`\`\`Rythme: ${'78%'}\nDribbling: ${'78%'}\nTir: ${'78%'}\nDéfense: ${'78%'}\nPasse: ${'78%'}\nPhysique: ${'78%'}\`\`\``,
    );

    const upSection = new SectionBuilder();
    upSection.addTextDisplayComponents(descripion);
    upSection.setThumbnailAccessory(characterPic);

    const midSection = new SectionBuilder();
    midSection.addTextDisplayComponents(statistics);

    const container = new ContainerBuilder();
    container.addSectionComponents(upSection);
    container.addSeparatorComponents(new SeparatorBuilder());
    container.addSectionComponents(midSection);
    container.addSeparatorComponents(new SeparatorBuilder());

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

The error i got:

C:\Users\Matis\Documents\code\inDev\ts-project-template\node_modules\.pnpm\@sapphire+shapeshift@4.0.0\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:1965
    return Result.err(new CombinedError(errors, this.validatorOptions));
                      ^

CombinedError: Received one or more errors
    at _UnionValidator.handle (C:\Users\Matis\Documents\code\inDev\ts-project-template\node_modules\.pnpm\@sapphire+shapeshift@4.0.0\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:1965:23)
    at _UnionValidator.parse (C:\Users\Matis\Documents\code\inDev\ts-project-template\node_modules\.pnpm\@sapphire+shapeshift@4.0.0\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:972:90)
    at SectionBuilder.toJSON (C:\Users\Matis\Documents\code\inDev\ts-project-template\node_modules\.pnpm\@discordjs+builders@1.11.2\node_modules\@discordjs\builders\dist\index.js:2169:37)
    at C:\Users\Matis\Documents\code\inDev\ts-project-template\node_modules\.pnpm\@discordjs+builders@1.11.2\node_modules\@discordjs\builders\dist\index.js:1870:64
    at Array.map (<anonymous>)
    at ContainerBuilder.toJSON (C:\Users\Matis\Documents\code\inDev\ts-project-template\node_modules\.pnpm\@discordjs+builders@1.11.2\node_modules\@discordjs\builders\dist\index.js:1870:35)
    at C:\Users\Matis\Documents\code\inDev\ts-project-template\node_modules\.pnpm\discord.js@14.19.3\node_modules\discord.js\src\structures\MessagePayload.js:151:46
    at Array.map (<anonymous>)
    at MessagePayload.resolveBody (C:\Users\Matis\Documents\code\inDev\ts-project-template\node_modules\.pnpm\discord.js@14.19.3\node_modules\discord.js\src\structures\MessagePayload.js:150:49)
    at TextChannel.send (C:\Users\Matis\Documents\code\inDev\ts-project-template\node_modules\.pnpm\discord.js@14.19.3\node_modules\discord.js\src\structures\interfaces\TextBasedChannel.js:189:32) {
  errors: [
    ExpectedValidationError: Expected
...
loud quartz

is the ... at the bottom added by you here?

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

loud quartz

because you cut off the actually useful part

loud quartz

your section doesn't have an accessory

waxen night
loud quartz

yes

if you don't need another thumbnail or button, simply use text display component instead of a section

waxen night

oh okk I didn't knew it, thank you very much!

icy hazel

I'm following a tutorial and the code isn't working for me unlike in the video.
The error I'm getting is TypeError: Cannot read properties of undefined (reading 'commands')

I'm using v 14

pearl venture

my guess is that the guild object is undefined | Guild

so you can probably just add if (!guild) return; above where you use guild

icy hazel

oh right

waxen night

Hi! Is there a way to reduce an image size in a mediaGalery? for exemple I want the image to fit the size of the selectMenu of the component, to make the component smaller laterally

Here is the code: https://pastebin.com/M7kWcfT7

icy hazel
pearl venture

actually that might have been the issue to start with I just realised that the error you sent happened while running and not compiling

where are you getting the guild IDs from?

pearl venture
icy hazel
pearl venture

guild IDs are strings not ints in discord.js

icy hazel

oh

now it works thx!

dense jackal
agile nest

can container have more than one action row or not

pearl venture

yeah I think so

steel trail

As many as you can fit within the total 40 components limit

rapid tendon

Hello, I wanted to know if it was possible to remove a specific role from many members quickly and without having to delete it and then recreate it ^^

polar karma

Nope

vital vortex

In v14, are we able to preselect things in a channel select when the menu is created?

pearl venture

yeah

sharp ginkgoBOT
vital vortex

Amazing. Thank you!

unique mountain

with components v2 - how do u add a sticker inside of a component thinkLul

topaz bluff

I don't believe you can as a sticker is a message of it's own

unique mountain

ah that makes sense

pearl venture

you might be able to get the image of a sticker and put that in a media gallery similar to how you can get the image of emojis

steel trail

Unless the sticker is a Lottie

wary coral
pearl roost

i was trying to edit te response embed with response.editReply inside the collector, but it seems wrong. It say that response.editReply is not a function, any solution?

rugged shore

Hello, anyone has a list of free or cheap host for a little utility bot which will be used on like 2-3 servers please?

sharp ginkgoBOT
wary coral

@pearl roost assumimining your with in 15 mins ues <interaction>#editrely

or if you are using a button interaction as the triger <buttonInteraction>#update

pearl roost

im using button so i think yea

sharp ginkgoBOT

method ButtonInteraction#update() discord.js@14.19.3
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);

wary coral

here is the button doc

pearl roost

great thanks!

do i need withResponse here?

vital barn
tardy sable

if user shares no servers with the bot, can the user still interact with any buttons that the bot sent in dm?

vital barn
pearl roost

alright

wait why i still get the error?

wary coral

update is not on the response but the button interaction

sharp ginkgoBOT

guide Message Components: Component interactions - Awaiting components
read more

wary coral

see the guide for awaiting message components

zenith violet
loud quartz
pliant forge

How can i add an image next to textdisplaycomponents?

i tried

        const exampleContainer = new ContainerBuilder()
            .setAccentColor(0x0099FF)
            .addTextDisplayComponents(textDisplay => textDisplay.setContent('Bu bir test mesajıdır. Aşağıda sistemlerimizin tamamını görüyorsunuz. Onların altında bulunan menüden direkt olarak o sistemin menüsüne ulaşabilirsiniz.'))
            .setThumbnailAccessory((thumbnail) => thumbnail.setDescription('alt text displaying on the image').setURL(client.user.avatarURL({ dynamic: false })))            .addActionRowComponents(actionRow => actionRow.setComponents(new UserSelectMenuBuilder().setCustomId('qweqweqw').setPlaceholder('Şimdilik üye seçim menüsü sonra değişecek')))
            .addSeparatorComponents((separator) => separator,)
            .addTextDisplayComponents(textDisplay => textDisplay.setContent('Bu bir test mesajıdır. Aşağıda başka bir temanın komutlarının tamamını görüyorsunuz. Onların altında bulunan menüden direkt olarak o komutun menüsüne ulaşabilirsiniz.'))
            .addActionRowComponents(actionRow => actionRow.setComponents(new UserSelectMenuBuilder().setCustomId('qweqweqw123').setPlaceholder('Şimdilik üye seçim menüsü sonra değişecek')))

error: js [EVENT] Slash command error [DATA] TypeError: (intermediate value).setAccentColor(...).addTextDisplayComponents(...).setThumbnailAccessory is not a function

bleak owl

.setThumbnailAccessory doesn't exist

pliant forge

what should i use instead

bleak owl

nvm it does im sorry

steel trail

It does, but only on SectionBuilder

bleak owl

for a section builder tho

you would use a mediagallery

steel trail

Put a section in your container, put your textdisplay and the thumbnail in that section

pliant forge

but how can i? So sorry im new for it

steel trail

What part do you need help with?

pliant forge
            .addSectionComponents(new SectionBuilder()
                .addTextDisplayComponents(textDisplay => textDisplay.setContent('Bu bir test mesajıdır. Aşağıda sistemlerimizin tamamını görüyorsunuz. Onların altında bulunan menüden direkt olarak o sistemin menüsüne ulaşabilirsiniz.'))
                .setThumbnailAccessory((thumbnail) => thumbnail.setDescription('alt text displaying on the image').setURL(client.user.avatarURL({ dynamic: false })))
                .addActionRowComponents(actionRow => actionRow.setComponents(new UserSelectMenuBuilder().setCustomId('qweqweqw').setPlaceholder('Şimdilik üye seçim menüsü sonra değişecek')))
            )```

i tried it but it says 
```js
[EVENT] Slash command error [DATA] TypeError: (intermediate value).addTextDisplayComponents(...).setThumbnailAccessory(...).addActionRowComponents is not a function```
verbal cave

await interaction.message.edit();
Does it no longer work to leave selected menus empty?

steel trail
pliant forge

yes but lemme try again

code: ```js
module.exports = {
data: new SlashCommandBuilder()
.setName('help')
.setNameLocalizations({ 'en-US': 'help', 'tr': 'yardım' })
.setDescription('The help menu for easiest ussage.')
.setDescriptionLocalizations({
'en-US': 'the help menu for easiest ussage.',
'tr': 'En kolay kullanım için yardım menüsü.'
}),

async execute(interaction) {

    const exampleContainer = new ContainerBuilder()
        .setAccentColor(0x0099FF)
        .addSectionComponents(new SectionBuilder()
            .addTextDisplayComponents(textDisplay => textDisplay.setContent('Bu bir test mesajıdır. Aşağıda sistemlerimizin tamamını görüyorsunuz. Onların altında bulunan menüden direkt olarak o sistemin menüsüne ulaşabilirsiniz.'))
            .setThumbnailAccessory((thumbnail) => thumbnail.setURL(client.user.avatarURL({ dynamic: false })))
            .addActionRowComponents(actionRow => actionRow.setComponents(new UserSelectMenuBuilder().setCustomId('qweqweqw').setPlaceholder('Şimdilik üye seçim menüsü sonra değişecek')))
        )
        .addSeparatorComponents((separator) => separator,)
        .addTextDisplayComponents(textDisplay => textDisplay.setContent('Bu bir test mesajıdır. Aşağıda başka bir temanın komutlarının tamamını görüyorsunuz. Onların altında bulunan menüden direkt olarak o komutun menüsüne ulaşabilirsiniz.'))
        .addActionRowComponents(actionRow => actionRow.setComponents(new UserSelectMenuBuilder().setCustomId('qweqweqw123').setPlaceholder('Şimdilik üye seçim menüsü sonra değişecek')))




    await interaction.editReply({
        components: [exampleContainer],
        flags: MessageFlags.IsComponentsV2,
    })
}

};```

error: js [EVENT] Slash command error [DATA] TypeError: (intermediate value).addTextDisplayComponents(...).setThumbnailAccessory(...).addActionRowComponents is not a function

bleak owl

the dynamic option doesn't exist anymore

steel trail
pliant forge
verbal cave
steel trail
pliant forge

oh then thats the error. We put it in the section

yeah its working now tysmm

rose tangle
sharp ginkgoBOT

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

plush veldt

Hello can someone tell me what does this option do in replying message?

allowedMentions: {parse: ["roles"]}

It disables mentioning any roles or only enables mentioning roles?

polar karma

Only roles would be mentioned, no users

pliant forge

in here, can i use the textdisplay like embed fields?

Like channel :blank::blank::blank::blank::blank::blank: blockedchannels
value value

plush veldt
dense jackal

you will have to wait until discord adds some sort of table or grid component first

pliant forge
sharp ginkgoBOT
vast nymph
loud plinth

Do you know if subcommands can have subcommands, and if so, is there any limitation?

bleak owl

you can have sub command groups

which can have subcommands

loud plinth

The max depth is of 3?

Or we can go deeper?

plush veldt
vast nymph

the default value will be getting overridden, so you would have to pass it manually

steel trail
steel trail
loud plinth
plush veldt
copper crystal

guys how can i use like this embed ?

wary coral
torn orchid

how do i make it where if i mention a role in a embed it doesnt ping when it sends

bleak owl

it won’t ping regardless

steel trail

That already is the case. If you're talking about components on the other hand...

sharp ginkgoBOT
snow fractal

How can some of the big bots such as Dyno send out so many DMs in a short period of time without being rate limited?

zenith violet

big bots have separate ratelimits

and thats not really a djs question

pliant forge
                const sections = await Promise.all(adminData.adminAction.map(async (action, i) => {
                    let memberName = 'NON';
                    if (action.member) {
                        try {
                            const memberUser = await client.users.fetch(action.admin);
                            memberName = memberUser.username || memberName;
                        } catch {
                            // Hata durumunda adminName değişmez
                        }

                        const unixTimestamp = Math.floor(Number(action.timestamp) / 1000);
                        return new SectionBuilder().addTextDisplayComponents(text =>
                            text.setContent(
                                `\`[Case ${i + 1}]\` ➔ **${action.action}**\n` +
                                `∟ Member: ${memberName}\n` +
                                `∟ Date: <t:${unixTimestamp}:f>\n`
                            )
                        )
                    }
                }))

                const container = new ContainerBuilder()
                    .setAccentColor(0x0099FF)
                    .addSectionComponents(sections);

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

My data is alright but when i try call that command it keeps say Bot is thinking...

what can be wrong

rose tangle

sections can't have only text displays

they also need a thumbnail

and if you're not getting any errors it sounds like you're silently ignoring them

pliant forge

i tried it but command even can't be executed im on it

rose tangle

you mean 'x' is not logged?

pliant forge

yes

rose tangle

then you must be deferring somewhere before actually calling the command

start from there and see where the execution stops

pliant forge

yes i do and i use editReply in my every command but im watching the steps rn

shall i deploy my commands again

rose tangle

that's unrelated

pliant forge

my all other commands are working currently

oh yeah my bad i didn't put slashcommandbuilder in {} wow

bleak owl

you would’ve gotten a syntax error though no?

pliant forge

yeah but i didn't and when i put it worked idk why

bleak owl

probably because of how your command handling functions

pliant forge
rose tangle

yes

pliant forge

a button or a thumbnail right

rose tangle

otherwise the section is quite useless

rose tangle
rose tangle
pliant forge

oh thank you

pliant forge
rose tangle

yes

sharp ginkgoBOT

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

rose tangle

hence why it's setXAccessory, unlike other addXComponents

pliant forge

i want them next to each other

rose tangle

just put them in the same row

pliant forge

right...
Sorry im eepy i need to stop trying new things. Tysm all ur patient and help

quasi trench

When sharding, is it okay to refresh the slash commands on every single shard, or should I find a way to only let it refresh once

loud quartz

there's no reason to refresh them at all

unless you changed some metadata for the commands

in that case, if they are global, well.. they are global. doesn't matter which shard did it, especially as we here recommend running that from a separate script that doesn't even login to the gateway, doing it with /rest subpackage directly

soft stag

anyone have the link of that webpage that helps you build discord embeds and outputs the code (with component v2) ?

zinc wyvern

I was looking at an open source bot and noticed that when I send a link in chat, it downloads the contents of the webpage and sends them back as an attachment. This is not the intended behaviour of that bot.

I looked through the code and in my opinion it simplifies to sending this (imagine discord.com is the link i sent) using discord.js:

{
  files: [ "https://discord.com" ]
}

Could I ask what exactly the behaviour is when putting a list of strings in files? Could it be by any chance downloading the webpage and sending it, or could this piece of code not be the cause of the behaviour?

loud quartz

where is that object located

zinc wyvern
    await client.channels.cache.get(config.discord.channels.guildChatChannel).send({
      files: [image]
    });
loud quartz

doing this does make d.js download the file from the link to attach it to that message

it's literally called "chat bridge"

zinc wyvern
loud quartz

yeah

zinc wyvern

It's meant to take messages from a minecraft server and send them to discord and viceversa (minecraft chats don't have images)

loud quartz

but they have links

zinc wyvern

Downloading links i send in the bridge is not intended behaviour, especially when unrestricted, that's what i meant

loud quartz

that might be to images

zinc wyvern

yea but in that case the bot is just supposed to send the link and if it's an image discord will render it safely using its own servers

loud quartz

tbh you're fine just putting the links into the content directly

and nothing else

if it happens to be an image, discord itself will fetch it

zinc wyvern

yea I don't know why the creator of the chat bridge made it like this, thank you for the help

rose tangle

what do you intend it to do if not fetch the link and upload the result?

zinc wyvern
rose tangle what do you intend it to do if not fetch the link and upload the result?

I intended none of this to happen, I host an instance of the bot for a guild playing on a minecraft server (Hypixel) and noticed this behaviour (which is extremely dangerous in my opinion).
After seeing it, I investigated the code and found this piece of code, which I thought might be the cause, but I wasn't sure if that's how discord.js handles it, so I asked here.
Thanks to you guys I now know it was indeed the culprit of this behaviour and will update my fork of the chat bridge to not have it

Sorry if I was unclear

(the bot is not coded by me, it's open source. I only have a fork with tiny changes)

rose tangle

ah, yeah I didn't read correctly the parts about it wasn't yours, my bad

yep, it sounds a weird design choice if that's not what they expected it to do

or maybe a not fully informed one

loud quartz

tbf, the code was edited 4 months ago

zinc wyvern
loud quartz

to upload to discord via d.js, instead of uploading to imgur

zinc wyvern

true, though I don't know why they would want to upload to imgur either

loud quartz

the code for imgur is still there, just commented out

zinc wyvern

but right now it doesn't check if it's an image or not, it works for anything starting with https apparently

loud quartz

this is kinda where it gets tricky though

url doesn't have to end with an extension to lead to an image

(ignoring things like query params here, of course)

zinc wyvern
loud quartz url doesn't have to end with an extension to lead to an image

Yea that's true, though in general I would really rather not it fetching any link sent by random people from my private vps (images or not). Especially for a bot meant to be ran by people who don't know how to code and don't realize the potential problems (some hosting services have networking limits for example)

trail fog

https://pastebin.com/tr28sFvX im trying to mimic my old biomes command with components v2, and I keep getting this error:

TypeError: Cannot read properties of undefined (reading 'Image')
    at createContainer (/home/container/commands/Pets/setbiome.js:90:31)
    at Object.execute (/home/container/commands/Pets/setbiome.js:104:16)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Client.<anonymous> (/home/container/index.js:159:5)```
radiant epoch

Is it possible to get emoji by it is name directly on developer portal?

radiant epoch

I kinda don’t want to reveal full emoji details in the public repo

trail fog
radiant epoch
trail fog ?

Yeah but just using name cause copying :name: is not what i would like to do (this is what i am doing right now)

crimson gale

why?

radiant epoch
trail fog
bleak owl
radiant epoch
trail fog
trail fog
bleak owl as far as i know, MediaType does not exist

https://pastebin.com/fwkE77xQ

TypeError: (intermediate value).addItems is not a function
at createContainer (/home/container/commands/Pets/setbiome.js:83:73)
at Object.execute (/home/container/commands/Pets/setbiome.js:92:16)
at processTicksAndRejections (node:internal/process/task_queues:95:5)
at async Client.<anonymous> (/home/container/index.js:159:5)

im tweakin

bleak owl

im not sure why you're passing an array

sharp ginkgoBOT
bleak owl

check this

sharp ginkgoBOT
trail fog

thank you

bleak owl

well okay it takes a RestOrArray, but as a spread array param so its not needed

rose tangle

should be MediaGalleryBuilder

btw you can also use the callback way

container.addSectionComponents((sectionBuilder) => sectionBuilder
  .addTextDisplayComponents((textDisplayBuilder) => ...)
  .addMediaGalleryComponents((mediaGalleryBuilder) => ...)
  // etc
);

though now that I double read that, yeah that's entirely wrong

tardy sable

are there docs yet for the new role color styles?

rose tangle

you don't add a media gallery to a section

you add it to the container

sections only support text displays and a button/thumbnail accessory

topaz bluff
tardy sable

alright thanks

hot fjord

Is here any way i can make this look better

The dropdown looks ugly cuz its bigger than everything

bleak owl

design is really up to you

hot fjord

can i even modify the width of that stuff tho?

hallow mesa

Other than like, adding a label. But some components might roll over to the next row on some devices, so it's ultimately not in your control

hot fjord

Rip

safe karma

Won’t help with the buttons overflow, but still

hot fjord
safe karma

V2 components

wary coral
safe karma

It will reduce the size of the select menu and might all line up a little better

hot fjord

ty

bleak owl

it won’t reduce the menu size at all

it’s how discord renders it

safe karma

I was more thinking it will fit it to the size of the container rather than edge of screen

halcyon bison
safe karma

Interesting. Either way, it will still probably look neater imo

distant bramble

are containers supported by djs now?

uncut quest

yes

distant bramble

discord.js@14.19.3?

clear garnet
pallid sparrow

how to create a poll in discord.js? cant find the builder for it, or any guides about it.

sharp ginkgoBOT
twilit shale

Anyone know of a simple template for a private dashboard?

sharp ginkgoBOT
steel trail

Most image and video file types

unique shoal

Have youy checked your intents

steel trail

Those events don't need any intent.

Are you sure an entitlement actually gets updated/created/deleted? Did you try fetching entitlements and comparing with what you had before? Was your bot running at the point in time you did the action causing an entitlement to change

novel mauve

in my command handler i realized i have execute(interaction, client) and use that client option instead of using interaction.client in the various command codes. is this a bad practice? is there any downside?

steel trail
novel mauve

outside of the order, would it have any meaningful impact on performance?

steel trail

not really

novel mauve

okay

thanks

steel trail

not to my knowledge

soft lance

I guess ChatInputCommandInteraction.id is the same as message.id since there is no ChatInputCommandInteraction.message.id?

steel trail

[...] and video file types

media gallery does allow it

steel trail

it is an id, but not of a message

slim prairie

how do u send messages to threads

  try {
    await thread.send(`**${message.author.username}:** ${message.content}`);
  } catch(err) {
    console.log(err)
  }
TypeError: Cannot read properties of undefined (reading 'send')
    at Client.<anonymous> (C:\Users\NotAdmin Kewl\Desktop\cODING\DiscordBot\Moderator Certification Python\index.js:90:18)
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
slim prairie
soft lance
pearl venture
slim prairie
pearl venture
slim prairie
pearl venture

I honestly can't remember I haven't worked with threads in a long time but try fetching all the channels then on each channel do channel.threads or something

sharp ginkgoBOT
steel trail
slim prairie
steel trail

either way you never should have to guild.channels.fetch(), instead use the cache

steel trail

guild.channels.cache.find(...)

your fetch there clears the cache and replaces it with whatever you fetched... which might not include the threads you're looking fornvm, the cache doesn't get cleared, only appended to

slim prairie
steel trail

the same as for your current find() call

slim prairie

Ok

slim prairie
steel trail the same as for your current find() call

i used caches and now theres no error and .send its defined but nothing sends into the thread

client.on('messageCreate', async (message) => {
  if (message.channel.parentId != 1379506056610447420) return;
  
  const guild = message.guild;
  const split = message.channel.name.split("-");

  let thread;

  try {
    thread = guild.channels.cache.find(
      ch => ch.isThread() && ch.name === `ticket-log-${split[1]}`
    )

    if (!thread) {
      console.log(`Thread not found for name: ticket-log-${split[1]}`);
      return;
    }
  } catch (err) {
    console.log("Error fetching channels:", err);
    return;
  }

  try {
    await thread.send(`**${message.author.username}:** ${message.content}`);
  } catch (err) {
    console.log("Error sending message to thread:", err);
  }
})
steel trail

your initial id check there is wrong btw, needs to be a string

sharp ginkgoBOT
  • Discord ids follow the snowflake format: learn more
  • Discord ids must be represented as strings as they are larger than Number.MAX_SAFE_INTEGER, the largest integer that can be represented in JavaScript
- client.guilds.cache.get(123456789012345678)
+ client.guilds.cache.get("123456789012345678")
slim prairie
steel trail

second line in your codeblock

slim prairie
steel trail

that's your fourth line

slim prairie
steel trail

no, that's your third line

slim prairie
steel trail

client.on('messageCreate', async (message) => { this is your first line. not sure if trolling or counting is really that hard

slim prairie
steel trail
slim prairie
steel trail

not nothing. that issue is fixed. it won't affect your sending issue. it was just an additional note

slim prairie
sharp ginkgoBOT

If you aren't getting any errors, try to place console.log checkpoints throughout your code to find out where execution stops.

  • Once you do, log relevant values and if-conditions
  • More sophisticated debugging methods are breakpoints and runtime inspections: learn more
slim prairie
steel trail

and gets filled on login/ready again, yes

it would error in your code there if the thread wasn't in cache. that's not your issue

slim prairie
steel trail it would error in your code there if the thread wasn't in cache. that's not your...
We are in the correct category
Fetching thread
Thread got found! ticket-log-873505666357157888
Sending message to thread!
client.on('messageCreate', async (message) => {
  if (message.channel.parentId != "1379506056610447420") { return; }
  
  console.log("We are in the correct category");

  const guild = message.guild;
  const split = message.channel.name.split("-");

  let thread;

  try {
    console.log("Fetching thread");
    thread = guild.channels.cache.find(
      ch => ch.isThread() && ch.name === `ticket-log-${split[1]}`
    )

    if (!thread) {
      console.log(`Thread not found for name: ticket-log-${split[1]}`);
      return;
    }

    console.log("Thread got found! " + thread.name);
  } catch (err) {
    console.log("Error fetching channels:", err);
    return;
  }

  try {
    console.log("Sending message to thread!");
    await thread.send(`**${message.author.username}:** ${message.content}`);
  } catch (err) {
    console.log("Error sending message to thread:", err);
  }
})
coarse remnant

would i be correct in assuming that this error was the product of me setting the presence before the client is actually ready?
Possible AsyncEventEmitter memory leak detected. 11 ready listeners added to WebSocketShard. Use emitter.setMaxListeners() to increase the limit.

oh there is another one too but instead of ready its on error

steel trail
slim prairie
steel trail

so not a code issue but a logic issue. having more than one thread by that name

slim prairie
modest surge

This bot seems to be a discord user how they do this

steel trail

report them, they violate TOS

sharp ginkgoBOT
modest surge

how they do that btw by getting the token in inspectelement?

steel trail

stop, we won't help with TOS violations

modest surge

ok

coarse remnant
steel trail yes

what about this?
Possible AsyncEventEmitter memory leak detected. 11 error listeners added to WebSocketShard. Use emitter.setMaxListeners() to increase the limit.

distant bramble

Error: ```js
Error: Received one or more errors
at _UnionValidator.handle (/home/container/projects/Diva-new/node_modules/@sapphire/shapeshift/dist/cjs/index.cjs:1965:23)
at _UnionValidator.parse (/home/container/projects/Diva-new/node_modules/@sapphire/shapeshift/dist/cjs/index.cjs:972:90)
at SectionBuilder.toJSON (/home/container/projects/Diva-new/node_modules/@discordjs/builders/dist/index.js:2169:37)
at /home/container/projects/Diva-new/node_modules/@discordjs/builders/dist/index.js:1870:64
at Array.map (<anonymous>)
at ContainerBuilder.toJSON (/home/container/projects/Diva-new/node_modules/@discordjs/builders/dist/index.js:1870:35)
at /home/container/projects/Diva-new/node_modules/discord.js/src/structures/MessagePayload.js:151:46
at Array.map (<anonymous>)
at MessagePayload.resolveBody (/home/container/projects/Diva-new/node_modules/discord.js/src/structures/MessagePayload.js:150:49)
at GuildMessageManager.edit (/home/container/projects/Diva-new/node_modules/discord.js/src/managers/MessageManager.js:186:8)

Command:

import { Command, type Context, type Divamusic } from '../../structures/index';
import {
  ContainerBuilder,
  MessageFlags,
  SectionBuilder,
  SeparatorBuilder,
  TextDisplayBuilder,
} from 'discord.js';

public async run(client: Divamusic, ctx: Context): Promise<any> {
    const msg = await ctx.sendDeferMessage('Pinging...');

    const latency = msg.createdTimestamp - ctx.createdTimestamp;
    const apiLatency = Math.round(client.ws.ping);

    const pingInfo = new TextDisplayBuilder().setContent(
      `# Bot Latency\n` +
      `**Websocket Latency:** \`${apiLatency}ms\`\n` +
      `**Message Latency:** \`${latency}ms\`\n` +
      `**Uptime:** <t:${Math.floor(Number(client.readyTimestamp) / 1000)}:R>`
    );

    const upSection = new SectionBuilder();
    upSection.addTextDisplayComponents(pingInfo);

    const container = new ContainerBuilder();
    container.addSectionComponents(upSection);
    container.addSeparatorComponents(new SeparatorBuilder());

    return ctx.editMessage({
      //content: ' ',
      components: [container],
      flags: MessageFlags.IsComponentsV2
    });
  }
steel trail
coarse remnant
safe karma
slim prairie
client.on('threadUpdate', async(oldThread, newThread) => {
  if (oldThread.channel.id != "1379777763421982732") { return; }

  newThread.setLocked(false);
  newThread.send({
    content: `**Automatically opened thread since it got archived!**`
  });
})

why wont this wrk

TypeError: Cannot read properties of undefined (reading 'id')
at Client.<anonymous> (C:\Users\NotAdmin Kewl\Desktop\cODING\DiscordBot\Moderator Certification Python\index.js:167:25)
at Client.emit (node:events:519:28)
at module.exports [as THREAD_UPDATE] (C:\Users\NotAdmin Kewl\Desktop\cODING\DiscordBot\Moderator Certification Python\node_modules\discord.js\src\client\websocket\handlers\THREAD_UPDATE.js:14:12)
at WebSocketManager.handlePacket (C:\Users\NotAdmin Kewl\Desktop\cODING\DiscordBot\Moderator Certification Python\node_modules\discord.js\src\client\websocket\WebSocketManager.js:351:31)
at WebSocketManager.<anonymous> (C:\Users\NotAdmin Kewl\Desktop\cODING\DiscordBot\Moderator Certification Python\node_modules\discord.js\src\client\websocket\WebSocketManager.js:235:12)
at WebSocketManager.emit (C:\Users\NotAdmin Kewl\Desktop\cODING\DiscordBot\Moderator Certification Python\node_modules@vladfrangu\async_event_emitter\dist\index.cjs:287:31)
at WebSocketShard.<anonymous> (C:\Users\NotAdmin Kewl\Desktop\cODING\DiscordBot\Moderator Certification Python\node_modules@discordjs\ws\dist\index.js:1190:51)
at WebSocketShard.emit (C:\Users\NotAdmin Kewl\Desktop\cODING\DiscordBot\Moderator Certification Python\node_modules@vladfrangu\async_event_emitter\dist\index.cjs:287:31)
at WebSocketShard.onMessage (C:\Users\NotAdmin Kewl\Desktop\cODING\DiscordBot\Moderator Certification Python\node_modules@discordjs\ws\dist\index.js:1007:14)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)

worthy drift

use oldThread.id and not oldThread.channel.id

slim prairie

fixed issue

worthy drift

what are you even trying to archive in the first place?

slim prairie
jagged shell

Hello guys, it's possible to put a local image in the footer url icon on embed?

steel trail
sharp ginkgoBOT

tag suggestion for @jagged shell:
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]
});
lucid dock

Hey, not sure if this is the correct channel but I'm using components v2 for the first time (/builders but not d.js) and I'm really confused. I'm trying to execute a webhook with this body:

{
    flags: MessageFlags.IsComponentsV2,
    components: [
        ...array.map((d, i) =>
            new ContainerBuilder()
                .setAccentColor(colors[i % colors.length])
                .addTextDisplayComponents(
                    new TextDisplayBuilder().setContent(
                        `## [${i} - Title](https://example.com)`,
                    ),
                    ...d.array.map((v) =>
                        new TextDisplayBuilder().setContent(
                            `### Text ${time(resolveDate(v.dt_com), TimestampStyles.ShortTime)}\n**${v.perc}%** (${v.vot_t})\n-# Text ${v.enti_p}/${v.enti_t}`,
                        ),
                    ),
                    new TextDisplayBuilder().setContent(
                        `-# Text: ${d.enti}`,
                    ),
                )
                .toJSON(),
        ),
    ],
} satisfies RESTPatchAPIWebhookWithTokenJSONBody &
    RESTPostAPIWebhookWithTokenJSONBody

However, I get a Cannot send an empty message. I tried to log the body and I get this:

{
    "flags": 32768,
    "components": [
        {
            "type": 17,
            "accent_color": 7391279,
            "components": [
                {
                    "type": 10,
                    "content": "## [0 - Text](https://example.com)"
                },
                {
                    "type": 10,
                    "content": "### Text <t:1749376800:t>\n**7,41%** (3.408.482)\n-# Text 61.591/61.591"
                },
                // ...
            ]
        },
        // ...
    ]
}

Which seems correct to me. If I add a random content I get that content is not available when using components v2. What am I doing wrong?

steel trail

What method do you feed that to and how? The payload looks fine, I assume you don't pass it correctly

And/or show the full error you receive

somber dome

hello

Is it forbidden for me to do

const tokens = [
"...","...","..." ];
for(let bot of tokens) {
client.login(bot);
}
```?
lucid dock
thin reef

if you have a valid use case

abstract flint

TypeError: message.createMessageComponentCollector is not a function
at Object.execute (file:///D:/Data/Coding/Repositories/airmalpi-occ/commands/public/pianifica.js:116:39)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async Object.execute (file:///D:/Data/Coding/Repositories/airmalpi-occ/events/interactionCreate.js:12:17)

I'm gettings this. I think it's something about the latest version, I've never got this error before

somber dome
worthy drift
somber dome

For Premuim Bots System

Is there a better way?

steel trail
steel trail
lucid dock
polar karma
worthy drift

Could you show some code for context?

thick hatch
bleak owl

do not compare yourself to other bot's that do not comply with the TOS

polar karma
thick hatch
polar karma

doesn't matter how you store the data, it's the act of requesting it that's against the TOS

thick hatch

Ahh that’s make sense

icy hazel

I have problem with interaction.reply not sending embed

it works with normal messages but not embeds

pls help

pearl venture

unknown integration means that your discord commands cache is out of sync with the server (most likely means that your command has been deleted)
if you restart your discord the command will probably disappear to confirm this (unless you have re-registered it)

icy hazel

I have

after refreshing discord it works

pearl venture

so it's fixed now?

icy hazel

Yes, but I'm confused

pearl venture

basically whenever you run commands discord doesn't fetch them from the server
it does it periodically and stores them in a cache to reduce load on the server
a command had been deleted on the server but your cache was outdated so when you ran the command discord couldn't find the command id on their server cuz it was deleted

icy hazel

ah

abstract flint
steel trail

message is not a Message here but an InteractionCallbackResponse

sharp ginkgoBOT
abstract flint
steel trail

It did, before you added withResponse: true, that changes the return type

abstract flint
steel trail

You're asking the wrong questions: just use response.resource.message instead (naming the result of the reply() call response instead to not get confused)

drifting dirge

whats this button in the embed?
did i miss some api update

steel trail
drifting dirge

is it's interaction handled the same way as a regular button?

steel trail

Yes, it's the same kind of button. The container is the thing that's different

drifting dirge

tag the docs please

somber dome
polar karma

Dunno why you need multiple for the same code, but as answered earlier, they should be in separate processes

sharp ginkgoBOT

documentation suggestion for @drifting dirge:
class ContainerBuilder discord.js@14.19.3
A builder that creates API-compatible JSON data for a container.

torn orchid

https://sourceb.in/2VvtkJbxP9
Error: Invalid Form body: ];

  await interaction.editReply({
  ^^^
    components,
      flags: MessageFlags.IsComponentsV2,
    });
},
zenith violet

what is the full error

torn orchid
zenith violet what is the full error

Invalid Form Body
content[MESSAGE_CANNOT_USE_LEGACY_FIELDS_WITH_COMPONENTS_V2]: The 'content' field cannot be used when using MessageFlags.IS_COMPONENTS_V2

pearl venture

you're trying to enable components v2 on a message that has contnet

zenith violet

when using editReply

torn orchid

oh alr

pearl venture

to show text on components v2 you need to use TextDisplayBuilder

ivory valve

Hello, there's a way to "set" the size of the text to move the part in the "void" (where there's no image/select menu) to a new line?

pearl venture

there's no way to specify the text size but you can put -# at the start of the line to make it a bit smaller

-# like this

ivory valve

Not really responsive xd

pearl venture

I mean you can use \n to make a new line but that isn't very responsive either
honestly your best bet is to either split it into 2 sentences and put them on new lines or just use -#

ivory valve

We were used an empty image before to set the size to the select menu like that for a perfect match, trying to do that in V2 but not really possible :(

pearl venture

actually I mean you might be able to use a section with a thumbnail accessory of a blank image

sharp ginkgoBOT

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

ivory valve

I will try thanks :)
section on top?

pearl venture

just put the text inside of a section

with an accessory of a thumbnail
it makes a similar style to a description with thumbnail in legacy embeda

ivory valve

Maybe it's just not possible

pearl venture

yeah it's slightly better but not much

toxic moat

what arguments are emitted by listeners at the 'ignore' event. the argument seems to be ...* but theres no further documentation on it

sharp ginkgoBOT
shadow pier

What are the different ways I can create containers?

loud quartz

with a raw object or with the builder

shadow pier
loud quartz

that's just gonna be pain

you can just pick one and use it

no need to alternate

analog oak

How to check if i can dm a user or not?

loud quartz

by sending them a dm

analog oak
loud quartz

no

analog oak

Thanks blobguns

pearl hazel

is it ok to put 2 type of component collector together ?
msg.createMessageComponentCollector({filter:filter, componentType: ComponentType.Button | ComponentType.StringSelect, time: 30000 })

cause it's only collect select menu and not collect any button

steel trail

Well, 2 | 3 is indeed 3. so that's not achieving what you want. Instead don't pass componentType at all and it'll collect all components on that message

pearl hazel

oh right ty

torn orchid

what are some recommended hosting services?

topaz bluff
bleak owl
sudden estuary
module.exports = {
    data: new SlashCommandBuilder()
        .setName('switch-category')
        .setDescription('Change the service category of the current ticket')
        .addStringOption(option =>
            option.setName('category')
                .setDescription('Select the new category for this ticket')
                .setRequired(true)
                .setAutocomplete(true)
        ),
    
    async autocomplete(interaction) {
        const focusedValue = interaction.options.getFocused();
        const choices = ['Popular Topics: Threads', 'Sharding: Getting started', 'Library: Voice Connections', 'Interactions: Replying to slash commands', 'Popular Topics: Embed preview'];
        const filtered = choices.filter(choice => choice.startsWith(focusedValue));
        await interaction.respond(
            filtered.map(choice => ({ name: choice, value: choice })),
        );
    },

I'm confused, why do I not get any autocomplete options with this?

bleak owl

did you register your command with autocomplete or add it after it was registered?

zenith violet

(and are you actually calling that autocomplete function)

sudden estuary
sudden estuary
sharp ginkgoBOT
topaz bluff

Yes, an AutocompleteInteraction is another type of interaction you have to handle

sudden estuary

ahaha yes thank you so much Heart have a blessed day

weak jay

what does this mean??

DiscordAPIError[50001]: Missing Access

zenith violet
pearl venture

guild commands or global commands?

zenith violet
weak jay

how do i remove a default authorisation link?

steel trail

DEV portal, your bot, Installation tab

weak jay
zenith violet showing your code would be really useful instead of just guessing
const { REST, Routes } = require('discord.js');
require('dotenv').config();

const commands = [
    {
        name: 'pingity',
        description: 'help'
    },
];

const rest = new REST().setToken(process.env.TOKEN);

(async () => {
    try {
        console.log(`Started refreshing application (/) commands.`);

        const data = await rest.put(
            Routes.applicationGuildCommands('1339327441784537098', '1327585829979422741'),
            { body: commands },
        );

        console.log(`Successfully reloaded application (/) commands.`);
    } catch (error) {
        console.error(error);
    }
})();

DiscordAPIError[50001]: Missing Access

what????

steel trail

Your bot doesn't seem to be in that guild

Check the ids

Both clientID and guildId as well as that the clientID matches the token

pearl venture

also if the IDs are correct then check if the bot was added to the guild with the applications.commands scope

cunning gazelle

else if (interaction.options.getSubcommand() === 'information' && interaction.commandName === "driver") {
When I run on replit works fine all good beautiful but when I run it on railway it doesn't detect command being run

Declared as this name: 'driver', description: 'Get the information of a NDC driver', options: [ { name: 'information', description: 'Get the information of a NDC driver', type: 1, options: [ { name: 'user', description: 'The user to get the information of', type: 6, required: false } ] },

oh hold up ima a fucking idiot

steel trail
pearl venture

oh I didn't know that
cool

alpine moat

is it possible to set a clan tag for a bot

bleak owl

no

wet hull

how can I use member var and edit permissions of a channel to set ViewChannel to netural state (not enabled nor disabled)?

I tried this:

await voiceChannel.permissionOverwrites.edit(member, {
                  allow: allow.bitfield,
                  deny: deny.bitfield,
                });

And it didnt work

unique shoal

Thats not the format that edit takes

dull hearth

i dont know how to fix this and need help with my account manager because after 45 minutes of having accounts launched all accounts but the first 4 launched will completely close. i recorded it and can send the moment it happens if it will help.

unique shoal

What does this have to do with discord.js?

are you running multiple bots?

dull hearth

roblox account manager is git hub and i looked up github discord and this popped up and it said to ask for help in this server if needed. sorry if im in the wrong spot. where could i get help?

dull hearth
unique shoal

You are in the wrong spot

This is a support server for discord.js bots

I have no idea where you can get support for Roblox account manager

dull hearth

ok, thanks and sorry.

unique shoal

No worries

smoky hedge

uhm

who can tell me how to get discord.js

@unique shoal

nova wasp

npm install discord.js

unique shoal
smoky hedge

where do i type that

unique shoal

Can you please read the server rules and not ping mods for no reason, thanks

smoky hedge

sure

unique shoal

If you don't know where to type that you aren't going to be able to use it

What do you think discord.js is?

smoky hedge

uhm i cant type npm init it does nto work

unique shoal

Why

smoky hedge

look let me take a ss

unique shoal

Suggest you follow the guide. It has a section on getting ready to use discord.js

smoky hedge

it says i need to use npm init

unique shoal

That error literally includes a link on how to fix it

smoky hedge

let me try

onyx wadi

I'm new to keyv, so I'll need help while I'm reading this doc. I won't require much help, just some simple answers, so I know if I'm heading in the right direction or not

polar karma
onyx wadi

not a discord.js v14 kinda question, i'm assuming 😭

smoky hedge

how to run my command

i saw i need to put npm app.js but it does not work

@unique shoal dont get mad but can you tell me how to run cmd i have discord.js now

unique shoal

No

nova wasp
smoky hedge

so how do i see if my cmds are working

nova wasp

Have you written the code for the commands?

smoky hedge

uhm

i have another question

rose tangle

which is?

smoky hedge

how to run scripts in my discord srver

rose tangle

what do you mean by "run scripts"

and how is it related to discord.js

smoky hedge

idk but i saw some people script to get memebers and i want to know how

topaz bluff
rose tangle
smoky hedge

maybe i saw people use discord.js to do that so i got in

rose tangle

discord.js is a library to code bots

like dyno, mee6, etc

smoky hedge

can you tell me how to make a bot

bleak owl

we already did

sharp ginkgoBOT

guide Home: Introduction - Before you begin...
read more

subtle girder
turbid igloo

there's no defferedReply for button interaction?

sharp ginkgoBOT
stable sun

There is. It’s just not an option of interaction.reply method

clear oar

eh. if i want my bot to reply to a message ephemerally
but simply message.reply({content: "hehe", ephemeral: true}) doesnt work

stable sun

You can’t. It’s exclusive to interactions

clear oar
unique shoal

Yes

It wont happen, since it would allow for endless unmoderatable spam

pearl roost

do collector can recieve modal submit?

snow onyx

either use <Interaction>#awaitModalSubmit() or use an InteractionCollector

sharp ginkgoBOT
slim prairie
  const embeds = message.embeds

    if (!embeds) {
      await thread.send(**${message.author.username}:** ${message.content});
    } else {
      await thread.send({
        embeds: [embeds],
        content: **${message.author.username}:** ${message.content}
      })
    }

what did i do wrong

    at handleErrors (C:\Users\NotAdmin Kewl\Desktop\cODING\DiscordBot\Moderator Certification Python\node_modules\@discordjs\rest\dist\index.js:748:13)
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
    at async SequentialHandler.runRequest (C:\Users\NotAdmin Kewl\Desktop\cODING\DiscordBot\Moderator Certification Python\node_modules\@discordjs\rest\dist\index.js:1149:23)
    at async SequentialHandler.queueRequest (C:\Users\NotAdmin Kewl\Desktop\cODING\DiscordBot\Moderator Certification Python\node_modules\@discordjs\rest\dist\index.js:980:14)
    at async _REST.request (C:\Users\NotAdmin Kewl\Desktop\cODING\DiscordBot\Moderator Certification Python\node_modules\@discordjs\rest\dist\index.js:1293:22)
    at async ThreadChannel.send (C:\Users\NotAdmin Kewl\Desktop\cODING\DiscordBot\Moderator Certification Python\node_modules\discord.js\src\structures\interfaces\TextBasedChannel.js:195:15)
    at async Client.<anonymous> (C:\Users\NotAdmin Kewl\Desktop\cODING\DiscordBot\Moderator Certification Python\index.js:298:7) {
crimson gale

message.embeds is a collection an array, which you wrap in another array

slim prairie
crimson gale

if you have any idea about what your code does, yes

correction, message.embeds is an array of embeds*

embeds: takes an array of embeds
you are now passing an array of array of embeds

clear oar

what's the ModerateMembers perm? i randomly find it in autocomplete along with Kick..., Ban..., Mute...

red coral

For timing out members

clear oar
red coral

Maybe? Idk though, I just know moderate members is for timing out people

snow onyx

MuteMembers is for muting voice

red coral

Ah ofc

snow onyx

ModerateMembers is for timing out, which prevents users from sending messages, joining voice channels etc.

snow onyx

Allows for timing out users to prevent them from sending or reacting to messages in chat and threads, and from speaking in voice and stage channels

clear oar
snow onyx

discord developer documentation

slim prairie
worthy drift

use embeds: embeds in short terms

slim prairie
unique shoal

Stop it

Yes, you are expected to know what an array is if you're writing Javascript

crimson gale

"you are passing an array of an array, where an array is expected" - 50hr long explanation - ok buddy

unique shoal

Its a very basic concept and we should not be expected to handhold you through that level of knowledge

slim prairie
unique shoal

Great! Glad you're here, but you do need a decent understanding of the language its written in to use it

We have great tutorials and guides on Javascript in #resources

slim prairie

i dont need tutorials i know the basics just for not knowing this one array thing bruh

clear oar

btw what's the << thing? like 1 << 3 is 0x8

sharp ginkgoBOT

mdn Left shift (<<)
The left shift (<<) operator returns a number or BigInt whose binary representation is the first operand shifted by the specified number of bits to the left. Excess bits shifted off to the left are discarded, and zero bits are shifted in from the right.

unique shoal
unique shoal

Oh but it is mmLol

clear oar
crimson gale

-ev (0b00100 << 2).toString(2) // @clear oar maybe that makes it clear

hoary nebulaBOT
crimson gale

0b lets you write binary literals .toString(2) displays a number as binary string

slim prairie
worthy drift

Did it too, trust me its way harder than just doing a course

clear oar
unique shoal

Do it however you like, just dont act entitled to volunteers handing you explanations

slim prairie
worthy drift

There are videos on youtube explaining basics in just hours

unique shoal

Lets move on

I dont care how people decide to learn, as long as it isn't burdening those who provide support here

clear oar
snow onyx

upside down guy lul

sudden grove

how to use emitter.setMaxListeners()

clear oar

how to get the author of interaction (e.g who clicked on button)

sharp ginkgoBOT
clear oar
sudden grove

i was wondering how to properly use it

clear oar
sudden grove
clear oar `emitter.setMaxListeners(int)` iirc

this seems to be it:

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

  const emitter = new EventEmitter();
  emitter.setMaxListeners(20); // Set the limit for this specific emitter to 20.

  const { commandName } = interaction;
// other code
clear oar

btw im bored with slash commands and still using conventional commands. is it good to create a button with id button-id-<user id> and when interactionCreate only match <user id> can use button

crimson gale

depends on how you want your buttons to work
there's use cases for either behavior
oh, you mean for validation - no, see monbrey

unique shoal

Why not just match on interaction.user

clear oar
sudden grove

i looked it up on google and thought

unique shoal

Why are you attempting to do this?

clear oar
unique shoal

The convention is slash commands

sudden grove
unique shoal Why are you attempting to do this?

06-10 10:27:02 (node:44) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 12 interactionCreate listeners added to [Client]. MaxListeners is 11. Use emitter.setMaxListeners() to increase limit

clear oar
unique shoal

So, constructing a new event listener that has no listeners attached and changing the max of that wont help

The real issue is - why do you have 12 interactionCreate listeners

clear oar
unique shoal

it does not

sudden grove

and i like chaos

unique shoal

Technically yes you can
Except now it throws warnings

Can yes, should, no

clear oar
sudden grove because i can

this is a bad reason; you should sacrify some pretty factors in your code, and merge all of them into one function, it's better

sudden grove
crimson gale

good on you, but what are you doing here then?

clear oar
sudden grove

was asking about event emitter resetting max to higher limit

sudden grove

soooo i ruined it all-

unique shoal

Yeah its fine

Client is an event emitter

Its a valid question

sudden grove

sorry my bad

clear oar
unique shoal Client is an event emitter

irrelated, but event emitter, api-er, represents a client, manage stuff, read messages, all in a client class is kinda impressive to me, not even speaking about how much more you can do with events
on top of all, every action will get a promise. rlly good

clear oar
let button = new ButtonBuilder()
    .setCustomId("ephemeral-" + m.author.id)
    .setStyle("Success")
    .setLabel("Click me.")
let actrow = new ActionRowBuilder().addComponents(button)
m.reply({components: [actrow], embeds: [{
    title: "Click on me to show an ephemeral message. (Disappears after 30 seconds)",
    color: Colors.Green
}]}).then(_ => {
    setTimeout(() => {
        _.delete().catch(e => {})
        m.delete().catch(e => {})
    }, 30000)
    m.createMessageComponentCollector({
        componentType: ComponentType.Button,
        time: 30,
        filter: (inter) => {inter.user.id == m.author.id}
    }).on("collect", i => {
        i.reply({content: success("Success!", "This is an emerpheral message. None except you can see it", i.user), flags: MessageFlags.Ephemeral})
    }).on("ignore", i => {console.log("Ignored " + i.user.id + " 's interaction to " + i.type + " " + i.customId)}).once("end", (is) => {console.log("Collected " + is.size)})
})

expected behavior

When user clicks the "Click me" it should responds with an ephemeral. The message and collectors last 30 seconds

results

Not doing anything, simply "Interaction failed"

more info

fatal(), success() is my preset embed building utility. treat them like an embed
fatal/success(string title, string description, discord.User author)

whoops wait i think it's because im setting time for the timer to 30ms than 30 seconds

night kindle

can my bot create guild invites?

clear oar
night kindle
sharp ginkgoBOT

documentation suggestion for @night kindle:
method TextChannel#createInvite() discord.js@14.19.3
Creates an invite to this guild channel.


// Create an invite to a channel
channel.createInvite()
  .then(invite => console.log(`Created an invite with a code of ${invite.code}`))
  .catch(console.error);

clear oar
night kindle
rich terrace

Can I add a role using the role ID?
For example:

const role = process.env.VERIFIED_ROLE_ID
await member.roles.add(role)
snow onyx

yes

rich terrace
remote cargo

can i add multiple MessageFlags?
like both Ephemeral & IsComponentsV2

sharp ginkgoBOT

The ephemeral option when replying to an interaction will be removed in v15

- {..., ephemeral: true}
+ {..., flags: MessageFlags.Ephemeral}
``` Read [here](<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_OR>) on how to specify multiple flags
zenith violet

yes

remote cargo
leaden shuttle

is there a djs function to escape all formatting?

sharp ginkgoBOT

function escapeMarkdown discord.js@14.19.3
Escapes any Discord-flavored markdown in a string.

leaden shuttle

ty

sharp ginkgoBOT
worthy drift

Use time: 30000

remote cargo

can ComponentsV2 can be sent through DMs

clear oar
worthy drift

Since m is a different message than _ the bot message

clear oar
worthy drift

Any errors that could help?

snow onyx

also please show your updated code

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.

clear oar

m is Message btw

snow onyx

componentType in the filter should be Button, not ActionRow

snow onyx

nothing and

change it

clear oar
snow onyx change it

oh it seems to ignore my interaction, but it shows type 3 while ComponentType.Button is 2

snow onyx

3 is select menu

you are not showing a select menu in the code

but interaction.type is also not a component type

its the type of the interaction, in this case MessageComponent

clear oar

done, i removed the filter and let it do when receive interaction instead
ig it's the filter not doing its job properly

clear oar
modest surge

nvm

modest surge

can someone help i followed the docs correctly

sharp ginkgoBOT
topaz bluff

In TypeScript, you define the generic on an ActionRowBuilder

new ActionRowBuilder<TextInputBuilder>()

modest surge
misty pilot

So in componentv2 am I able to make an image go on the left?

steel trail

No

mellow frigate

does MessageCreate event also trigger for thread messages?

wary coral

yes

steel trail

Yes, if the bot can see that channel/thread

topaz bluff

Do you need the Channel partial for threads, or are they cached like normal guild channels?

steel trail

Active threads the bot can see are cached. Channel partial is only needed for DMChannel

topaz bluff

👍

That's what I thought, just couldn't remember 100%

cunning gazelle

Guys how do I log users who have a specific role? I did it but nothing came out in the array

steel trail

You'd need to have all members cached for that to work. So fetch all members once in your code, the it'd be accurate for the runtime of your bot

solid summit

djs is very good guys. i love it

remote cargo

can ComponentV2 be sent through DMs?

steel trail

Yes

remote cargo

thanks

woven schooner

Hey guys, a bot cannot forward the message object it gets from listening to onMessageDelete right?

keen phoenix

For the life of me I cant get the attachment url after sending this

  embeds: [responseEmbed],
  files: [attachment],
  components: [row.toJSON()],
  withResponse: true,
});```

wherever I find "attachments" its always emtpy collection

clear garnet

Can you show how you're actually trying to get the URL? You've only showed how you're sending the reply

clear garnet
woven schooner

Oh well Reflexiom So when trying to log this message (moderation purpose) I should post the snapshot Reflexiom

clear garnet

Not sure what snapshot you'd be talking about here

woven schooner
clear garnet

That's for if the message itself is a forward of another message

The only data you'd be getting from that event is the channel ID, message ID, and any other data that d.js already has cached about that message (taking into account Partials)

So what you see is what you get. You can't take anymore API actions on the message after the event emits because as far as Discord is aware, it's now gone

signal ibex

Is it possible to send components V2 via WebhookClient? While my mesage sends fine via a normal message, in a webhook it results in 'Cannot send an empty message', code: 50006. I'm using query ?with_components=true on the end of my webhook URL, for some reason however when the error comes back the query has changed to ?wait=true Am I doing something wrong or is there a known issue in discord.js atm?

vital barn
signal ibex

it fails the very first time I send the webhook

Here is a quick example of my code, as I say, results in 'Cannot send an empty message', code: 50006:

const { WebhookClient, MessageFlags, TextDisplayBuilder } = require('discord.js');
const templatesWebhook = new WebhookClient ({ url: 'https://discord.com/api/v10/webhooks/_redacted_/_redacted_?with_components=true'});
const textComponent = new TextDisplayBuilder().setContent( 'test message webhook');
await templatesWebhook.send({flags: MessageFlags.IsComponentsV2, components: [textComponent]});```

I can only assume that for some reason the 'with_components' query is not applying

zenith violet

you need to pass withComponents: true in the send call

i dont know if those query params are passed on

hallow mesa

Discord.js parses out the webhook ID and token from the URL. That query is getting discarded

signal ibex

right, ill try shortly what you suggest @zenith violet

perfect, many thanks, that did the trick.

brave nimbus

if the server has access to it and unlocked, can a bot set a role gradient or not yet avaible through api?

zenith violet

it has not been documented by discord yet

keen phoenix

is it because its a reply or something, I tried so many different ways the attachments are just never there

steel yacht

Hi,
Is there any easy loop-free way to apply permissions to a role in all channels of a guild ?
Thanks

hallow mesa

No, but depending on what you're trying to do there might be a better way anyways

steel yacht

The objective is :

overwrites all channel-specific permissions

hallow mesa

Why? Because if you're trying to grant a permission, do it in role permissions. If you're trying to mute, consider using timeouts. If you're granting permissions to a user, can it be done by giving them a role instead?

hallow mesa
steel yacht

I'm trying to grant a permission to a user via a role yes, and assigning the permissions only globally might not be enough because of pre-existing channel-specific permission overwrites.

hallow mesa

Okay. That's still pretty vague so to go back to your original question: No, there is not a way to bulk change permission overwrites in multiple channels. So if you're insistent that's the best solution, then you would need to loop through them (which seems like a pretty spammy workflow)

steel yacht

That's still pretty vague
I have been asked to build a bot that temporarily gives a permission to a user.
That permission should apply server-wide.
If that permission was explicitly denied to at-everyone or any role that the user has in specific channels, then the bot must override that.
if you're insistent that's the best solution
I'm not, that's only what I was suggested to do, and I'm precisely here to ask if there's anything better.

hallow mesa

I mean personally I'd just give them a role and assume any conflicting overwrites were intentional. If not, have the admins refactor server permissions as a one-time thing so that it can be done without mucking up overwrites every time you need to temporarily give perms. But that's not really a discord.js thing

steel yacht

Well, unfortunately I've been explicitly asked to deal with that this way. 😭
Thanks anyway

hallow mesa

Unfortunate. Sometimes it is that way. Best of luck!

steel yacht

Thank you, have a good day !