#djs-help-v14
78874 messages · Page 66 of 79
djs won't do anything for you then
then what should i do? its a ede function, allowing users to chaneg per guild personalization of bot from web dsahboard
well that's one way yeah
huh? wdym
I'm just saying that's outside the scope of a djs support channel
oh, so that ratelimit is just ratelimit, im not being dumb or ruining it?
better to ask in dev server #useful-servers
the error seems pretty straightforward imo
ill ping ya tmrw if this shows up again
ok pengu
you should ask where BakeWithMe said for non djs related issues
We are not Discord, just some nerds who develop Discord bots!
- /report appeals and age updates
- /howtoreport reports (harassment/hacking/spam/abuse)
- /support anything Discord related
- /billing payment/nitro
- /feedback feedback/feature requests
i'll ping you there, dw
can bots set voice channel status?
i seen this feature in few bots
yes but it's an undocumented endpoint so djs doesn't have a method for it
you'd need to do a raw request
like this
correct
like how
Client#rest discord.js@14.25.1
The REST manager of the client
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
REST#post() discord.js@14.25.1
Runs a post request from the api
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
ok thx for the little help
i try to search for that
https://discord.com/api/v10/channels/CHANNEL ID/voice-status
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'
}
Good evening, is there any way to filter a UserSelectMenu to display users that have a specific role ?
nope
Alright, thx 🙁
Hello, using components v2 is it possible to seperate two buttons on each side? So one button is far left and one far right?
No
Could have buttons which are secondary style and disabled, with an empty character for the label?
No
is it a bad practice to have a collector inside a collector? for example a game invitation and then the game?
Usually yes because every time the first one collects, it will create the second collector again
If that's intended, no it's fine
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?
Yea, that seems off
is there a docs for a list of all rate limits?
No. Discord doesn’t provide that
does cdn of epheral attachments expires?
all cdn links expire
alright, thanks both
does discord.js not support command names with spaces? I thought they did
The only time a space is technically allowed if it has subcommands
oh i see
actually that makes sense I forgot about subcommands
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.
And for the record, it's not that d.js doesn't support it, it's that Discord themselves don't allow it
well discord needs to stop making new modals and get to making /commands look nicer
They didn't make new modals
And this was something that was 4 years overdue
I don't know what I just did. I moved my ping command to the commands folder and now its all red
can we make it like a embed sent having a select menu of roles and a role is auto selected when its sent?
probably applied some formatter to the node_modules folder?
can just delete node_modules and run your npm i/yarn/pnpm i again
would also recommend excluding node_modules from version control (add it to your .gitignore file)
I tried unistalling and reinstalling
welp im just gonna move folders
there we go moving folders worked
.
you mean setting a default value for the role in the select menu?
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?
link?
thanks
can a bot send a file or voice message as empherial?
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
yes
as an interaction reply
no
oka
can a single message have container + embed?
No
can a single message have multiple containers?
I think yes looking at the builder
const components = [
new ContainerBuilder(),
new ContainerBuilder(),
];``` something like this
i dont think so
creative way of highlighting.
The only limit on components V2 is you are limited to 40 components per message
there's any event that triggers after having cache loaded?
bruh why building the message editor page is tooo difcult...
i literally lost half of my braincells
What is the limit on the number of options in StringSelectMenuBuilder?
So what if there are more than 25?
throw error
Select string options in modals
same limit
yes
I mean, is there another way?
multiple menus
Ohh
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
i don't think so
MSG.awaitMessageComponent();
counts as a collector right?
seems like it
yeaa
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
Just a guess but you are replying to the command interaction not the button interaction wait that is not right.
what is your filterrow?
row is a button
const row = new ActionRowBuilder().addComponents(button);
documentation suggestion for @crude mist:
AwaitMessageComponentOptions#filter discord.js@14.25.1
The filter applied to this collector
it's supposed to be a function
:this:
the example from the guide in your screen shot is
const collectorFilter = (i) => i.user.id === interaction.user.id;
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
ohh wait it's u zizzle
so then why did you set the filter as an action row
if I knew I wouldnt be asking on here
What you would want to do is set the filter to something like
const filter = (i) => i.customId === "eee";
for the code block you shared
The filter should be a function or a lambda expression that returns a boolean expression
yeah I found this which shares a lot with components and I think I got it
and it makes more sense than the guide
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
obviously you dont learn from copying and pasting
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'
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
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???
show your code snippit
can't edit an ephemeral message like that
they didnt mention ephemeral tho?
it is ephemeral, should have mentioned that
you would have to do editreply then
i can assume based on the snippet and error 
but how come i can edit them exactly like this when they stem from responses to command interactions?
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
ephemeral messages should be interacted with by editReply, they don't exist like traditional messages
.
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)
if theyre both interaction replies. they shouldnt behave different
in containers we can set custom image size also?
like how he did it, both images size
thats probably one image but png
okk
You asked this yesterday and we told you it was one image, you didn't beleive it and now you asked again 💔
before typing this "ok" i was typing for 15s same thing "ty pengu, i just remembered that someone told me this before that its 1 image" lol. then i just sent okk
but if thats the case then why can i edit them with .edit() when the message is derived from a ie. command interaction? I just wanna know if im accidentally abusing something
Ephemeral messages are not sent to the channel. edit only works on "real" messages in a channel
So you can see how they are different
Message edit route:
PATCH /channels/{channel.id}/messages/{message.id}
Interaction editReply
PATCH /webhooks/{application.id}/{interaction.token}/messages/{message.id}
i understand, but i still can do it
it works exactly as outlined here, except the interaction is a command
not what you asked, but i think you should use
flags: [MessageFlags.Ephemeral, MessageFlags.IsComponentsV2]
instead of
flags: MessageFlags.IsComponentsV2,
ephemeral: true
you should show your code because i think youre confusing it for something else
that is literally it
ok, then what is your problem then? If it works.
i want to figure out whether this is a bug that i should steer away from or if im safe to keep this
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
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
https://youtu.be/GVeIqO0pGE4
Perhaps you are referring to this where the dev who worked on cv2 made it as demonstration?
Yep ! That's what I was looking for, thank you so much
Would anyone know how to have a bot react to an embed that it sends?
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);
Same way you would on any message
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?
You emitted the messageCreate event with an old message
Ummm. How?
client.emit("messageCreate", ancientMessage)
I’ll scan for this, but let’s assume I didn’t do this, how else could it occur?
Use console.trace to see who emitted it
There’s not rly any other reasonable explanation for it
yes, by supplying the MessageFlags.IsComponentsV2 flag and the withComponents: true option
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?
discord js 15 better be good
you should add withResponse to the interaction reply and set your collector on the message.resource.message
InteractionReplyOptions#withResponse discord.js@14.25.1
Whether to return an InteractionCallbackResponse as the response
Is there a way for the bot to reply to the message that the user is replying to when running the command?
yes by just using .reply on that message
got it ty
You'll ALSO need to respond to the interaction independently or else there will be an error in the client
but a user cant reply and do a command at the same time? unless youre not talking about slash commands
ah so I will have to do message commands?
Oh you're right...that is how that works
Yh its easy to forget people still use message commands lol
You could use context menu commands instead of slash commands to reference the original message
well yes. you cant reply and perform a slash command. or do what samtino says
I will look into that, appreciate it!
how can I tell my TS that interaction.message.components[0] is a buttons row?
Does as ActionRow<ButtonComponent> work?
ActionRow is not generic
Should be 🤔
Is this some web storm thing?
wait, i have imported ActionRow from a wrong library (eris.js) -.-
it works now, thx
For webhook messages, is https://discord.js.org/docs/packages/discord.js/14.25.1/User:Class#bot set to true?
Should be
But it's pretty easy to test
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
You could use ComponentsV2 to send that image in a MediaGalleryComponent or you could send the image in the files field
alrighty, thanks
Yeah it is, thanks.
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?
Pretty much every action can be rate limited. I wouldn't be surprised if you could run into rate limiting issues with that
Do you think adding a short cooldown between every 5 reactions would be a good idea to avoid hitting rate limits?
DJS does handle rate limits for you. It will just queue the action until the rate limit expires
thx
how can I make such embed how can I fit images in embed?
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.
It's not an embed
you're already using a container, simply add a media gallery at the beginning and end of its nested components
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}`)
the rate limit is 2 changes every 10 minutes
Yeh, but can I not try catch that ratelimit error? Like it just hangs
ratelimits are queued by default, you can change that in the client options
ClientOptions#rest discord.js@14.25.1
Options for the REST manager
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
Ah ty, perfect
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?
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
Do you mean I should loop through all the bot's message and disable them before shutting down the bot?
all the ones that you want to disable, yes
This is an illogical solution. Let's assume the bot was on many servers and there were many messages; when I wanted to disable it, it would take time for all the messages to be disabled.
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
Okay thx for helping
You can do it, but its best to not do it and find another solution.
Or do nothing and see how your bot should behave after starting back up.
Bots are made to be online all the time, so handling shutdown isnt really something you should spend too much time on.
I simply let interactions fail if the bot is offline.
For persistent stuff like message ids I have a database.
is doing roll all is against tos? like giving all memebrs of a guild a role at a time with api
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?
Not against tos, but it can be pretty much spammy depending on the amount of members a server has, so you have to keep rate limits in mind before doing it
where i can see the ratelimits like how much possible in how much time etc
You cannot show a modal from a modal submit, you can show a button in between that shows the second modal when clicking
Do you have maybe another idea how I could program an application system with 15 questions?
Individual ratelimits are not documented intentionally, rate limits are dynamic and changes depending on usage.
Rate Limits - Header Format
X-RateLimit-Limit - The number of requests that can be made
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
With modal, that's the only way
like you do have an approx idea ? how much i can ? and i have one question. like how it works in bots for example ,roleall @role do it call discord api at once means discord can add to all immedietly or i takes time? or its just the bot who add intervals to avoid ratelimit
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.
but discord does immedietly?
i'm not testing just asking, like i saw this feature in a lot of bots like carl bot, which is in a lot of servers, so was wondering how they do it
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
fine
can we fetch with api the user join source?
like who invited him
No
the invite link?
Moderators can check that in native mod view, no need for a bot to know that
ig he want to make invite checker
wanted to show it on dashboard.
btw, if i do ,roleall @role in a 10k members server, do it sends discord 10k request or 1
10k
dayum
why don't discord allow us to fetch the server analytics shown in the dev portal?
Privacy reasons 🤷
are there ways to check if bot can dm a user before trying to .send()?
I don't think so. You're just going to have to catch the error
User#createDM() discord.js@14.25.1
Creates a DM channel between the client and the user.
you have this one right
How can I check if a channel is in a specific category, or has no category?
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
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.
I need to emphasize that this code hasn't been touched in 3 months, and only recently stopped working. I had to add debug logs in every step before it just to figure out it was being caused by this part specifically. Am I doing something wrong? Is this a Discord.js thing? A little help would be appreciated
im not sure whats a container, but try wrapping the string select into a label builder, set the label there then add your component
theres a new rate limit on fetching all guild members. better to keep them in cache so you also dont need to store user ids in a db
container is from componentsv2, the new discord component
and thanks, i will try right now
oh you mean the in-content buttons thing i saw a while ago? I haven't seen it in action till now tbh
that's very neat
I'm assuming this check relied on that internally and now it can't since the rate limit is present..
place the string menu inside actionrow at addActionRowComponents
Well, It's a good thing that I already cache members indefinitely so the change is quite simple
*also dont suggest stuff if you dont know what it is because this isnt a modal for label builders
I'm sad about spending 28 minutes trying to figure out what was causing it though..
yeah, sorry
.addActionRowComponents should be an actionrow component itself as far as i know
you can always ask for help here 
I thought it was the other logic unrelated to djs since there are 500 other lines of logic above this part haha
youd normal do
.addActionRowComponents(
new ActionRowBuilder()
.addComponents(...)
)
normally i do it without new ActionRowBuilder, is it a new update by any chance?
im not sure im kinda confused too by the two ways people are doing containers. either like this or something like component => component.setComponents
but try place it in an actionrow and see
yeah i use component => component.setComponents already
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
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
check if the channel’s parentId exists and compare it to the id of the category you want to check
why await channel.messages.fetch(id).catch(() => null) always returns object even if the id doesnt exists?
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
oh okay that makes sense thanks for clearing up confusion
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!
You need Channel partial
wdym but that exactly?
like when I make the client I need to specify Channel partials?
To receive direct message events on "messageCreate" with your bot, you will need:
- The
DirectMessagesgateway intent - The
Channelpartial setting
Only The channel partial point applies to you
ok ty! can I still do things like edit the message? that is currently where I run into an issue
Through the interaction webhooks, yes
ok, will try it, ty
DMChannel#isSendable() discord.js@14.25.1
Indicates whether this channel is sendable.
Sigh, where can I find the changes? 😄
LabelBuilder discord.js@14.25.1
A builder that creates API-compatible JSON data for labels.
guide suggestion for @tepid wigeon:
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.
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;...
We have #app-commands for personal use, or the hide option
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
Should be data.customId
Nvm i was wrong, what does it say when you try to access custom_id?
same as customId
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
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' ?
Idk what way you are doing it to tell, why do you think you are doing something wrong?
because in eris.js that would be 10 lines of code, here is like 30+
You don't need to use builders. You could just .filter(...) the array of buttons in the json
Or .map(...) it
AI told me that I cannot modify directly the interaction message lol
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
ok, I loop through and then what?
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
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
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
but bruh... -.-
what i said doesn't really exclude what qjuh said
then how do I make a new one out of existing?
Something like this
new ButtonBuilder(<Message>.components[0].components[0].toJSON())
how can I make the png show normally without having it inside the embed?
By using components v2 for example. There you can put a media gallery outside the container
EmbedBuilder#setImage() builders@1.13.0
Sets the image of this embed.
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)
okay! Thank you all. I will try all your suggestions to see whats best
I tried what you suggested for .setImage() but it doesn't show the image in the embed. And yeah inside the AttachmentBuilder() I have { name: "fight-card.png" }
whats gameCard
AttachmentBuilder
the gameCard is the png shown here
it should show in the embed that way. have you tried sending the file separately to see if its valid?
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
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
i suppose this isn't entirely discord.js related but whatever
then why ask in this channel anyway
you guys usually know shit 🤷
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"
ask in #1081585952654360687 or #archive-offtopic
mb i guess
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?
You can
wait what
It will only show you and the bot user though
how stupid is that. what about the role select? WIll that error though?
All selects work
Though role select doesn't show anything
lmao why did they not just deny it hahaha
I might make an issue on github for this; Thanks so much!
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
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
for createMessageCollector i should always do it on a channel? i cant do message right?
A message doesn't have messages (threads don't count)
yeah but its pointless. Why would you want to select a channel in a DM channel if you get the channel through the interaction anyways?
The same goes for the user/bot.
When i download animated emoji from a vuil5, the resulting file isn't animated, how do i animate it?
this isn't really related to discord.js so there's not much we can do to help with that, sorry
Sorry i meant guild
as in a discord server
that's still not something discord.js can help you with, sorry
I see
I'll try to look on my own then, thanks for replying ❤️
can a bot have rich presence and play a custom game?
hi, how i can fetch user who invited the bot
can the bot send ephemeral messages outside of replying to interactions?
no
No. It's not the bot that sends, but an app, and an app can only ever respond to interactions
that information is only available through audit logs and accordingly requires the permission to read audit logs
bot can't read that right
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);
Hey how to reduce message Latency
:( pls help
Depends, how high is it?
And where do you host and run your bot?
On normal 200
On high traffic 1k sometimes
Vps
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 ...?
Canada
It's not hitting rate limits havnt seen tho it's just on high traffic it takes longer to reply
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
thank you
I mean if it does hit ratelimit won't it stop sending the msg I told u based on that
And about vps capacity I didn't understood what you said could you please elaborate
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
Ohk I will do that and ask for help if needed
Thank you
So I checked
1271ms
This is ping without any rate limit
I was constantly viewing console
"ping" is ambiguous
where did you get that from or how did you measure that
It's measured by how long it takes bot to send and discord to show
and how do you do that
By sending a test message and waiting for discord to show or recieve
show code
how do you actually measure the number
const sendStart = Date.now();
const sent = await message.channel.send('Testing');
const sendEnd = Date.now();
const messagePing = sendEnd - sendStart;
const sentTime = Date.now();
const latency = Date.now() - sentTime;
const wsPing = client.ws.ping;
And you did listen to the rateLimited event?
Yeahh, I didn't saw anything
Show how you listen to the event
how to do something like setSectionComponents? bc that doesn't exist. by duplicating the old container and replace that section?
It's add not set
But if you want to replace components, use spliceComponents
ContainerBuilder#spliceComponents() discord.js@14.25.1
Removes, replaces, or inserts components for this container.
is this coming from discord.js?
return await message.reply({ embeds: [embed], files: [attachment] });
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...
Is that in a try/catch block? It looks like a custom error message
Hi there
Who know how to correctly cut or disable buttons from container after button interaction?
I'm tried methods from #1115775988857581668 but didn't fully understand
- I'm not really sure what methods from #1115775988857581668 you're referring to given that there aren't any posts relating to that topic there
- I notice you already have a #986520997006032896 thread about this where it's mostly been pointed out what's wrong with your current code, so I'm going to continue there
in future please stick to one channel
I'm not really sure what methods from faq you're referring to given that there aren't any posts relating to that topic there
I means https://discord.com/channels/222078108977594368/1370478227872551032
in future please stick to one channel
okay, my bad
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
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
Oh, i don't think the problem comes from that, i've added the console log to sure that iconUrl is not undefined
none of them are undefined
.setThumbnailAccessory(thumbnail =>
thumbnail.setURL(guild.iconURL()),
),
try ts maybe it work
already, but it doesn't :<
its working on my side
what's your djs ver
lastest, 14.25
me 2
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;
}
try to remove the thumb and try again, if not work then...
the section builder requires at least 1 accessory...
give it a button
lms
it still
then its not from thumb, try to remove section rn, add it with textdisplay
its called debug lol
it works when i
container.addTextDisplayComponents(
new TextDisplayBuilder().setContent(detailsLines.join('\n'))
)
``` 💀
💀
I'm late to the convo, is it still this error that's being debugged?
if so, could you show how you're importing the builders?
oh wait, i've imported it from djs builder
💀 you should import from djs
my fault 💀
discord.js includes multiple sub-packages, installing these separately can mess with internal code:
[0;31mnpm [0;0muninstall discord-api-types @discordjs/rest @discordjs/builders
[0;34myarn [0;0mremove discord-api-types @discordjs/rest @discordjs/builders
[0;33mpnpm [0;0mremove discord-api-types @discordjs/rest @discordjs/builders
Using
client.rest.on('rateLimited', (rateLimitData) => {
console.log('Rate limited!', rateLimitData);
});
Sorry I didn't saw that yesterday
is that a copy/paste issue or is that your actual code... cuz... that's not right
ty all, it works now
I didn't found anything from internet its a example I found from ai
but that's like not even valid javascript
So what's the fixed version
client.rest.on('rateLimited', (rateLimitData) => {
console.log('Rate limited!', rateLimitData);
});
Oh no the upper part it's when I pasted it was due that that
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
Updating channel statuses are undocumented and thus unsupported by DJS
It's possible but I do not know how
Ahaa its still undocumented
Incorrect login details were provided.
at WebSocketConnection
how do I fix this
by providing correct login credentials
whatever you pass as token is not a valid, active, bot token
Then it's really your VPS or its connection being slow
If by connection you mean ws.ping then ahh its 40-50ms
No, that's a completely different metric and you probably didn't even measure that at the time your bot was under high load
Ws ping was fine even under high load (i was chrcking back then)but about connection what do you mean by that and is there a way to fix it
For a voice channel if the user limit is infinite, would that be 0 in VoiceBasedChannel#userLimit ?
or negative or what?
yes userlimit would be 0
Question, does the messagecreate event tell you if a message is marked as a spoiler? 
I mean specifically pictures
Attachment#spoiler discord.js@14.25.1
Whether or not this attachment has been marked as a spoiler
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);
}
}
});
correct, because on the very first line if there is no channel in the new state you immediately return
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
what exactly is not working? the modal will not go through if above 4000 length
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
yes thats just a discord thing they changed. nothing to do with djs
what ?
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
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.
that error should be discord sided and not bot
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?
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
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
okay
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
being able to type and being able to submit are different things
hi, why my code doesnt reply the container (in confirm phase)
are you getting an error
no
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
oh i forgot to put the "MessageFlags.IsComponentV2" to the flags, thanks
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 ;-;
What's the full error including stack?
@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'
}
Is it an ephemeral message?
no, it is public for all
Did you log fetched to confirm it is a message object? Is there something deleting the message before that line?
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 ;-;
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 🙏
Are you supplying the customId of the component to your .getUploadedFiles(customId)?
Yes
Is the field required or not? If not required, it should return null if no files were uploaded, rather than an empty Collection
Can StringSelectMenu have autocomplete and extend 25+ menu options?
so max 25 options
correct, String Select Menu cant not have more than 25 options
but others can
alright, thanks
Wdym?
role and channel ofc
Those are not String Select Menu and users can only select 25 options(role & channels respectively) in those
With the new modal components, how many rows can I add to the modal?
You can still only have 5 components in a modal
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
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.
correct
Hi! Sorry, I have a quick question. It is possible to delete the message like "XXX has pinned….." when a message is pinned?
yes listen for that message type
You can try to delete latest message where channelPinsUpdate event triggered
documentation suggestion for @unreal stone:
MessageType#ChannelPinnedMessage discord.js@14.25.1
Does system messages trigger messageCreate?
yes message.system
Didnt know that, ty
Thanks! Another question! What is the limit of message.fetch() ? I read 100, but I know that pinned is 50
Message#system discord.js@14.25.1
Whether or not this message was sent by Discord, not actually a user (e.g. pin notifications)
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);
bless ! 🙏
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.
You can only fetch pinned messages up to 50
oh, thanks :D
But discord mentioned a way to fetch more than 50
Yeap, i do something like that
message.fetch() only fetches that message though
if you want to fetch many you'll need the messages manager of the channel, channel.messages.fetch(...)
yes, it was a typo on my side! thank you :)
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
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...
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
oldUser = await oldUser.fetch();
This is pointless. All this is going to do is turnoldUserintonewUser, because you can't fetch outdated user data from the API, it's only gonna give you current data
so what do i do xd
if (newUser.partial)
This also seems pointless, since your own typings say thatnewUsercannot be a partial
do i just remove all of it or
Not try and fetch it. It's old data which is only gonna be present due to d.js' caching
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?
Sure
but i still need this right
Correct, otherwise the event is not going to emit at all if there's any partial oldUser
thanks
If you want to explicitly ignore firings where there's partial old data, then don't subscribe to the User partial
if oldUser is a partial then oldUser.avatar will be null
are u sure
partial means that the data doesnt exist
Hello, when selecting channel in select channel menu is the channel permission inside the payload? Or does it have payload after selecting?
my assumption is, if it's a cached channel... then yes...
but the interaction payload itself only contains the channel id
Because im stuck on how to check permission in the selected channel, I am using core so my bot is stateless. I avoid fetching too to prevent rate limit.
Do you have any suggestion?
if your app is stateless... then fetching or an unreliable cache is really all you can do
In this code snippet (permission), Is this number represents what the User (who submitted the modal) can do?
Or is the permission enabled in the channel
computed permissions for the invoking user in the channel, including overwrites, only included when part of the resolved data received on an interaction. This does not include implicit permissions, which may need to be checked separately
https://discord.com/developers/docs/resources/channel#channel-object-channel-structure
since these are mostly just questions about the api rather than@discordjs/coreitself, these are probably better suited to ddevs #useful-servers
how we can check user dm enabled or not 😭
i need it to dm a user w/ bot
By dming them
DM should only be sent by invocation of the user
try to dming them, and we catch error right
alr ty
btw when i can't send msg to the user it will throw error 50007 (CannotSendMessagesToThisUser) right
Refer to the API docs for the error messages to confirm
can I do ChatInputCommandInteraction.deferReply({flags: MessageFlags.Ephemeral})
and cancel the Ephemeral?
you cannot change the ephemeral state of a message
okay
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?
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
yea no there would be no new message, update changes the existing one so if i updated after a defer update it would be the same message yea?
i dont want a new message, i just want to make sure that my updates arnt taking longer than 3 seconds and want to add this as a safty
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
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
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
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
Yea, such a flag doesn’t exist for deferUpdate
ok thanks
ephemeral isn’t an editable property/flag
yea makes sense
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?
Edit reply for editing the interaction message. Use followup to reply to the defer
i dont want a new message tho
Then edit reply to edit the message
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
You cant update twice use the editreply
ok and before i add that, that works if i use defer update right
Yes
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!
It takes some times to understand all the reply methods, np
think i got them all now finally lol
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.
ButtonBuilder discord.js@14.25.1
Represents a button builder.
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
Check for the icon first
And don't add a section/thumbnail if it doesn't
oh ty, btw if i set the url = '', did it throw an error?
I don't know, but it probably will because it validates real URLs
okay imma try it
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?
- if i also register the public commands for the dev guilds with
Routes.applicationGuildCommands, because of the previousRoutes.applicationCommandsthe public commands will be duplicated, so not that way - if there is no way to fix the registering above, i could possibly do
client.guilds.fetch()and useRoutes.applicationGuildCommandsto register commands for each guild separately, just need a little bit of confirmation if there is really no other way than this
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
ahh didn't know that was an available option my bad, yeah that will be good enough, tysm
where i can see avilable video quality/bit rate limit for guilds depending or their boost level?
documentation suggestion for @grave trench:
Guild#maximumBitrate discord.js@14.25.1
The maximum bitrate available for this guild
@cobalt plover what about video quality?
max video quality on the server is always linked to the boost level/tier of that server
where is guild tag exposed? im expanding my server info command and this would be a perfect addition
only in the User class, not in the Guild class
but it has to be unlocked from a guild, weird logic ig
its only displayed next to a user's username tho
-- but yeah I don't see why its added to the guild object too
are the role enhancments accessible on role or ias that a non-logical flag 🙄
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
👍
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
);
secondarycolor etc is on the colors property
Role#colors discord.js@14.25.1
The colors of the role
oh so its .colors.x
correct
also theres a guild feature to check if the guild has enhanced role colors unlocked
documentation suggestion for @rigid crest:
GuildFeature#EnhancedRoleColors discord.js@14.25.1
Guild is able to set gradient colors to roles

that would be easier, is that just guild.EnhancedRoleColors
No. It's checking for that to be included in guild.features
no under features. features is in an array
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
It shouldn't. That will always give you no
Because you check something that is always undefined
yh you have to check for include cuz its an array
You should be proficient with js by now to know what an array is
you also need to do the enum correctly not just EnhancedRoleColors but GuildFeature.EnhancedRoleColors
Hey, a quick question. If I fetch the member, are all their roles always cached?
if you got the guild members intent yes
alright, thanks
Guilds intent
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?
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);
@wary coral TypeScript says ModalSubmitInteraction doesn't have an update method, though?
ModalMessageModalSubmitInteraction#isFromMessage() discord.js@14.25.1
Whether this is from a MessageComponentInteraction.
Use this typeguard to ensure the modal interaction is actually from a message thus allowing you to use update()
That did it. Thank you two for the quick response
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.
there's nothing that filters only you
just check the user id and return if it's not you
but why is it spamming so many people to start with
because even members going offline/online triggers the event
can you edit an ephemeral message normally?
cause whenever I try I get an error saying it can't find the message
are you using editReply?
um no I am just doing interaction.message.edit() (I did make sure to reply to the interaction as well)
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()
I see
I also found that doing interaction.webhook.editMessage() also worked for some reason
I've never tried that one but that makes sense that it works. Interactions are webhooks
oh they are? interesting, ty
can defer reply contain flags?
Or actually it can, mb
It’s deferUpdate that can’t
can editReply?
Yea
Prob only for suppress embeds iirc
Oh right, you can also enable components v2
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
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
await interaction.deferReply({flags: MessageFlags.SuppressNotifications}).catch((error) => logger.error(error));?
Interaction responses don't support suppressed notifications

ChatInputCommandInteraction#editReply() discord.js@14.25.1
Edits a reply to this interaction.
// Edit the initial reply to this interaction
interaction.editReply('New content')
.then(console.log)
.catch(console.error);
Consult the docs for which flags are supported for which operation for an interaction
thanks
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
It's probably better if you share your full code instead of the ... parts. Also, a tip is to stick to the common naming convention for variables which is lowerCamelCase
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.
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?
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.
Do you do anything else with commandModal before?
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
that code isn't throwing for me
make sure it's saved and it's the correct snippet
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
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
can you show index.js line 48
const data = await rest.put( Routes.applicationGuildCommands(CLIENT_ID, GUILD_ID), { body: commands } );
and CLIENT_ID, GUILD_ID are defined as?
Im pulling them from the JSON
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...
}
yeah they're stored as numbers
- 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")
so wrap them in ""
oo
yeah that worked
thanks
it is being imported from discord.js itself.
that code doesn't throw though, so like duck said something is missing or it's not that altogether
do you need a flag enabled for modals to be sent.
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
but where, i even referenced the guide page and my code fits nicely with how that stuff is written
hmmm
but where's what?
discordjs.guide
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?
oh, where could the malformed data be provided at
not there like I said, that code runs perfectly
Thats the only code written in that function
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
can you share the whole stacktrace
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
you aren't using deno?
yes, yes I am.
it's pulling from builders but i don't import from builders
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
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
¯_(ツ)_/¯
at least it works now ig
yeah haha, thank y'all for the help 
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
They don't anymore (it's why this doesn't say 100k)
And even if, how could we here know, we merely display you what api tells us
how i can make like ts
guide suggestion for @warm charm:
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.
thanks
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
and how does your interactionCreate listener look like
the one that will actually receive the interaction and execute that method
this code has worked since ive had my bot, and other buttons in the same folder work so idk how it would be a issue there
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?
you can't, you need another interaction in between

welp, time to set up a button interaction
I think it looks fine at first glance, place some logs starting at the top of the listener and see where it stops
ok
you must have the magic touch
adding the logs fixed it 😭
i assume the button just needed to be refreshed or something lol, thanks
maybe the file wasn't saved correctly lol
yea maybe not, im checking my gh commit history and for some reason the file was not makred as a js for some reason, so probably that but yea weird
oh there it is. i forgot the file type
yeah it says ,js
well that explains it lol
weird because it showed up as normal when commiting it first and in my file tree but oh well
thanks
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.
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.
thanks :)
uisng defer fix uknown interaction?
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
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
note that you still have to defer within 3 seconds
afterwards you can take all the time you want (as long as that time is under 15 minutes) to follow up
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?
That's a question for discord, nothing the library handles. Check in ddevs
where can I apply? i cant find a proper link
If you're asking about intents, the message content intent is not required to receive DMs
nono the oauth scope
Ddevs in #useful-servers
alright ill ask there, thanks
not related to discord.js lol
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.
wdym with selectable?
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.
Yh isnt possible and not something you can configure in djs
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
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
so what's my fix here? deleting the part where it says "Deleted by:"?
also, that code looks like v13
we do not support v13 here
thats up to you if you want to keep it or not
what is discord.js equivalent of this eris.js method
channel.createInvite({ maxAge: 0, temporary: false });```
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);
so
guild.invites.create(channel.id)
ye
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
something for #archive-offtopic . also this probably looks very bad on mobile
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
Hey i'm having a little truble while trying to edit a message, here is the code and the error
https://pastebin.com/ftj8rDEc | selectMenuInteraction
https://pastebin.com/w1XStf4g | verificationSystem.js
https://pastebin.com/ssjWM4Fe | Error
are you using message.edit() on ephemeral interaction responses?
so they can't be edited once being sent, just with editReply?
Correct
Ephemeral messages are not real messages and can only be modified using the interaction token/endpoints
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
You can either hold onto the old interaction token or you can use interaction.update() to edit the message a component interaction originated from
how would i edit something with the interaction token?
interaction.editReply()
oh like that ok
thanks mate
If I can't fix it, why keep it?
we can’t help you much further regardless due to you using v13
How is it any diff from v14?
older, unmaintained, unsupported
there isnt really something to fix. you just cant expect to always accurately get the audit log
Ah I see, alr thx
Mind giving me docs to changing from 13 to 14 pls, latest version
it's on the channel description
Latest version tho? Or was there no other changes afterwards in v14
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)
Alr, thanks
How can I get a user and member display name? For example mine would be "زين" not "zein_try"
User#displayName discord.js@14.25.1
The global name of this user, or their username if they don't have one
Yh tried that, still shows as zein_try
User#globalName discord.js@14.25.1
The global name of this user
Alr, thanks. I'll try it
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
So displayName better, alr thanks!
Both r giving me undefined
impossible, displayName cant return null, and neither can be undefined
Whats the actual code and response/error if any
Is there somewhere which shows exactly which kinds of API errors each API-facing function might throw?
No
Darn 😔
You can get a list of http status codes that Discord uses
And the json codes
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
Can’t rly get more specific than that
so I could match all of the variants of the DiscordjsErrorCodes enum
I mean... discordjs does, no?
D.js doesn’t document what each method can throw specifically
I got that from your first message ^^; I'm just sadge
madge, even
I never found error safety that useful tbh
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
That’s error safety
I feel like safety is just making sure it gets handled
Or ig it’s more so actually handling the error
But still, you’d have to indicate pass through
I can just slap a process.on("unhandledRejection", () => {}) and be safe as can be x3
Ah yes, I love when my bot doesn’t crash when I make a typo
I do. I mayyy be using typescript justttt a bit
I mean ideally you'd have some checks in there :(
No
Maybe if you unconditionally call process.exit()
But now we have unhandledRejectionMonitor, so no reason to use unhandledRejection in 2026
whomst
I am unfamiliar
can I have some material on this?
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
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
Wdym?
Just do try { await command.run(); } catch (e) {…}
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
I’m assuming you are using a command handler since you mentioned separate files
yes?
Just wrap the run call with try catch and await it
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
I mean, it is assuming that you use async/await inside of the run function
Depends on how granular you want to get ig
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 });
}
}
I usually only do it for guards and early returns
I'd like to give a particular message if it had missing permissions, cache inconsistency, etc
Should only give messages that the user can fix
not to the user, for logging
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
that sounds like hell :D
Do you not just log the entire error object and stack?
Find a compromise then, I don't see any easy way to get what you're looking for ¯_(ツ)_/¯
Who are you trying to impress?
I currently do, but I'd like to save less, as logs have been eating up my vps storage space
Could log it elsewhere like to logtail
Or periodically upload and purge logs to gdrive
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
You can just look through the error codes and convert it to a shorter string accordingly if ur still fixated on doing that
Could just log the error code whether it's a d.js error or an API error and then save a reference for what each error code means. Would be a bit less verbose log-wise than saving the entire errors including their human-readable sentences
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
and then there's DiscordjsErrorCodes
That's just what DiscordjsError#code consists of
Yes, and depending on the code, I want to do different things, so it would be helpful to know what each function is capable of throwing
First half
this.interaction_collector = message.createMessageComponentCollector({
idle: 1_00_000,
})
how long is the time in component collectors options? I assume its ms
yes
Why crossed out 'setLabel'?
deprecated
Mmm , what replace it then?
@deprecated — Use a label builder to create a label (and optionally a description) instead.
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
Thank you.
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?
documentation suggestion for @hallow horizon:
User#primaryGuild discord.js@14.25.1
The primary guild of the user
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
yes .tag
UserPrimaryGuild#tag discord.js@14.25.1
The user's guild tag. Limited to 4 characters
hydrabolt#0001 - Is the old legacy naming system - which we don't use - Why does the docs mention it for .tag?
idk ask djs maintainer 💀
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
The User#tag value is a legacy feature added by DJS a very long time ago. The User#discriminator value isn't deprecated as it's still relevant for bots as they use the legacy username system.
Renaming User#tag would be a breaking change as well, so they can't do that yet.
User#primaryGuild is how you see the Server Tag. That's how the API is designed.
What is the length limit for the title of the choice in StringSelectMenuBuilder?
that'd be User#primaryGuild#tag
not User#tag
they're different things, hence the confusion from the other guy
tag suggestion for @subtle girder:
Learn more about select menu limits at the Discord Developer Documentation
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:'}`,
documentation suggestion for @rigid crest:
ClientUser#guildTagBadgeURL() discord.js@14.25.1
A link to the user's guild tag badge.
have to pass argument ()
No, don't have to pass arguments
Have to call the function
What shoud i set for a type in the <> of the ContainerBuilder?
nothing
I'm pretty sure it's not generic.
But hold a min, let me confirm
Based on the latest d.ts, it doesn't have any type args. so remove that <>
Is ur editor not telling that the class takes no type args?
also, it's not supposed to go in the embeds field. A container is a component, not an embed.
That’s prob why it’s also red
Components v2 can’t be used w/ embeds and content
and that's prolly a third reason for red squigglies
omg your right my mistake
what's wrong?
idk why but you show as likely spammer. share what error message youre getting
no idea, i dm'ed a guy, just a single guy. got banned from dev server + marked as spammer
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,)."}]}}}}
i cant make much from that code tbh, did ai write that? youre also just using the raw methods not any djs
its a edge function
used for sending container from website to discord channel
this isn't related to d.js, you should ask in ddevs in #useful-servers
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'.
Sections require a text display and accessory
Aaah
But how do I get the button below the text, and not next to it...
use an action row
Owh
And What about this issue?
I assume a passing bug
Alright.
Like this?
.addActionRowComponents((actionRow) =>
actionRow
.setButtonAccessory((button) =>
button
.setCustomId('deleteButton')
.setLabel('Delete Message')
.setStyle(ButtonStyle.Danger),
)
)
yes