#djs-help-v14

78874 messages · Page 16 of 79

polar karma

they can be, but if you do defer() then followUp(), then followUp will be editing the defer, not sending a new message

did you log finalRoles and check the positions? i know you're doing a function to check stuff, but it's also good to double check the final results

latent plume

the two roles in the text bar are the ones my bot is trying to remove. this fails with the missing permissions error

polar karma

that's not what i asked. i asked you to check finalRoles and its value

latent plume

yeah those roles - sorry i worded it badly

final roles is [ '1023670751921971260', '1023671077932634243' ] (just the ids of the two roles)

polar karma

and those are the roles you want it to keep? so one role is being removed?

latent plume

yep, those are the roles i want
both of them are below the bots role and it should have permission to manage them

polar karma

that's not the problem, if they're already present. the issue would be coming from the role that's not present in that array/set

roles.set(...) should only be the role (ids) of the roles you want to keep (including other roles you're not modifying)

latent plume

i want to keep the * role its just been filtered out cause the bot doesnt have permission to manage it

ahh sorry i think i get it - should final roles still have that * role and any that it is unable to manage?

polar karma

yes, it's going to make the member's roles exactly what's in the array provided

so if it's already present on the member but not in the set(...) method, it will try to remove it, then fail if it doesn't have perms

set() is preferred when you want to both add and remove roles in the same command/flow, since it saves on api requests. it takes a bit of work to understand, but i think you got it now

latent plume

yep, thanks so much for your help!

normal veldt

I still have the issue I described here even after spending an hour trying to fix it, so if anyone would help me, I'd appreciate that 🙂

polar karma

You were given some guidance earlier about a build folder, is there anything new for you to add, also should be in #1081585952654360687

normal veldt

Oh okay, my bad

Will try few more things then if I don't get it to work i'll make a post. thanks

sinful scaffold

Hi guys, i've a question how to preview server profile than the main profile? displayavatar and avatar both returns same image

steel trail

You want the value from GuildMember, not User

sharp ginkgoBOT

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

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

but why do both has display avatar and avatar url which does same operation 🤔

steel trail

Because it wouldn't if avatar was null

Then displayAvatarURL would fallback to the one that actually is displayed while avatarURL would just be null

sinful scaffold
steel trail

It does, that's what displayAvatarURL is for. If you want the one displayed, independent of why.

rose tangle

every user has a displayed avatar, so displayAvatarURL always returns something

not every user has a custom avatar, so avatarURL is nullable

sinful scaffold

make sense, so it's safe to use displayavatar than avatar itself am i right?

rose tangle

it kind of depends on what you want

but if you just want to get how the user looks in discord, yes

the member displayAvatar would be the most accurate to account for custom guild avatars

sinful scaffold
hexed marsh

Is there a way to "Skip" replying to a message? I have an embed that self-updates whenever state changes and I'd like to avoid having to reply to an interaction, because it moves the chat up and down frequently when interacting a lot. I've tried to "Defer" but that doesn't quite do what I'm expecting, and even if I deferReply, then immediately delete the reply, it causes all manner of edge-case scenarios. What's the proper way to "Skip" a reply?

red coral

You can’t do that with any interactions other than message components. But buttons etc you can use .deferUpdate. Other then that, you can’t unless you want that interaction failed response discord side

rose tangle

but if a button is meant to update the message, then just .update() ?

novel mauve

can you not pass the same data in .setAccentColor and .setColor? passing a hex code works in embeds but not in containers, is this intentional?

rose tangle

you can pass a hex code to containers too, just need to pass it as a number, not string

novel mauve

ah ok, but why isn't it consistent with embeds too?

rose tangle

and yes, it's intentional since v2 component builders were made like discordjs/builders v2 builders

it's not possible to remove that functionality from embed builders since that'd be a breaking change

which is coming in v15

sharp ginkgoBOT
novel mauve

ah so it'll be consistent in the next version

steel trail

You can also use that if you want the same functionality for containers

sage mural

Bit confused here. I previously updated these messages fine but now that I moved over to containers, it gives me this error:

DiscordAPIError[50035]: Invalid Form Body
components[COMPONENT_DISPLAYABLE_TEXT_SIZE_EXCEEDED]: Components displayable text size exceeds maximum size of 4000```
I have 3 containers in 1 message. 3637+573+1118 characters in this case. Is the limit 4000 in total for the entire message?
rose tangle

for all text displays in the same message, yes

5300 characters is way too much info to display to the user at once either way imo

sage mural

90% of it are hyperlinks but yes

rose tangle

maybe you could setup some "tabs" with buttons, or "collapsable" sections

sage mural

Yeah I got that. This is supposed to be the overview menu
I'll see what I can remove then, thank you

wary coral

Could you use link buttons the move the Hyperlink out of the text? do link buttons count against the character limit?

rose tangle

no, only text displays

junior ore

is there a way to reply the message without sending a message?
example:

client.on("messageCreate", (m) => {
        if(message.author.bot)
         if(message.content == "a!reply") { message.reply() 
 message.channel.send("hi!")
}
})

without using content

zenith violet

just not reply at all if you dont want to reply?

junior ore
zenith violet

you need content, embeds or an image

i dont see the point of an empty reply eitherway

junior ore
zenith violet

djs doesnt control that

and it wouldnt make any sense

if you reply you need to reply with something

junior ore
zenith violet

just dont reply at all?

junior ore

also i saw something like my idea in a string-based package, so i think they just getting messages, not functions

zenith violet

what

junior ore
zenith violet

i have 0 clue what you are talking about

junior ore

return is counts as non function i think

zenith violet

but in short, no, you cannot reply with nothing

pine quarry
const { ComponentBuilder, TextDisplay, ContainerBuilder, UserSelectedBuilder, ActionRowBuilder, RoleSelectedBuilder, MentionableSelectedBuilder, ChannelSelectedBuilder, Separator } = require("v2componentsbuilder");
module.exports = {
  name: 'testing',
  description: 'testing v2',
  async execute(message) {
    const components = new ComponentBuilder().setComponents([
      new ContainerBuilder()
      .setComponents([
        new TextDisplay('Testing'),
        new ActionRowBuilder()
        .setComponents([
          new UserSelectedBuilder()
          .setCustomId('testing'),
        ]),
        new Separator()
        .setSpacing(2),
        new ActionRowBuilder()
        .setComponents([
          new RoleSelectedBuilder()
          .setCustomId('testing2'),
        ]),
        new Separator()
        .setSpacing(2),
        new ActionRowBuilder()
        .setComponents([
          new MentionableSelectedBuilder()
          .setCustomId('testing3'),
        ]),
        new Separator()
        .setSpacing(2),
        new ActionRowBuilder()
        .setComponents([
          new ChannelSelectedBuilder()
          .setCustomId('testing4'),
        ]),
      ])
      .setColor(1146986)
        .setSpoiler(true)
    ]);
    return message.reply(components.toJSON());
  }
}```
I think I did this code wrong, where is my mistake?
zenith violet

you do not need a separate package

djs supports it natively

but then you'd need to use the proper reply call and set the IsComponentsV2 flag

pine quarry
const { ComponentBuilder, TextDisplay, ContainerBuilder, UserSelectedBuilder, ActionRowBuilder, RoleSelectedBuilder, MentionableSelectedBuilder, ChannelSelectedBuilder, Separator } = require("discord.js");```
So you're saying it's like this?
zenith violet

Not quite

djs uses differnt naming

pine quarry

hmm

pine quarry
sharp ginkgoBOT

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

pine quarry

I couldn't find one

thx :]

narrow geode

How do I set a voice channel's "set voice status" permissions? I don't see an entry in Discord.PermissionsBitField

bleak owl

it's not documented so discord.js does not support it

narrow geode

Thanks - do you happen to know if there's an issue about supporting this on discord-api?

bleak owl

there might be, but i am not sure myself

narrow geode

Thanks, I'll investigate

steel yacht

Hi,
Can't I show a modal if I disappear the button beforehand ?

bleak owl

which button?

steel yacht

The button the user clicks for the modal to show up

bleak owl

you can’t make it disappear before the modal is shown

steel yacht

Okay, can I know if the user presses cancel ?

steel yacht

Okay, when using awaitModalSubmit, what's the good practice for dealing with the button after cancellation ?

bleak owl

there’s no way to detect when a user presses cancel

unique shoal

Thats why you have a timeout

steel yacht

But the user might press cancel or click outside the modal on accident and retry the button, which will lead to interaction failure, so what's the proper way to prevent this ?

unique shoal

Using unique custom ids each time the modal opens

New button click = new button interaction

The easiest way is to include that id in the modal custom id in some way

steel yacht

But a Promise doesn't fire twice. awaitMessageComponent works only once.

unique shoal

So dont use awaitMessageComponent, if you need to handle more than one possible button click

steel yacht

I don't, really, I just need to prevent the user from trying

unique shoal

I mean... the interaction failing does that

Thats just how it works unfortunately

warped ivy

Hello, I am having trouble with deleting an ephemeral message.

  1. User does slash command, which is replied to with an ephemeral messagse containing a select dropdown
  2. When select dropdown is changed, I want to delete the ephemeral message and open a modal

I have the modal opening successfully, but when I do interaction.message.delete() I get "Unknown message" error. Any ideas? It seems like the message is ephemeral so it's unable to be deleted, but I see here that deletion of ephemeral messages is supported. Any help would be appreciated. Thanks!

bleak owl

you would use interaction.deleteReply()

warped ivy
bleak owl

you can’t delete a reply if you never replied

unique shoal

Either delete via the original interaction, or use deferUpdate then deleteReply on the second

warped ivy
warped ivy
unique shoal

you dont fetch interactions

bleak owl

you can pass the message as a parameter in deleteReply

warped ivy
bleak owl

interaction.fetchReply will fetch the reply and return a Message

unique shoal

Do you not have interaction.message already

bleak owl

oh wait yeah forgot that ^

warped ivy

It's very weird, interaction.message exists and interaction.message.deletable is true, but interaction.message.delete() gives "Unknown message"

bleak owl

because it’s ephemeral

warped ivy

So how do I delete it? Sorry I don't follow. fetchReply on message returns unknown

unique shoal

interaction.deleteReply(interaction.message)

Try that

warped ivy

InteractionNotReplied

unique shoal

oh cause we have that check internally

bleak owl

can you show your relevant code please? it’s hard to help with such vague information

unique shoal

Okay back to a solution I already suggested

warped ivy
unique shoal Okay back to a solution I already suggested

So if I want to delete from the original interaction (slash command), I don't know how I would be able to tell when the select has been fired? Please advise.

And for deferUpdate and deleteReply, how would that fix the deleteReply error I've already faced?

unique shoal

🤦‍♂️

bleak owl

lol okay it’s really not this confusing

unique shoal

Like Jo said there's a lot of context missing here which makes it difficult to help effectively

Are these events being handled in two completely separate locations with absolutely no ability to reference the original interaction variable?

And as for your second question - thats what the deferUpdate is for

warped ivy
bleak owl

please just show your code

warped ivy

Slash command:

export async function execute(interaction: ChatInputCommandInteraction) {
    const selectMenu = new StringSelectMenuBuilder()
        .setCustomId('support_type_select')
        .setPlaceholder(
            localize(interaction.locale, 'commands.support.selectTypePlaceholder')
        )
        .addOptions(supportTypeOptions);

    const row = new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(
        selectMenu
    );

    await interaction.reply({
        content: localize(interaction.locale, 'commands.support.selectTypePrompt'),
        components: [row],
        ephemeral: true,
    });
}

String select change interaction:

export async function handleInteraction(interaction: Interaction) {
    // Set up modal
    const modal = ...;

    try {
        if (interaction.message && interaction.message.deletable) {
            await interaction.deleteReply(interaction.message);
        }
    } catch (err) {
        console.warn('Failed to delete select menu message:', err);
    }

    await interaction.showModal(modal);
    return;
}
unique shoal

Okay, so yes, these are handled in completely separate functions rather than via an awaitComponent style, thats fine

So lets go with the section option

Oh, but you also want to show a modal

Yeah I really dont think this is worth the trouble

warped ivy

I'd be happy to change it to an awaitComponent style. Didn't know that was a thing. Would that make it easier?

unique shoal

No, since youre responding with a modal

You can try deleting after that? Im not sure how that works actually

warped ivy

Deleting after creation of the modal?

unique shoal

yeah

a modal is a response

warped ivy

That worked! lol what the heck

Thank you so much! I don't really understand why that worked. The modal is a reply -- but why would that suddenly make discord.js think that the original message was replied to?

unique shoal

It has nothing to do with the message

It was always about responding to the interaction

orchid latch

Why between .setColor() and .setAccentColor()
The required type changes from ColorResolvable to RGBTuple | number ??

raven hearth

hey! was the max_length option renamed? it doesn't work anymore

orchid latch
rose tangle

oops replied too late

rose tangle
raven hearth
rose tangle

that's for djs data though

raven hearth
rose tangle

the raw API data uses snakecase

raven hearth

yes but you see if it gets renamed it won't be defined

i have it set as max_length: 5 and currect version is maxLength

rose tangle

it didn't get renamed, that'd be a breaking change

it's just a matter of where you send it

if you make a raw request, like through the REST class, djs won't parse it and transform it to snake_case

raven hearth

it's not raw 👍

rose tangle

yep, hence why you send it like that, not snake_case

which is how the api actually accepts it

raven hearth

mhm, i get that, anyways thank you

warped ivy

Would anyone happen to know why Events.MessageDelete is not firing at all when I delete a message?

        client.on(Events.MessageDelete, () => {
            console.log('test');
        });
rose tangle

the message needs to be cached (sent or fetched after the client logged in)

unless you enable partials

sharp ginkgoBOT

guide Popular Topics: Partial Structures
read more

warped ivy
rose tangle

try with user and member as well

warped ivy
        client.on(Events.MessageDelete, () => {
            console.log('test');
        });
        client.on(Events.ClientReady, () => {
            console.log('client ready');
        });

Client ready fires, but message delete does not fire when a message is deleted

rose tangle

is the bot in the guild as a member?

warped ivy

Yes - oh I might need to mess with its intents or something, let me check on that

rose tangle

I'm pretty sure Guilds should be enough

however if it still doesn't work maybe there's something I'm forgetting

someone else can figure it out, gtg, sorry

warped ivy

Yeah I tried message content intent and still not working. Hmm 🤔 np, thanks for your help! Hope someone else can shed some light.

vast nymph
hushed mirage

Hi

I have a question, if I make a defer reply in the bot, i.e. to make the bot think for a moment, how can I set a different text in this message?

because in my bot in this message it writes "(bot name) thinks" and I would like to make it write e.g. like in the picture "sending command..."

if someone replies to me, please ping me

vital barn
topaz bluff
hushed mirage

Thx

safe karma

Follow up. You need the deferreply to have the flag

modest marsh

How do I refer to the activity in try block? (And more importantly, how to know the options)

const response = await interaction.reply({
  content: '**Choose activity type from the list!**',
  components: [row],
  withResponse: true,
});

const collectorFilter = i => i.user.id === interaction.user.id;

try {
  const chosenActivity = await response.resource.message.awaitMessageComponent( { filter: collectorFilter });
  // What variable to refer to to show the chosen activity?
  await chosenActivity.update( { "You chose " content: `${}!` } ); */
} catch {

(I guess it's response.something but didn't manage to guess the right combination so far)

clear garnet

Is this for a select menu?

modest marsh
clear garnet

Then you'd grab it from the select menu interaction itself, which in this case will be chosenActivity

sharp ginkgoBOT
modest marsh
steel trail

Get it from the menu you sent by filtering by value. But what's the use case?

modest marsh

I'd just like to show the user the activity that they just chose as a kind of confirmation, it's not absolutely necessary though

junior ore
modest marsh
steel trail
modest marsh

Thanks, got it working 👍

I assume there's no way to add autocompletion to large list of select menu items?

loud quartz

no, string select menus cannot have autocomplete, and other kinds cannot have less entries than all entries for their type, which is why those have ability to search

modest marsh

Hmm, so I guess I'll have to tinker with those other kinds

south sigil

I have a small problem that I don't understand. I load the events correctly and I can see that they are loading. But
client.once(event.name, (...args) => event.execute(...args, client));
client.on(event.name, (...args) => event.execute(...args, client));
loads the events and there are no errors, but these events aren't running like ClientReady, for example.

I also see that the events go through this but nothing happens.

when the event should be triggered.

novel mauve

did you enable the corresponding intents?

south sigil

Yes, I enabled everything and it was just a loading error...

ruby grove

how to check if the sender of a message has a specific permission with /core? do i need to make another api call

wary coral
sharp ginkgoBOT
ruby grove

intellisense is trolling me then

wary coral

which event are yo getting the message from?

ruby grove

message is GatewayMessageCreateDispatchData, i also console logged the .member to be sure, permissions is not there

wary coral

Your not using the messageCreate event?

ruby grove

i do. i am just using the @discordjs/core with a custom websocket manager, let me log the raw user object from the websocket manager to be sure

wary coral

I guess. then you should uses a cache to store the member other wise you need to fetch the member from the API

ruby grove

i can confirm that permissions doesnt exist in the raw websocket data too

api.guilds.getMember also doesn't return a permission array

proud arrow
ruby grove api.guilds.getMember also doesn't return a permission array

You're correct, traditionally member api structure doesn't have permissions but member returned with interaction payload do, so any other places, you'll have to calculate the permissions yourself taking in account the roles they have and permission overwrites if you want it to be channel specific

ruby grove

that would be a lot of api calls without caching... i'd need to fetch every role noooo

oh wait i can fetch all the roles at once

proud arrow

Do you not cache all guilds on ready? They pretty much have all the information you need

ruby grove

i... dont Clueless

maybe i can free myself of that suffering.. is it possible to initialize the (actual djs) Client object with a custom Gateway? i can see that the constructor ClientOptions has a ws property but i dont think thats exactly what I am looking for, currently i just initialize the core version of Client with my custom gateway and rest

molten holly

hii, I don't use discord.js from months. Could I ask you if the problem of tag an user in an embed is fixed or sometimes show the id instead of the username

polar karma

that's just discord behavior, nothing related to the library. if the user is uncached in your USER client (the one viewing this message right now), it will show as the id because discord does not send the user data with the message payload

however, if you update to use components v2, the user data is sent with the message payload, and it will resolve normally

molten holly

okk thank you so much, but I have to use a specif component or just the EmbedBuilder is ok?

polar karma

components v2 is not compatible with embeds. a message can contain one or the other, but not both (along with some other mutually exclusive items)

molten holly

okok perfect, thank you again

inner cipher

for some reason I cant seem to resolve 4 low vurns, anyone that knows any fixes?

Ill have to downgrade my DJS, but that only results in more

polar karma

uhh... why are you not using the latest version of d.js? Thonk the undici vuln may have been resolved in a newer version, i forget exactly, but i do know that the undici vulnerability is not relevant to d.js, since the library doesn't use the affected part of unidici

inner cipher

I just updated to djs 14.19

modest marsh

Any idea why autocompletion in slash command always fails ("loading options failed")? I have less than 25 entries, the fields are always strings and even special (Unicode) characters are taken into account

Edit: got it working after intense debugging

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
red coral

We don’t know how your code works, so no we don’t know why

pliant forge

is it possible to check member's join timestamp when member leave a voice channel

hybrid olive

does SectionBuilder need a button or thumbnail?

zenith violet
hybrid olive
fast lion

is it possible to move the position of a single button in a button row?

e.g. put a single button in the 3rd slot and leave all others blank

loud quartz

there is no "slots" like that

it's just a row that takes up to 5 buttons

hybrid olive

you can use a section and an invisible unicode to bump it to the right

loud quartz

that's just using section

partially like intended

hybrid olive

yeah pretty much

loud quartz

but has nothign to do with action rows

fast lion

sweet will check that out. thanks.

pliant forge
inner cipher
polar karma

What sub versions are you talking about?

fast lion

is there a way to make the message send as silent when using components v2? with it pinging people in the containers i was curious

inner cipher

and yes its v14.9.3

sharp ginkgoBOT

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

{ ..., allowedMentions: { parse: ["users", "roles"] } }
fast lion

thanks!!

polar karma

Why is there 14.14.2-dev in there

Can you show the output of npm ls discord.js

inner cipher

it wants me to downgrade to 14.14.2

vestal sun

did you delete node_module folder and clean installed everything ?

echo hill

Help

türk varmı la

little pebble
molten holly

hii, is there a way to add a color on the ContainerBuilder of components v2?

sharp ginkgoBOT
sharp ginkgoBOT

Please add the following code to your code base outside of any other event listeners and provide the full log output relevant to your issue.

client
    .on("debug", console.log)
    .on("warn", console.log)
  • Note: if you initialize your Client as bot or other identifiers you need to use these instead of client
  • If the output is too long to post consider using a bin instead: gist | paste.gg | sourceb.in | hastebin
bleak owl
inner cipher

still the same issue, everything is gone w/o discord.js

snow onyx

just... ignore it?

inner cipher

so itsn othing to really worry ab ?

snow onyx

correct

"Applications that use undici to implement a webhook-like system are vulnerable. If the attacker set up a server with an invalid certificate, and they can force the application to call the webhook repeatedly, then they can cause a memory leak."

inner cipher

ahh

soft lance

How should I get the amount of attachments in a message? I thought of using message.attachments.map.length but it gives 2 even when there are none

rose tangle

um, there's no message.attachments.map (unless you meant you called that method)

snow onyx

message.attachments.size

rose tangle

message.attachments is a collection, which is a map by itself

soft lance
spring iron

What are the things I have to look for in a server member to see if they can add a bot to a server or not?

Can only server owners add bots or other users too?

zenith violet

anyone with the ManageGuild permission

spring iron

Thanks :D

loud plinth

Do anyone have a link to a github repository showing a "large-scale" usage of the modular discord.js 🤔

loud quartz

modular discord.js? you mean the subpackages themselves?

loud plinth

Yeah

Not the discord.js library itself, using the subpackages.

modest surge

Why is there is an catergory option in a channel option

loud quartz

because categories are channels

modest surge

how do u make "text" channels option

loud quartz

pass the channel types you want into the option builder

if you're using the builder

modest surge

nvm i found thx

do i use options.getChannel?

zenith violet
modest surge
sharp ginkgoBOT
modest surge

thanks

zenith violet

compare that to the member or user id

rose tangle
modest surge

can u make a slash command that is only visible to specific user

rose tangle
rose tangle
modest surge

ok how

"hide the command"

rose tangle

how which?

since there are two things I mentioned, to members with permission and to members with a role

modest surge

with a role

zenith violet

you as a dev cannot

modest surge

ok

zenith violet

well, you can, if you have the oauth2 token of the user but djs does not support oauth2

modest surge

ye i hate oauth2 a bot joined me on a 30 servers after i verify

rose tangle

well you gave it permissions to do so

oauth works with permissions (scopes)

you can make your app not require that permission to join other servers for you

modest surge

📩

how do u send this on a discord bot

zenith violet

just like you would for a regular, default emote

just :name:

modest surge

sure bro

zenith violet

how am i supposed to know you wanted in an embed?

i cant just smell it

sharp ginkgoBOT

Some parts of an embed will not properly resolve mentions (leave them in the @sharp ginkgo format):

  • Author name
  • Footer text
  • Embed title
  • Embed field name
zenith violet

same for emotes

modest surge

how do u get that emote id

zenith violet

default emotes do not have an id

sharp ginkgoBOT
zenith violet

seems like thats what youre after

assuming thats a button

or an embed

modest surge

is this normal button looks skinny

topaz bluff

Looks normal to me

You could try another button style if you don't like "secondary"

prime wren

forgot how to get user platform, hw can i?

sharp ginkgoBOT
prime wren

uh not that

zenith violet

then what do you mean by user platform

prime wren

message author/guild member platform

sharp ginkgoBOT

property Message#member discord.js@14.19.3
Represents the author of the message as a guild member. Only available if the message comes from a guild where the author is still a member

steel trail

wdym by platform?

bleak owl

maybe mobile or desktop

prime wren
prime wren
steel trail

They have presences too

clientStatus here refers to the discord client they use to chat. Not your bot client

sharp ginkgoBOT
radiant bough

Is there a text size in component V2 that is equal to the size of title text in embeds?

The ## sizing is bigger and i had hoped to get a bit closer to the embed sizing

copper lichen

Hello! How can I mention someone with my bot? like "@[username]"??

sharp ginkgoBOT
copper lichen
zenith violet

(or stringify the user/member object)

somber dome

hello

this.login(
process.env.token
).catch((err) => console.log(err));

not connecting, why?

zenith violet

and how have you determined

stable sun

Are you sure it’s even called?

zenith violet

are you listening to the ready event

did you log to see if it gets called at all

does your bot run at all

somber dome
zenith violet

and how did you determine it doesnt connect

somber dome

Mode of the Bot : Globaly Mode.
[Handler] Loading events...
[Handler] Events loaded.
[Handler] Loading commands...
[Handler] Commands loaded.
[Handler] Loading message commands...
[Handler] Message commands loaded.
(node:756) [DEP0040] DeprecationWarning: The punycode module is deprecated. Please use a userland alternative instead.
(Use node --trace-deprecation ... to show where the warning was created)
(node:756) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 interactionCreate listeners added to
[CustomClient]. Use emitter.setMaxListeners() to increase limit
[DataBase Redis] ﺕﺎﻧﺎﻴﺒﻟﺍ ﺓﺪﻋﺎﻗ ﻂﺑﺭ ﺡﺎﺠﻨﺑ ﻢﺗ
[DataBase MongoDB] ﺕﺎﻧﺎﻴﺒﻟﺍ ﺓﺪﻋﺎﻗ ﻂﺑﺭ ﺡﺎﺠﻨﺑ ﻢﺗ

zenith violet

so did you confirm your ready event is loaded

somber dome
export default class CustomClient extends Client implements ICustomClient {
  handler: Handler;
  commands: Collection<string, Command>;
  subcommands: Collection<string, SubCommand>;
  colldowns: Collection<string, Collection<string, number>>;
  devlopmentMode: boolean;
  redis: any;
  messagecommands: Collection<string, messagecommands>;
  messagecommandshorts!: Collection<string, messagecommandshorts>;
  polls: Map<string, Map<string, string>>;  // This will store the votes for each poll by message ID
  constructor() {
    super({
      intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.MessageContent,
        GatewayIntentBits.GuildMembers,
        GatewayIntentBits.GuildVoiceStates,
      ],
      partials: [],
    });
    this.redis;
    this.polls = new Map(); 
    this.handler = new Handler(this);
    this.commands = new Collection();
    this.subcommands = new Collection();
    this.colldowns = new Collection();
    this.devlopmentMode = process.argv.slice(2).includes("--devlopment");
    this.messagecommands = new Collection();
    this.messagecommandshorts = new Collection();
  }
  start(): void {
    console.log(
      `Mode of the Bot : ${this.devlopmentMode ? "Dev" : "Globaly"} Mode.`
    );
    this.LoadEvents();
    
    this.login(
      process.env.token
    ).catch((err) => console.log(err));
   
              }



              LoadEvents(): void {
  console.log("[Handler] Loading events...");
  this.handler.LoadEvents();
  console.log("[Handler] Events loaded.");
  
  console.log("[Handler] Loading commands...");
  this.handler.LoadCommands();
  console.log("[Handler] Commands loaded.");

  console.log("[Handler] Loading message commands...");
  this.handler.LoadMessageCommands();
  console.log("[Handler] Message commands loaded.");
}

  
}
zenith violet

also you only need 1 listener per event. Not 11

somber dome

"It doesn't even work on Discord."

radiant bough

the more the merrier /s

zenith violet
somber dome

The ready event wasn't triggered, and nothing related to it was logged in the console.

zenith violet

sounds like theres your issue then

if your ready event isnt loaded yes you wont get any confimation about your bot being online or not

somber dome

"I suddenly realized the bot is not connecting to Discord."

and not any errors in console

umbral jetty

Ainr

sharp ginkgoBOT

tag suggestion for @somber dome:
Please add the following code to your code base outside of any other event listeners and provide the full log output relevant to your issue.

client
    .on("debug", console.log)
    .on("warn", console.log)
  • Note: if you initialize your Client as bot or other identifiers you need to use these instead of client
  • If the output is too long to post consider using a bin instead: gist | paste.gg | sourceb.in | hastebin
somber dome

[Handler] Events loaded.
[Handler] Loading commands...
[Handler] Commands loaded.
[Handler] Loading message commands...
[Handler] Message commands loaded.
Provided token: MTE5ODY4NTE3Mzc2ODc5ODM4OQ.GOz-MV.**************************************
Preparing to connect to the gateway...
(node:6520) [DEP0040] DeprecationWarning: The punycode module is deprecated. Please use a userland alternative instead.
(Use node --trace-deprecation ... to show where the warning was created)
[DataBase Redis] ﺕﺎﻧﺎﻴﺒﻟﺍ ﺓﺪﻋﺎﻗ ﻂﺑﺭ ﺡﺎﺠﻨﺑ ﻢﺗ
[DataBase MongoDB] ﺕﺎﻧﺎﻴﺒﻟﺍ ﺓﺪﻋﺎﻗ ﻂﺑﺭ ﺡﺎﺠﻨﺑ ﻢﺗ

zenith violet

what host are you using

somber dome

vps windows

zenith violet

looks like youre cf banned

somber dome

!!!

why?

zenith violet

thats up to you to figure out

somber dome

"How do I unban? Is the ban only on the API?"

zenith violet

you wait

and figure out what caused

start by looking at your host

if you use free hosting, boom, you have your answer

somber dome

how do i unban

zenith violet

you wait

copper trail

anyone know where i can find info on creating and activiating listening events

more specifically on activitating them so it works

sharp ginkgoBOT

guide Creating Your Bot: Event handling
read more

copper trail

ty

fringe solstice

Does DiscordJS provide any interfaces for interacting with Discord through HTTPS rather than through the Websocket Gateway?

zenith violet

No

i mean you can use /rest

sharp ginkgoBOT

HTTP-only applications receive interactions through HTTP webhooks instead of the Discord Gateway. Bots that are not connected to the Gateway, but use HTTP interactions appear as online without a status. Discord.js does not support HTTP interactions. Use discord-interactions instead.

zenith violet

But also that

copper trail

if i wanted to create a new event would i create it as a sepreate file or import it into a index.js file

fringe solstice
zenith violet
copper trail

im gonna try again i think i understand what i did wrong

somber dome
zenith violet
nova pond

Hello, I'm testing the new version of ComponentsV2 and I'm encountering this error. Can you help me resolve it?

Code :

const { ApplicationCommandType, PermissionsBitField, Client, CommandInteraction, Colors, MessageFlags, ContainerBuilder, SectionBuilder, TextDisplayBuilder, SeparatorBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, } = require("discord.js");

const moment = require("moment");
moment.locale("fr");
const { QuickDB } = require("quick.db");
const db = new QuickDB();


module.exports = {
    name: "test",
    description: "📝・Permet de renvoyer les informations du bot",
    type: ApplicationCommandType.ChatInput,
    category: "Information",

    /**
     * @param {Client} client
     * @param {CommandInteraction} interaction
     */
    run: async (client, interaction) => {
        try {

            const section = new SectionBuilder()
                .addTextDisplayComponents(
                    new TextDisplayBuilder().setContent(
                        `Testing msg`

                    )
                )
                .setButtonAccessory([
                    new ButtonBuilder()
                        .setLabel("Invite Bot")
                        .setStyle(ButtonStyle.Link)
                        .setURL("https://google.com"),
                    new ButtonBuilder()
                        .setLabel("Support Server")
                        .setStyle(ButtonStyle.Link)
                        .setURL("https://google.com"),
                    new ButtonBuilder()
                        .setLabel("Documentation")
                        .setStyle(ButtonStyle.Link)
                        .setURL("https://google.com"),
                    new ButtonBuilder()
                        .setLabel("Top.gg")
                        .setStyle(ButtonStyle.Link)
                        .setURL("https://google.com")
                ]);

            const container = new ContainerBuilder()
                .addSectionComponents(section)
                .addSeparatorComponents(new SeparatorBuilder())
                .addTextDisplayComponents(
                    new TextDisplayBuilder().setContent("🔧 Ce message utilise Components V2 pour une interface enrichie.")
                )
                .setAccentColor(Colors.Blue)
                .setId(1);


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

        } catch (error) {
            console.error("An error occurred in the command [TEST]", error);
        }
    }
};

Error : js An error occurred in the command [TEST] RangeError: Non-premium buttons must have a label and/or an emoji. at validateRequiredButtonParameters (C:\Users\Teck Génération\Desktop\Bad-Protect\node_modules\@discordjs\builders\dist\index.js:575:13) at ButtonBuilder.toJSON (C:\Users\Teck Génération\Desktop\Bad-Protect\node_modules\@discordjs\builders\dist\index.js:739:5) at SectionBuilder.toJSON (C:\Users\Teck Génération\Desktop\Bad-Protect\node_modules\@discordjs\builders\dist\index.js:2169:59) at C:\Users\Teck Génération\Desktop\Bad-Protect\node_modules\@discordjs\builders\dist\index.js:1870:64 at Array.map (<anonymous>) at ContainerBuilder.toJSON (C:\Users\Teck Génération\Desktop\Bad-Protect\node_modules\@discordjs\builders\dist\index.js:1870:35) at C:\Users\Teck Génération\Desktop\Bad-Protect\node_modules\discord.js\src\structures\MessagePayload.js:151:46 at Array.map (<anonymous>) at MessagePayload.resolveBody (C:\Users\Teck Génération\Desktop\Bad-Protect\node_modules\discord.js\src\structures\MessagePayload.js:150:49) at ChatInputCommandInteraction.reply (C:\Users\Teck Génération\Desktop\Bad-Protect\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:192:56)

topaz bluff

Common misunderstanding. A Section in ComponentsV2 is a very specific things. It's a TextDisplay with an inline Button or Thumbnail. No more, and no less

rose tangle

ask discord

they designed embeds that way

if you want more control over the layout you can switch to v2 components instead of embeds

though inline fields aren't a thing there

rose tangle

I'm pretty sure they should be the same size as in an embed?

topaz bluff

Ya, other than the tiny images in the Author and Footer field of an Embed, the images should be exactly the same in Components

uneven plover

Is it possible to send an ephermeral message with v2 components? I tired an arary, but get an interaction error.

halcyon bison

you can
what error are you receiving?

uneven plover
sharp ginkgoBOT

tag suggestion for @uneven plover:
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
uneven plover

Yeah, I get all that, but here is the thing...

flags: MessageFlags.IsComponentsV2 no error
flags: [MessageFlags.IsComponentsV2, MessageFlags.Ephemeral] Unknown interaction

halcyon bison

that is strange, but that definitely wouldn't be the exact cause
I assume that isn't the only change and that you're also adding components to the message, correct?
is it possible the creation of the components is causing your bot to respond slightly late?

uneven plover

It is very strange. The only thing I can think of is that I am not doing the flags correctly. I am not real clear on bitfields.

halcyon bison

what you have is fine, and it wouldn't cause this issue
if you're really sure that you aren't doing anything that could cause the response to be late, care to share more of your code?

uneven plover

Well doing some digging, and based on some Copiolt suggestions this works...

flags: MessageFlags.IsComponentsV2 | MessageFlags.Ephemeral

I have no clue what that is doing, so I gotta go study

sharp ginkgoBOT

mdn Bitwise OR (|)
The bitwise OR (|) operator returns a number or BigInt whose binary representation has a 1 in each bit position for which the corresponding bits of either or both operands are 1.

uneven plover

Thank you!

rose tangle

either should work tbh

maybe you have a race condition

so it sometimes work, and sometimes doesn't

but it's unrelated to using [] or |

uneven plover

Hmm, interesting. I will play with it. And see what I can figgure out.

sharp ginkgoBOT

guide Slash Commands: Command response methods
read more

guide Message Components: Component interactions - Responding to component interactions
read more

unique shoal

This details all the differences

unique shoal

If you deferUpdate you should then use editReply

Bit confusing I know

fading girder

for slash command localization, if I set,

    .setName('dog')
    .setNameLocalizations({
        pl: 'pies',
        de: 'hund',
    })```

will I receive the command as `/dog` or as the name localization
unique shoal

It depends on your localisation

If your locale is pl or de you should get those

fading girder
unique shoal

oh, english

inland sapphire

anyone else getting these error on there disc bot? button related


DiscordAPIError[40060]: Interaction has already been acknowledged.```
cobalt tree

Is D.js fully stable with Components V2?

snow onyx

yes

last prism

Hello, is there a way to retrieve the tag of a server? Anyway, let me explain, I would like to make a bot that allows you to know with a /start if the server is a guildtag or not and if so specify the name of the tag, I searched a little in discord js but I didn't find anything

steel trail

guild tags are not documented by discord yet, as they are still experimental. so no, not with discord.js yet

last prism

okayyy tysm

zenith violet
echo hill

Help me

Türk yokmu yaw

snow onyx

keep it english

echo hill

Are there no Turks?

snow onyx

Does it matter?
This server is english only, if you need support in turkish you'll need to find a server that offers that.

echo hill

Anyway. I am making an entry and exit system and it always gives an error or the message never comes.

Handing

Can you help me?

snow onyx

With entry and exist system you mean guild members joining/leaving the server?

echo hill

I don't know, I installed it a few days ago, DJS always gives me chatgpt codes.

snow onyx

If you dont know what kind of sytem you are building I can't help you

echo hill

I am setting up an entry and exit system and that handling

I have a lot of commands working and now the only thing that doesn't work is the input and output system.

Help me please

snow onyx

You will need to provide way more information than that, and also relevant code.

echo hill

No sample commands

inland sapphire
nova pond
snow onyx

you dont

nova pond
snow onyx you dont

Yes, because I saw a bot doing an embed and there were buttons on the right side.

snow onyx

those are a lot of sections with a button

its automatically aligned to the right

nova pond
snow onyx

Then... do so?
Add a lot of sections.

sharp ginkgoBOT

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

nova pond
nova pond

Thanks you

covert vine

when i try to rest.put() my commands, it doesnt work even though the response is ok, then when i try to run the old commands, this happens

polar karma

Refresh your user client (the one you're reading this with)

covert vine

ok aight thats what i thought the issue was, its annoying to do though

polar karma

Ctrl + r is annoying?

covert vine
snow onyx

you only need to do this when you remove/add a command
not when you change behaviour of a command

covert vine

wheres the @ ping attribute or something

snow onyx

the what?

rose tangle

you can't get a user's ping

wary coral
sharp ginkgoBOT

method User#toString() discord.js@14.19.3
When concatenated with a string, this automatically returns the user's mention instead of the User object.


// Logs: Hello from @remote siren!
console.log(`Hello from ${user}!`);

rose tangle

to set/clear the button's id

which is a property added since v2 components, and present on every component

its purpose is clearer with non interactive components, to identify them on the message

since those don't have a customId

winter merlin

Oh! I understand now, thank you!

smoky grail

What should I do? I'm on discord.js version 14.19.3 but it has 4 low severity vulnerabilities and one is a denial of service(DoS) attack via bad certificate data.

snow onyx

ignore them

they are all the same vulnerability and not relevant for djs

smoky grail

Okay

Do you know if they will be fixed in a later update?

rose tangle

it's not an issue that requires to be addressed

like Octobacca said the code is not used at all

so maybe but such an update would probably be unrelated to that issue

cobalt tree

Hello! how can i set the bot profile as thumbnail without using URL?

snow onyx

client.user.displayAvatarURL()

queen roost
cobalt tree

since embed can use .setThumbnail(interaction.client.user.displayAvatarURL())
can i use that in container too? using sectionBuilder??

snow onyx
queen roost
cobalt tree

I'm confused, i got error on my code. On the picture i sent, how can i implement that?

snow onyx

show the error?

wait, no

you still use a thumbnail builder with the seturl method

cobalt tree

do i need to add
.setThumbnail(interaction.client.user.displayAvatarURL())

Under ```const thumbnail = new ThumbnailBuilder()

snow onyx

no, setURL() not setThumbnail()

snow onyx
cobalt tree

wait lemme try

snow onyx

yes, that makes sense

you need to build the thumbnail before using it

cobalt tree
snow onyx

no thats absolutely not what I said

cobalt tree

Error in interactionCreate: TypeError: (intermediate value).setThumbnail is not a function

snow onyx

yes, I told you to use setURL

sharp ginkgoBOT
cobalt tree
snow onyx

its setThumbnailAccessory not addThumbnailComponents

cobalt tree
queen roost

hope they add but you can get it from message.member.primary_guild.tag, am i true?

wary coral
queen roost
wary coral

sure but it wont be added to djs till it is added to the docs

polar karma

you can make a request via /rest (or another method) to get the raw user object from the api, but it won't be in mainlib until discord documents it

barren nacelle

is there an open PR in the discord-api-docs for that guild tags data at all?

barren nacelle
pearl hazel

could this error trigger with message.delete() ?

DiscordAPIError[10008]: Unknown Message
    at handleErrors (/root/100/131/node_modules/@discordjs/rest/dist/index.js:727:13)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async SequentialHandler.runRequest (/root/100/131/node_modules/@discordjs/rest/dist/index.js:1128:23)
    at async SequentialHandler.queueRequest (/root/100/131/node_modules/@discordjs/rest/dist/index.js:959:14)
    at async _REST.request (/root/100/131/node_modules/@discordjs/rest/dist/index.js:1272:22)
    at async GuildMessageManager._fetchSingle (/root/100/131/node_modules/discord.js/src/managers/MessageManager.js:107:18) {
  requestBody: { files: undefined, json: undefined },
  rawError: { message: 'Unknown Message', code: 10008 },
  code: 10008,
  status: 404,
  method: 'GET',
  url: 'https://discord.com/api/v10/channels/1263418623351848991/messages/1378016839606472836'
}

red coral

Sure

pearl hazel

cause i'm sure that i put delete().catch(() =>null); with every message.delete call

wary coral

No? but are you fetching the message after you delete it

snow onyx

yeah thats a fetch request

red coral

Oh yes mb

pearl hazel

so it's only trigger with fetch ? so i will check ever fetch request to see what i miss

wary coral
red coral

Yes

red coral

If it helps you also don’t await it either which means you don’t get the stack trace

pearl hazel

yes i find it i have fetch request without catch ty all

late pelican

If someone might find it usefull. Not official yet but here's how I obtained clan tag from user profile if its going to help someone for now. Discord might change it later.

const data = await client.rest.get(
 `/guilds/${GUILD_ID}/members/${USER_ID}`
);
"clan": {
  "identity_guild_id": "someguildid",
  "identity_enabled": true,
  "tag": "SLVA",
  "badge": "4c7a2167ae0a7b03c69e1419197cf704"
},
"primary_guild": {
  "identity_guild_id": "someguildid",
  "identity_enabled": true,
  "tag": "SLVA",
  "badge": "4c7a2167ae0a7b03c69e1419197cf704"
}
sharp ginkgoBOT

discord.js does not support features until they are officially documented.
While there might be a way for these features to work, it can change at any time without any notice

thorn gate

can i create multiple events file like two messageCreate events files for different events

topaz bluff

You can but it's not recommended. You should instead, have 1 event listener and then filter the messages to do different things

thorn gate

ok ty

agile nest

whats the difference between on() and once()

sharp ginkgoBOT
topaz bluff

Exactly what it says. Once runs once. On runs indefinitely

agile nest

so ready is once and messageCreate is on for example?

topaz bluff

In general practice, yes. Because ready really only fires once so no need to waste memory listening for an event that'll never happen again. And typically if you want to listen to created messages, you want to do that more than once

You could use once or on for either as they both work on the same events. It's just how you use the listeners

But generally speaking, you will use on for everything other than ready

rigid crest

im missing something or i didnt need to unclude URL for the message? await interaction.editReply({ content: Creating giveaway... (${giveawayMessage.url}), flags: MessageFlags.Ephemeral }).catch(console.error);

nvm it may be on me i used the wrong caller im using giveawayID instead of message i switched it as was easier for me

yes it was on me for that

loud plinth

Hey, quick help. How do I check if an APIInteractionGuildMember has a permission like Administrator? member.permissions.includes(...) throws a bigint error.

polar karma

are you using /core or mainlib?

loud plinth

mainlib

polar karma

you should be typeguarding your interaction so ts knows where the interaction is coming from (and should give you a full GuildMember) unless this is a user app?

sharp ginkgoBOT
loud plinth

Right now I tried this, but member.permissions is a string

(member.permissions.includes(PermissionsBitField.Flags.Administrator)
polar karma

which even if it's a user app (and the guild is uncached), that should work

again - what is the context of the command? regular command, user app, what

loud plinth

Regular command.

polar karma

then you need to typeguard your interaction

sharp ginkgoBOT
polar karma

that will narrow down the type for ts, so it knows you have a full GuildMember object and member.permissions will be the full permissions bitfield

half rover

Is there a method like ContainerBuilder.from()

loud plinth

Alright. I'll take a look.
Thank you.

half rover
steel trail
toxic moat

if(Interaction.member.has(PermissionBitField.Flags.Administrator)) {}

zenith violet

that wasnt their issue

And they were answered

Nor is that code correct

vast frigate

I feel like I'm losing my marbles here:

async function editIntroPost(member: GuildMember, guild: Guild, message: Message) {
    try {
        const webhook = await getIntroWebhookClient();

    

        const payload = await getIntroMessagePayload(member, guild);


        console.log(message);

        console.log("isMessageInstance --------> ", isMessageInstance(message))

        if (!message.inGuild()) throw new CustomError("Message attempting to be edited is not in guild.", ErrorType.Error);
        await webhook.editMessage(message, payload as WebhookMessageEditOptions)
    } catch (err) {
        throw err;
    }
}

like, it exists, it's a message instance, and it's in the guild

so why am I getting unknown message 😭

zenith violet

show the full code (including your custom functions) in a pastebin

vast frigate

alright

debugSync.ts is the command file, it just calls into the syncIntroPost method within intro.ts

webhook.ts is where I initialize the webhook client

and then intro.ts has the methods doing the meat of the operations

I just don't get how it's possible that I check if it exists (yes ✅ ), if it isMessageInstance (yes ✅ ), and it is inGuild (yes ✅ ) and then get the unknown message error 😭

in case it was maybe reporting the wrong error via my custom handling, I replaced my handling with a standard console.error

could this be a sapphire.js issue?

rigid ridgeBOT
shadow pier

Will this be added in v14 as well? ⬆️

true tree

quick question - with components v2 how do i get the components in an interaction when im using a collector?

keen jungle

Is the new version V14 or V15?

dense jackal
dense jackal
errant inlet

who can help me

im doing music bot with lavalink

clear garnet

I'm going to wager and say no one due to the ToS violation that Lavalink imposes

vast frigate

doesn't look unknown to me

am I hitting some kind of weird edge case?

red coral

I swear djs has an emoji regex somewhere to match custom emojis but I can’t find it

Nvm it's just FormattingPatterns.emoji

pearl hazel

i'm working on ticket bot but it seem that it send too many request for permissions edit
like adding admins roles and remove it after close is it wrong to use permissionOverwrites.set() ?

or it's a natural thing and the bot will not get limited

vast frigate

it's better to create a new WebhookMessageEditOptions and set the fields I have manually. Wasted like 2 hours on this

and now I have to go to work 😭

I was hoping to finish this feature before work, but I guess not, dang

zenith violet
pearl hazel

ig it's just natural no way i can avoid this

zenith violet

not setting them after

you can directly pass them in the create call

pearl hazel

but pass it with the create will make it lighter ig i will try

zenith violet
steel yacht

Hi,
Why can't the delete method be used on the Message object returned by followUp from a CommandInteraction object but only the deleteReply method from the CommandInteraction object itself ?

unique shoal

Is it ephemeral?

steel yacht

Yes
(And thank you for replying fast, the slowmode is making it so hard to reply back as fast 😭)

zenith violet

ephemeral messages can only be deleted through the interaction webhook

steel yacht

Okay, is there any way to get back there from the Message object returned by followUp ?

zenith violet

no

pliant forge
client.on("interactionCreate", async (interaction) => {
    if (!interaction.isStringSelectMenu() || !interaction.customId?.startsWith('message-settings')) return;
    await interaction.deferReply({ ephemeral: true })

    const user = interaction.customId.split('.')[1]

    let guildData = await guildSchema.findOne({ guild: interaction.guild.id })
    if (!guildData) guildData = await guildSchema.create({ guild: interaction.guild.id })
    if (interaction.user.id !== user) return interaction.editReply({ ephemeral: true, content: '' + client.getLanguageString({ language: guildData.language, key: "notYourMenu", variables: { user: user } }) })


    const hasPermission = await checkPermissions(interaction, 1, guildData);
    if (!hasPermission) return;

    let g = interaction.values[0].split('-')[3]
    let get = g.split('.')[0]
    if (get === 'blockedchannels') {

        const menu = new Discord.ChannelSelectMenuBuilder()
            .setCustomId('message-blockedchannels-editx.' + interaction.user.id)
            .setPlaceholder(client.getLanguageString({ language: guildData.language, key: "SYSTEM-MESSAGE-PICKBLOCKCHANNEL" }))
            .setMaxValues(1)
        const menurow = new Discord.ActionRowBuilder().addComponents(menu)

        return interaction.editReply({
            content: ' ',
            ephemeral: true,
            components: [menurow]
        })

    }

})```

But it says Unknown Interactin, whats wrong?
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
pliant forge

Yeah it doesn't take 3 seconds. And its true interaction im pretty sure

zenith violet

it either does, or you have duplicate listeners

if that is the actuall full code, thats likely your issue

you should have only 1 listener per event

pliant forge

i have very much interactionCreate event but i filter them like

    if (!interaction.isStringSelectMenu() || !interaction.customId?.startsWith('message-settings')) return;
zenith violet

also, editReply doesnt take ephemeral, and itrs deprecated

zenith violet

you only need 1

or else this happens

pliant forge

Oh

So i need to put all in one with filters for like these things?

zenith violet

yes

and preferably have a handler per component type

not just cram it into a single file

pliant forge

Thank you i didn't know it

steel yacht
zenith violet no

Okay, is there any way to automatically delete a message when a timeout is reached on awaitMessageComponent ?

zenith violet

the promise will reject after the time expires

pliant forge

Tysm have a nice one

zenith violet

so if you catch that rejection, you can edit it

steel yacht
pliant forge

one for handlers, one for these things

zenith violet
zenith violet
steel yacht
sharp ginkgoBOT

documentation suggestion for @steel yacht:
method ButtonInteraction#deleteReply() discord.js@14.19.3
Deletes a reply to this interaction.


// Delete the initial reply to this interaction
interaction.deleteReply()
  .then(console.log)
  .catch(console.error);

zenith violet

you can pass in the message to delete

steel yacht

Which object has a deleteReply method ?

pliant forge

uhm f my english so sorry but im asking for like
one page for interactionCommandHandler which knows if its a command and one for these things

pliant forge
steel yacht

What do I put before the dot ?

pliant forge

interaction ?

zenith violet
steel yacht

So, not the Message object I was talking about

zenith violet

you need an interaction webhook to delete an ephemeral message

as you were told

pliant forge
sharp ginkgoBOT

guide Creating Your Bot: Command handling
read more

zenith violet

you can use a similar approach for buttons and other components

steel yacht

So, to recap : I call await Message.awaitMessageComponent, then in the catch, what can I do ?

steel yacht

I have a Message, not a ButtonInteraction

pliant forge

Ig i can not explain myself
i am asking for using client.on('interactionCreate') twice

pliant forge
zenith violet
steel yacht
pliant forge
zenith violet

any reply can using withResponse

pliant forge

Oh yeah my bad, and thank you for your help

zenith violet
steel yacht
                                             // ⬐ Here
await onInput(await commandInteraction.followUp())
```And here's `onInput` :
```ts
async (
    parent:
        Message |
        MessageComponentInteraction |
        InteractionResponse |
        InteractionCallbackResponse
): Promise<AnySelectMenuInteraction | ButtonInteraction> => new Promise(async resolve => {
    let _parent: Message | InteractionResponse, userId: string;
    if(parent instanceof Message){
        _parent = parent;
        userId = parent.interactionMetadata!.user.id;
    }
    if(parent instanceof MessageComponentInteraction){
        _parent = parent.message;
        userId = parent.user.id;
    }
    if(parent instanceof InteractionResponse){
        _parent = parent;
        userId = parent.interaction.user.id;
    }
    if(parent instanceof InteractionCallbackResponse){
        _parent = parent.resource!.message!;
        userId = parent.resource!.message!.interactionMetadata!.user.id;
    }
    try {
        resolve(await _parent!.awaitMessageComponent({
            filter: interaction => interaction.user.id === userId,
            time: 5 * 60 * 1000
        }));
    }
    catch {
        // TODO: delete
    }
})
zenith violet

boom theres your interaction

steel yacht

Where ?

zenith violet

did you write that code yourself

steel yacht

Yes, but I don't have access to it in that catch scope

zenith violet

Then youre gonna have to find a way to pass it in if you want to delete your message

steel yacht

So, I'm asking, what's the proper way to delete in the catch scope of awaitMessageComponent ?

sharp ginkgoBOT
zenith violet

same answer as before

and it will remain the same answer

steel yacht

So, deleting an expired awaitMessageComponent requires a variable outside of its own scope ? 😭

zenith violet

you need an interaction webhook

zenith violet

Nothing djs can do about

steel yacht
steel yacht
zenith violet

thats not quite how any of this works

djs is an api wrapper

what the api returns is what djs returns

in this case a Message

if you had a non ephemeral message you could call .delete just fine

steel yacht

Okay, what about the opposite then ?
Could I call awaitMessageComponent from CommandInteraction ?

zenith violet

Only on a Message (or InteractionResponse, but thats broken more often than not)

steel yacht

Could I get the Message object from the CommandInteraction object ?

zenith violet

depends on whether its a ChatInputCommandInteraction or a context menu command interaction

steel yacht

There's a replied property on it, so the reply should be somewhere

spark hare

How can I add multiple button accessories in sections?

zenith violet

a ChatInput does not have a message property, so no

zenith violet
spark hare

fair

steel yacht
zenith violet

same answer

there is no message property

steel yacht

How can there be a replied property then ?

unique shoal

To record that it was replied to

zenith violet

check the source code

im done here

unique shoal

But you can reply with a defer, or other things

Arguing the point when you're told the answer is pointless

zenith violet

you have your answer, i dont see why you keep trying to change the fact you need the webhook to delete an ephemeral message

steel yacht

I'm just trying to understand why it has been made so difficult

loud quartz

what was made so difficult

steel yacht

Managing interactions

unique shoal

Its really not very difficult - you should really do everything via the webhook, as it was designed by Discord

loud quartz

because interactions are done with webhooks

that sometimes might leave a regular message that your bot user might have access to

zenith violet

you not having access to the interaction webhook in your code is a you issue

its nothing djs can do about

unique shoal

It's really coincidental that for proper messages, bots can delete them due to unrelated message deletion functionality, if your bot has those permissions in a server

But for ephemerals, since they use a completely different architecture, you MUST use the webhook

steel yacht
unique shoal

It kinda sounds like youve done the opposite

steel yacht

Really ? Because what I've done is make a universal function to call awaitMessageComponent. That has been very much simplifying my dev experience

loud quartz
unique shoal

Actually yeah thats true, lots more places than there used to be

cobalt tree

Hi! is the button interaction to show modals on Container is supported?

loud quartz

why wouldn't it be?

interaction is interaction. only thing matters is the button, doesnt' matter where have you placed it

cobalt tree

Ohh okay thank you!

trim elm

Under what conditions would discord obviously be ratelimiting an endpoint but not triggering the rateLimited event from REST?

fallen trellis

like its already explained with Types of mentions to be parsed but i still don't understand it

trim elm
fallen trellis

thank you

trim elm

No worries

trim elm
radiant jewel

I'm trying to embed an audio player in a componentsV2 container, just like discussed here https://discord.com/channels/222078108977594368/1367967621068357643
However, it doesn't embed a player. I've tried OGG, WAV and MP3. The file served works okay and even embeds when re-uploaded. Discord.js 14.19.3; NodeJS 22.12
What's wrong?

const container = new djs.ContainerBuilder();

const audioPath = bot.features.dialog.getAudioPath(dialogLine);
const audioData = await readFile(audioPath);
const audioAttachment = new djs.AttachmentBuilder(Buffer.from(audioData), { name: 'test.ogg' });

const file = new djs.FileBuilder().setURL('attachment://test.ogg');
container.addFileComponents(file);

return {
    components: [container],
    files: [audioAttachment],
    flags: djs.MessageFlags.IsComponentsV2,
} as djs.BaseMessageOptions;```
rose tangle

file components don't support the preview

same for text files

there's no workaround other than not using v2 components

rose tangle
rose tangle

yeah maybe they aren't aware of that

trim elm
rose tangle define "obviously be ratelimiting"

For example editing the same message over and over 5 times the 4th and 5th edits are 5s apart roughly, which is the retryAfter duration. The rateLimited event from rest doesn't go off anymore (anymore meaning last ~3 days)

(was only doing this to find the problem, not production code)

radiant jewel

Can embeds hold audio players? Having a hard time finding info about this

topaz bluff
radiant jewel

Alright, so, the only way is just send the file/buffer

rose tangle

yeah, as a regular file

it'll appear outside the embed

below iirc

radiant jewel

Ohh, but like, in the same message? I didn't know that was possible

topaz bluff
rose tangle

only with v2 components you can only send components

or files, but must be referred in a component

so essentially just components

red coral

Hey, I'm struggling with trying to disabled buttons from comp v2:

 const components = interaction.message.components;
            const actionRow = components.find((comp) => comp.type === ComponentType.ActionRow);
            if(!actionRow) return await interaction.reply({
                content: "No action row was found. Please report to gwapes",
                flags: "Ephemeral"
            });
            const newRow = ActionRowBuilder.from(actionRow);

            newRow.components
                .filter((comp) => comp.data.type === ComponentType.Button)
                .forEach((comp) => comp)

The forEach comp is still AnyComponentBuilder. The buttons are the ones outside of the main container

rose tangle

use the generic

red coral

Oh in the action row?

sharp ginkgoBOT

In TypeScript the ActionRowBuilder class has a generic type parameter that specifies the type of component the action row holds:

const row = new ActionRowBuilder<ButtonBuilder>().addComponents(button)
const row = new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(selectMenu)
const row = new ActionRowBuilder<TextInputBuilder>().addComponents(textInput)
rose tangle

yep

I don't think the .type narrows it

might be wrong though

red coral

Then I get this, would I need to as ... it, since I know they're going to be buttons?

rose tangle

yeah

radiant jewel
red coral

do yk what I'll be as'ing it as by any chance?

topaz bluff

Amgelo knows more than I about this, they did most of the helping

But if you have any issues, feel free to ask

rose tangle

something like ActionRow<ButtonComponent> I think

red coral

yes that's it, thanks a lot man

const components = interaction.message.components;
const actionRow = components.find((comp) => comp.type === ComponentType.ActionRow);
if(!actionRow) return await interaction.reply({
    content: "No action row was found. Please report to gwapes",
    flags: "Ephemeral"
});
const newRow = ActionRowBuilder.from<ButtonBuilder>(actionRow as ActionRow<ButtonComponent>);

newRow.components.forEach((comp) => comp.setDisabled(true));

How would I then rebuild the entire comp v2 container etc? I'm guessing it's something to do with the components const but not too sure

Also, is the guide done yet for v2 comp? Does it cover this?

wary coral
red coral

component being components[0]?

wary coral

yes

topaz bluff
red coral

Thanks everyone, managed to get it working 🙏

limpid sage

Is there a way to take a defined new SlashCommandBuilder() and parse a JSON http body? When working in deno/cloudflare I don't have the advantage of the bot-client. I would like to maintain as much strong typing as possible.

red coral

Those are only for deploying though? But you'd have to parse the json body yourself by calling each function

limpid sage

Thats a shame, I was hoping there was a way to define the slash command once for deploying and parsing

red coral

Could just do it locally rather then on your worker, since commands only need to be deployed once you've changed something. You could also just use a type and pass json itself rather then using a builder

limpid sage

Oh, yeah I dont need to deploy the commands from the worker. Sorry if I was unclear.

I want to be able to parse the HttpBody with the same typescript types that the InteractionCreate handler uses.

red coral

Djs doesn't work on workers as I'm sure you'd know anyway. If you wanted some better types then look at discord-interactions which works as an entire library. If you don't want all that, then you would have to make your classes using discord-api-types/v10

limpid sage

Right, Im not trying to use the bot client on workers. The bot client is handy for deploying commands, and for local debugging. Eventually though, I will deploy the real handlers to cloudflare workers. This is all working fine, but I have a bunch of parsing that feels duplicative since I know the interaction handler does the same parsing from the same input. I was just hoping to re-use what appear to be djs internals.

rose tangle

yeah the builders actually build to raw rest data

which is how the deploy script works

maybe you can get an idea from there

sharp ginkgoBOT

guide Creating Your Bot: Registering slash commands
read more

limpid sage

Thats going from SlashCommandBuilder to JSON. I want to go from JSON (the APIInteraction body on the incoming http request for interaction handling) to a parsed Interaction.

rose tangle

ah, I misunderstood, my bad, so you're making an http only bot?

limpid sage

Yes

red coral

Again you kinda have to make those classes yourself. Unless you use a lib like discord-interactions. You can copy and paste and modify the code from the source code for djs though

limpid sage

I don't think discord-interactions helps with this, unless I am missing something. It only has the very top level InteractionType, it doesn't help with parsing options or subcommands

red coral

It does, but you can just copy djs implementations if you want

rose tangle

you can try the @sapphire/discord-utilities package

it provides an interaction option resolver similar to djs'

which is made to accept raw api data

crystal imp

How do I get the total individual users using the bot

cobalt tree

hello! since container is different from embed and about the media gallery, is it possible to use the embed resizer on container? because when adding image url the image is pretty big.

rose tangle
crystal imp

adding it to your apps

rose tangle
crystal imp
sharp ginkgoBOT
rose tangle

you get the ClientApplication via client.application

crystal imp

alr thanks

cobalt tree
sharp ginkgoBOT

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

topaz bluff

arent you just talking about the mediagallery? the container should form to fit the image supplied

trim elm
topaz bluff So if the rareLimited event isn't going off, why do you think you're being rate ...

I've made a test script to force a ratelimit to test my handlers, so I've ran that again and magically they don't even fire, but I can physically see discords ratelimiting. I'm aware that it's not static hence why I'm using the event than a set limit.
My problem is why the events aren't firing anymore. No code was changed at all it's still:

// Not the full logic example, but good enough for you to understand

client.rest.on("rateLimited", (info) =>{console.error(info)})
calm maple

not sure if this is a stupid question, but with messages v2 is it possible to have multiple accessories? ie, a button and an image? i want to recreate https://www.youtube.com/watch?v=GVeIqO0pGE4 without using emojis for the pokemon sprites on the left; is there any way to accomplish this? (or something similar)

wary coral
calm maple

hm alright

fading girder

Hey! Is there any way to get the user’s locale Timezone from an interaction?

bleak owl

nope

fading girder

That’s unfortunate

trim elm
rigid crest

is there a limit on how many buttons are allowed inside a component?
im struggling to use masked links why is it adding this god awful space? heres what im using if someone can help fix this spacing

                const messageText = [
                    `## Search results for "${query}"`,
                    results && results.length
                        ? results.map(item => `**${item.title}**\n[Visit page: ${item.name}](${item.link})`).join('\n\n') // Adds spacing
                        : 'No results found.'

                ].join('\n');

the spacing being the massive gap from each white text section, it just gets worse dead

rigid crest

so i added ## it managed to fixed the text section but split level the link to look
like
this

steel trail

Do your item.title contain those spaces in them maybe?

rigid crest

im pulling directly from fandom wiki so could that be the reason to the masked links acting how its acting?

ok after looking at the caller from the fandom function it was indeed that

analog oak

how to check if a channel is a category or not?

ember crest
sharp ginkgoBOT
graceful plinth

This error is breaking my whole bot, I am getting Error [ERR_IPC_CHANNEL_CLOSED]: Channel Closed (and some other stuff in the error but doesn't seem to important) a bunch, like all the time. My bot is in over 4000 servers and this only just started happening as it hit 4000 server, if anyone has a quick fix please lmk asap.

wary coral
graceful plinth
sharp ginkgoBOT

guide Sharding: Getting started - How does sharding work?
read more

graceful plinth

but thats too all i know about the error

graceful plinth
steel trail
graceful plinth
steel trail

The error means one of your child processes (shards) lost contact to the ShardingManager

graceful plinth
rancid shoal

Line 3 says cannot access channel before initialization but if you were to consoel.log() channel the data shows just fine. Yet the error shows the wrong stack trace and says that channel isn't defined.

for (const channel of GuildChannels) {
  for (const overwrite of channel.permissionOverwrites.cache.values()) {
    const channelId = channel.id;
                   // ^^^

I did not check if channel.permissionOverwrites is empty, but the internal iterator tries to read non-exstitant data... ig djs forgot to create the interable flag when creating the class.

graceful plinth
steel trail
steel trail
steel trail

That's djs code and still not your error

graceful plinth
steel trail Two questions: - can you show your sharding manager file - are you sure your pi...
import {
    ShardingManager,
    fetchRecommendedShardCount
} from 'discord.js';

import {
    monitorItemsLoop,
    monitorEggsLoop,
    monitorCosmeticsLoop,
    monitorWeatherLoop
} from './utils/monitor.js';
import {
    checkConfigs
} from './utils/config.js';

const token = 'token';

const recommended = await fetchRecommendedShardCount(token);
const customShardCount = recommended * 2;

const manager = new ShardingManager('./bot.js', {
    token: token,
    totalShards: customShardCount
});

manager.on('shardCreate', shard => console.log(`Launched shard: ${shard.id}`));

manager.spawn();

monitorItemsLoop(manager).catch(error => {
    console.error(`[MONITORING ERROR] Failed to start item monitoring loop:`, error);
});

monitorEggsLoop(manager).catch(error => {
    console.error(`[MONITORING ERROR] Failed to start egg monitoring loop:`, error);
});

monitorCosmeticsLoop(manager).catch(error => {
    console.error(`[MONITORING ERROR] Failed to start cosmetics monitoring loop:`, error);
});

monitorWeatherLoop(manager).catch(error => {
    console.error(`[MONITORING ERROR] Failed to start weather monitoring loop:`, error);
});

setTimeout(async () => {
    await checkConfigs(manager).catch(error => {
        console.error(`[CONFIG ERROR] Failed to check configs:`, error);
    });
}, 15000);```

I know my network can handle it, I get like 600-800 MBPS speeds, not 100% sure if my pi can
steel trail

Any reason why you spawn twice as many shards as recommended?

And do those two utils files import any of your other bot files? Maybe indirectly even your client file?

rancid shoal
steel trail
graceful plinth
graceful plinth
sharp ginkgoBOT
steel trail
graceful plinth
steel trail No it's not

Idk, just seemed to take less time when more shards, it needs to send the messages as close to xx:x5/xx:x0 as possible

unkempt thistle

im trying to set the context of a command.

.setContexts(InteractionContextType.Guild)

but it is also appearing in the DM's. Could it be cache?

(i didn't work alot with discord.js lately lol)

steel yacht

Hi,
Why don't DiscordAPIError errors show a stacktrace within my own code but only within node_modules ?

jaunty urchin

how can i make bot do thread

steel trail
steel yacht

you either don't await the call causing it
Nope, it's not uncaught.
or have set the max stacktrace length too low
I have set no such value so it must be default, how to increase it ?

jaunty urchin
wary coral
sharp ginkgoBOT

node Error.stackTraceLimit
The Error.stackTraceLimit property specifies the number of stack frames collected by a stack trace (whether generated by new Error().stack or Error.captureStackTrace(obj)).The default value is 10 but may be set to any valid JavaScript number.

wary coral

@jaunty urchin ⬆️

jaunty urchin

❤️

steel trail
unkempt thistle

is it possible to set a normal slash-command in a normal discord bot for a discord server only to be visible in dm's?

wary coral
unkempt thistle
wary coral

You can set the context for the command to dm. but I dont think that is limit uses from using it if they leave the server so you will still what to check

sharp ginkgoBOT
wary coral

To set a command to be in server and bot DM
.setContexts(InteractionContextType.Guild, InteractionContextType.BotDM)

steel trail
unkempt thistle
steel trail

Then you indeed want only the BotDM context (not usable in the server) and users can't dm your bot if they share no server with it, so got that covered too

unkempt thistle

i tried that but that doesn't work for normal slashcommand bots?

steel trail

Sure it does

unkempt thistle
steel trail Sure it does

hmmmm weird stuff. I deleted all the commands by code and added them back. Now they only appear in the server and not in dms Thonk

wary coral

Could you share your command builder?

unkempt thistle

have it like this

this is whats gets put to the api

livid kettle

Is there a way to set a single message as nsfw? Or does it need to be the whole channel? I might need to use componentsV2 to spoiler certain images but it’s not most messages. If possible I’d rather not flag the whole channel.

steel trail
unkempt thistle

Then the first command should work in the server only, the second in dm with the bot only

steel trail

As minors need to completely stay clear of that content

unkempt thistle
steel trail

How did you determine that to be the case? Did you reload your discord afterwards? Did you try using it in the server?

livid kettle
analog oak

im getting errors from the node_modules (djs) exactly why is that happening?

analog oak

well alot of them, like this for example

steel trail

Well, why are you linting node_modules?

analog oak

no i guess? let me check

steel trail

That's not an error, just that your linter disagrees with djs' coding style

unkempt thistle
steel trail

And you deleted the command before you said?

unkempt thistle

deleted all the commands indeed

steel trail

And they are deployed as global commands?

cobalt tree

Hello, how can i add color on container?

sharp ginkgoBOT
unkempt thistle

always use guild specific commands

steel trail
unkempt thistle
loud quartz

undocumented

feel free to try it out

steel trail

4000 for all characters in components

loud quartz

does that mean that any and all singular components don't have any limits themselves?

only limit being 4k in a message?

steel trail

Yes (apart from the existing limits of interactive components)

loud quartz

hm, would be cool if that was documented then. explains why components don't mention it, but nowhere does it say that using cv2 doubles character limit per message

embeds field for creating message does say

[...] (up to 6000 characters)

loud quartz

seems to be "no limit" on TDB, but capped to 4k at message level

loud quartz
steel trail

Exactly

And afaik the character limit is not documented so they can theoretically change it later

rose tangle

4k in the entire message for all content components (currently only text displays), not per text display

steel yacht

Hi,
Why would an editReply containing buttons lead to an immediate "interaction failed" error without being clicked ?

zenith violet

You arent responding to the button interaction, you're just editing the reply of the commandinteraction probably

steel yacht

Yes, is that yet another impossibility ?

zenith violet

You have to reply to the ButtonInteraction

You have to reply to any interaction

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

unique quest

Should durable sku be in the entitlements object?

leaden shuttle

i have a guildMemberUpdate event and checking for old and new roles. why do my old roles just display as @everyone even though i had other old roles?

bleak owl

do you have the GuildMembers and Guilds intents?

leaden shuttle

yeah

export const client = new Client({
  partials: [Partials.Message, Partials.Channel, Partials.User, Partials.GuildMember, Partials.GuildScheduledEvent, Partials.ThreadMember],
  intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent]
});
bleak owl

do you need all those partials?

leaden shuttle

no ill remove some

bleak owl

enabling partials can actually limit what info is shown

leaden shuttle

same issue

const event: Event = {
  name: getFileName(import.meta),

  async run(oldMember: GuildMember, member: GuildMember) {
    if(member.guild.id !== guilds.main) return;

    console.log(1);

    console.log("Old roles:", oldMember.roles.cache.map(r => r.name));
    console.log("New roles:", member.roles.cache.map(r => r.name));
  }
};
clear garnet

Even if you have the GuildMember partial, that won't mean the old member's role data will always be there. Discord does not provide the old member data in the event, so discord.js has to rely on the cache for this old member data. If the member wasn't cached before the event emitted, then you aren't going to get much old member data. Nothing you can do about that

leaden shuttle

how do i ensure the member is cached?

clear garnet

By not having the GuildMember partial

leaden shuttle

if i remove the partial what are the cons of that?

clear garnet

If you exclude the partial, the guildMemberUpdate event will only emit if there is cached data for the member

leaden shuttle

so that still wont help me? im trying to update my database when someone's roles update- is there a better way to do this?

clear garnet

If your app is built around a single guild and you don't plan for it to be added to other guilds, another option would be to fetch all guild members on ready

I add that caveat because if your app is in hundreds if not thousands of guilds, it's not gonna be wise to fetch every member for every one of those guilds

leaden shuttle
clear garnet

300 members to fetch is hardly anything

leaden shuttle

surely you cant make 300 api requests and not get ratelimited?