#djs-help-v14

78874 messages · Page 66 of 79

rose tangle

yeah you're doing a raw request

djs won't do anything for you then

strange turret
rose tangle

well that's one way yeah

strange turret
rose tangle

I'm just saying that's outside the scope of a djs support channel

strange turret

oh, so that ratelimit is just ratelimit, im not being dumb or ruining it?

tardy sable
rose tangle

the error seems pretty straightforward imo

strange turret

ill ping ya tmrw if this shows up again

strange turret
rose tangle
sharp ginkgoBOT

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

strange turret

i'll ping you there, dw

hasty comet

can bots set voice channel status?

i seen this feature in few bots

rose tangle

yes but it's an undocumented endpoint so djs doesn't have a method for it

you'd need to do a raw request

hasty comet

like this

rose tangle

correct

hasty comet
sharp ginkgoBOT
rose tangle

you can use that to make authenticated requests to the api so you don't have to manage that yourself, it'll also handle ratelimits and whatnot

eg post requests which is most likely what that endpoint takes

sharp ginkgoBOT
rose tangle

as to what the endpoint is, it's undocumented so you'd have to search it, I'm pretty sure it's been mentioned a few times here

undocumented stuff is bound to break or change at any moment though

hasty comet

ok thx for the little help

i try to search for that

crude mist

I found a couple years back when I was learning some basic bot APIs

Only requires header authorization and body

body: {
'status': 'string of text for the status'
}
spice knoll

Good evening, is there any way to filter a UserSelectMenu to display users that have a specific role ?

wary coral

nope

spice knoll

Alright, thx 🙁

jolly radish

Hello, using components v2 is it possible to seperate two buttons on each side? So one button is far left and one far right?

stable sun

No

red coral

Could have buttons which are secondary style and disabled, with an empty character for the label?

warm charm

No

tardy sable

is it a bad practice to have a collector inside a collector? for example a game invitation and then the game?

unique shoal

Usually yes because every time the first one collects, it will create the second collector again

If that's intended, no it's fine

subtle girder
resource = createAudioResource(
    createReadStream(join(__dirname, 'file.webm'), {
        inputType: StreamType.WebmOpus,
        inlineVolume: true,
    }),
);

The code in the guide seems wrong,
Should the option be given to createAudioResource instead of createReadStream?

stable sun

Yea, that seems off

gleaming radish

is there a docs for a list of all rate limits?

stable sun
gleaming radish

does cdn of epheral attachments expires?

loud quartz

all cdn links expire

gleaming radish

alright, thanks both

crude mist

does discord.js not support command names with spaces? I thought they did

fallow finch

The only time a space is technically allowed if it has subcommands

crude mist

oh i see

actually that makes sense I forgot about subcommands

sharp ginkgoBOT

guide Subcommands
Subcommands are available with the .addSubcommand() method. This allows you to branch a single command to require different options depending on the subcommand chosen.

clear garnet

And for the record, it's not that d.js doesn't support it, it's that Discord themselves don't allow it

crude mist

well discord needs to stop making new modals and get to making /commands look nicer

loud quartz

They didn't make new modals

And this was something that was 4 years overdue

crude mist

I don't know what I just did. I moved my ping command to the commands folder and now its all red

strange turret

can we make it like a embed sent having a select menu of roles and a role is auto selected when its sent?

crimson gale
crude mist

I tried unistalling and reinstalling

welp im just gonna move folders

there we go moving folders worked

crude mist

you mean setting a default value for the role in the select menu?

strange turret

maybe

we run ,test -> embed sent with with a select menu inside embed letting us select roles -> but there should already a role will be selected -> and we can change it, possible?

crude mist
strange turret

link?

strange turret

thanks

strange turret

can a bot send a file or voice message as empherial?

balmy kraken

is there a way to register commands so that there is both the base commands and a subcommand? im registering like this:

    data: new SlashCommandBuilder()
        .setName("deposit")
        .setDescription("Withdraw money or items from the bank")
        .addSubcommand((subcommand) => subcommand.setName("manage").setDescription("Show item list panel")),```

but it results in only the subcommand appearing
faint smelt

as an interaction reply

strange turret

oka

strange turret

can a single message have container + embed?

golden laurel

No

strange turret

can a single message have multiple containers?

crude mist

I think yes looking at the builder

const components = [
        new ContainerBuilder(),
        new ContainerBuilder(),
];``` something like this
strange turret

i dont think so

strange turret
wary coral
median ferry

there's any event that triggers after having cache loaded?

strange turret

bruh why building the message editor page is tooo difcult...

i literally lost half of my braincells

flint pier

What is the limit on the number of options in StringSelectMenuBuilder?

flint pier
warm charm
flint pier
faint smelt

same limit

warm charm

yes

flint pier

I mean, is there another way?

faint smelt
flint pier

Ohh

crude mist

Is the only way to handle components callback on the same file using a collector function? I tried looking up ways and its either using an event listener on the main file or using a collector

faint smelt
MSG.awaitMessageComponent();

counts as a collector right?

crude mist

seems like it

faint smelt
crude mist

the docs is for a ban command so im not actually sure which parts are needed

cuz all im doing is just trying to make it reply

 try {
      const confirmation =
        await response.resource.message.awaitMessageComponent({filter: row});
      if (confirmation.customId === "eee") {
        await confirmation.reply({
          content: `Button was pushed by ${interaction.user.tag}`
        });
      }
    } catch (e) {
      console.log(`there was an error with the button: ${e}`);
    }``` this what I got going
wary coral

Just a guess but you are replying to the command interaction not the button interaction wait that is not right.

what is your filterrow?

crude mist

row is a button

const row = new ActionRowBuilder().addComponents(button);

sharp ginkgoBOT
obtuse laurel

it's supposed to be a function

faint smelt

:this:

wary coral

the example from the guide in your screen shot is
const collectorFilter = (i) => i.user.id === interaction.user.id;

crude mist

this is too annoying Im going back to python

im aware

Im not trying to make a ban command which is why I was trying to adapt it for a simple reply

faint smelt
wary coral

so then why did you set the filter as an action row

crude mist

if I knew I wouldnt be asking on here

wary coral
velvet cipher
crude mist

and it makes more sense than the guide

velvet cipher

Keep in mind that the examples and the guide are just examples of how something conceptually can be used, it's not meant to be copy-pasted

crude mist

obviously you dont learn from copying and pasting

heady aspen

I created a config json for my token. I set my type to Module in my package json. Now I want to call the token in the index with import configToken from ‘./configs/config.json’; and get this error. Why?

TypeError [ERR_IMPORT_ATTRIBUTE_MISSING]: Module “file:///Users/jevin/Desktop/Bot/configs/config.json” needs an import attribute of “type: json”
at validateAttributes (node:internal/modules/esm/assert:88:15)
at defaultLoadSync (node:internal/modules/esm/load:164:3)
at ModuleLoader.load (node:internal/modules/esm/loader:821:12)
at ModuleLoader.loadAndTranslate (node:internal/modules/esm/loader:591:31)
at #createModuleJob (node:internal/modules/esm/loader:623:36)
at #getJobFromResolveResult (node:internal/modules/esm/loader:329:34)
at ModuleLoader.getModuleJobForImport (node:internal/modules/esm/loader:294:41) {
code: 'ERR_IMPORT_ATTRIBUTE_MISSING'

polar karma

this is not a d.js error, this is a node/settings issue. please make a post in #1081585952654360687 if you need help with it
-# alternatively, use an env file instead of a plaintext config,json

balmy kraken

i respond to a button interaction with .reply({ withResponse: true })

im then trying to edit the message that i receive with response.resource.message.edit() but i get unkown message error. Despite that, .createMessageComponentCollector() creates as it should

printing the message im doing .edit() on gives <ref *1> Message { (...) }

why???

polar karma

can't edit an ephemeral message like that

tardy sable

they didnt mention ephemeral tho?

balmy kraken

it is ephemeral, should have mentioned that

tardy sable

you would have to do editreply then

polar karma

i can assume based on the snippet and error mmLol

balmy kraken

but how come i can edit them exactly like this when they stem from responses to command interactions?

balmy kraken
tardy sable show your code snippit
        const response = await button_interaction.reply({
            components: [container],
            flags: MessageFlags.IsComponentsV2,
            withResponse: true,
            ephemeral: true,
        })

        const panel = new PanelNPCConversation(button_interaction)
        const pageuiManager = new PanelManager(response.resource.message, panel)```

PanelManager
```js
    constructor(message, panel) {
        this.panel = panel
        this.message = message
// ...

        await this.message.edit({ components: [this.panel.container] })```

this.panel.container also exists ofc

polar karma

ephemeral messages should be interacted with by editReply, they don't exist like traditional messages

topaz bluff

Ephemeral messages have to be edited with an interaction.

If it's the interaction that created it, it's editReply... If it's an interaction from a sub components, it's update (which edits the message where the interaction it came from instead of sending a new reply)

tardy sable

if theyre both interaction replies. they shouldnt behave different

strange turret

in containers we can set custom image size also?

like how he did it, both images size

tardy sable
strange turret

okk

tiny condor
strange turret

You asked this yesterday and we told you it was one image, you didn't beleive it and now you asked again 💔

strange turret
balmy kraken
wary coral
balmy kraken
balmy kraken
faint smelt
tardy sable
balmy kraken
wary coral
balmy kraken

i want to figure out whether this is a bug that i should steer away from or if im safe to keep this

rose tangle

you can't, or at least aren't meant to (by discord), edit ephemeral messages via Message#edit()

only for non ephemeral ones and I think you also need to be in the guild

limpid mulch

Hello, I don't really need help, but I am looking for a screen I have seen of someone showing a Pokédex made with Components v2. The screen was with Discord light mode, if it can help.
Thank you for your help

proud arrow
limpid mulch
serene robin

Would anyone know how to have a bot react to an embed that it sends?

sharp ginkgoBOT

method Message#react() discord.js@14.25.1
Adds a reaction to the message.


// React to a message with a unicode emoji
message.react('🤔')
  .then(console.log)
  .catch(console.error);

topaz bluff

Same way you would on any message

elfin sun

I’m getting a rare but random messageCreate interaction to my bot, for a message that was written 1,2,3 or 4 YEARS ago.

While I can certainly filter for this, does anyone know why this might be occurring?

stable sun
stable sun

client.emit("messageCreate", ancientMessage)

elfin sun
stable sun

There’s not rly any other reasonable explanation for it

bleak owl

yes, by supplying the MessageFlags.IsComponentsV2 flag and the withComponents: true option

quasi trench

I'm currently having a problem where my MessageComponentCollector is not emitting the collect event.

So when a user does a ButtonInteraction, i do this

const row = new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(
    new StringSelectMenuBuilder()
        .setCustomId("partyprompt_select_size")
        .setPlaceholder("Select an option")
        .addOptions(
            ...
        ),
);

const message = await interaction.reply({
    content: "Please select an option.",
    components: [row],
    flags: MessageFlags.Ephemeral,
});

// Create a collector for the select menu
const collector = message.createMessageComponentCollector({
    componentType: ComponentType.StringSelect,
    time: ExpirationTime,
});

collector.on("collect", async (select) => {
  ... // This is not firing
});

does anyone know why this is not working?

jagged rock

discord js 15 better be good

tardy sable
sharp ginkgoBOT
brittle cipher

Is there a way for the bot to reply to the message that the user is replying to when running the command?

tardy sable
brittle cipher

got it ty

topaz bluff

You'll ALSO need to respond to the interaction independently or else there will be an error in the client

tardy sable
brittle cipher

ah so I will have to do message commands?

topaz bluff
tardy sable

Yh its easy to forget people still use message commands lol

topaz bluff
tardy sable
brittle cipher
civic jungle

how can I tell my TS that interaction.message.components[0] is a buttons row?

red coral
civic jungle

ActionRow is not generic

red coral
civic jungle
red coral

Is this some web storm thing?

civic jungle

wait, i have imported ActionRow from a wrong library (eris.js) -.-

it works now, thx

ivory wasp
loud quartz

Should be

But it's pretty easy to test

leaden wadi

is there a way to hide the "1401427693425397935.png" text?

I am using this link for the image https://cdn.discordapp.com/attachments/901961384038920242/1456104644169170964/1401427693425397935.png?ex=695726a0&is=6955d520&hm=e9f41397f76b97dc449c0183cb43c08c44c73d78584bf9948d29e912465a18d0

topaz bluff

You could use ComponentsV2 to send that image in a MediaGalleryComponent or you could send the image in the files field

leaden wadi

alrighty, thanks

ivory wasp
plush charm

Hi, I’m not sure if this is the right place, but if it’s not, feel free to delete this message. I have a quick question: Can a Discord bot get rate-limited or blocked for reactions? I’m working on a quiz bot where, if the answer is wrong, it adds an "X" emoji reaction. I'm concerned that if too many users give wrong answers in the same 30-second window, the bot might hit a rate limit. Is that something that could happen?

topaz bluff

Pretty much every action can be rate limited. I wouldn't be surprised if you could run into rate limiting issues with that

plush charm
topaz bluff

DJS does handle rate limits for you. It will just queue the action until the rate limit expires

olive lynx

how can I make such embed how can I fit images in embed?

sharp ginkgoBOT

guide Display Components
While you might be familiar with embeds in Discord, there are more ways to style and format your apps messages using display components, a comprehensive set of layout and content elements. To use the display components, you need to pass the IsComponentsV2 message flag (in docs: MessageFlags) when sending a message. You only need to use this flag when sending a message using the display components system, not when deferring interaction responses.

topaz bluff

It's not an embed

novel mauve

you're already using a container, simply add a media gallery at the beginning and end of its nested components

rancid palm

Is there a reason setName here isn't throwing an error after trying to rename a channel and (what I assume) is hitting a ratelimit

await textChannel.setName(`closed-${ticketRecord.ticketId}`)
crude mist
rancid palm
rose tangle

ratelimits are queued by default, you can change that in the client options

sharp ginkgoBOT

propertysignature RESTOptions#rejectOnRateLimit discord.js@14.25.1
Determines how rate limiting and pre-emptive throttling should be handled. When an array of strings, each element is treated as a prefix for the request route (e.g. /channels to match any route starting with /channels such as /channels/:id/messages) for which to throw RateLimitErrors. All other request routes will be queued normally
Default value: null

timid ice

Hello, I have a question. For example, there's a message with a button that I want to expire and not be reused when I reset the bot. How can I do that?

rose tangle

components can't be disabled by themselves, you need to explicitly disable them by editing the message

you can edit it before restarting the bot or you could edit it after a restart if it expired, replying with an ephemeral message saying "you can't use this anymore" or something

timid ice
rose tangle

all the ones that you want to disable, yes

timid ice
rose tangle

each network request is a Promise so it shouldn't take that much

unless you do the requests one by one and await them, in which case yeah

the performance side is a matter of how you implement it

you're pretty much stuck with that either way if you want them to be completely unusuable while it's shut down

like I mentioned you can't make them auto disable

timid ice

Okay thx for helping

hybrid fable
strange turret

is doing roll all is against tos? like giving all memebrs of a guild a role at a time with api

pine plover

I have a question. When I fill out a modal form and submit it, can a new one be opened immediately? Or does it first require another trigger, such as a button or something similar?

proud arrow
strange turret
proud arrow
pine plover
proud arrow
sharp ginkgoBOT
proud arrow

You can check these headers mentioned to know how much req you have left, or just don't do anything that would make you come close to hitting limits

proud arrow
strange turret
proud arrow

I have no idea, nobody does that's the point. It's generally not a good idea to test the rate limits. As for your other questions, they probably make requests with sufficient wait periods.

strange turret

but discord does immedietly?

strange turret
proud arrow

It's no point guessing how big bots do it, they get increased rate limits since you know they are big

Not to mention there's global limit on top of route specific

strange turret

fine

can we fetch with api the user join source?

like who invited him

loud quartz

No

strange turret

the invite link?

steel trail

Moderators can check that in native mod view, no need for a bot to know that

warm charm

ig he want to make invite checker

strange turret

btw, if i do ,roleall @role in a 10k members server, do it sends discord 10k request or 1

crimson gale

10k

strange turret

dayum

why don't discord allow us to fetch the server analytics shown in the dev portal?

tardy sable

Privacy reasons 🤷

balmy kraken

are there ways to check if bot can dm a user before trying to .send()?

wary coral
sharp ginkgoBOT
dense jackal

you have this one right

ripe topaz

How can I check if a channel is in a specific category, or has no category?

cobalt solstice

Hello, small issue regarding components in container
Code: https://sourceb.in/ah12XfvJAX
Error when running:TypeError: (intermediate value).setCustomId(...).setPlaceholder(...).addOptions(...).setLabel is not a function

anyone has ideas of the reason? thank you in advance

zealous knot

Hello,

For one of my utility bots, I need to check whether a user has permission to view a specific channel. I already store the user’s ID in my database, so I’ve been using that ID directly to avoid fetching the member.

This approach has worked reliably for months. However, very recently it stopped working: the permission check now only succeeds if I explicitly fetch the guild member first. If I skip the fetch and use the ID directly, the check fails entirely. Below are a couple of simplified examples to illustrate the behavior.

const member = await message.guild.members
  .fetch(config.user_id)
  .catch(() => null);

if (!member) continue;

const canViewChannel = message.channel
  .permissionsFor(member)
  .has(PermissionFlagsBits.ViewChannel);

// Will return the correct result.
const canViewChannel = message.channel
  .permissionsFor(config.user_id)
  ?.has(PermissionFlagsBits.ViewChannel);

// Will now always return false despite it working fine for literal months.
zealous knot
ripe topaz
tardy sable
cobalt solstice
ripe topaz
zealous knot
tardy sable
zealous knot

Well, It's a good thing that I already cache members indefinitely so the change is quite simple

tardy sable
zealous knot

I'm sad about spending 28 minutes trying to figure out what was causing it though..

cobalt solstice
tardy sable
zealous knot
tardy sable
cobalt solstice
tardy sable

but try place it in an actionrow and see

cobalt solstice

yeah i use component => component.setComponents already

polar karma
dense jackal you have this one right

Creating the DM channel is always an option, but it's not checking if you can DM them. Just like you as a user can open a DM channel with a user you can't DM, you can try to DM but get an error

cobalt solstice

lmfao i think i found the issue, im using vsc and everytime you move the mouse 1mm more it moves the selected code otherwise... yes... it moved the parenthesis above

thanks for help XD

novel mauve
tardy sable

why await channel.messages.fetch(id).catch(() => null) always returns object even if the id doesnt exists?

steel trail

If the id is undefined then you're effectively fetching 50 messages (because you don't pass an id and it ends up being a bulk fetch)

If the id is a snowflake that doesn't exist it would throw and thus return null

tardy sable

oh okay that makes sense thanks for clearing up confusion

nimble obsidian

are bots allowed to use buttons in other's private dms? I have a user installed app and a message with buttons, if I use the command in my friends DM and try interacting with the buttons I get an error

Could not find the channel where this message came from in the cache!

nimble obsidian

like when I make the client I need to specify Channel partials?

sharp ginkgoBOT

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

proud arrow

Only The channel partial point applies to you

nimble obsidian
proud arrow
nimble obsidian
sharp ginkgoBOT
tepid wigeon

Sigh, where can I find the changes? 😄

sharp ginkgoBOT
sharp ginkgoBOT

guide suggestion for @tepid wigeon:
guide Modals
Modals are pop-up forms that allow you to prompt users for additional input. This form-like interaction response blocks the user from interacting with Discord until the modal is submitted or dismissed. In this section, we will cover how to create, show, and receive modals using discord.js! This page is a follow-up to the interactions (slash commands) page. Reading that page first will help you understand the concepts introduced in this page.

sharp ginkgoBOT

guide Container
A Container is a layout component which groups its child components inside a visually distinct rounded box with an optional accent color on the left, similar to the message embed look. Unlike embeds, not specifying a color will make the left side of the Container component match the background color. You can mark Container components as spoiler, which blurs all content inside the container. You can use the ContainerBuilder class to easily create a Container component. - a Separator component;...

loud quartz
civic jungle

how to get customId from a ButtonBuilder?

like I have created an ActionRow from an interaction

const row = ActionRowBuilder.from<ButtonBuilder>(interaction.message.components[0] as ActionRow<ButtonComponent>)```

and now when i do

row.components[0].data.custom_id```

it complains

proud arrow
civic jungle
proud arrow

Nvm i was wrong, what does it say when you try to access custom_id?

civic jungle

same as customId

proud arrow

Ok so yeah its of an union type, you need to typeguard it, so something like if ("custom_id" in <Component>) to narrow it further

civic jungle

that is so weird

maybe I'm doing something wrong
what would be the proper way to disable buttons in a row whose custom_id contains the word 'dog' ?

proud arrow

Idk what way you are doing it to tell, why do you think you are doing something wrong?

civic jungle

because in eris.js that would be 10 lines of code, here is like 30+

steel trail

You don't need to use builders. You could just .filter(...) the array of buttons in the json

Or .map(...) it

civic jungle

AI told me that I cannot modify directly the interaction message lol

steel trail

While that is never a good way to start a sentence neither of the two methods I told you is modifying anything. Both give you a new array

civic jungle

ok, I loop through and then what?

loud quartz

Then you do what you need to do with the single component

And leave the rest intact

Pass that all to an edit method of your choice/situation

civic jungle

ok, i see it now

but still, i cannot make a button disabled, it complains

disabled is read only

i tried
disabled = true // read only
.setDisabled(true) // not exists

loud quartz

well, you're trying to edit the received component

you need to make a new one out of that received one, then you can edit it to your will

loud quartz

what i said doesn't really exclude what qjuh said

civic jungle

then how do I make a new one out of existing?

wary coral
jolly radish

how can I make the png show normally without having it inside the embed?

steel trail

By using components v2 for example. There you can put a media gallery outside the container

sharp ginkgoBOT
topaz bluff

But if you want to use an Embed. You can use this which will place it at the bottom of the embed (components V2 would probably look better however given you want buttons as well)

jolly radish

okay! Thank you all. I will try all your suggestions to see whats best

jolly radish
jolly radish
jolly radish
tardy sable
jolly radish

I am dumb... When I send the card buffer as response to the api call I did .toString() instead of .toString("base64") so it tried to make the attachment with wrong encoding

vast bloom

i suppose this isn't entirely discord.js related but whatever
anyone here know of a fast way to convert lottie animations to gif / mp4 / literally any format ffmpeg can process into a gif
and not like "Online Lottie Converter #12930810238123" those are practically useless to me
the only thing i've found so far is one made in js which uses puppeteer, problem with that one is that it has to open the damn thing in a web browser and takes AGES to render anything
obviously im trying to use this for sending animated stickers, so if theres a better way than this lmk
i might just be overcomplicating things to hell

i don't really care what it is as long as its something which can be done programmatically somewhat reasonably & doesn't take ages

loud quartz

i suppose this isn't entirely discord.js related but whatever
then why ask in this channel anyway

vast bloom
loud quartz

doesn't change the fact that this isn't a channel for it

"i know this isn't d.js but how do i do my taxes"

vast bloom

mb i guess

versed current

lads, is it technically possible to use a user select menu in dms? I assume not but does the API throw a specific error there?

versed current

wait what

proud arrow

It will only show you and the bot user though

versed current

how stupid is that. what about the role select? WIll that error though?

proud arrow

All selects work

Though role select doesn't show anything

versed current

lmao why did they not just deny it hahaha

I might make an issue on github for this; Thanks so much!

tardy sable

it works with cache so its just easier to show whats available instead of denying something. this isnt a bug or something. its also logical that nothing would show up

proud arrow

Except for maybe role select, all other working is not stupid, bot user is still an user, so it can work with user select, dms are still channels so there's that for channel select

tardy sable

for createMessageCollector i should always do it on a channel? i cant do message right?

polar karma

A message doesn't have messages (threads don't count)

versed current
trail hull

When i download animated emoji from a vuil5, the resulting file isn't animated, how do i animate it?

bleak owl
trail hull

as in a discord server

bleak owl

that's still not something discord.js can help you with, sorry

trail hull

I see

I'll try to look on my own then, thanks for replying ❤️

low spear

can a bot have rich presence and play a custom game?

warm charm

hi, how i can fetch user who invited the bot

balmy kraken

can the bot send ephemeral messages outside of replying to interactions?

crimson gale

no

loud quartz
crimson gale
sharp ginkgoBOT

method Guild#fetchAuditLogs() discord.js@14.25.1
Fetches audit logs for this guild.


// Output audit log entries
guild.fetchAuditLogs()
  .then(audit => console.log(audit.entries.first()))
  .catch(console.error);

placid mural

Hey how to reduce message Latency

:( pls help

steel trail

Depends, how high is it?

And where do you host and run your bot?

placid mural
placid mural
steel trail

That is a concept, not an actual where. Is the VPS in Korea or USA or ...? Is your bot hitting ratelimits on those high traffic times? Or is it just slow network or ...?

placid mural
steel trail

How did you determine that it doesn't hit ratelimits? If it takes longer on high load then it's an issue with your vps' capacity. Not djs related

placid mural
steel trail

Well, if you do have 1k latency then that IS stopping the message send and doing it later. Listen to the rateLimited event to find out if you are

placid mural
placid mural
loud quartz

"ping" is ambiguous

where did you get that from or how did you measure that

placid mural
loud quartz

and how do you do that

placid mural
loud quartz

show code

how do you actually measure the number

placid mural
loud quartz show code
const sendStart = Date.now();
const sent = await message.channel.send('Testing');
const sendEnd = Date.now();
const messagePing = sendEnd - sendStart;
kind pagoda
const sentTime = Date.now();
const latency = Date.now() - sentTime;
const wsPing = client.ws.ping;
steel trail
placid mural
steel trail

Show how you listen to the event

flint zenith

how to do something like setSectionComponents? bc that doesn't exist. by duplicating the old container and replace that section?

topaz bluff

It's add not set

But if you want to replace components, use spliceComponents

sharp ginkgoBOT
tribal birch

is this coming from discord.js?

return await message.reply({ embeds: [embed], files: [attachment] });

topaz bluff

It's not a DJS error... but looks like it is because of DJS... however that is a generic error message and I couldn't tell you what caused it...

polar karma

Is that in a try/catch block? It looks like a custom error message

past spear

Hi there
Who know how to correctly cut or disable buttons from container after button interaction?

halcyon bison
past spear
sand minnow
        container.addSectionComponents(
            new SectionBuilder()
                .addTextDisplayComponents(
                    new TextDisplayBuilder().setContent(detailsLines.join('\n'))
                )
                .setThumbnailAccessory(new ThumbnailBuilder().setURL(guild.iconURL() || ''))
        );

Received:

Error: Cannot properly serialize component type: undefined

Djs: ^14.25.1

topaz bluff

I don't think you can set the URL of a thumbnail to an empty string... you should do a check to see if the iconURL exists, and if it doesnt, just dont build a Section

sand minnow

none of them are undefined

warm charm
sand minnow
warm charm
sand minnow
warm charm

lastest, 14.25

sand minnow

me 2

warm charm
sand minnow
warm charm can you send me full (giveaway) code, maybe i can help you
static createGiveawayContainer(giveaway: Giveaway, guild: Guild): ContainerBuilder {
        const container = new ContainerBuilder();

        container.addSeparatorComponents(new SeparatorBuilder().setSpacing(SeparatorSpacingSize.Small).setDivider(false));

        container.addTextDisplayComponents(
            new TextDisplayBuilder().setContent(
                `## ${config.emojis.blank} ${config.emojis.tadaa}   ${giveaway.prize} ${config.emojis.tadaa}${config.emojis.blank}`
            )
        );

        container.addSeparatorComponents(
            new SeparatorBuilder().setSpacing(SeparatorSpacingSize.Small).setDivider(false)
        );

        container.addSeparatorComponents(
            new SeparatorBuilder().setSpacing(SeparatorSpacingSize.Large).setDivider(true)
        );

        container.addSeparatorComponents(
            new SeparatorBuilder().setSpacing(SeparatorSpacingSize.Large).setDivider(false)
        );

        const detailsLines = [
            `${config.emojis.blank}  ・Winner(s): ${giveaway.winnerCount}`,
            `${config.emojis.blank}  ・Ends at: ${time(giveaway.endTime, TimestampStyles.RelativeTime)}`,
            `${config.emojis.blank}  ・Hosted by: ${userMention(giveaway.hostedBy)}`
        ];

        if (giveaway.requiredRoles && giveaway.requiredRoles.length > 0) {
            detailsLines.push('\n');
            detailsLines.push(`${config.emojis.blank}  ・Whitelist: `);
            giveaway.requiredRoles.forEach((roleId) => {
                detailsLines.push(`${config.emojis.blank}${config.emojis.blank}${roleMention(roleId)}  `);
            });
        }

        if (giveaway.blacklistedRoles && giveaway.blacklistedRoles.length > 0) {
            detailsLines.push('\n');
            detailsLines.push(`${config.emojis.blank}  ・Blacklist:`);
            giveaway.blacklistedRoles.forEach((roleId) => {
                detailsLines.push(`${config.emojis.blank}${config.emojis.blank}${roleMention(roleId)}  `);
            });
        }

        console.log(guild.name, guild.iconURL());
        console.log(detailsLines.join('\n'));
        container.addSectionComponents(
            new SectionBuilder()
                .addTextDisplayComponents(
                    new TextDisplayBuilder().setContent('test')
                    // new TextDisplayBuilder().setContent(detailsLines.join('\n'))
                )
                .setThumbnailAccessory(
                    (thumb) => thumb.setURL('https://cdn.discordapp.com/icons/1456088416092553239/8b0e6d86e82370c478d2322cd64c78ea.png')
                )
                // .setThumbnailAccessory(new ThumbnailBuilder().setURL(guild.iconURL()!))
        )

        container.addSeparatorComponents(
            new SeparatorBuilder().setSpacing(SeparatorSpacingSize.Large).setDivider(false)
        );

        container.addTextDisplayComponents(new TextDisplayBuilder().setContent(`-# soradery`));

        return container;
    }
warm charm
sand minnow
warm charm
sand minnow

lms

sand minnow
warm charm
sand minnow it still

then its not from thumb, try to remove section rn, add it with textdisplay

its called debug lol

sand minnow
warm charm

💀

halcyon bison
sand minnow

oh wait, i've imported it from djs builder

warm charm
sand minnow

my fault 💀

sharp ginkgoBOT

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

npm uninstall discord-api-types @discordjs/rest @discordjs/builders
yarn remove discord-api-types @discordjs/rest @discordjs/builders
pnpm remove discord-api-types @discordjs/rest @discordjs/builders
placid mural
topaz bluff

is that a copy/paste issue or is that your actual code... cuz... that's not right

sand minnow

ty all, it works now

placid mural
topaz bluff

but that's like not even valid javascript

placid mural
topaz bluff
client.rest.on('rateLimited', (rateLimitData) => {
    console.log('Rate limited!', rateLimitData);
});
placid mural

Oh no the upper part it's when I pasted it was due that that

steel bronze

is there away for me to set channel status? like the one you can change in Vc? like the that or what ever its called

topaz bluff

Updating channel statuses are undocumented and thus unsupported by DJS

It's possible but I do not know how

steel bronze

Ahaa its still undocumented

solid trout

Incorrect login details were provided.
at WebSocketConnection

how do I fix this

crimson gale

by providing correct login credentials
whatever you pass as token is not a valid, active, bot token

steel trail
placid mural
steel trail

No, that's a completely different metric and you probably didn't even measure that at the time your bot was under high load

placid mural
ripe topaz

For a voice channel if the user limit is infinite, would that be 0 in VoiceBasedChannel#userLimit ?
or negative or what?

dire rose

Question, does the messagecreate event tell you if a message is marked as a spoiler? Thonk

I mean specifically pictures

sharp ginkgoBOT
ripe topaz

How can I detect whenever someone leaves any voice channel?

I tried this, but it only logs when someone joins

import { CustomClient } from '@classes/client/CustomClient.js';
import { DiscordEvent } from '@classes/events/DiscordEvent.js';
import { tempVoiceCategoryId } from '@common/constants.js';

export default new DiscordEvent('voiceStateUpdate', async (oldState, newState) => {
  if (!newState.channel) return;

  const client = newState.client as CustomClient;
  const vc = newState.channel;

  console.log(`voice update ${vc.name}`);

  // If the channel has a limit and it's been reached, remove active lfg entry
  if (vc.userLimit !== 0 && vc.members.size >= vc.userLimit) {
    if (client.activeLfg.find(e => e.channelId === vc.id)) {
      client.activeLfg = client.activeLfg.filter(i => i.channelId !== vc.id);
    }
  }

  // This handles cases where the lfg voice channel is not under the temp voice category
  // and therefore the channel wont be deleted and removed from client.activeLfg
  if (vc.parent?.id === tempVoiceCategoryId) return; // ignore temp voice category

  // When the channel is empty, if it was in the temp voice category
  // it would be deleted along with it's entry (this is handled in channelDelete)
  if (vc.members.size === 0) {
    // But this is not a temp vc so we just remove the active lfg entry assigned to it
    // when it becomes empty
    if (client.activeLfg.find(e => e.channelId === vc.id)) {
      client.activeLfg = client.activeLfg.filter(i => i.channelId !== vc.id);
    }
  }
});
loud quartz

correct, because on the very first line if there is no channel in the new state you immediately return

cosmic pilot

Hello, I can't understand why my modals don't have a limit? I'm defining it correctly with setMaxLength(4_000).

export class ContainerModalView {

    static textAdd(messageId: string) {
        console.log('1')
        const textInput = new TextInputBuilder()
            .setCustomId("content")
            .setStyle(TextInputStyle.Paragraph)
            .setMaxLength(4_000)
            .setRequired(true);

        const textLabel = new LabelBuilder()
            .setLabel("Contenu du texte")
            .setTextInputComponent(textInput);

        return new ModalBuilder()
            .setCustomId(`container:modal:text_add:${messageId}`)
            .setTitle("Ajouter un affichage texte")
            .addLabelComponents(textLabel);
    }
}

console:

...
1
tardy sable

i think 4000 is also the default max length anyways

cosmic pilot
tardy sable i think 4000 is also the default max length anyways

Exactly! But if I spam my modal with random characters and therefore exceed the 4000 limit for a TextDisplay I get an error... Whereas before in modals we saw the number of characters in the bottom right and the modals blocked us when we reached the defined limit.

DiscordAPIError[50035]: Invalid Form Body
data.components[COMPONENT_DISPLAYABLE_TEXT_SIZE_EXCEEDED]: Components displayable text size exceeds maximum size of 4000
    at handleErrors (/home/ntiako-hp/Documents/0waBotTS/node_modules/@discordjs/rest/src/lib/handlers/Shared.ts:148:10)
    at processTicksAndRejections (node:internal/process/task_queues:105:5)
    at BurstHandler.runRequest (/home/ntiako-hp/Documents/0waBotTS/node_modules/@discordjs/rest/src/lib/handlers/BurstHandler.ts:144:20)
    at _REST.request (/home/ntiako-hp/Documents/0waBotTS/node_modules/@discordjs/rest/src/lib/REST.ts:210:20)
    at ModalSubmitInteraction.update (/home/ntiako-hp/Documents/0waBotTS/node_modules/discord.js/src/structures/interfaces/InteractionResponses.js:354:22)
    at addComponent (/home/ntiako-hp/Documents/0waBotTS/src/controllers/interactions/container.interaction.controller.ts:91:13)
    at Function.handleModal (/home/ntiako-hp/Documents/0waBotTS/src/controllers/interactions/container.interaction.controller.ts:97:17)
    at Object.execute (/home/ntiako-hp/Documents/0waBotTS/src/events/interactionCreate.event.ts:80:17)
[ERROR] 15:18:48 DiscordAPIError[50035]: Invalid Form Body
data.components[COMPONENT_DISPLAYABLE_TEXT_SIZE_EXCEEDED]: Components displayable text size exceeds maximum size of 4000
tardy sable
cosmic pilot

what ?

tardy sable

the modal will not to go through right if above that max length?

youre probably adding other stuff to the reply which explains why you get the max length error

cosmic pilot

No, I limited my TextInput to 4000 characters, yet I can go beyond that and create an error. This is because the input from my modal allows me to subsequently generate a TextDisplay with the content provided via the modal. However, TextDisplays are limited to 4000 characters.

tardy sable
cosmic pilot

I just don't understand why the character limit is no longer visible in the modal window? And why, if I set my limit to 10, can I enter 11 characters?

tardy sable

you can enter 11 characters but as you said it would say an error then. idk either why they changed it like this its not user friendly anymore. you should ask in ddevs server

cosmic pilot

okay thx

tardy sable
cosmic pilot okay thx

i just tested it and this happens if you add trailing/white spaces at the end/start. discord will still block you from typing more than the allowed length

cosmic pilot

okay

tardy sable

although i did also experience being able to type more than the allowed length (errors on trying to submit). maybe this happens with text input paragraph styles

loud quartz

being able to type and being able to submit are different things

warm charm
warm charm
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
warm charm
cunning hinge

am i missing something here?

so i fetched a message like so:

const fetched = await channel.messages
  .fetch(this.overviewMessageId)
  .catch(() => undefined);

and after that i try to delete it like so:

[this.overviewMessage] = await Promise.all([
  channel.send(this.overview()),
  fetched?.delete(), // this line specifically
]);

but then it gives me an Unknown Message error ;-;

polar karma

What's the full error including stack?

cunning hinge

@polar karma

[2026-01-03 18:02:02] [UpdateEnvOverview/Error] Error with updateEnvOverview event
DiscordAPIError[10008]: Unknown Message
    at handleErrors (C:\dev\Node\Aeonix\node_modules\.pnpm\@discordjs+rest@2.6.0\node_modules\@discordjs\rest\dist\index.js:762:13)
    at process.processTicksAndRejections (node:internal/process/task_queues:103:5)
    at async SequentialHandler.runRequest (C:\dev\Node\Aeonix\node_modules\.pnpm\@discordjs+rest@2.6.0\node_modules\@discordjs\rest\dist\index.js:1163:23)
    at async SequentialHandler.queueRequest (C:\dev\Node\Aeonix\node_modules\.pnpm\@discordjs+rest@2.6.0\node_modules\@discordjs\rest\dist\index.js:994:14)
    at async _REST.request (C:\dev\Node\Aeonix\node_modules\.pnpm\@discordjs+rest@2.6.0\node_modules\@discordjs\rest\dist\index.js:1307:22)
    at async GuildMessageManager.delete (C:\dev\Node\Aeonix\node_modules\.pnpm\discord.js@14.25.1\node_modules\discord.js\src\managers\MessageManager.js:334:5)
    at async Message.delete (C:\dev\Node\Aeonix\node_modules\.pnpm\discord.js@14.25.1\node_modules\discord.js\src\structures\Message.js:936:5)
    at async Promise.all (index 1)
    at async StartEnvironment.updateOverviewMessage (file:///C:/dev/Node/Aeonix/dist/models/environment/environment.js:54:34)
    at async EnvironmentEvent.callback (file:///C:/dev/Node/Aeonix/dist/events/environment/itemAdded/updateEnvOverview.js?t=1767459721970&debug=fromPlayerEventHandler:7:9) {
  code: 10008,
  method: 'DELETE',
  rawError: { code: 10008, message: 'Unknown Message' },
  requestBody: { files: undefined, json: undefined },
  status: 404,
  url: 'https://discord.com/api/v10/channels/1289589923510489118/messages/1457055617972834358'
}
polar karma

Is it an ephemeral message?

cunning hinge

no, it is public for all

polar karma

Did you log fetched to confirm it is a message object? Is there something deleting the message before that line?

cunning hinge

i did, and it is one, and no, there is nothing but newlines between those lines of code

hold up, im gonna double check the ids

wth, the error stopped, im guessing i had an incorrect id stalling it, no idea how it got fetched properly though.

nvm, its back ;-;

latent lark

Hey everyone, I need some help with modal file uploads.

I’m using FileUploadBuilder inside a modal and then trying to read the files with:

interaction.fields.getUploadedFiles()
But it always returns an empty array, even when I upload a file before submitting the modal.
The UI shows the upload component correctly, but on submit I get:

  • Avatar files count: 0
  • Banner files count: 0

am I missing something in the implementation? Any clarification would be really appreciated 🙏

topaz bluff

Are you supplying the customId of the component to your .getUploadedFiles(customId)?

topaz bluff

Is the field required or not? If not required, it should return null if no files were uploaded, rather than an empty Collection

radiant epoch

Can StringSelectMenu have autocomplete and extend 25+ menu options?

radiant epoch
wary coral

correct, String Select Menu cant not have more than 25 options

radiant epoch
wary coral

Wdym?

radiant epoch
wary coral

Those are not String Select Menu and users can only select 25 options(role & channels respectively) in those

hasty gulch

With the new modal components, how many rows can I add to the modal?

topaz bluff

And just btw, you should NOT be using ActionRows in Modals anymore... they are deprecated and Label Components should be used for all new modals

hasty gulch

So, with the new update, if I add two string inputs, can I also add three select menus?

I still can't add the 6th one.

topaz bluff

correct

unreal stone

Hi! Sorry, I have a quick question. It is possible to delete the message like "XXX has pinned….." when a message is pinned?

tardy sable
viscid hill
sharp ginkgoBOT
viscid hill
tardy sable
viscid hill

Didnt know that, ty

unreal stone

Thanks! Another question! What is the limit of message.fetch() ? I read 100, but I know that pinned is 50

sharp ginkgoBOT

method DMMessageManager#fetchPins() discord.js@14.25.1
Fetches the pinned messages of this channel, returning a paginated result. The returned messages do not contain any reaction data. Those need to be fetched separately.


// Get pinned messages
channel.messages.fetchPins()
  .then(messages => console.log(`Received ${messages.items.length} messages`))
  .catch(console.error);

topaz bluff
unreal stone

Strange that i got an error with limit 100 with fetchPins: DiscordAPIError[50035]: Invalid Form Body limit[NUMBER_TYPE_MAX]: int value should be less than or equal to 50.

viscid hill

You can only fetch pinned messages up to 50

unreal stone

oh, thanks :D

viscid hill

But discord mentioned a way to fetch more than 50

unreal stone

Yeap, i do something like that

rose tangle

if you want to fetch many you'll need the messages manager of the channel, channel.messages.fetch(...)

unreal stone

yes, it was a typo on my side! thank you :)

civic jungle

how can I play a mp3 file from the web to AudioPlayer?

play(track: Track) {
  const resource = createAudioResource(track.cloud_url);
  this.player.play(resource);
}```

this doesn't work

zealous knot

Hi. Is there a way to fetch an emoji given just it's ID?
TypeScript LSP was just acting up and didn't show the cache as an option...

tribal birch
import { ApplyOptions } from '@sapphire/decorators';
import { type Events, Listener } from '@sapphire/framework';
import type { PartialUser, User } from 'discord.js';

@ApplyOptions<Listener.Options>({})
export class BotListener extends Listener<typeof Events.UserUpdate> {
  override async run(oldUser: User | PartialUser, newUser: User) {
    if (oldUser.partial) {
      try {
        oldUser = await oldUser.fetch();
      } catch {
        return;
      }
    }

    if (newUser.partial) {
      try {
        newUser = await newUser.fetch();
      } catch {
        return;
      }
    }

    if (newUser.avatar && oldUser.avatar !== newUser.avatar) {
      void this.container.avatarsService.saveAvatar(newUser);
    }

    if (oldUser.username !== newUser.username || oldUser.displayName !== newUser.displayName) {
      void this.container.usernameDisplayNameService.saveUsernameDisplayName(newUser);
    }
  }
}

is this right way to handle partials in userUpdate event

clear garnet

oldUser = await oldUser.fetch();
This is pointless. All this is going to do is turn oldUser into newUser, because you can't fetch outdated user data from the API, it's only gonna give you current data

clear garnet

if (newUser.partial)
This also seems pointless, since your own typings say that newUser cannot be a partial

tribal birch

do i just remove all of it or

clear garnet
tribal birch
import { ApplyOptions } from '@sapphire/decorators';
import { type Events, Listener } from '@sapphire/framework';
import type { PartialUser, User } from 'discord.js';

@ApplyOptions<Listener.Options>({})
export class BotListener extends Listener<typeof Events.UserUpdate> {
  override run(oldUser: User | PartialUser, newUser: User) {
    if (newUser.avatar && oldUser.avatar !== newUser.avatar) {
      void this.container.avatarsService.saveAvatar(newUser);
    }

    if (oldUser.username !== newUser.username || oldUser.displayName !== newUser.displayName) {
      void this.container.usernameDisplayNameService.saveUsernameDisplayName(newUser);
    }
  }
}

so this?

clear garnet

Sure

tribal birch

but i still need this right

clear garnet

Correct, otherwise the event is not going to emit at all if there's any partial oldUser

tribal birch

thanks

clear garnet

If you want to explicitly ignore firings where there's partial old data, then don't subscribe to the User partial

wary coral
tardy sable
cobalt tree

Hello, when selecting channel in select channel menu is the channel permission inside the payload? Or does it have payload after selecting?

topaz bluff

my assumption is, if it's a cached channel... then yes...

but the interaction payload itself only contains the channel id

cobalt tree
topaz bluff

if your app is stateless... then fetching or an unreliable cache is really all you can do

cobalt tree

Or is the permission enabled in the channel

halcyon bison
warm charm

how we can check user dm enabled or not 😭

i need it to dm a user w/ bot

polar karma

By dming them

DM should only be sent by invocation of the user

warm charm

alr ty

btw when i can't send msg to the user it will throw error 50007 (CannotSendMessagesToThisUser) right

polar karma

Refer to the API docs for the error messages to confirm

subtle girder

can I do ChatInputCommandInteraction.deferReply({flags: MessageFlags.Ephemeral})
and cancel the Ephemeral?

topaz bluff

you cannot change the ephemeral state of a message

subtle girder

okay

wintry laurel

i assume deferUpdate is the same as deferReply just for updates?

so for example if i defer a reply, then edit it with new buttonsw, then in another button interaction i defer update it and then update it that works fine? also i assume this is also able to be done as many times as wanted just like normal update

also, i probably dont need to specifiy new message flags like ephemeral right?

loud quartz

deferReply creates a place for your eventual actual reply to be in

deferUpdate only exists as a response to component interactions, and doesn't create a place for a new message, because you just told discord you will update the message the interaction came from instead

wintry laurel
loud quartz

if you need more than 3 seconds to produce a response, defer

you defer what you need to do

you can defer an update, you can defer a reply

you can't defer a modal (at all) or a followup (simply send one), so those defers don't exist

wintry laurel

ok, and deferUpdate behaves the same as deferReply where you get 15 mins to update it, but with the expected response as a update right

im just now adding this to my code because theres been this unknown interaction error with this section of my code for a while, but it only happens on some clients, and this is the only thing i can think to fix it

loud quartz

when an interaction is created, you have 3 seconds to respond to it. after you respond to it, the interaction token is valid for another 15 minutes

this means that you can reply and then edit reply within those 15 minutes

defering is a response to interaction

so you get the same 15 minutes because your bot acknowledged the interaction

wintry laurel

ok thank you

if my interaction response is already ephemeral, it dosnt matter if i do or dont pass the ephemeral flag in deferupdate right

stable sun
wintry laurel
stable sun

ephemeral isn’t an editable property/flag

wintry laurel

yea makes sense

wintry laurel

after deferupdate to edit the message what do i have to use? update dosnt work because that acknowlages the interaction, editReply wouldnt because thats for replys only right?

tardy sable
wintry laurel
tardy sable

Then edit reply to edit the message

wintry laurel

heres what my execution looks like

user clicks button -> deferReply(ephemeral) then editReply() right after. the edit adds all the content and buttons
user clicks new button from the reply to the first interaction -> deferUpdate(), then update() with new content and buttons.

this keeps going for a bit

.update after the deferupdate causes issues

tardy sable

You cant update twice use the editreply

wintry laurel
tardy sable

Yes

wintry laurel

oh wait i think im understanding it all now, i was just confused because .deferReply seems like you can only use editReply to change it, and deferUpdate makes it seem like you can only use update to change it, however update also acknowlages the interaction.

i didnt realise editreply applied to any defered interactio. thank you!

tardy sable

It takes some times to understand all the reply methods, np

wintry laurel
fading girder

getting this error on clicking button that are 3 months old in a thread channel.

Any idea why this happens? no error on my logs too.

sharp ginkgoBOT
warm charm
    const welcomeContainer = new ContainerBuilder()
      .setAccentColor(EmbedColors.random())
      .addTextDisplayComponents(textDisplay =>
        textDisplay.setContent('## YunaBot'),
      )
      .addSeparatorComponents(seperator => seperator)
      .addSectionComponents(section =>
        section
          .addTextDisplayComponents(textDisplay =>
            textDisplay.setContent('Cảm ơn bạn đã sử dụng bot!'),
          )
          .setThumbnailAccessory(thumbnail =>
            thumbnail.setURL(guild.iconURL()),
          ),
      );

hi, i have code like this, how we can handle if the server doesnt have icon

unique shoal

Check for the icon first

And don't add a section/thumbnail if it doesn't

warm charm

oh ty, btw if i set the url = '', did it throw an error?

unique shoal

I don't know, but it probably will because it validates real URLs

warm charm

okay imma try it

mystic ridge

when i register my public commands globally using Routes.applicationCommands and my dev only commands for dev guilds using Routes.applicationGuildCommands , everything is fine, public guilds only have the public commands, and dev guilds also have public+dev commands... but when i fetch a dev guild's commands, ONLY the dev commands show up while in discord public commands are available.
is there a way to fix this or should i go the guild.fetchIntegrations to get my bot's commands to show them?

  1. if i also register the public commands for the dev guilds with Routes.applicationGuildCommands, because of the previous Routes.applicationCommands the public commands will be duplicated, so not that way
  2. if there is no way to fix the registering above, i could possibly do client.guilds.fetch() and use Routes.applicationGuildCommands to register commands for each guild separately, just need a little bit of confirmation if there is really no other way than this
unique shoal

Global commands are under client.application.commands

There isn't anything broken, in much the same way as you deploy separately, you fetch separately

Global commands aren't deployed to each guild individually and aren't available in that fetch

mystic ridge

ahh didn't know that was an available option my bad, yeah that will be good enough, tysm

grave trench

where i can see avilable video quality/bit rate limit for guilds depending or their boost level?

sharp ginkgoBOT
grave trench
dense jackal

max video quality on the server is always linked to the boost level/tier of that server

rigid crest

where is guild tag exposed? im expanding my server info command and this would be a perfect addition

dense jackal
rigid crest

but it has to be unlocked from a guild, weird logic ig

dense jackal
rigid crest

are the role enhancments accessible on role or ias that a non-logical flag 🙄

also are these accessible?

dense jackal
rigid crest also are these accessible?

this isn't available with the API as its relatively new, role enhancements are available with Role#colors, which has properties of primaryColor, secondaryColor etc

rigid crest

👍

rigid crest

can someone tell me where im going wrong, im targeting specifically secondary and holographical and it says its active when its not as seen in img 3 i clearly have 0 perks active

const hasEnhancedRoles = interaction.guild.roles.cache.some(role =>
                role.secondaryColor !== null && role.tertiaryColor !== null
            );
tardy sable
sharp ginkgoBOT
rigid crest

oh so its .colors.x

tardy sable

correct

also theres a guild feature to check if the guild has enhanced role colors unlocked

sharp ginkgoBOT
rigid crest

stressed

that would be easier, is that just guild.EnhancedRoleColors

steel trail

No. It's checking for that to be included in guild.features

tardy sable

no under features. features is in an array

sharp ginkgoBOT
rigid crest

do i need to call a .includes? or is this just fine for a simple yes no interaction.guild.features.EnhancedRoleColors ? 'yes' : 'no';

ok that seemed to work fine

steel trail

It shouldn't. That will always give you no

Because you check something that is always undefined

tardy sable

yh you have to check for include cuz its an array

steel trail

You should be proficient with js by now to know what an array is

tardy sable

you also need to do the enum correctly not just EnhancedRoleColors but GuildFeature.EnhancedRoleColors

naive shoal

Hey, a quick question. If I fetch the member, are all their roles always cached?

tardy sable
naive shoal

alright, thanks

steel trail
spice spire

Is there any way to update a message sent in response to a ChatInputCommandInteraction from a ModalSubmitInteraction?. I reply to a user command with a menu (ComponentsV2), and this menu has buttons that can show modals, and those modals can modify data displayed by the menu, so I'm looking for a way to update that menu after the modal is submitted, somehow. Is there a way to accomplish this?

sharp ginkgoBOT

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

spice spire

@wary coral TypeScript says ModalSubmitInteraction doesn't have an update method, though?

sharp ginkgoBOT
clear garnet

Use this typeguard to ensure the modal interaction is actually from a message thus allowing you to use update()

spice spire
barren nacelle

What would i need to do in order to make my bot only listen for my profile presence status update. I have the intent but am i missing anything else? Cause it just spams users when so much in console with this.

import { ActivityType, Events } from "discord.js";
import Event from "../types/Event";

export default new Event(
    Events.PresenceUpdate,
    { once: false, enabled: true },
    async (noxify, oldPresence, newPresence) => {

        console.log(`Presence updated for user: ${newPresence.user.tag}`);

        // if (newPresence.activities.length >= 0) {
        //     if (newPresence && newPresence.member) {
        //         const activity = newPresence.activities.find((activity) => activity.type === ActivityType.Listening && activity.name === "Spotify");

        //         console.log(activity);
        //         if (activity) {
        //             console.log(`${newPresence.member.user.tag} is listening to Spotify!`);
        //         }
        //     }
        // }

    }
);

Like i wanna have it check if I'm playing Spotify on my activities

There can't be thousands of users updating their presence every second. It almost acts like it's fetching every user.

rose tangle

there's nothing that filters only you

just check the user id and return if it's not you

barren nacelle

but why is it spamming so many people to start with

tardy sable
nimble obsidian

can you edit an ephemeral message normally?

cause whenever I try I get an error saying it can't find the message

bleak owl

are you using editReply?

nimble obsidian
topaz bluff

You can't use message.edit() on an ephemeral message. They're not real messages and the normal edit endpoint doesn't work

You can only interact with them using the interaction endpoints. If you want to edit the message a button was used on, then use interaction.update()

nimble obsidian
topaz bluff

I've never tried that one but that makes sense that it works. Interactions are webhooks

nimble obsidian
dusty heart

can defer reply contain flags?

stable sun

Or actually it can, mb

It’s deferUpdate that can’t

dusty heart
stable sun

Yea

Prob only for suppress embeds iirc

Oh right, you can also enable components v2

dusty heart

thanks

it's don't work

                        await interaction
                            .editReply({
                                content: i18n.get(guildLocale, 'commands.play.track_added', {
                                    title: track.title,
                                    uri: track.uri,
                                    user: interaction.user.username
                                }),
                                flags: MessageFlags.SuppressNotifications
                            })

no flags

clear garnet

Because you can't edit an already-sent message to suppress notifications. Notifications are distributed when the message is sent, so it makes no sense to try and prevent those notifications after the fact

dusty heart

await interaction.deferReply({flags: MessageFlags.SuppressNotifications}).catch((error) => logger.error(error));?

clear garnet

Interaction responses don't support suppressed notifications

dusty heart

__

sharp ginkgoBOT
clear garnet

Consult the docs for which flags are supported for which operation for an interaction

dusty heart

thanks

elder bear
const NorthAmerica = new StringSelectMenuOptionBuilder().setLabel("North America").setDescription("North America").setValue("na");
const SouthAmerica = ...
const Africa = ...
const Europe = ...
const Asia = ...
const Australia = ...

const ContinentSelectMenuBuilder = new StringSelectMenuBuilder()
            .setCustomId("cont_select_menu")
            .setPlaceholder("Continent Select")
            // .setPlaceholder()
            .setRequired(true)
            .addOptions(NorthAmerica, SouthAmerica, Africa, Europe, Asia, Australia);


const ContinentSelectLabel = new LabelBuilder()
            .setLabel("Continent Select")
            .setDescription("Continent Select")
            .setId(1)
            .setStringSelectMenuComponent(ContinentSelectMenuBuilder);

commandModal.addLabelComponents(ContinentSelectLabel);

await interaction.showModal(commandModal)

this code is making me receive a bunch of errors, any idea what may be going wrong?

i've condensed down the other continent constants, but they are formatted the exact same as NorthAmerica

velvet cipher
elder bear
velvet cipher It's probably better if you share your full code instead of the `...` parts. Als...
const commandModal: ModalBuilder =    new ModalBuilder().setTitle("Simulate income").setCustomId("simulate_income");
const NorthAmerica = new StringSelectMenuOptionBuilder().setLabel("North America").setDescription("North America").setValue("na");
const SouthAmerica = new StringSelectMenuOptionBuilder().setLabel("South America").setDescription("South America").setValue("sa");
const Africa = new StringSelectMenuOptionBuilder().setLabel("Africa").setDescription("Africa").setValue("af");
const Europe = new StringSelectMenuOptionBuilder().setLabel("Europe").setDescription("Europe").setValue("eu");
const Asia = new StringSelectMenuOptionBuilder().setLabel("Asia").setDescription("Asia").setValue("as");
const Australia = new StringSelectMenuOptionBuilder().setLabel("Australia").setDescription("Australia").setValue("au");

const ContinentSelectMenuBuilder = new StringSelectMenuBuilder()
            .setCustomId("cont_select_menu")
            .setPlaceholder("Continent Select")
            // .setPlaceholder()
            .setRequired(true)
            .addOptions(NorthAmerica, SouthAmerica, Africa, Europe, Asia, Australia);


const ContinentSelectLabel = new LabelBuilder()
            .setLabel("Continent Select")
            .setDescription("Continent Select")
            .setId(1)
            .setStringSelectMenuComponent(ContinentSelectMenuBuilder);

commandModal.addLabelComponents(ContinentSelectLabel);

await interaction.showModal(commandModal)

Any variables not modified after initialization are always given capital letters. those that have their objects modified get treated with lower camel case.
There's a rhyme to the reason, you'll notice it now.

velvet cipher

That convention is pretty uncommon and will confuse anyone who's used to js standards, but I guess you should do what you prefer

Anyways, how have you localized the error to this part of the code?

elder bear

because i added this code and it fails on interaction.showModal, they are validation errors on the data inside the modal therefore this segment of code is the only segment responsible... it is also the only segment of modal code in the entire project at this time.

velvet cipher

Do you do anything else with commandModal before?

elder bear

oh frick my code didn't include that

I used my autosnippet plugin, didn't cooperate myb

i put it in the big block above

rose tangle

that code isn't throwing for me

make sure it's saved and it's the correct snippet

halcyon bison
elder bear ```ts const NorthAmerica = new StringSelectMenuOptionBuilder().setLabel("North A...

at first glance, I'd guess that this is another case of something being imported from @discordjs/builders instead of discord.js, but I notice you're using ts, and I believe if that were the case, ts should let you know something strange is going on which would've required some silly nonsense like tagging an as any somewhere
so I worry either

  • this is the issue and something important was excluded by your 'autosnippet plugin'
  • in general the issue lies outside the code shown
crude mist

I've gotten this error before but I forgot how I fixed it
DiscordAPIError[10002]: Unknown Application at handleErrors (C:\Users\User\node_modules\@discordjs\rest\dist\index.js:762:13) at process.processTicksAndRejections (c:\Users\User\Documents\TestingDiscord.js\lib\internal\process\task_queues.js:105:5) at async SequentialHandler.runRequest (C:\Users\User\node_modules\@discordjs\rest\dist\index.js:1163:23) at async SequentialHandler.queueRequest (C:\Users\User\node_modules\@discordjs\rest\dist\index.js:994:14) at async _REST.request (C:\Users\User\node_modules\@discordjs\rest\dist\index.js:1307:22) at async C:\Users\User\Documents\TestingDiscord.js\index.js:48:18 {requestBody: {…}, rawError: {…}, code: 10002, status: 404, method: 'PUT', …} any ideas

rose tangle

can you show index.js line 48

crude mist

const data = await rest.put( Routes.applicationGuildCommands(CLIENT_ID, GUILD_ID), { body: commands } );

rose tangle

and CLIENT_ID, GUILD_ID are defined as?

crude mist

Im pulling them from the JSON

rose tangle

make sure they're strings in the json, not numbers

so

{
  "CLIENT_ID": "1234...",
  "GUILD_ID": "1234..."
}

but not:

{
  "CLIENT_ID": 1234...,
  "GUILD_ID": 1234...
}
crude mist
rose tangle

yeah they're stored as numbers

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

so wrap them in ""

crude mist

oo

yeah that worked

thanks

elder bear
rose tangle

that code doesn't throw though, so like duck said something is missing or it's not that altogether

elder bear
rose tangle

nope

also that's a validation error

so it's the builder telling you there's malformed data, not the api

but that code doesn't throw, so

elder bear

Pain but where, i even referenced the guide page and my code fits nicely with how that stuff is written

hmmm

rose tangle

but where's what?

elder bear
rose tangle

what?

I mean to ask

but where, i even referenced the guide page and my code fits nicely with how that stuff is written
but where, what?

elder bear

oh, where could the malformed data be provided at

rose tangle

not there like I said, that code runs perfectly

elder bear

Thats the only code written in that function

halcyon bison

you're correct, the code you've shown looks fine
this is why the issue likely lies outside the code shown
we will not be able to help further without seeing the rest of the code

rose tangle

can you share the whole stacktrace

elder bear

Yeah

hang on lemme get back to pc

 at _ObjectValidator.handleIgnoreStrategy (file:///home/monarchalia/WebstormProjects/Shadow/node_modules/.deno/@sapphire+shapeshift@4.0.0/node_modules/@sapphire/shapeshift/dist/cjs/index.cjs:2136:70)
    at _ObjectValidator.handleStrategy (file:///home/monarchalia/WebstormProjects/Shadow/node_modules/.deno/@sapphire+shapeshift@4.0.0/node_modules/@sapphire/shapeshift/dist/cjs/index.cjs:1983:47)
    at _ObjectValidator.handle (file:///home/monarchalia/WebstormProjects/Shadow/node_modules/.deno/@sapphire+shapeshift@4.0.0/node_modules/@sapphire/shapeshift/dist/cjs/index.cjs:2089:17)
    at _ObjectValidator.parse (file:///home/monarchalia/WebstormProjects/Shadow/node_modules/.deno/@sapphire+shapeshift@4.0.0/node_modules/@sapphire/shapeshift/dist/cjs/index.cjs:972:90)
    at LabelBuilder.toJSON (file:///home/monarchalia/WebstormProjects/Shadow/node_modules/.deno/@discordjs+builders@1.13.1/node_modules/@discordjs/builders/dist/index.js:1769:20)
    at file:///home/monarchalia/WebstormProjects/Shadow/node_modules/.deno/@discordjs+builders@1.13.1/node_modules/@discordjs/builders/dist/index.js:2868:64
    at Array.map (<anonymous>)
    at ModalBuilder.toJSON (file:///home/monarchalia/WebstormProjects/Shadow/node_modules/.deno/@discordjs+builders@1.13.1/node_modules/@discordjs/builders/dist/index.js:2868:35)
    at ChatInputCommandInteraction.showModal (file:///home/monarchalia/WebstormProjects/Shadow/node_modules/.deno/discord.js@14.25.1/node_modules/discord.js/src/structures/interfaces/InteractionResponses.js:402:46)
    at Object.execute (file:///home/monarchalia/WebstormProjects/Shadow/commands/Econ/simulateIncome.ts:42:27)

line 42 is interaction.showModal

wait wtf deno

rose tangle

you aren't using deno?

elder bear
elder bear

it's pulling from builders but i don't import from builders

rose tangle

I think the stacktrace is supossed to look like that indeed then

I really don't see any difference in our setup, other than I use node

the log below at the right shows that it builds correctly for me

elder bear

ok so i literally just wiped some stuff out of existence and it works, i have my workspace configured to cache the discord.js library in local, I made it exclude a directory when loading it

specifically builders, for some reason whatever i have setup is just being a bitch

rose tangle

¯_(ツ)_/¯

at least it works now ig

elder bear

yeah haha, thank y'all for the help Heart_Hug

rigid crest

question, is there a way to refine actual over "actual"? i am using ``### ❱ Server Member Limit: ${interaction.guild.maximumMembers},

i mean i understand this is what the api says it is, but i know server owners have to request a member elevation, every few 100k members

loud quartz

And even if, how could we here know, we merely display you what api tells us

warm charm

how i can make like ts

sharp ginkgoBOT

guide suggestion for @warm charm:
guide Context Menus
Context Menus are application commands which appear when right clicking or tapping a user or a message, in the Apps submenu. This page is a follow-up to the slash commands section. Please carefully read those pages first so that you can understand the methods used in this section.

warm charm

thanks

wintry laurel

how is this possible?

somehow interactions with a custom id of skipTutorialNo are not being forwarded to my bots code. there are none of the logs that i put in the button code

im not sure how this isnt working, the yes button works fine, and every other button works fine so it can't be a handler issue. maybe i should put a console log before the defer? but it dosnt make sense that it would need one because why would deferupdate not work?

no error logs in console either

if someone could help me with this that would be great

rose tangle

and how does your interactionCreate listener look like

the one that will actually receive the interaction and execute that method

wintry laurel
elder bear

heya folks, how can i potentially chain modals?
Upon modal submit there's more information i need users to fill out so i need to send them another modal... any basic implementation example i can reference?

rose tangle

you can't, you need another interaction in between

elder bear

Pain

welp, time to set up a button interaction

rose tangle
wintry laurel
rose tangle

maybe the file wasn't saved correctly lol

wintry laurel

oh there it is. i forgot the file type

rose tangle

yeah it says ,js

well that explains it lol

wintry laurel

weird because it showed up as normal when commiting it first and in my file tree but oh well

thanks

worthy sail

maybe a weird question, some bots dont have a presence (like a green dot, online dot) in their logo. Do you guys how you do this? Check this sc.

sharp ginkgoBOT

tag suggestion for @worthy sail:
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.

worthy sail

thanks :)

jagged rock

uisng defer fix uknown interaction?

topaz bluff

Not necessarily but it often does. A common cause for that is taking too long to acknowledge the interaction. Deferring early fixes that, then you have longer to actually send your reply

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
odd stirrup

afterwards you can take all the time you want (as long as that time is under 15 minutes) to follow up

clever hazel

i wanted to use the dm_channels.messages.read and write scope. it says i need to apply for it. Can I not use it without permission on personal apps?

polar karma

That's a question for discord, nothing the library handles. Check in ddevs

clever hazel

where can I apply? i cant find a proper link

polar karma

If you're asking about intents, the message content intent is not required to receive DMs

clever hazel

nono the oauth scope

polar karma
clever hazel
clever hazel

not related to discord.js lol

gritty sedge

Is none of the text inside a modal selectable? I'd like to link to a FAQ page within a modal but I can't find a good way to do so.

gritty sedge

You can't hold and drag your mouse over the text to select and then copy it. Otherwise a non-clickable url would be fine and users could copy it if need be.

tardy sable

Yh isnt possible and not something you can configure in djs

sand minnow
client.on("messageDelete", async (message) => {
  try {
    const logData = await logSchema.findOne({ Guild: message.guild.id });
    if (!logData) return;

    const logChannel = message.guild.channels.cache.get(logData.Channel);
    if (!logChannel) return logData.delete();
    setTimeout(async() => {
    const fetchedLogs = await message.guild.fetchAuditLogs({ limit: 1, type: 72 });
    const deletionLog = fetchedLogs.entries.first();
    const executor = deletionLog?.extra?.target?.username || 'Unknown';
    console.log("executor", executor);
    console.log("deletionLog", deletionLog);
if(message.channel.id !== deletionLog.extra.channel.id) return;
if(message.author.id !== deletionLog.executorId) return;
    const embed = new MessageEmbed()
      .setTitle("Message Deleted")
      .setColor("RED")
      .addFields([
        { name: "Content", value: `${message.content}` },
        { name: "Author", value: `${message.author.tag}` },
        { name: "Deleted by", value: `${executor}` },
        { name: "Channel", value: `${message.channel}` },
      ])
      .setThumbnail(message.author.displayAvatarURL({ dynamic: true }))
      .setTimestamp();

    logChannel.send({ embeds: [embed] });
  }, 2000)
  } catch (error) {
    console.error("Error logging message delete: ", error);
  }
});```
it doesn't get the correct "executor" of the message when deleted
polar karma

there is no guarantee that the audit log is generated by the time the messageDelete (or any event) is emitted, and not all message deletions generate an audit log to begin with

sand minnow
bleak owl

also, that code looks like v13

we do not support v13 here

tardy sable
civic jungle

what is discord.js equivalent of this eris.js method

channel.createInvite({ maxAge: 0, temporary: false });```
sharp ginkgoBOT

method GuildInviteManager#create() discord.js@14.25.1
Create an invite to the guild from the provided channel.


// Create an invite to a selected channel
guild.invites.create('599942732013764608')
  .then(console.log)
  .catch(console.error);

civic jungle

so

guild.invites.create(channel.id)
tiny condor

ye

spice spire

Just wanted to help anyone in the future trying to align text in a table without losing markdown with code blocks and monospace. I found this npm package called discord-button-width that can do it. You just need to use zero width spaces (\u220b) and pass it the string that needs padding and how long it needs to be.

`\u200b${padStringToWidth(
          user.username, // some string that needs padding
          160, // width in px
          "left" as Align // "left", "right", or "center"
        )}\u200b _(${truncateUserId(user.id)})_ [${permissionString}]` // just the rest of the string
tardy sable
spice spire

I can't even see general tbh

I'll post it there, thanks. Also I checked on mobile, it's not too bad but the edit button wraps to the next line

glacial quail
loud quartz

are you using message.edit() on ephemeral interaction responses?

glacial quail

so they can't be edited once being sent, just with editReply?

topaz bluff

Correct

Ephemeral messages are not real messages and can only be modified using the interaction token/endpoints

glacial quail

so i should use a collector to still edit that message?

i mean, like that i separate the 2 interactions but still being able to esit that message

topaz bluff

You can either hold onto the old interaction token or you can use interaction.update() to edit the message a component interaction originated from

glacial quail

how would i edit something with the interaction token?

topaz bluff

interaction.editReply()

glacial quail

oh like that ok

thanks mate

sand minnow
bleak owl
sand minnow
unique shoal

older, unmaintained, unsupported

tardy sable
sand minnow
rose tangle

it's on the channel description

sand minnow
rose tangle

there are no breaking changes for a given major (ts type changes aren't considered breaking but you don't seem to use ts anyways so that wouldn't affect you)

sand minnow

How can I get a user and member display name? For example mine would be "زين" not "zein_try"

sharp ginkgoBOT
sand minnow

Yh tried that, still shows as zein_try

sharp ginkgoBOT
sand minnow

Alr, thanks. I'll try it

topaz bluff

That one is nullable btw just so you're aware. displayName should use globalName if it's not null and falls back to username if it is

sand minnow

So displayName better, alr thanks!

unique shoal

impossible, displayName cant return null, and neither can be undefined

Whats the actual code and response/error if any

noble cairn

Is there somewhere which shows exactly which kinds of API errors each API-facing function might throw?

noble cairn

Darn 😔

stable sun

You can get a list of http status codes that Discord uses

And the json codes

noble cairn

nah, I'm trying to write correct jsdoc @throws tags for all of my functions

so ideally I'd get the error type of each of the different functions instead of generic DiscordAPIError

stable sun

Can’t rly get more specific than that

noble cairn

so I could match all of the variants of the DiscordjsErrorCodes enum

noble cairn
stable sun

D.js doesn’t document what each method can throw specifically

noble cairn

I got that from your first message ^^; I'm just sadge

madge, even

stable sun

I never found error safety that useful tbh

noble cairn

not safety as much as just saying different things for different errors

and knowing what to handle without having to go read the file and each of their sub-files is nice

stable sun

That’s error safety

noble cairn

I feel like safety is just making sure it gets handled

stable sun

Or ig it’s more so actually handling the error

But still, you’d have to indicate pass through

noble cairn

I can just slap a process.on("unhandledRejection", () => {}) and be safe as can be x3

stable sun

Ah yes, I love when my bot doesn’t crash when I make a typo

noble cairn
noble cairn
stable sun

No

Maybe if you unconditionally call process.exit()

But now we have unhandledRejectionMonitor, so no reason to use unhandledRejection in 2026

noble cairn

whomst

I am unfamiliar

can I have some material on this?

stable sun

Mb, was thinking of unhandledException

But still, just handle ur rejections properly

It’s rather easy if you stick w/ await and try catch blocks

noble cairn

yeah that's what I'm trying to do. I want to pass them to the caller to handle on a more global scale instead of 100000000 .catch(logger.error)s

I don't want to have a file-long try-catch 😭

ideally I can just pop any errors up the call stack and handle them at the caller

stable sun

Just do try { await command.run(); } catch (e) {…}

noble cairn

I have API calls all over the place. I don't want 500 try-catch bocks, and I don't want an extra level of indentation

stable sun

I’m assuming you are using a command handler since you mentioned separate files

noble cairn

yes?

stable sun

Just wrap the run call with try catch and await it

noble cairn

that's basically what I'm doing, but I want some granularity to the messages, so I was looking for individual error types so I could handle each differently

stable sun

I mean, it is assuming that you use async/await inside of the run function

Depends on how granular you want to get ig

noble cairn

currently:

try {
    await command(interaction);
} catch (e) {
    logger.error(`Encountered error when attempting to execute ${interaction.commandName}: ${e}`);
    if (interaction.replied) {
        interaction.editReply({ content: "Talking Stick encountered an issue. Please try again." });
    } else {
        interaction.reply({ content: "Talking Stick encountered an issue. Please try again.", flags: MessageFlags.Ephemeral });
    }
}
stable sun

I usually only do it for guards and early returns

noble cairn

I'd like to give a particular message if it had missing permissions, cache inconsistency, etc

stable sun

Should only give messages that the user can fix

noble cairn

not to the user, for logging

clear garnet

Best bet I'd say is to look at d.js' source code to see what d.js errors can be thrown - if any - and then what API calls are made, and then corroborating that with the Discord API documentation to see what API error codes can be thrown from a given API call

stable sun

Do you not just log the entire error object and stack?

clear garnet

Find a compromise then, I don't see any easy way to get what you're looking for ¯_(ツ)_/¯

stable sun

Who are you trying to impress?

noble cairn

I currently do, but I'd like to save less, as logs have been eating up my vps storage space

stable sun

Could log it elsewhere like to logtail

Or periodically upload and purge logs to gdrive

noble cairn

thing is I often need logs from like a week ago. also my gdrive is packed, but ig I could make a new dedicated account

I wish everyone used jsdoc to the fullest extent so we wouldn't have these kind of compromise-necessary situations

if we had more graceful error handling, I personally believe we wouldnt be living in (as much of) an era of incrudification

but this isn't the place for my opinions lol I'll get back to it

stable sun

You can just look through the error codes and convert it to a shorter string accordingly if ur still fixated on doing that

clear garnet
stable sun

Hopefully you’d still have enough info to track/debug the error tho

Although, it sometimes isn’t possible to fix due to the async nature of Discord and the volatility of the internet

There’s DiscordAPIError and DiscordjsError

noble cairn

and then there's DiscordjsErrorCodes

clear garnet

That's just what DiscordjsError#code consists of

noble cairn
balmy kraken
        this.interaction_collector = message.createMessageComponentCollector({
            idle: 1_00_000,
        })

how long is the time in component collectors options? I assume its ms

unique shoal

yes

sleek sigil

Why crossed out 'setLabel'?

warm charm
sleek sigil
warm charm
        const pictureOfTheWeekLabel = new LabelBuilder()
            .setLabel('Picture of the Week')
            .setDescription('The best pictures you have taken this week')
            // Set file upload as component of the label
            .setFileUploadComponent(pictureOfTheWeekUpload);

        ... 

                          modal
                    .addTextDisplayComponents(text)
                    .addLabelComponents(pictureOfTheWeekLabel);

here is the example from djs docs

hallow horizon

Is there a way to track discord tags?

For example, seeing whether or not members are wearing our discord tag, and whether or not they take it off throughout a month etc?

sharp ginkgoBOT
hallow horizon

This user's username, or their legacy tag (e.g. hydrabolt#0001) if they're using the legacy username system

Sorry, I mean the tag, like next to my name is a server tag - This seems to refer to just the users username

sharp ginkgoBOT
hallow horizon

hydrabolt#0001 - Is the old legacy naming system - which we don't use - Why does the docs mention it for .tag?

warm charm

idk ask djs maintainer 💀

hallow horizon
The tag of this user This user's username, or their legacy tag (e.g. hydrabolt#0001) if they're using the legacy username system

I'm just saying this is confusing documentation, if .tag is what I am after (The servers tag at the end of my name) - Why does it say it will get the users username, or there legacy tag?

I'll try it anyway - Thanks for sharing, just looks confusing on the front of it

topaz bluff
subtle girder

What is the length limit for the title of the choice in StringSelectMenuBuilder?

rose tangle

not User#tag

they're different things, hence the confusion from the other guy

sharp ginkgoBOT
rigid crest

well, this wasnt meant to happen

`### ❱ Has A Guild Tag? ${member.user.primaryGuild.tag ?  `:accept: [${member.user.primaryGuild.tag}](${member.user.guildTagBadgeURL} "${member.user.primaryGuild.tag}")`: ':decline:'}`,

sharp ginkgoBOT
tardy sable

have to pass argument ()

loud quartz

No, don't have to pass arguments

Have to call the function

silk forge

What shoud i set for a type in the <> of the ContainerBuilder?

outer plume

Based on the latest d.ts, it doesn't have any type args. so remove that <>

stable sun

Is ur editor not telling that the class takes no type args?

outer plume

also, it's not supposed to go in the embeds field. A container is a component, not an embed.

stable sun

That’s prob why it’s also red

Components v2 can’t be used w/ embeds and content

outer plume

and that's prolly a third reason for red squigglies

grave trench

what's wrong?

tardy sable
sharp ginkgoBOT

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

grave trench

it was my first dm after like months

error : Failed: Discord API rejected the message: {"message": "Invalid Form Body", "code": 50035, "errors": {"components": {"0": {"_errors": [{"code": "UNION_TYPE_CHOICES", "message": "Value of field "type" must be one of (1,)."}]}}}}

tardy sable

i cant make much from that code tbh, did ai write that? youre also just using the raw methods not any djs

grave trench

its a edge function

used for sending container from website to discord channel

polar karma
torpid marsh
const Ping = interaction.client.ws.ping == -1 ? 'Ping not measured yet, please try again later.' : `${interaction.client.ws.ping} ms`
    const Developer = await interaction.client.users.fetch(Config.DeveloperID)

    const Container = new ContainerBuilder()
    .setAccentColor(Config.Color)
    .addTextDisplayComponents((textDisplay) =>
      textDisplay.setContent('# Bot Information',),
    )
      .addSeparatorComponents((separator) => separator)
      .addSectionComponents((section) =>
          section
              .addTextDisplayComponents(
                  (textDisplay) => textDisplay.setContent(`### 🛠️ Developer 🛠️\n${Developer}`),
                  (textDisplay) => textDisplay.setContent(`### 📡 WebSocket 📡\n${Ping}`),
              )
      )
    .addSeparatorComponents((separator) => separator)
    .addSectionComponents((section) =>
          section
              .setButtonAccessory((button) =>
                  button.setCustomId('deleteButton').setLabel('Delete Message').setStyle(ButtonStyle.Danger),
              )
      );
  
    await interaction.reply({
        components: [Container],
        flags: MessageFlags.IsComponentsV2,
    });

I get the error:

 /eceived one or more errors/

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

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

And a different thing... When I add .setEmoji('🗑️') to the button... It says:

Type '"🗑️"' has no properties in common with type 'APIMessageComponentEmoji'.
wary coral
torpid marsh

Aaah

But how do I get the button below the text, and not next to it...

wary coral

use an action row

torpid marsh

Owh

wary coral

I assume a passing bug

torpid marsh

Alright.

Like this?

.addActionRowComponents((actionRow) => 
  actionRow
  .setButtonAccessory((button) =>
    button
    .setCustomId('deleteButton')
    .setLabel('Delete Message')
    .setStyle(ButtonStyle.Danger),
            )
    )
wary coral

yes