#djs-help-v14

78874 messages · Page 6 of 79

noble turtle

But can I get it to not show the URL in the message, just embed the image?

If I send the URL in the message content

steel trail

If you only send the URL it should do that, yes

noble turtle

There's other content in the message

steel trail

Then what you ask for needs (an actual embed or) components v2 with a media gallery having one single item

frosty epoch
//admins
let serversAdmin = servers[0].filter(guild => (guild.permissions & 0x8) === 0x8);

for 'manage server'

(guild.permissions & 0x20) === 0x20

20 or 32?

crimson gale

nkoSigh just use the enum

sharp ginkgoBOT
fading girder

Got a TS question, Property 'cache' does not exist on type 'GuildMemberRoleManager | string[]'. Property 'cache' does not exist on type 'string[]'.

This is what I am trying to do,

            interaction.member.roles.cache.some((role: any) =>
                [interviewData.createRole].includes(role.id)```
steel trail

Use interaction.inCachedGuild() typeguard before trying that

And definitely remove that any there

fading girder

Got it

coarse storm

Why does client.application.commands doesn't include any commands? I know for certain that I have application commands

steel trail

Because you didn’t fetch them. Cache only has what the API sent at least once

coarse storm
steel trail

Doing that once would cause your cache to have all commands for the lifetime of the process, yes

coarse storm
steel trail
coarse storm
steel trail

Show your code

The part where you fetch and the part that makes you say it didn’t fetch anything

plush portal
throw new DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData);
            ^

DiscordAPIError[50035]: Invalid Form Body
options[0].required[APPLICATION_COMMAND_REQUIRED_INVALID]: Required cannot be configured for this type of option
name: "art",
                description: "يُمكنك كتابة اسم بطاقة معينة للحصول على صورتها فقط.",
                options: [
                    {
                        name: "name",
                        description: "name of the card",
                        type: 2,
                        required: true
                    }
                ]

is there any problem with this ?

i wanna the option be required, must i remove the type or i can use another type ?

steel trail

That’s a subcommand. Subcommands are always required

plush portal

so i don't need to use type ?

steel trail

You probably meant another type. Which is why using the ApplicationCommandOptionType enum would be better

steel trail
plush portal

no, i wanna it required,
this will do great?

type: ApplicationCommandOptionType.String,
                        required: true
steel trail

Yes, now the type is correct

plush portal

well as i create a command, i can't see it in the App

steel trail

Then you didn’t deploy it yet

plush portal
steel trail

Reload your discord if you did deploy

plush portal

thanks, It shows now

merry hamlet

uh...?

sharp ginkgoBOT

We highly recommend you extend the Client structure properly instead of just attaching custom properties like .commands to the regular discord.js Client instance.

merry hamlet
unique shoal

The tutorial isnt written in TypeScript though

merry hamlet

true
but wouldnt Client still be the same type of object?

steel trail

Yes. But JavaScript won‘t complain about it

merry hamlet

thats crazy 💀
okay
thanks

unique shoal

Well... yeah. Its an object with no commands property

So in a loosely typed language (JS) you can just add it by pretending it exists

In TypeScript you cant

rose kite
merry hamlet uh...?

You are also directly mutating a client property that should be immutable. I would recommend you don’t do this.

plush portal
art command used by Astax
TypeError: Cannot read properties of undefined (reading 'description')
```?
zenith violet

Whatever you're trying to call .description on is undefined

minor maple
rose kite
steel trail Huh? No they don’t

Yeah if you check the screenshot that are creating client and then directly mutating the property commands which is an anti pattern in typescript.

zenith violet

and recommended by the guide to do so

in typescript it requires casting or augumenting

elder fable

How can i turn <Message>.components into their respective builders i thought i could do the following but this expect a API type instead of TopLevelComponent

const components = i.message.components.map(c => new ContainerBuilder(c));
steel trail

c.toJSON() to get that API type

elder fable
steel trail

Well, you‘d need to cast or better type check that it‘s a container before

You indeed can’t make a ContainerBuilder from non-container data

elder fable

isn't every component in message.components a container?
I thought it was looking at the docs but idk still very new to how it works now i haven't touched discord.js in a little while

steel trail

No. A container is the embed-like border. You don’t have to put stuff in a container

elder fable

Oh wait yea i see it now my bad

I just have to make a parser for the builders with in TopLevelComponent idk why i thought what i did 🤣

sharp ginkgoBOT
steel trail

Just use that

steel trail
elder fable

Yea i saw it but trying to make sense of it my brain isn't braining

steel trail

.map(createComponentBuilder) should do the trick

merry hamlet

is there a way to make commands dev only? or do i just individually filter out any command via user id or create a wrapper class for it?

keen salmon

when are docs being updated for containers

steel trail

They already are?

elder fable

maybe you've got the wrong version selected but they are uptodate for me

keen salmon
steel trail
elder fable
steel trail
elder fable

was stuck on it for 5min and ofc i figured it out as i sent that i forgot to remove the [] i had around it before cuz i used to just pick and update 1 component instead of parse all of them FACEPALM

updatedComponents.map(c => c.toJSON())
compact forge

how to get such command list in bio?

polar karma

added automatically by discord when your bot is verified

steel trail
elder fable
steel trail
elder fable
vital raven
elder fable

ah yea that explains it cuz it just assumes all components

rigid hinge

how can i fetch user by username?

leaden shuttle
import { REST } from "discord.js";
import { API } from "@discordjs/core";

const rest = new REST({ version: "10" }).setToken(token);
const api = new API(rest);

Property '#private' in type 'REST' refers to a different member that cannot be accessed from within type 'REST'.
only happens after updating to the new djs

rose tangle

why do you have djs and /core?

rose tangle
sharp ginkgoBOT
thin cosmos

Can I have a ChannelSelection dropdown in a modal yet?

dense jackal

no

thin cosmos

Okay thank you

main mason

is there documentation for in what cases guild.channels.fetch() errors?

leaden shuttle
rose tangle

but you only need /rest for that

and that's inside djs

leaden shuttle

how can i do it with djs? API isnt exported from djs

sharp ginkgoBOT

guide Creating Your Bot: Registering slash commands - Resulting code
read more

rose tangle

you don't need API

leaden shuttle

huh? im not registering slash cmds

rose tangle

there's an example there on how to use rest

the example happens to be for registering commands

but it applies to any endpoint

halcyon bison

I mean if you want to use API that's perfectly fine, particularly if you're in some environment where you need to use @discordjs/core/http-only
however in that case, you should just import REST from @discordjs/rest (which /core depends on)
there wouldn't be a need to install discord.js at all in that case

leaden shuttle

const botUser = await rest.get("/users/@me").catch(() => null);

the type for botUser is unknown when i use the djs module

leaden shuttle

i just want to make single api requests to other bots

leaden shuttle
rose tangle

const foo: T

halcyon bison
leaden shuttle i use djs too

then the question is, why do you need to make these requests without logging into the gateway if you're logged into the gateway?

leaden shuttle
leaden shuttle
rose tangle

type assert then

leaden shuttle
rose tangle

I think it should be APIUser

leaden shuttle

ahh ok

rose tangle
leaden shuttle
rose tangle

doesn't make it less against the tos

leaden shuttle

i understand, ty

main mason

what is the maximum value that .setMaxValue() can be passed? (for a SlashCommandBuilder definition of a .addIntegerOption())

sharp ginkgoBOT
split thunder

Hi, Is there a way to get the moderator who moved a member from Channel A to Channel B in a voice? I can detect when a user moves themselves to another channel, but when someone else does it, I can't fetch that information

steel trail

No

radiant epoch

Do we use .publish() to publish message?

sharp ginkgoBOT

method Message#crosspost() discord.js@14.19.1
Publishes a message in an announcement channel to all channels following it.


// Crosspost a message
if (message.channel.type === ChannelType.GuildAnnouncement) {
  message.crosspost()
    .then(() => console.log('Crossposted message'))
    .catch(console.error);
}

radiant epoch

okay

Can we set max character for slash option?

okay we can

hexed marsh

Does anyone know of a way to properly schedule repeating tasks?

Should I just use a setInterval after the bot is ready and logged in?

rose tangle

depends on your task

djs doesn't have anything for that though

hexed marsh

Okay wasn't sure if there was a task manager of sorts or not.

near siren

is there a type for Guild.toJSON() and GuildMember.toJSON()? I tried using APIGuild and APIGuildMember but then <member>.permissions isn't a thing with that typing

(im using broadcast eval so they're serialised)

near siren
stable sun
near siren

but its a GuildMember serialised, does it not return even the bitfield? only because member.roles are an array of roleIds

stable sun

D.js calculates it for you based on the roles

It represents what Discord would’ve provided

near siren

i had the assumption that djs would turn permissions into just the bitfield number as it cant parse the permissionbitfield class

so is there a difference between APIGuildMember and <GuildMember>.toJSON()
in terms of properties

because obviously <GuildMember>.toJSON() has the ability to parse the calculated permissions

steel trail

Yes

near siren

yes? to what?

worldly coyote

how to run a bot with a prefix?

worldly coyote

i don't want a / cmd bot.

steel trail
near siren
stable sun

I don’t think there’s a type for it

In the types, it’s unknown

steel trail
worldly coyote why wouldn't I?

Because it’s not worth the effort, won’t get approval by discord to work in more than 100 guilds, is way harder to implement and use, …

near siren
steel trail What’s the use case?

using broadcast eval to retrieve a member from a guild and check if they have permissions

const member = await sharder.fetchGuildMember(guild.id, userId);
if (!member?.permissions.has(PermissionFlagsBits.ManageGuild)) return res.status(403).json({ message: 'Missing Permissions' });

public async fetchGuildMember(guildId: string, userId: string): Promise<APIGuildMember | null> {
  const member = await this.manager.broadcastEval(async (shard, { guildId, userId }) => {
    try {
      return await shard.guilds.cache.get(guildId)?.members.fetch(userId);
    } catch {
      // todo
    }
  }, { context: { guildId, userId } }) as APIGuildMember[];
  return member.find(Boolean) ?? null;
}

in the process of sharding my bot, currently using the type APIGuildMember until i remembered that serialised GuildMember !== APIGuildMember so when checking member's permissions, I won't have to calculate their permission bitfield from roles

steel trail
near siren

that is probably true but I would reuse this function in other places where I need the member properties

steel trail

Sending full structures over IPC is big overhead

near siren

i need to do .toJSON() still

steel trail

No

near siren

?

steel trail

If you do the check in the eval you can use djs methods on the instance

.permissions.has(…)

near siren

i understand that but i could just do

new PermissionsBitField(member.permissions).has(...)
assuming member.permissions exists on GuildMember.toJSON()

steel trail

It does. But that adds even more overhead now

broadcastEval should transfer as little data as possible between shards for scalability

near siren

so you recommend having another helper function to check permissions specifically? what about in cases where i need the member object and to check their permissions?

i could also edit this broadcast eval function to only occur on the cluster containing this guild by parsing a cluster id

steel trail

What cases are there where you need the full member „object“ (aka the json structure you get out of it) on a shard that member isn’t on?

steel trail
near siren

it's for my website, to check if the user has permissions to do X action, and i need their member object for database, logging purposes etc and for my anti-spam system which uses their member data for a scoring system

zenith violet
rigid hinge

is there any way i can return the person who executed that command when i click the button?

snow onyx

if the interaction is cached, interaction.message.interaction.user I believe

sharp ginkgoBOT
snow onyx

ah, use that instead I guess kekw

rigid hinge

okay thanks

coral hollow

Hello!!!

Uhhhh for PM2, it says this, pm2 start your-app-name.js, and i was wondering how thats gonna work?

Is it like, the app name on discord, or the folder?

steel trail

How is that djs related? Look at pm2 docs for that

coral hollow

I dont know- it was in djs docs.

rose tangle

pm2 is a process manager

it's not related to djs itself

it manages any node process, a bot happens to be one

coral hollow

Okay. Sorry.

rose tangle

as for your question, it't most likely index.js

it's whatever your start script is

coral hollow

Okay. Thank You!!

topaz bluff

Are you responding to the interaction? Show your interactionCreate event handler

cosmic grotto

Is there a guide page for d.js components v2?

hexed marsh

Wrap it in a try-catch to find the error.

topaz bluff
hexed marsh
cosmic grotto

Is there an ETA?

topaz bluff

When it's ready

cosmic grotto

Makes sense, but ETA = estimated time

hexed marsh

ooof here we go xD

topaz bluff
cosmic grotto

Aighty

wary coral

It is not related to your error but in the replies you should use flags: MessageFlags.Ephemeral instead of ephemeral: true as the ephemeral option is deprecated

leaden shuttle

where can i view all the functionality of components v2?

red coral
covert vine

how do i deal with a ```typescript
class APIInteractionDataResolvedChannelBase

when i receive it from Interaction.options.getChannel(); ?

it doesnt have most channel attrs

weak karma

hey quick question how do i get defaultMemberPermissions to work on sub commands?

wary coral
weak karma

ok cool so if i make a command called x then all of x's sub commands are going to follow the same perms?

wary coral

yes

weak karma

can i do that with roles also?

wary coral
weak karma
wary coral

That is what I mean if a user is not permitted to use the command by default permission or override it will not be displayed to them

weak karma

ah okay so i have to write a check anyway for perms 2_tired

wary coral

I dont. If the user can use the commanded then they can use it. set the default permission for what is needed to manually preform the action. then if the server owner want a role without the perms to use it they set that in the override

weak karma
proud arrow
wary coral
covert vine
weak karma
wary coral

np, best of luck

proud arrow
covert vine so that means that object is a channel my bot cant access?

It doesn't necessarily mean that. It maybe that typescript is inferring that interaction can be in uncached guild so it is showing you that type. So you should have typeguards for that, like interaction.inCachedGuild(). But if the interaction is recieved from unchached guild, then yes you'll only get that information. Be that due to your bot not being in that guild, or not having bot scope or missing guilds intent (in this case though, you maybe able to fetch the channel if the bot is in the guild)

covert vine
proud arrow

User app

covert vine

mines not a

proud arrow

Then you should use the typeguard I said to narrow the type

sharp ginkgoBOT
covert vine

ok thanks

jolly radish
index.d.ts(631, 53): 'fetchReply' is declared here.```

Why do I get this errors on a message reply?
proud arrow

Show the full error, that is usually a suggestion not an error (also the code)

covert vine
covert vine
jolly radish
covert vine

i ended up not using that method at all

can we get the call that this appeared on too?

proud arrow
jolly radish
rancid folio

Hey y'all. I may be blind but I don't see this in the docs anywhere, but is it not possible to do message.reactions.removeAll() in a DM channel? I keep getting an error for that, so I assume the answer is yes, I just don't see it documented.

rancid folio
jolly radish Whats the error?

Pretty much what I said, it's a DiscordAPIError[50003]: Cannot execute action on a DM channel error.

I just find it extremely odd that I can't remove a bot's own reactions in a DM channel.

jolly radish
loud quartz

it's the same as with bulkDelete

even if you would pass only your bot's messages to it, it's not a valid method on a DM channel

remove your bot's user from the reaction, one by one

or consider using buttons instead

rancid folio

the reactions are just a simple validation check, so the user sends something to the bot and the bot adds a check or cross reaction just to confirm validation. there is one instance where the bot will do something like "Did you mean....?" and if you click yes, then it should switch the reaction over.

but also noted

jolly radish
loud quartz

can disable the buttons too

but at this point it's mostly stylistic decisions and opinions

rancid folio
loud quartz

disabled buttons are also functionless

rancid folio

OH i see what y'all mean now

loud quartz

for an example of a DM from a bot

it's a disabled button

rancid folio

honestly, good idea, i'll use that. thank you

proud arrow
jolly radish
proud arrow

Yeah, so message reply cant be ephemeral, hence the error. You need to narrow the type to an interaction

jolly radish
proud arrow Yeah, so message reply cant be ephemeral, hence the error. You need to narrow th...

so basically if I rewrite it to work with this types:

interface BaseTypes2048 {
  client: Client;
  embed: Embeds;
  emojis?: {
    up: string;
    down: string;
    left: string;
    right: string;
  };
  othersMessage?: string;
  notifyUpdate?: boolean;
  time?: number;
}

export type Types2048 = (
  { message: Message; interaction?: never } |
  { interaction: ChatInputCommandInteraction; message?: never }
) & BaseTypes2048;

it should remove the error

jolly radish

can messages reply be ephemerals?

wary coral
jolly radish

okay thanks

worldly coyote

hey i need help.

what's wrong here ? :
message.mentions.id.first();

halcyon bison

in future, please elaborate on what makes you think something is wrong (e.g. any errors you may be receiving)
however in this case, <MessageMentions>.id doesn't exist
were you looking for <MessageMentions>.users.firstKey() (since it's keyed by user id)?

worldly coyote
halcyon bison

I don't see how that's relevant to what I said

worldly coyote

just saying.

halcyon bison

that's great
there aren't any mentions in interactions

worldly coyote

`module.exports = {
name: "deban",
description: "déban un membre du serveur.",
async execute(message, args) {
if (!message.member.permissions.has("BanMembers")) {
return message.channel.send(
"Tu n’as pas la permission de débannir des membres."
);
}

  const user = message.mentions.users.firstKey();
  if (!user) {
    return message.channel.send("Tu dois donner l'id de l'utilisateur à débannir.");
  }

  // 🔒 Empêcher de se bannir soi-même
  if (user.id === message.author.id) {
    return message.channel.send("Tu ne peux pas te débannir toi-même.");
  }

  // 🔒 Empêcher de bannir le bot
  if (user.id === message.client.user.id) {
    return message.channel.send("Tu ne peux pas me débannir.");
  }

  // 🔒 Vérifie la hiérarchie des rôles
  if (user.roles.highest.position >= message.member.roles.highest.position) {
    return message.channel.send(
      "Tu ne peux pas débannir quelqu’un avec un rôle égal ou supérieur au tien."
    );
  }

  // 🔒 Vérifie si le bot a le droit de bannir cette personne
  if (!user.unbannable) {
    return message.channel.send(
      "Je ne peux pas débannir cet utilisateur. Il a peut-être un rôle plus haut que moi."
    );
  }

  const reason = args.slice(1).join(" ") || "pas de raison";
  try {
    await user.ban({ reason });
    message.channel.send(
      `${user.user.username} a été déban pour ${reason}`
    );
  } catch (err) {
    console.error(err);
    message.channel.send("Une erreur est survenue lors du débannissement.");
  }
},

};`

@halcyon bison

halcyon bison

I don't know what you want me to do with this

worldly coyote
halcyon bison

in future, please elaborate on what makes you think something is wrong (e.g. any errors you may be receiving)

worldly coyote

it says "give the id"

halcyon bison

ok I can't read french, but I'm going to assume that's the second if statement

worldly coyote

it is.

halcyon bison

I had assumed that when you did message.mentions.id.first();, you were looking for the id
currently, user is the id
therefore user.id is undefined since <string>.id doesn't exist
if you want the User object, you should just use <MessageMentions>.users.first()
however I notice you're also attempting to treat this user as a GuildMember, so I imagine you'll probably want <MessageMentions>.members.first() instead

worldly coyote
halcyon bison

that doesn't change what I said, no

abstract flume

i need help

zenith violet
worldly coyote
worldly coyote
abstract flume
zenith violet
worldly coyote
zenith violet

because you cannot ban a user like that

worldly coyote
loud quartz

user.unbannable

zenith violet
worldly coyote

yea?

loud quartz

where did you get that property from

zenith violet

did you write that code

i dont think so

worldly coyote
loud quartz

but like, this isn't a shooting range. writing random stuff won't really result in working code

did you see this property somewhere?

worldly coyote

yea like there is user.bannable.

zenith violet

no there isnt

a user isnt a GuildMember

worldly coyote

there is.

zenith violet

which is also one of your issues

zenith violet
worldly coyote
zenith violet

because your user was a GuildMember

not a user

worldly coyote
zenith violet

and what is user defined as here

loud quartz

please do console.log(user.constructor.name)

worldly coyote

then what should i do?

loud quartz

and show the result

zenith violet

you call it on the GuildMember first of all

worldly coyote
loud quartz

in that code

just to see the result of it

zenith violet

and you should know what code you write if it isnt ai code

your ''unban'' command just bans

worldly coyote
halcyon bison
loud quartz

any

as long as it's after you define the user

worldly coyote

doesnt show anything.

halcyon bison

though actually now that I think about it, a banned user will never be a GuildMember, so coming back to what luna said
you can't handle it that way in the first place
you will need the User or their id, and instead use <Guild>.bans.remove()

loud quartz
worldly coyote
loud quartz then you didn't put what i said in a line that runs

const user = MessageMentions.users.first();
if (!user) {
return message.channel.send("Tu dois mentionner un utilisateur à bannir.");
}

console.log(user.constructor.name)

// 🔒 Empêcher de se bannir soi-même
if (user.id === message.author.id) {
  return message.channel.send("Tu ne peux pas te bannir toi-même.");
}
zenith violet

...

loud quartz

sigh

sharp ginkgoBOT

Explaining <Class> and Class#method notation: learn more

zenith violet

you seem to be lacking basic understanding of js

worldly coyote
zenith violet

not to mention you refuse to use slash commands, which would have tackled this issue in seconds

zenith violet

you're just wasting our time by making it yourself very hard by refusing to use slash commands and not understanding what you are being told

oblique talon

what's the new "ephemeral" for interaction.reply?

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
oblique talon

thanks

worldly coyote

i asked chatgpt but im not proud i wanna understand it.

zenith violet
worldly coyote

i dont know what to search..

zenith violet

the basics of javascript

oblique talon

i can use it like

await interaction.reply({
  components: [containerRules], flags: ´[MessageFlags.IsComponentsV2, MessageFlags.Ephemeral]
    });
  }

halcyon bison

I do however see a section titled Learning JavaScript and node.js

worldly coyote

alr sry.

red coral

I swear you can also do .IsComponentsV2 | .Ephemeral ? Like use | ?

zenith violet

yes

zenith violet
worldly coyote
halcyon bison
worldly coyote

i have to read all of it?

zenith violet
worldly coyote

alr.

tribal warren

Hey!
I'm looking for ways to improve how I handle component creation and interactions. I was wondering, how do you guys manage it? Is interaction.customId the only way you use to identify which component was triggered? And if so, how do you usually generate a unique customId?

halcyon bison

this isn't really the place to ask about general conventions/standards
ultimately how you generate your custom ids is entirely up to you
but yes the customId is what you would use to identify the interacted component
and I do often recommend using a previous interaction's id as a nonce in the custom id assuming this component is being sent in response to an application command or something

fathom warren

hello i'd like to ask if it's possible to filter out users in UserSelectMenu to show only those available to select?
-# i mean, i have warnlist command and I want specific users to be shown here, so like if I have user X displayed in embed, I'd like to be able to select it from user select menu to view more details about their warn cases etc.

halcyon bison

no you cannot

fathom warren

that's sad :/

nimble obsidian
fathom warren

that's what I'm actually trying to accomplish

sharp ginkgoBOT

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

- {..., fetchReply: true}
+ {..., withResponse: true}

```This returns an [InteractionCallbackResponse](https://discord.js.org/docs/packages/discord.js/14.17.3/InteractionCallbackResponse:Class)
Use `<InteractionCallbackResponse>.resource.message` to get the message
halcyon bison

@fair prairie please use #app-commands for personal use of the bot

fair prairie
halcyon bison

no worries, just for future

fair prairie

For the devs passing by this message.

please i want to ask you about the interaction editReply and the the followUp.
my code is working perfectly and was responding normally to the interactions, but lately i noticed that he wasn't able to respond to the interaction.deferReply({withResponse: true}) no more.

i tried to debug the code and console.log every step the bot is passing by, and everything seems normal, until he reach the interaction.followUp/editReply he can't send it. even if the console mention that it does so.

btw the interaction.channel.message.send works and the interaction.reply works too.

so my question is: is that issue caused by some discord limitations or something else?

Additional: The bot is verified and it's on more than 30K servers and all the intents are enabled

unique shoal

In what way cant it be sent? Is it erroring?

fair prairie
unique shoal

It seems odd that interaction.reply works - it shouldnt work if you deferred

Are you awaiting the calls?

fair prairie

as you can see from this simple of the console.log

it does perfectly send the response

but doesn't appear to do on discord

unique shoal

Uhh, all that shows me is it being deferred

But are you saying it doesnt appear deferred on discord?

fair prairie

it's confusing i know, the interaction is perfectly deferred but the followUp/Edit doesn't happen

unique shoal

Can you show your code please

fair prairie

sure and i'm sorry if it's breaking Discord TOS in some Kind of ways 🙏🏻

i added some tests followUps to check

halcyon bison

(it is breaking tos, and we don't provide support for tos violations)

hexed marsh

It doesn't appear to be breaking any ToS if it's on 30k servers xD

halcyon bison

I'm not sure how its server count affects whether it breaks tos or not
but if you have questions about why they've allowed something their tos explicitly disallows, feel free to ask discord

fair prairie
halcyon bison (it is breaking tos, and we don't provide support for tos violations)

yes my bad. Btw i found the issue

basically the bot every time it does restart or connect take a while to connect to the discord end point i think what cause the interaction to not being working perfectly for a brief moment, but does after 2mins or so. i had to console log the time that the interaction take to fully load and everything to notice that out

i will be deleting the code from the room for TOS breaking

hexed marsh

I was thinking if you're at 30k servers, don't you HAVE to get verified past 100?

halcyon bison

breaks both youtube's and potentially spotify's tos as

  • youtube doesn't allow restreaming due to dodging ads
  • spotify doesn't have a public streaming api, so either the lib they're using breaks spotify's tos, or usually they just search for the song on youtube
    and this breaks discord's developer tos as they disallow misuse of third party apis for discord apps
    discord can and has banned bots for this (you may remember this is why rhythm disappeared in the first place)
    yes you have to be verified to go past 100
    there's several possibilities for their situation including
  • these features were added after being verified
  • discord overlooked it for some unknown reason
    but again, if you have questions about why discord has overlooked it, you should ask them
hexed marsh

Oh that makes sense, learn something new every day

rancid folio

If I'm not mistaken, containers have a limit of 10 components each. When I do something like a section which has text and a button, would the text and button each count as one component, or would only the section as a whole count?

hexed marsh

No, 5 X 5. You can have 5 Action Rows each containing 5 components. So 25 total. Someone correct me if I'm wrong but I feel like I read that in the discordjs.guide

unique shoal

5x5 buttons refers to the original components, not v2

rancid folio
rose tangle

oops didn't see monb already mentioned it

my bad

keen salmon

has djs added accent_color for containers?

unique shoal

Confused as to why you think we would have excluded one specific property while supporting all the others?

flat forum

why the ephemeral option will be removed in v15?

rose tangle

to favor how it actually works, with the flag

rose tangle
sharp ginkgoBOT
soft socket

Is there a way to see if a channel has an event going on in it other than grabbing all events and filtering for active ones in said channel?

rose tangle

doesn't look like there's a way to do the former

rancid shoal

is there any option to not have a color on an embed at all

unique shoal

yeah dont set one

rancid shoal
rose tangle

there isn't a way

only in containers

rancid shoal

hm

unique shoal

i mean you can set it to the same colour as the background

But that will only work for matching themes

rancid shoal

diff appearences on discord tho so it wont be great better than nothing

rose tangle

or move to cv2

rancid shoal
crimson thistle
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
crimson thistle

oh i thought the message flag was gonna be removed
well thanks anyways

little pebble
errant void

Could someone help me with a problem?
I can interact with slash commands in the bot chat, but if a user adds the app to his profile, he can't use it in his friend's DMS.

Is there a Gateway im Not aware of?

granite lion

do gallery items from the new components v2 api work with attachment:// urls?

rose tangle

also you should probably look into what the gateway actually is

rose tangle
errant void
rose tangle

it's unrelated to the issue

sharp ginkgoBOT
rose tangle

there, those two

primal edge

idk where to ask this, but uhh, anyone got any opinions?
you think i should leave it like this, or, add a seperator between text & button?

errant void
alpine wadi

Components v2 can only work in the slash command?

rose tangle

no, you can also send them directly

alpine wadi

In msg command?

main mason

if you run interaction.deferReply() on an interaction, and then later attempt to interaction.reply() instead of interaction.editReply(), will it error with Unknown Interaction?

rose tangle
sharp ginkgoBOT
rose tangle

huh, I selected the InteractionAlreadyReplied value

weird

well, that

rose tangle
alpine wadi
rose tangle

you can send them anywhere you make a message

alpine wadi

Fixed

rose tangle

in an interaction, in a "message command", etc

alpine wadi
rose tangle

yeah

you don't make the collector in the row, you make it in the message

or the channel

alpine wadi

Ok ty 😊

undone coral

i'm getting this error:
DiscordAPIError[50035]: Invalid Form Body
data.components[0].components[0].style[BASE_TYPE_REQUIRED]: This field is required

code:

if (!modal) {
    if (isNumber) {
        const numModal = new ModalBuilder()
            .setCustomId(`configmodal~${settingID}~${int.user.id}`)
            .setTitle("Cambiar configuración");

        const numOption = new TextInputBuilder()
            .setLabel("Nuevo valor")
            .setStyle(1)  
            .setCustomId("configmodal_value")
            .setMaxLength(200)
            .setRequired(true);

        const numRow = new ActionRowBuilder().addComponents(numOption);
        numModal.addComponents(numRow);

        console.log("Modal Structure:", JSON.stringify(numModal.toJSON(), null, 2));

        return int.showModal(numModal);
    }
}

i got the latest discord.js ver

rose tangle

can you share the whole error

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.

undone coral
rose tangle

it looks like there's more below

rose tangle
undone coral

This error occurs and the application does not respond when I execute a specific slash command.

rose tangle

the error comes from a .reply(), not a .showModal()

nimble otter
undone coral

you are prolly replying the interaction with a button component without Style attribute, which is required

oblique anchor

Hey, does d.js support Discord's Poll feature? And if it does, how can I acess it?

rose tangle

yeah

oblique anchor
rose tangle yeah

How can I access it? I've been scrolling around with the Guides and Docs for like an hour

rose tangle

polls are part of messages, so that's a hint where to look

oblique anchor
sharp ginkgoBOT
rose tangle

for instance

sharp ginkgoBOT
rose tangle

or for interactions ^^

though both are the same thing in reality since they're inherited from the same base message options

then you can listen to poll votes

sharp ginkgoBOT
rose tangle

or -Remove

turbid igloo

what's the activitytype custom?

clear garnet

A custom status

turbid igloo
clear garnet

Your It will take a while To... on your profile

turbid igloo

like about time,

turbid igloo
clear garnet

Same behavior as setting other statuses on your app

turbid igloo
clear garnet

Not necessarily, as the first ℹ️ point in the thread mentions

turbid igloo

Ooo
thx for info

willow cedar

does member.voice.channel use cached data? if so, when im fetching the member every time it says member.voice is undefined, how do i get around this?

zenith violet

Show how you fetch it

And do you have the GuildVoiceStates intent

sand minnow
     container.addSectionComponents(
          new SectionBuilder()
               .setThumbnailAccessory(
                    new ThumbnailBuilder()
                    .setURL(
                         'https://cdn.discordapp.com/icons/1243137862757650464/819f2e5d8f55faf24854fecdfdb564fa.png'
                    )
                    .setId(123)
                    .setDescription('test')
               )
               .setId(123)
     )

return error:

error: Invalid Array length
 constraint: "s.array(T).lengthGreaterThanOrEqual()",
      given: [],
   expected: "expected.length >= 1",
nimble otter
sand minnow
nimble otter

that’s weird, thumbnails don't have ids, neither do sections

hmmm

nimble otter
nimble otter
little pebble
sharp ginkgoBOT
little pebble
nimble otter
worthy grail

I have a question, when we submit a modal, is there also a 3 seconds response time before the interaction expires?

worthy grail
zenith violet yes

and we can defer the reply of the modal ?
in my memory idk why but we can't

zenith violet

you can defer replying to it yes. You cannot defer showing it

worthy grail

ok thanks !

sand minnow

i just don't know when i send this components, it returns

756 | var BaseError = _BaseError;
757 |
758 | // src/lib/errors/BaseConstraintError.ts
759 | var _BaseConstraintError = class _BaseConstraintError extends BaseError {
760 |   constructor(constraint, message, given) {
761 |     super(message);
                            ^
error: Invalid Array length
 constraint: "s.array(T).lengthGreaterThanOrEqual()",
      given: [],
   expected: "expected.length >= 1",

      at new BaseError (1:23)
nimble otter
nimble otter
zenith violet

whats the full error

sand minnow
zenith violet whats the full error
756 | var BaseError = _BaseError;
757 |
758 | // src/lib/errors/BaseConstraintError.ts
759 | var _BaseConstraintError = class _BaseConstraintError extends BaseError {
760 |   constructor(constraint, message, given) {
761 |     super(message);
                            ^
error: Invalid Array length
 constraint: "s.array(T).lengthGreaterThanOrEqual()",
      given: [],
   expected: "expected.length >= 1",

      at new BaseError (1:23)
      at new BaseConstraintError (...\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:761:5)
      at new ExpectedConstraintError (...\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:780:5)     
      at run (...\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:1045:79)
      at <anonymous> (...\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:972:67)
      at reduce (1:11)
      at validateComponentArray (...\node_modules\@discordjs\builders\dist\index.js:1532:191)
      at toJSON (...\node_modules\@discordjs\builders\dist\index.js:2166:5)
      at map (1:11)
      at toJSON (...\adruinmenon\node_modules\@discordjs\builders\dist\index.js:1871:35)
sand minnow
proud arrow
crystal cargo

is this correct ```js
perms?.has([PermissionsBitField.Flags.SendMessages, PermissionsBitField.Flags.ViewChannel], true)

proud arrow
sand minnow
fading girder

Got a question with replies to interaction. If I have an embed with a button, on click, I do interaction.deferReply() and edit the content further more with interaction.editReply()

How can I edit the initial embed that has the button?

proud arrow
fading girder
proud arrow

Yes

And if you want to edit the followUp reply, you can pass the id of the message to the editReply call

fading girder

message: 'id' right

proud arrow

Yeah

fading girder
proud arrow

You could yeah, but if it is an ephemeral response or your bot doesn't have access to the message, then you can only do it through interaction webhook

fading girder

Okay got it, ty for the help

merry hamlet

is there a way to get channel id given message id?

polar karma

Not reliably, no

merry hamlet

would there ever be a scenario where a slash command CommandInteraction interaction.channel is ever null or undefined?

context:

async execute(interaction: CommandInteraction) {
  interaction.channel // some other method call
}
near siren

whats the most effective way to fetch a user? im using broadcast eval currently but that will fetch on each shard, whereas I want it to only do it until it's fetched it atleast once (no more), but i don't want to specifiy a shard unless that shard isn't online

near siren

re-read my question
in this instance, i dont have a client only shardmanager

steel trail
steel trail
merry hamlet
near siren yes

i know the library say it may be null i just wanted to know in what case scenario (like qjuh said)
thanks though

near siren
steel trail

That’s still not saying what for, just stating that you do

near siren

not sure how the use case of public user data is relevant

crystal cargo

is this correct:
channel.permissionsFor(guild.members.me).has(PermissionsBitField.Flags.ViewChannel)

steel trail
near siren

i only have their ID

steel trail

when it‘s related to your website I‘d have expected oauth2 to be a part of it

near siren

well i could use oauth data but its not exactly kept up to date

steel trail

Huh? Oauth2 data is always up-to-date if you request it from the endpoint with access_token. Which would be the preferred way for getting information about the logged in user on your website

near siren

and then stored in a database

granite shale

is there documentation on discordjs.guide on components v2?

rose tangle

there isn't

granite shale

When will there be?

hushed mirage

how to do something like that?

granite shale
rose tangle

no etas or guarantees

granite shale
hushed mirage
rose tangle

not any official one

granite shale
rose tangle
granite shale
steel trail
ivory valve

Hi, I'd just like a little technical confirmation. It's impossible to join a voice channel following a user interaction if the user isn't in a voice channel?

rose tangle

sure you can

steel trail

no, why would it?

we agree, although it might sound differently

rose tangle

it's just that most bots won't do that because they don't know where to join

since normally voice related bots are meant to follow the user

ivory valve

We have a bot that lets you create voice channel, but we have a lot of them, so we'd like to use a button to create a voice channel instead. The aim would be to move the player into a new voice chat room, not the bot.
I forgot to specify that...

rose tangle

sure that's possible

ivory valve

without the user being in a channel first? He will therefore join one of them from the interaction

rose tangle

oh, no that's not possible

ivory valve

ah yeah thanks =)

steel trail

Reply with an ephemeral message containing the channel mention instead

near siren
steel trail
near siren

the access token is stored on the database

steel trail

„From the source“ here means „from discord API“

near siren

ah - thought you meant from my website and avoid making a request to my api to handle this

steel trail
near siren

basic data such as name, avatar and id is stored in the cookie

steel trail
near siren

well i also need to figure out the most effective way to fetch an invite also

probably just an api req to discord without using djs methods?

steel trail

fetch an invite from what information?

near siren

the invite code

steel trail

Then yes, discord API

near siren

would it be bad practice to fetch the invite using a new REST instance just so the handling of the request is processed using discord.js ratelimit handler and the data is turned into camelCase

sharp ginkgoBOT
steel trail
near siren
steel trail

top level of what? Didn’t you say you‘re running serverless?

near siren

the API isn't serverless, the website is

steel trail

Why is the API suddenly getting involved again? I thought you‘d request directly from website to discord API now

near siren

all requests need to be processed through the API from the website because the api has the bot and the database connections

in your original message, i thought you were calling my website the source, not the discord api

merry hamlet

is it possible to send colored text with discord bot without using the 3 backtick ansi method? i cant seem to find one online

rose tangle

there isn't

worldly coyote

and if not how bcz i tried and i have no issues.

rose tangle

if you tried and it works then why are you asking if there's issues? Thonk

sounds like an xy question

worldly coyote

it wasnt working bro.

rose tangle

well if you have a Message called message yeah

but Guild#name is always a thing

umbral prairie

Is there no guild tag for this server? :c

polar karma
shell ravine

Can we use the new component, or not yes? I tried using it since 2h but not working... 😅

rose tangle

you can

show your code

shell ravine

Actually it's awfull, sorry :

const { ComponentBuilder, MediaGalleryBuilder, MediaGalleryItemBuilder, TextDisplayBuilder } = require('discord.js');

[...]

const components = new ComponentBuilder()
      .setComponents([
        new MediaGalleryBuilder({
          items: [
            {
              description: "Some text here",
              media: {
                url: 'https://media.discordapp.net/attachments/1184590231194837013/1367848342444572712/rect4.png?ex=6816138a&is=6814c20a&hm=423e474c6bd5d9769d07aed41910f59957751169b8bd18bd6cb4f16b6c2221df&=&format=webp&quality=lossless&width=786&height=254',
              },
            },
          ],
        })
      ]);

    await interaction.reply({
      content: 'Testing new component :',
      components: components.toJSON()
    });
rose tangle

ComponentBuilder is the base builder for other component builders

you aren't meant to use it

if you just want the media gallery only pass that to components

(in an array)

and you need to send the IsV2Components flag as well

shell ravine

So I have to use ContainerComponentBuilder instead, right?

rose tangle

ContainerBuilder if you want a container, yeah

it's not mandatory so you don't have to

shell ravine

Because I don't only want a gallery, I want to try other things in my container

rose tangle

well you can pass pretty much every component that can go inside a container, outside one

like I said, components is an array, you can pass more than one component

just making it clear that you don't need a container, it's a matter of looks

shell ravine

Ok! I'll try again! Thanks!

toxic moat

Can you have more than 1 image in message with components v2 ?

rose tangle

you could always have more than one image in a message

you just couldn't position it

rose tangle
crystal cargo

didn't understand if i want: { dynamic: false }, how to do it

forceStatic: true ?

zenith violet
tardy sable

can i do deferreply and later update interaction?

or get the interaction message first, then do defer and then edit the interaction message? or i cant use defer in this case?

zenith violet
hearty quest

Error: Cannot find module 'dotenv'

polar karma

does not seem like a d.js issue, please use #1081585952654360687 (also not necessary for a separate package with new versions of node, env support is native)

hearty quest

sorry

hearty quest
polar karma

nope, deployment is instant. you may need to refresh your user client to see the new data

hearty quest
loud quartz

Are you deploying global commands or guild commands

loud quartz

Are you checking in the correct guild?

hearty quest
merry hamlet

https://github.com/0x5b62656e5d/zephybot

/home/pepper/zephybot/node_modules/@discordjs/rest/dist/index.js:748
      throw new DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData);
            ^

DiscordAPIError[10062]: Unknown interaction
    at handleErrors (/home/pepper/zephybot/node_modules/@discordjs/rest/dist/index.js:748:13)
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
    at async BurstHandler.runRequest (/home/pepper/zephybot/node_modules/@discordjs/rest/dist/index.js:852:23)
    at async _REST.request (/home/pepper/zephybot/node_modules/@discordjs/rest/dist/index.js:1293:22)
    at async ChatInputCommandInteraction.reply (/home/pepper/zephybot/node_modules/discord.js/src/structures/interfaces/InteractionResponses.js:194:22) {
  requestBody: {
    files: [],
    json: {
      type: 4,
      data: {
        content: ':ping_pong: Pong! -1ms',
        tts: false,
        nonce: undefined,
        enforce_nonce: false,
        embeds: undefined,
        components: undefined,
        username: undefined,
        avatar_url: undefined,
        allowed_mentions: undefined,
        flags: 64,
        message_reference: undefined,
        attachments: undefined,
        sticker_ids: undefined,
        thread_name: undefined,
        applied_tags: undefined,
        poll: undefined
      }
    }
  },
  rawError: { message: 'Unknown interaction', code: 10062 },
  code: 10062,
  status: 404,
  method: 'POST',
  url: 'https://discord.com/api/v10/interactions/1367881414262919269/aW50ZXJhY3Rpb246MTM2Nzg4MTQxNDI2MjkxOTI2OTo0bzlhc1JTazkxR1g0SWpkT0xyWDU2SGI0YkNPMVk1N2tMQWRySlVIbUVZTHhNd3BIR2t1a1ZHVDdSWHBrejIzZEtZWnRhZkdTVVF0UXNQQzJXSUFrT3ZMMks3RlliRG1USm9jTWJjOUR1N21rVjJFWmFvcVcyZ0F2WndqRWN2Yw/callback?with_response=false'
}

Node.js v22.15.0

when i run it on my macos, it works fine
but the moment i run it on my raspberry pi, it throws this error when i run a command

loud quartz

Did you stop the one running on your mac before running the one on your pi?

merry hamlet

yes
ive ensured that the bot is offline before running on my raspi
ive also ensured all my application ids/tokens are correct

sharp ginkgoBOT

Common causes of DiscordAPIError[10062]: Unknown interaction:

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

The token being wrong would absolutely not cause this error

Because your app wouldn't be able to log in to receive the interaction in the first place

merry hamlet

im pretty lost rn man...
exact same code, nothing changed between the two systems
i just git cloned it, npm install, then npm start
and running /ping threw that error

loud quartz

Is your pi old or overloaded or something

merry hamlet

its a raspberry pi 4b
ive ran a js version of this bot before and it ran just fine

loud quartz

Since you have 3 seconds to respond to interaction, if you take longer you will get that error too

loud quartz
merry hamlet

yes

loud quartz

It was not a yes/no question

merry hamlet

mb ts-node

loud quartz

Then don't

Transpile and run the resulting js

merry hamlet

nvm that means i transpile it ig
I do rimraf dist/ && npx tsc && node dist/index.js

loud quartz

Then idk what to tell you

merry hamlet

what the sigma 😭

merry hamlet

it runs on a dockerfile now
wtf
its just awfully slow

FROM node:22.15.0
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
CMD ["npm", "start"]
vagrant flare

How to add the --openssl-lagacy-provider flag to all shard processes when using the sharding manager?

sharp ginkgoBOT
steel trail

no wait, wrong one nvm, it is the correct one

vagrant flare
wraith geyser

Hey, I got this file and I always used the interaction.options.getSubcommand() but it always gives me the error TypeError: interaction.options.getSubcommand() is not a function

This is the file:

//_SLASH_COMMAND

import { SlashCommandBuilder, Client, ChatInputCommandInteraction } from "discord.js";
import db from "../../handler/database";

import responseAnimations from "../../scripts/responseAnimations";

export default {

    data: new SlashCommandBuilder()
    .setName("server")
    .setDescription("Toggle features")
    .addSubcommandGroup( group => group
        .setName("features")
        .setDescription("Toggle features")
        .addSubcommand( subcommand => subcommand
            .setName("response-animation")
            .setDescription("Enable or disable the response animation")
            .addBooleanOption( option => option
                .setName("state")
                .setDescription("Enable or disable the response animation")
                .setRequired(true)
            )
        )
    ),

    async execute(client: Client, interaction: ChatInputCommandInteraction) {

        const subcommand = interaction.options.getSubcommand();
        // ! The line above causes the error.

        if (subcommand === "response-animation") {

            await responseAnimations.runScript(client, interaction);

            return;

        } else {

            await interaction.reply({ content: "Unknown subcommand", ephemeral: true });

        }

    }

}

Anybody know why?

sharp ginkgoBOT

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

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

Thanks, that solved the issue haha

hearty quest

is there a way to troubleshoot why my slash commands aren't showing up

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
hearty quest
wary coral
hearty quest
wary coral

closing the window does not restart the client

hearty quest
halcyon bison
hearty quest
halcyon bison

that doesn't sound like "it isnt detecting any failures whilst registering"
that sounds like it isn't registering
what does execute?
care to share your code?

hearty quest
halcyon bison that doesn't sound like "it isnt detecting any failures whilst registering" that...

require('dotenv').config();
const { REST, Routes } = require('discord.js');

const commands = [
  {
    name: 'testingcommand',
    description: 'yeah i work',
  },
  {
    name: 'help',
    description: 'help embed soon',
  },
];

const rest = new REST({ version: '10' }).setToken(process.env.TOKEN);

(async () => {
  try {
    console.log('attempting to register slash commands');

    await rest.put(
      Routes.applicationGuildCommands(
        process.env.CLIENT_ID,
        process.env.GUILD_ID
      ),
      { body: commands }
    );

    console.log('registered correctly');
  } catch (error) {
    console.log(`error found: ${error}`);
  }
})();

halcyon bison

what does execute?
does attempting to register slash commands log?

hearty quest
halcyon bison

sounds like you aren't running this file at all
this script is intended to be run separately from your bot since you only need to deploy/redeploy commands when you change the command data (e.g. the name, options, etc)

hearty quest

could you leave/tag the guide to the empheral messages (the ones only the command runner can see)

sharp ginkgoBOT

guide Slash Commands: Command response methods - Ephemeral responses
read more

halcyon bison
wraith seal

Would be best to know where I can find documentation about components v2 ngl

topaz bluff
wraith seal

For this reason

And if you're curious how this message was built, check out the source code!

topaz bluff
wraith seal

How do I find documentation for components v2 specifically?

topaz bluff
wraith seal

I can't open that kind of file

clear garnet

Sounds like you're trying to open it as a video rather than as a text file

topaz bluff

Your computer doesn't recognize it. Just open it as a text file in your text editor (like VSCode)

wraith seal

Got it, thank you for your help!

icy surge

what are the limits with components?

topaz bluff
topaz bluff

I believe we're still waiting on an update for DJS for that. Right now you have to use raw API data to exceed 10

icy surge

oh alright

stable sun

There is a way to disable validators in builders until then

stable sun
icy surge oh alright

You can use disableValidators() (from /builder or d.js), but it will disable it for all builders

icy surge
stable sun

validators

icy surge

So the error?

stable sun

Yes

You just run the risk of getting validation errors from Discord API

hushed mirage

I have a question, how many buttons can be in one message at most? discord.js 14.19.2

hushed mirage

Thanks

stable sun

Or wait a second, it's only 1 per section bc it's an accessory

If you use 20 sections, you can get 20 buttons

halcyon bison

I mean you still have action rows available, so with the new limit you can have 7 action rows containing 33 buttons

stable sun

Yea, was gonna say that

flat forum

Could someone give me an example of the container command with button and separator together?

steel trail
steel trail

the .mts file

flat forum
shadow pier

can bots have buttons in there status?

red coral

No

versed current

Guys, I've got the error code 50024: Cannot execute action on this channel type.
However, I'm not quite sure which action caused this error. What do you think?
It must be either one of those two options:

  • await ctx.guild.channels.create(...) - Create a category
  • await category.children.create(...) - Create a forum channel
loud quartz

did you not get the request path alongside the error?

versed current

I have to see what sentry captured, one moment

  • forgot to do this earlier

nope, I don't see the error.

icy surge
wraith seal

After trying to send a message with components v2 to a user with

const container = new ContainerBuilder()
        const text = new TextDisplayBuilder().setContent(`# New order available`)
        const section = new SectionBuilder().addTextDisplayComponents(text)
        container.addSectionComponents(section)
        await user.send({
            components: [container],
            flags: MessageFlags.IsComponentsV2
        })```
I get `CombinedError: Received one or more errors`. How to fix that?
zenith violet

and sharing the full error would be helpful

wraith seal
wraith seal

Works, thank you!

regal flax
  const filter = (reaction, user) => { return reaction.emoji.name === '⏰'; }
  message.awaitReactions({ filter, time: 15_000 , max:1, errors: ['time'] })
  .then(collected => console.log("then"))
  .catch(console.error);

Hii, I am attempting to use <Message>.awaitReactions promise, but the code errors this out:

    if (collect && (await this.filter(...args, this.collected))) {
                               ^

TypeError: Function.prototype.apply was called on #<Object>, which is an object and not a function

ive tried using example straight from the guide, but yet still the same

steel trail

sounds like filter was not defined as arrow function like your code block suggests. can you double check the error refers to that code and that the file is saved?

regal flax
steep siren

How can I remove ban from guildmember?

sharp ginkgoBOT

method GuildMemberManager#unban() discord.js@14.19.1
Unbans a user from the guild. Internally calls the remove method.


// Unban a user by id (or with a user/guild member object)
guild.members.unban('84484653687267328')
  .then(user => console.log(`Unbanned ${user.username} from ${guild.name}`))
  .catch(console.error);

steep siren

Thanks haha

topaz bluff

And just for clarification...you can remove the ban from a User...but you can't remove a ban from a GuildMember...as no such GuildMember can exist (because...ya know...they're banned)

...wait...did you just thank a bot?

wraith seal

Are there limits to how many characters one container can have?

wraith seal
wraith seal
hearty quest

Error: Cannot find module 'C:\Users\User\Desktop\EverythingDMA\src\register-command.js'
at Function._resolveFilename (node:internal/modules/cjs/loader:1401:15)
at defaultResolveImpl (node:internal/modules/cjs/loader:1057:19)
at resolveForCJSWithHooks (node:internal/modules/cjs/loader:1062:22)
at Function._load (node:internal/modules/cjs/loader:1211:37)
at TracingChannel.traceSync (node:diagnostics_channel:322:14)
at wrapModuleLoad (node:internal/modules/cjs/loader:235:24)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:170:5)
at node:internal/main/run_main_module:36:49 {
code: 'MODULE_NOT_FOUND',
requireStack: []
}

polar karma

you have an incorrect path, this is not related to d.js

cosmic grotto

Can we add images to components? If yes, how?

sharp ginkgoBOT
hearty quest

do you still use .addStringOption or no

tidal sail

hey im getting unhandled rejection issue its happening when my bot is in timeout but i have check to see if bot has send message perms

cosmic grotto

I'm trying to make a embed with comp v2 with just 1 single image there, here is my code:

  async execute(interaction, client) {
    if (interaction.user.id !== "530067274766483487") return;

    // URL for the image
    const imageUrl = 'https://cdn.discordapp.com/attachments/1011355084514394164/1181676507605774559/META_A_LUMBERJACK.png?ex=6815c3c1&is=68147241&hm=33b76dda150a9b98ad8f0cfa7fb86ff62644682162403a021d3a189fa3243b68&'; 

    try {

      const mediaItem = new MediaGalleryItemBuilder()
        .setURL(imageUrl);

      const container = new ContainerBuilder()
        .addMediaGalleryComponents([mediaItem]); 

      await interaction.reply({
        components: [container],
        flags: MessageFlags.IsComponentsV2,
      });
    } catch (error) {
      console.error("Error attaching image:", error); // Log any error
      await interaction.editReply("Something went wrong while trying to display the image.");
    }
  },

but im getting a large error:

Error attaching image: ExpectedConstraintError > s.array(T).lengthGreaterThanOrEqual()
  Invalid Array length

  Expected: expected.length >= 1

  Received:
  | []
cosmic grotto
little pebble Show the full error
Error attaching image: ExpectedConstraintError > s.array(T).lengthGreaterThanOrEqual()
  Invalid Array length

  Expected: expected.length >= 1

  Received:
  | []

    at Object.run (I:\Coding\Discord Bot\Meta\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:1045:79)
    at I:\Coding\Discord Bot\Meta\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:972:67
    at Array.reduce (<anonymous>)
    at _ArrayValidator.parse (I:\Coding\Discord Bot\Meta\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:972:29)
    at validateComponentArray (I:\Coding\Discord Bot\Meta\node_modules\@discordjs\builders\dist\index.js:1532:191)
    at MediaGalleryBuilder.toJSON (I:\Coding\Discord Bot\Meta\node_modules\@discordjs\builders\dist\index.js:2048:5)
    at I:\Coding\Discord Bot\Meta\node_modules\@discordjs\builders\dist\index.js:1871:64
    at Array.map (<anonymous>)
    at ContainerBuilder.toJSON (I:\Coding\Discord Bot\Meta\node_modules\@discordjs\builders\dist\index.js:1871:35)
    at I:\Coding\Discord Bot\Meta\node_modules\discord.js\src\structures\MessagePayload.js:151:46
Error [InteractionNotReplied]: The reply to this interaction has not been sent or deferred.
    at ChatInputCommandInteraction.editReply (I:\Coding\Discord Bot\Meta\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:247:48)
    at Object.execute (I:\Coding\Discord Bot\Meta\commands\developer\preview.js:30:25)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Object.execute (I:\Coding\Discord Bot\Meta\events\interactionCreate.js:16:13) {
  code: 'InteractionNotReplied'
}
loud quartz

don't think so

tidal sail

where can i read component v2 docs

wraith seal

Are there limits to how many characters one container can have?

Container as in components v2

loud quartz

it's not exactly hard to check yourself

wraith seal
loud quartz

dapi docs should have everything

wraith seal

?

tidal sail
loud quartz

wdym "?"

wraith seal

I searched dapi docs and it appears to be a bank thingy

loud quartz

dapi as in discord api

wraith seal

Oh lol

loud quartz

but the link to docs would be

tidal sail

ty

wraith seal

It appears as if there are no limits characters-wise

loud quartz

you can check it yourself then

string.repeat() might come handy

and like with embeds, i'd expect there to be an overall char limit over entire thing

cloud mulch

what is the max length of text allowed on a Container text display component?

loud quartz

what do you mean with "doesn't work"

are you sure the avatar link you have still points to an existing avatar?

which is built from cdn url and avatar hash, along with an extension (defaulting to one), and if you set it - size query param

where hash is taken from cache (and default extension deducted from it)

so it's not impossible for the avatar to change since you last fetched/received the member if you don't have a way to get the new avatar updated in your cache

it's also possible that the user changed their avatar since you got the link

tidal sail

can TextDisplayBuilder have color

steel trail

no

proper monolith

Is there a way for me to globally view the date the user started boosting on Discord?

clear garnet

No, you can only do it on a per-guild basis via <GuildMember>.premiumSince

proper monolith
clear garnet

🤷 Beyond my knowledge

unique shoal

...who is they?

proper monolith
unique shoal

k

proper monolith

I believe that would be wrong, right? Because discord does not allow storing this type of information for privacy reasons

loud quartz

storing is one thing

the much, much bigger problem is how they obtain it

but that's not a topic for this channel, really

primal edge
        collector.on("end", () => {
            selectMenu.setDisabled(true);
        });

why doesnt this disable it? it just makes the interaction not work. im still able to click the select menu.

oh im slow my bad lol.

yay i got it

mystic tinsel

is there a better & easier way to handle buttons than do the whole
if(button.customId === "xyz"){...} and doing that for every button? It feels very.. bare bones and tedious- any solutions?

hushed mirage

I have a question, is it possible to send several surveys in one message or can you send a maximum of one survey in one message? (discord.js 14.19.2)

topaz bluff
hushed mirage

okay

rose tangle

but you're free to route your interactions however you want

rancid folio
mystic tinsel is there a better & easier way to handle buttons than do the whole ```if(button...

it's pretty easy to make a variant of your interactionCreate.js event to handle button interactions.

personally this tutorial has something fairly close to what i use, but i have something a bit different, but it definitely helps declutter your code in the long run because you can just make individual files for buttons.

i have a very modified version that allows for keying buttons and also handles modals and every other interaction type as well. very handy!

-> https://youtube.com/watch?v=3AZ2ZA6_GJg&ab_channel=Lyxcode

worth noting i believe that this tutorial applies to d.js v13, so be wary of that. i don't think anything super substantial has changed but there will likely be some deprecated methods in that video

but you still get the gist of it

tidal sail

can we .setColor method on new component builder

rancid folio
tidal sail
rancid folio
tidal sail no embed color?

accentcolor does effectively the same thing, but i don't think you can do like .setColor("Blue") or something like that. example of one of my new bots below using accentcolor

tidal sail

thank u

mystic tinsel
rancid folio
mystic tinsel I'll look into it, thanks a lot! You did mention however its for djs v13- are th...

i honestly cannot remember if i had to change anything in that handler when i ported over to v14, but i don't really think so.

if you do, the errors should help you figure out stuff, and you can always check here to see if your issue is one of the things that changed.

worst case scenario there are some other similar tutorials and scripts out there probably updated for v14, just search button handler and you should find some

hushed mirage

what is the name of this element? because it is not embed, I mean specifically the name of what it is called

hushed mirage

Thanks

rancid folio

np y'all

hushed mirage

or maybe someone knows how many such containers can be in one message at most?

rose tangle

there isn't a limit specifically for containers

there's a total component limit

40

rose tangle

djs really isn't particularly optimized to run in systems with more limited resources

maybe you could try with @discordjs/core if you really want to host a bot there

it should be as lightweight as it can get in a js environment

merry hamlet

i used to use commandkit for all my commands but im just using djs only now
would that change anything?

rose tangle

frameworks do add additional overhead, yeah

merry hamlet

wdym overhead

rose tangle

that there's more resources, both in computational time and ram usage, with a framework than without one

since they just wrap around djs

adding more stuff to it

merry hamlet

so aka less efficient?

rose tangle

it's not the same thing for you to directly listen to interactionCreate and reply than the framework adding its own command manager, doing the command location and routing up to your command object

rose tangle
rose tangle
merry hamlet

😭
it used to run perfectly fine and smooth with commandkit
now it cant even respond in time without commandkit…

rose tangle

have you tested if it actually fully works without it?

tidal sail

can we add dropdrown menu inside components v2

merry hamlet

exact same machine and os
ik you mentioned less sys resources may affect but the exact same code and node versions run perfectly fine on my mac, no errors
when i git cloned then npm install then start on my rpi, it lagged then threw a 404

rose tangle

if it's the exact same reply code then yeah sounds like the framework's overhead is causing an issue for you

merry hamlet
rose tangle
tidal sail

ok

verbal plinth

Is there a list of each Endpoint and how many times you can request it before you get ab 429?

merry hamlet

is it possible to get the userid of the message that was replied to on a messagecreate event?
eg, if A replies to B, is there a way to get the userid of B from the message created by A?

halcyon bison
halcyon bison
hollow oriole

can i add fields like i did to my embed in a container?

shadow pier

You can just add text display components

hollow oriole

alrighty thank you

oak yoke

do new containers support text inputs?

shadow pier
oak yoke

by the models you mean what?

sharp ginkgoBOT

guide suggestion for @oak yoke:
guide Other Interactions: Modals
read more

oak yoke

oh modals

thanks!

shadow pier

yeah my bad I made an error

oak yoke

np, thanks anyway

rancid palm

Does the djs guide contain anything on the new components yet?

shadow pier
hearty quest

can someone link me to the guide for this

sharp ginkgoBOT

guide suggestion for @hearty quest:
guide Other Interactions: Modals
read more

shadow pier

Random question, do collectors have a significant impact ram usage?

proud arrow

It is an event listener underhood, so it is same situation as that. Too many listeners will obviously consume more memory. Too much listener may cause memory leak. Although d.js increases maxListener amount for collectors so as to not get that warning, but you get the gist. Collectors are cleaned up when their use is done, but too many at once may slightly impact memory usage

shadow pier
proud arrow

Yes

shadow pier
proud arrow

What issues? It is only one listener. Unless you are creating multiple interactionCreate listener for different types of interaction, which you should not do

cobalt tree

HI! i am working on automod feature for my bot using Discord's Automod API. Is it possible to toggle on/off the native Block Mention Spam using the bot and edit the mention limit?

if (mentionRule) {
await mentionRule.edit({
enabled: action === 'on',
triggerMetadata: {
mentionTotalLimit: mentionRule.triggerMetadata.mentionTotalLimit || defaultLimit,
mentionRaidProtectionEnabled: true,
},
});
} else if (action === 'on') {
mentionRule = await guild.autoModerationRules.create({
name: 'Block Mention Spam',
eventType: 1,
triggerType: 4,
triggerMetadata: {
mentionTotalLimit: defaultLimit,
mentionRaidProtectionEnabled: true,
},
actions: [{ type: 1 }],
enabled: true,
});

sharp ginkgoBOT
sharp ginkgoBOT
cobalt tree
shadow pier yeah you can

i did it earlier by using the automod ID (test) but since servers automod has different automod ID and idk how to implement it to my bot

steel trail

Fetch rules and .find it by type

terse tiger

how to edit a interaction message, how to let it and edit at last

sharp ginkgoBOT

documentation suggestion for @terse tiger:
method Message#edit() discord.js@14.19.3
Edits the content of the message.


// Update the content of a message
message.edit('This is my new content!')
  .then(msg => console.log(`Updated the content of a message to ${msg.content}`))
  .catch(console.error);

zenith violet

Only works for non ephemeral messages

Ephemeral messages have to be edited through an interaction webhook using editReply

cobalt tree
crimson thistle

is it possible to get a CommandInteraction from a ButtonInteraction?
reason i need this is because i need to get the options that were passed when using a command

shadow pier
shadow pier
crimson thistle
cobalt tree
shadow pier sorry what?

is per trigger type counted as 1 rule? for example my automod bot create a type 1 is it counted a 1 rule?

shadow pier

yeah ig?

cobalt tree

@steel trail & @shadow pier Thank you! finally i can control it using my bot!

shadow pier

no worries

merry hamlet

yeah i guess my raspberry pi really was the culprit @loud quartz
im running the bot on a rog laptop and it runs smooth like butter

shadow pier

because I haven't faced any issues on mine

merry hamlet
shadow pier

ahh

im running ubuntu server, only has a cli

primal yoke

How can i make sure that i don't hit the Discord 3s timeout?

shadow pier

what timeout

primal yoke
primal yoke

Let me try

sharp ginkgoBOT
primal yoke

Im still getting same error.. Tried updated my InteractionCreate.js file and the command

merry hamlet
steel trail
oak yoke

Is it possible to show 2 TextDisplays inline to each other in a container?

steel trail

No

oak yoke

okay, thanks!

primal yoke

When i use editReply after deferReply, its not possible to remove the edited lable right?

oak yoke

No

primal yoke

Damn..

toxic moat

With Component v2 I was able to figure out some of basics with the new components but I am not sure if I can add fields to TextDisplayBuilder? I am using TextDisplayBuilder so I can split the sections.

TextDisplayBuilder

const PingInfo = new TextDisplayBuilder().setContent(
  `**Message Latency**: \`${MessageLatency}ms\`\n` +
   `**API Ping**: \`${ApiLatency}ms\`\n` +
    `**MongoDB**: \`${MongoLatency}\`\n` +
    `**Uptime**: \`${Uptime}\``
);

Building the Message

const Section = new SectionBuilder()
  .addTextDisplayComponents(PingInfo)
  .setButtonAccessory(RefreshButton); 

const Container = new ContainerBuilder()
   .setAccentColor(0x5865F2)
   .addSectionComponents(Section); 
proud arrow

You can't have fields in components v2

toxic moat
shell ravine

Hey, don't know if I can do this, but I find a very usefull website to build containers : https://discord.builders/

Hope it can helps someone 🙃 !

sharp ginkgoBOT
rigid yarrow

Is there a way to make a defer reply but then make it ephemeral if I want to? And even not ephemeral ?

I know when trying to do that with defer it will always will not be ephemeral unless I make it ephemeral in the defer itself but I mean is there a way to make it ephemeral or not ephemeral after?

leaden shuttle

are there any examples on how to use the new builders?

rigid yarrow
leaden shuttle
const container = new ContainerBuilder()
  .addTextDisplayComponents(
    new TextDisplayBuilder()
      .setContent("hello!")
  );

return interaction.reply({ components: [container] });

data.components[0][UNION_TYPE_CHOICES]: Value of field "type" must be one of (1,)

am i missing smth?

zenith violet
leaden shuttle
visual verge

I'm using guild.channels.cache to count my server's channels, filtering by type (text, voice, etc.), but the total count is incorrect. It's showing more channels than I actually have. I'm excluding threads using c.isThread(), but the count is still inflated. How can I get an accurate count of real (non-thread) channels?

zenith violet
zenith violet
visual verge

Thanks!

leaden shuttle

why cant i use hex with setAccentColor for the new components?

visual verge
zenith violet Categories are also counted as channels

I'm trying to get the total number of channels in a guild using guild.channels.cache.size, but the count is lower than expected. Some private channels (like staff-only) and the rules channel aren't included. The bot likely doesn't have View Channel permission for all of them. How can I get the total channel count including all types, even ones the bot can't see?

vital barn

you can still convert hex to rgb very easily

foggy grove

I have a question how the logic is implemented when creating channels (CategoryChannel), why they are created not on the position that is specified or conditionally not under the category that is specified

leaden shuttle
sharp ginkgoBOT
steel trail

use that function

leaden shuttle

ty

steel trail
steel trail
steel trail

and there is no getChannel method on Client Thonk

also there's no need to explicitly pass the generice to the create() method, that gets inferred from the passed properties

foggy grove
steel trail
steel trail
foggy grove
foggy grove
rigid crest

is there a bug? or whats caused this

steel trail
steel trail
rigid crest

ah