#djs-help-v14
78874 messages · Page 47 of 79
it's just an alias like the docs say
I'm asking about whether the listener will also collect from the edited message, or if I have to attach a new one
how i can set vanity guild invite link with bot
well that really depends on your editReply's contents and in your collector's options
if your collector is set to only collect 1 then it won't if you received the cancel button interaction
you can completely ignore the sleep, it's the same workflow in general
that is not possible anymore
Alrighty, thanks!
why discord removed the future or what
it was abused
so its not avalible any more
correct, as i originally said
thx
how do i get someones user id from someone @ing them in a message
message.mentions
does that give id
will contain what you need
It can
Message#mentions discord.js@14.22.1
All valid mentions that the message contains
ty
how do i get the id of the user from this
i'm a bit confused
It contains all mentions
yes but how do i get the id?
message.mentions.users.id doesnt work
So you can iterate over the message.mentions.users collection and get ids from there
users is a collection, potentially containing more than one
how do i iterate over it
If there is only one you can just use users.first().id
ty
i getting error if i using my language system in event, but it works in commands, how can i fix it
#1081585952654360687 as it's not djs related
hi how can i get count of timeout members?
for example some user timeouted by staff and you use server info command and field return some information about server + timeout member count
fetch all members (guild.members.fetch()), filter for member.isCommunicationDisabled() and check the size of that collection
const member = await guild.members.fetch()
const timeoutCount = member.filter( m => m.isCommunicationDisabled()).size
like this or different way
Missing an await on the fetch
i edit it now
should be good, try it out and see
Hello! I am hosting a bot in ~8k servers. Recently, I have been encountering an issue during startup. Shard #1 and Shard #2 start perfectly. However, Shard #3 fails to start (hindering ongoing startups).
From the error and logging, I have not yet identified the issue. I can imagine several reasons that I could not verify
- Guild in shard #3 is bugged
- Recent update? I use the newest discord.js
Error:
0|. | Shard #3 is online.
0|. | Error [ShardingReadyTimeout]: Shard 3's Client took too long to become ready.
0|. | at Timeout.onTimeout (/root/snaky/node_modules/discord.js/src/sharding/Shard.js:190:16)
0|. | at listOnTimeout (node:internal/timers:573:17)
0|. | at process.processTimers (node:internal/timers:514:7) {
0|. | code: 'ShardingReadyTimeout'
0|. | }
Sharding Code:
var manager = new ShardingManager("./bot.js", {
token: auth[key],
execArgv: ['--trace-uncaught', '--trace-warnings', '--inspect=0'],
totalShards: 'auto',
timeout: 120_000
});
manager.spawn({ amount: 'auto', delay: 10000, timeout: 120000});
// Track when all shards are ready
let readyShards = new Set();
manager.on("shardCreate", shard => {
console.log(`Shard #${shard.id} is online.`); // THIS FIRES FOR SHARD 1, 2, and 3
shard.on("ready", () => { // THIS ONLY FIRES FOR SHARD 1 and 2
readyShards.add(shard.id);
console.log(`Shard #${shard.id} is ready. (${readyShards.size}/${manager.totalShards} shards ready)`);
if (readyShards.size === manager.totalShards) {
console.log("All shards are now ready!");
}
});
});
}
I appreciate any help and hints. Thank you!
5x5 grids with the new display components look completely broken on mobile 🙁
Nothing we can do about that
Yes, am aware, I'd post it on DDevs but I got banned from there a while back, just wanted to share
Really more of a #archive-offtopic thing then, since this isnt something we can provide support for
Bot response speed is only based on network or also on vps components
Is the Guild#unavailable supported within discordjs? Want to make sure i don't accidentally delete any data when servers do become unavailable. Since it's documented in the discord api references to be included when it sends a guildDelete for unavailable guilds.
documentation suggestion for @proud shoal:
Guild#available discord.js@14.22.1
Whether the guild is available to access. If it is not available, it indicates a server outage
D.js handles this for you
(event) Client#guildUnavailable discord.js@14.22.1
Emitted whenever a guild becomes unavailable, likely due to a server outage.
You don’t even need to check it
Ah, so it's a separate event that D.js does a check for and only sends the guildDelete if bot is removed. Otherwise sends guildUnvailable event.
If i'm understanding you right?
Yea
i have a bot hosted, and im getting Unknown interaction on all interactions, button, commands, etc
the same code works with a diff token on my local machine
why could this be?
tag suggestion for @brittle dawn:
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
Why are my clickable commands rendering a bit differently and not working inside embeds(on mobile, they seem to work okay on PC)? I've used the same syntax: </command name:command id>
First image: my bot
Second image: another bot
Both on mobile
difference between mobile and computer client, nothing you can control
Dont want to sound inpatient but whats taking so long for the modals update, the pr is like a month old now. Does djs dev support it?
one is a container one is an embed maybe?
since you seem to be following the prs, dev builds are released automatically, daily
so if a pr is merged (to main, backports not included), a dev build will be released within the day
I see one of the prs has already been merged, so that feature is supported in the dev build
edit: two
thanks
https://discord.com/developers/docs/components/reference#label noticed this exists but I'm not sure how to use it in discordJS? Label component doesn't exist it seems.
const input = new TextInputBuilder()
.setLabel(`${id} ${name}`)
I can only set a single label here, there's no setDescription or overload for setLabel 
Label components (aka new modal stuff) is not yet supported by DJS
Ah I see
what type of thing is this embed msg or what?
i found this thing in rythm bot
That's Components V2, not an embed
Popular Topics: Display Components
read more
those icons has transprent buttons right?
It's just a button with the Secondary style
You can't make a transparent button...iirc
new ButtonBuilder().setCustomId("home").setEmoji(":Home:").setStyle(ButtonStyle.Secondary), is this correct?
Secondary would be the transparent option
Is it transparent or grey? I honestly forget if it uses your client theme
It's secondary. Nobody should rely on it having a specific color
Use style according to what the button does, not how it looks
Primary for button that should be the primary focus/the one used mostly
Secondary for other buttons or ones used similarly often
Success for buttons as confirmation
Danger for destructive actions
But the complete dev version is incompatible with v14. Is there a way to select specific PRs/code changes to install?
I'm migrating some embeds I have to componenets, is there anything similar to inline text I had on embeds?
I have quite a long list of items, and with an embed I just inlined half of them.
No, there is nothing similar to this in V2 components.

you'd probably want to have a pagination system if you insist on components v2
there isn't
someone know how can i get the voice call active time on guilds?
its not a documented feature so discord.js does support it
discord.js does not support features until they are officially documented.
While there might be a way for these features to work, it can change at any time without any notice
oh ok
~~Hello, could anyone push me in the right direction of setting up an audit log event listener?
Just trying to get all the events as they happen and pop them in a message.~~
Figured it out 🙂
is it possible to mention server tags?
like your DFT tag? you mean mention that? no not that im aware of
yeah, would be neat. hopefully they'll add it
i doubt they’ll add that feature since you can click the tag on the user profile
yeah its a bit niche, would just be nice to have the option
would be better to just update the invite banner to include the tag
i would like to mention it here is all
tags dont have an ID...they're just a value...you can represent it as a string
Thank you for using our Server Tag,
DFT
but no, it wouldn't contain the badge, you would have to display that as an image from the badge hash
You could add the badge icon as an emoji to get closer
yes, i figured as much. would be neat is all i'm saying
yup, that's what i'm doing now
is there a way to access the custom id of a button component
something like
row.components.forEach((c) => console.log(c.customId));
Did you try it?
yeah
So you’ll have your answer then
it gives undefined
What’s row
const row = new ActionRowBuilder<ButtonBuilder>();
It’ll be components.forEach((c) => c.data.customId) I believe
still undefined it looks like
just log what c is then
it was .custom_id
weird that there are no typings tho, thanks
the JSON uses the APIName values so the JSON for an action row is APIActionRowComponent<APIButtonComponentWithCustomId>
that didn't work
TLDR: custom_id is what the API calls it...DJS just renames it to match JS casing
https://discord.js.org/docs/packages/discord.js/14.22.1/APIButtonComponentWithCustomId:Interface <-- here is the docs page
(Backticks inside the square brackets)
ya i was being lazy and pasting the links over...should have just put them underneath
How do I use a mentionable option safely in TS? The only properties I'm seeing are flags, toString, and valueOf...
This command is only usable in a guild
(please ping in replies)
Is this on the interaction.options? Are you typing it as ChatInputCommandInteraction? If not can u give more detail?
It is typed as ChatInputCommandInteraction, and a required getMentionable option. Is using instanceof with Role and GuildMember the proper way to go?
Yh that’s best, since it could be either ofc. I’ve not used it so idk if there’s a better way
Alr sounds good, can't test crap rn because my wifi is out (hotspot isn't working for my laptop either)
Rip
Is it physically possible to fetch the argument (5) from the ChatInputCommandInteraction from a ButtonInteraction on the same message?
I want the button to be able to see the arg (5) without having to hide it somewhere in the 2nd embed to make it look super clean
You can’t just put it in the custom id?
Could do tbf, did that in another place but didn't think to do it here.
Is there any other way or is that the only reasonable way to try it?
That’s the only way
Gotcha, thanks
Discord didn’t document the arguments as part of the message like shown in the app
Yeah, I could get the embed delete part from the ChatInput[...] object, but not the args for it
Might change by interactionCreate handler to support args
Something like a customId that splits by $$ for extra args, like ceb_delete_confirm$$5 or something to pass 5 as an arg to it
Yea, that’s what I do
Do you know how long a customId can be before it curls up and dies?
ButtonBuilder#setCustomId() builders@1.11.2
Sets the custom id for this button.
100 chars

Ok, ty. Will impl that change tmr :D
Is it possible to change a bot's profile avatar and display name per server?
the api added that recently, but djs doesn't support it yet
Alright thank you!
how do i add a component to a message
Message#edit() discord.js@14.22.1
Edits the content of the message.
// Update the content of a message
message.edit('This is my new content!')
.then(msg => console.log(`Updated the content of a message to ${msg.content}`))
.catch(console.error);
Use message.edit to edit the components that the Message has
Unless it was from an interaction
but is there a way to send a message with a component?
Yea
sorry thats what i meant
Specify the components field when you send the message
like how would i add a button
.send({components: […]})
Interactive Components: Buttons
read more
is there a list of components?
Are you using the new ones?
yea
Well, newer
Popular Topics: Display Components
read more
ty
how to put button in embed
its not an embed its a container
read this guide ^
thank
Webhooks not owned by a bot can't send any components? Not even URL buttons?
they can, non-interactive ones - like URL buttons
Gotcha, I am having trouble doing that are there any examples on how to? 
On what? It’s the same as anything else you just need to make sure your bot owns the webhook
talking about "not owned by a bot"
still valid tho - nothing special, just send it as you would otherwise
Kinda my point of “what do you need help with” but yes
if you have issues with doing that, explaining the issue tends to be more productive than asking for random samples
Don't you need to set with_components: true
If you’re sending v2 components
am i the only one who got this problem ?
\@discordjs\rest\dist\index.js:188
static {
^
SyntaxError: Unexpected token '{'
What’s ur node version?
v16.6.0
Update it
thank you, i forget that i didn't download the latest lol
Yes sorry, here's my code:
const { EmbedBuilder, WebhookClient, ButtonBuilder, ButtonStyle, ActionRowBuilder } = require('discord.js');
require('dotenv').config();
const webhookUrl = process.env.WEBHOOKURL;
const webhookClient = new WebhookClient({ url: webhookUrl });
const embed = new EmbedBuilder()
.setTitle('Some Title')
.setColor(0x00FFFF);
const button = new ButtonBuilder()
.setStyle(ButtonStyle.Link)
.setLabel('Read Now!')
.setURL('https://wwechampions.scopely.com/');
const buttonRow = new ActionRowBuilder().addComponents(button);
webhookClient.send({
embeds: [embed],
components: [buttonRow]
});
And it sends the message but the button doesn't appear
You need to enable withComponents in the send method for Webhooks
Is that just for cv2 components or for all?
Thank you very much that worked 
Ah right cool
For all
if I put many GatewayIntentBits to intents list of ClientOption
will this make the RAM usage of bot increase rapidly? (because of cache)
It’s likely
Typing events usually kill
I wouldn’t say it’s from cache. Just receiving events you don’t use
oh~ ty
You can always adjust the cache settings for most collections anyways
Miscellaneous: Cache customization - Limiting caches
When creating a new Clientopen in new window, you can limit the size of caches, which are specific to certain managers, using the makeCache option. Generally speaking, almost all your customizations can be done via the helper functions from the Optionsopen in new window class.
read more
Discord tracks this information now, is this available through the API too?
From what I can see, no
okay ty
now i'm curious where the info is coming from
can't be client-side tracked, since it's accumulative session length, not individual time in voice
so i suppose it's in the voice gateway packets? - client doesn't seem to make a call when i join a channel that'd retrieve it
{"op":43,"d":{"guild_id":"399667662625701893","fields":["status","voice_start_time"]}} is whats being sent from wss://gateway.discord.gg/?encoding=json&v=9&compress=zlib-stream, thats all I could find though
Team question, is there a section that discord js can read reactions per certain channel? If a reaction is added or removed? And how many etc?
Like a discord.js doc?
Any known issues fetching members currently? I am getting a lot of timeouts running this command guild.members.fetch() started in the past 12 hours or so. I checked Discord, but don't see any status events on their site.
How can I get the online member count in a server?
I've tried ```js
const members = await guild.members.fetch({ withPresences: true }); // checked that it doesn't fail
const onlineMembers = members.filter(m => m.presence.status !== offline).size; // m.presence is null
reactions are per message, so not natively, no. you'd a) want to have each message cached, and b) if you have messages cached in general for other channels as well, filter the event by reaction.message.channel.id and return if it's not your desired channel
offline member presence is null, so you need to account for that in your code. you can use optional chaining ?. which will return undefined if a value is null in the chain
Optional chaining (?.)
The optional chaining (?.) operator accesses an object's property or calls a function. If the object accessed or function called using this operator is undefined or null, the expression short circuits and evaluates to undefined instead of throwing an error.
But this causes online member count to be pretty much the same number as the total member count, which isn't right 😅
you'd want to change your logic of what you're checking for. filter it to equal an online presence or idle presence and it should be more accurate
how do i send a component with interactionreplyoptions
it's always the same option
components
So ```js
const onlineMembers = members.filter(m => [online, idle, dnd].includes(m.presence?.status)).size;
but how do i use interactionReplyOptions the docs arent really helpful
I'm not sure what you mean with "use"
they're the options interaction.reply takes
Is there a way we can set up a button that when used will let us upload a file or upload to a modal?
the only attachment option is in slash commands
is Role#members always populated correctly? getting it from chat input interaction option
I believe it is only populated with members in cache
^
Role#members discord.js@14.22.1
The cached guild members that have this role
Is it possible to create a container using an object like in embeds
Wdym "object like in embeds"
like how embeds can be created using the embed object
Are you talking about EmbedBuilder.from()?
what's the attachment size limit and how many attachments i can send in one message?
documentation suggestion for @junior moat:
API Reference - Uploading Files
read more
Is it possible to fetch attachment urls from forwarded messages?
I meant this
All the DiscordJS builders are just building JSON in a similar structure to that. The builders are just there to make it easier to add data without worrying about defining the types
Component Reference
read more
The official Discord Docs show how all the object structures need to be built. You can construct it yourself if you so choose (many prefer this was for certain usecases for many different reasons)
Thanks that was what I needed
how to make a modal with custom json data (so i can use modal components)?
documentation suggestion for @simple gorge:
Using Modal Components
read more
yeah but how do i do that @dense jackal ?
in djs*
Just be aware, you're also going to have to use the raw InteractionCreate event as DJS's InteractionCreate event will throw out events with Labels because they're "malformed" events
you use the json that's given on the docs to send it, but you cannot respond to it yet
TBH. It's better to just wait...as you're going to have to change quite a bit to support them yourself
and when is that?
There's no ETAs, never are
Your username and profile pic looks oddly familiar.
🤷♂️
a gfx guy made me this for 120 robux
yet you have "I'm new here" icon attached.
value.channel
.send({
components,
flags: MessageFlags.IsComponentsV2,
options: {
allowedMentions: {
parse: [],
},
},
})
.catch(null);
I don't understand why mentions still exists ?
I want to prevent mentions
In reply it works as expected, but in channel not
message
.reply({
components: [container],
flags: MessageFlags.IsComponentsV2,
allowedMentions: {
roles: [],
users: [],
repliedUser: null,
parse: [],
},
})
.catch(null),
not sure why you wrapped it on an options object
the usage is the same as in your 2nd example
This resolved my problem
Thx <3
during guild fetches or channel fetches, does it matter if the id is a string or an int?
every id in djs is a string
you can't do ids with numbers, they're bigger than the biggest number you can use in javascript
in JS, you should store and use all ID's as strings...or you risk rounding errors
is there any way to achieve the mobile icon in status?
Not supported by us. Because bots aren't mobile users
oh.. it was possible on v13 ryt
possible and supported are not the same thing
oh yea..
Hey question can i check what platform person is on line desktop or mobile
i do not believe bots have access to that information
Presence#clientStatus discord.js@14.22.1
The devices this presence is on
They do!
nvm i am wrong...i was looking at the official docs not the djs one...thanks
ya litsen to monbrey... not me
somone need help?
no, which is why there are no pending questions
anyone know how to stop this from showing when using attatchment builder
I believe by updating node
i keep getting this
node:internal/process/promises:289
triggerUncaughtException(err, true /* fromPromise */);
^
[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "#<Response>".] {
code: 'ERR_UNHANDLED_REJECTION'
}
network issues or problem with api?
how do you add a string select menu to a modal i thought they added it recently like this
Currently not supported by DJS
nooooo 💔 💔
is there a way to sort of hack it in perchance or no
Yes and no. You can send raw API requests to bypass the validation in DJS...but you're also going to have to handle raw INTERACTION_CREATE gateway events as the new Label components would cause DJS to throw out the event for being "malformed"
mmmm ok ty
is there any way currently to display media URL embeds with components v2?
to be a bit more verbose, i want to display an image, video, or whatever-else media file by an external link, such as https://www.w3schools.com/csS/paris.jpg
similarly to sending it plain in the message content, like any other embed, or sending a custom embed with the URL as the #image.url property
Yeah, the media gallery component
oh, thats curious. i was a bit mistaken scrounding around in the docs
I looked at the file component doc first, and missed the note under the file property
The APIUnfurledMediaItem ONLY supports attachment:// references
which is in fact different from the media gallery component. my mistake
i thank you
Ah! Legend! Thanks
Can't use server emojis in a dropdown?
You can
StringSelectMenuOptionBuilder#setEmoji() discord.js@14.22.1
Sets the emoji to display on this option
And in slash auto complete options it doesn't convert them right?
That's correct
Should it be with ID or what is it?
ID and name
Is it better to use interaction.update() for button interactions as opposed to interaction.editReply() ?
They aren’t the same thing, so you can’t compare them
What's the difference?
update is an initial interaction response that updates the message that the interaction came from
editReply edits the initial interaction response (default) or a followUp message
sorry you lost me, so both of them handle the initial interaction response no?
No
afaik, update is mainly used with buttons
Only update is an initial interaction response
when u say initial ie it can only be used once?
Yes
You can’t use reply twice, for example
yeah correct, you would use editReply
Yea, or followUp if you wanted to send a new message
So update is a one time use thing only?
Yes
right so if im using a button like a counter then its not ideal to use update
It is ideal to use update
It’s once per interaction
Every button click is a new interaction
yeah but the button will be pressed more than once
OHHHH right ok ok i got you, its once per interaction unlike with editReply() where you can send 1 and then edit it after 10s too
Yea
so update() works like reply() but reply() is used to initially send once and then update() is used as a "reply once"
but if i use update(), can i then use editReply() after it?
Using editReply after an update would edit the message the button is on
do you need to defer for a update() ?
deferUpdate exists, similar to deferReply
deferX methods are initial responses too. So you call it then use editReply when ur ready to actually provide the response
yup exactly that but js Error [InteractionNotReplied]: The reply to this interaction has not been sent or deferred. So technically I can heavily avoid this as update() would just work as reply() 🤔
That error is caused by using editReply or followUp before an initial response is called
whats the difference between deferReply() and deferUpdate() ?
It’s what calling editReply will do when you call it afterwards
deferReply will send a loading message until you editReply with the data to fill the message with
deferUpdate does nothing at this time and calling editReply afterwards will edit the message the button is on
you can use deferReply() on a button or na?
Yea
and you can use deferUpdate() on a slash command?
No
There’s no message to update in such case
OHH deferUpdate() has to be used on a message only
The message has to exist when the interaction occurs
yeah i got u
Basically only buttons, select menus, and modals that came from buttons and select menus
So let's say I click a button and reply in 1s with interaction.reply(), that's all good.
I click a button and use deferUpdate(), now I have to use interaction.editReply() because interaction.reply() won't work as interaction was defered.
my question is
if i click a button, can i use interaction.update() or do i need to defer it first?
if i click a button and use deferUpdate(), can i still use interaction.update() ?
If you deferUpdate, then you must use editReply to update the message
You can use update first if you want to edit the message within the 3 second window
right so update kind of works the same as reply() then
Yea
I thought it would handle it internally on what to pick or something lol
I had this as this was a simple function to pick what to use
It's commented out because I don't use it much anymore but previously I used to just interaction.deferUpdate() without await so by the time the reply was ready, i used to check if its deferred and if so to edit the reply otherwise reply
Yea, you should almost always know what to do at any point in the command without guessing/checking
Only exception I’ve come across is during error handling
Heh, exception
Yeah thing is I always want to reply in under 3s but sometimes the API (external) lags and thats why I chose to do it this way because I noticed that deferReply() used to take like 500ms aswell
In this project i solely use discord so majority of my responses are under 3s but that code was from another project
because I got this error
from this line js return interaction.editReply({ components: [row] }); // line 126 but literally prior to that i have ```js
await interaction.deferUpdate().catch(err => handleError(err, null))
I used `await` so it should 100% be defered and I use should be able to use editReply() so I was confused as to how that's happening
I can only assume that there was some issue defering the update and code proceeded past it
https://discord.js.org/docs/packages/discord.js/14.21.0/ClientEvents:Interface#guildScheduledEventUpdate any reason as to why oldEvent can be null
Because it might not be cached upon receiving the update event. If you have the scheduledevent partial
Ah makes sense
I mean, you did catch it
So you now have to check the return value to see if it errored
can d.js return guild tag and member has it?
Or check interaction.deferred
Or use try catch block instead of Promise.catch
documentation suggestion for @glossy sky:
User#primaryGuild discord.js@14.22.1
The primary guild of the user
❤️
Does anyone know what the character limit is for message's content field?
Via a bot/app
2000
Ah :/ ty
using cv2 text display components this is increased to 4000 characters @eternal drift
Popular Topics: Display Components - Text Display
read more
sometimes I need to list few usernames for example boosters list or something like that and the problem is that some users has ** in their names and for example it makes parts of my text Bold or users who has _ in their names make parts of the text underlined what should I do? create a function to add \ before * and some other symbols or DJS have a solution for it?
you should use their user id instead of their username
no i want to show their displayName
escapeMarkdown discord.js@14.22.1
Escapes any Discord-flavored markdown in a string.
can use this helper function then
Discord.escapeMarkdown("**String**") will return **String** ?
It will return "\*\*String\*\*"
oh okay <3
I get this even though i mention channel like #example
Even when i do 1423631864287203389 just channel id
It happens immediately after running command and my bot takes a little while to run
What's the code
Let me send it
When i get home i am so sorry when i get home i will send it
whats the max # of components in a container
no limits, but total for a message is max 40
thanks
are buttons the only one supported in sections rn
Thumbnails are also a supported section accessory
Hello where can I find the upload file size limits for a bot? (and with server tier levels)
Any chance anyone knows how to find Server Subscription SKUs? They are not in the developer portal like the ones for apps/bots
https://smalldev.tools/share-bin/8GvAWYZG
This is code for that image i set above weird thing is i am not getting any errors that i programmed
Also i am not getting any errors in logs
The file upload size limit applies to each file in a request. The default limit is 10 MiB for all users, but may be higher for users depending on their Nitro status or by the server's Boost Tier. The attachment_size_limit value provided when working with interactions is calculated as the maximum of these values.
-# ref
thanks
any eta for 14.23? if not is there a dev version i can use?
that's a system error, nothing djs can control
sounds like an issue with your client
make sure it's updated, otherwise ask in ddevs #useful-servers
no for both
👍
is it possible to change the gateway url in discord.js to some other gateway?
why would you want to do that?
At that point, just use a websocket library and connect to another websocket...this one is designed to work for the Discord Gateway Websocket
Do you mean a gateway proxy?, if so yes
Also. #how-to-get-help
Looks like you have too many commands
You can only have 100 global slash commands, 5 global user commands, 5 global message commands (if I'm remembering the numbers correctly)
Which is why you're getting the "must be 110 or fewer" error
??
oo so what to do
Delete commands
Or consolidate commands using SlashCommandGroups
Or. The likely better option. Split your bot up. If you have >100 commands, your bot is likely doing WAYYY too much. Split responsibilities between bots
Even offers better downtime as you only need to restart one bot at a time. When that specific bot needs changes
what if i use as sub command
Sub commands and slash command groups are a great way to combine commands of similar or same purpose under a single command slot for Discord
Like you don't need a /config-set and /config-delete
Just a single /config set/delete
yep going to do that
They appear different for the user but to Discord, they are the same command just using Options to split them
oo thx
you can see it in action when you would type “/report” in this server, its 1 command named “report”
with subcommands “message” and “user”
more info here 👇
Application Commands - Subcommands and Subcommand Groups
read more
guys why i cant see my user app commands on dms?
Are they deployed globally? And do you have your user app installed to your account?
📜 Your Scripts:
1. ID: 68e0051e7f52123140082187
Executes: 4
Last Updated: 10/3/2025, 7:19:40 PM
2. ID: 68e00328f3c4e34519ee4e8f
Executes: 0
Last Updated: 10/3/2025, 7:09:19 PM
here an example it doesn't work on dms tho
i mean in dms w diff people
Are you setting any contexts on the command structure? Ensure you have PrivateChannels
any docs for this? i have no clue where it is located
SlashCommandBuilder#setContexts() discord.js@14.22.1
Sets the contexts of this command.
Application Commands - Interaction Contexts
read more
And I was trying to find that one. Thx b3ssel
What do I need to do to make sure my slash commands appear in DMs? People can add my bot to their own apps (can use it on every server but not in dms) and I set .setDMPermission(true) and also deploy my slash commands globally
.setDMPermission is deprecated in favor of .setContext() as seen above
ooo thank you so much!!!
im sorry i didnt see it above
You're fine.
Command usage is defined by 2 things...integration types and contexts
- Integration Types: where people get access to commands (guild install means all people in a guild, user install means all people who "install" your app)
- Context: where the commands can be used (guilds means any server, dms means with the bot's dms, and private channels means other user's dms and group dms)
Do bots receive their own ephemeral messages as a message event
ephemerals are only sent to the adressed user
they are returned from the respective endpoints, if used with the wait query (i think we have an option in the call for those in djs), if you need them on the app
Thank you :)
withResponse is the option key (example: https://discord.js.org/docs/packages/discord.js/14.22.1/ButtonInteraction:Class#reply)
💙
How do you get the join method from a user? It's visible in the members list, so it should be visible to the bots, right? Or is that exclusive to users only
not available to bots
ughhhhhhhh
Thank you. I guess I'll figure something out. idk
Is this ther correct way to fetch a message?|
const message = await channel.messages.fetch(voteData.messageId).catch((error) => {
console.error(`Impossibile recuperare il messaggio di voto ${voteData.messageId}:`, error);
return null; // Restituisce esplicitamente null in caso di errore
});
Because I am getting always an error
What’s the error?
Uknown message even if voteData.messageId is the ocrrect str id
Is that message also in that channel? Is it also a string?
okay I see thank u so much, unfortunately my deploy script just randomly stopped working, I didn't make any changes but it's just stuck on loading the commands and doesn't deploy them
if you make a rest instance, use rest.on('rateLimited', console.log) to see if you’re rate limited as it’s likely that
ohhh i see tysm
im not rate limited, hmm very weird
hey, is it possible to mention users in a embed title?
No.
you can easily test this out, but while some parts of an embed don't resolve to mentions, nowhere inside of an embed will actually notify the mentioned user
It will just show @{their username} without the ping nor display name.
will it?
Yeah i think so, doesn't show pings in title but it does for description.
well, that's not how mentions work, and embeds don't replace unresolved mentions with usernames
Lemme check
Or it shows <@123456789 whatever their id is
yeah, that's the mention format
which would mean that embed title doesn't resolve user mentions at all
Yeah thats what i said
When i deploy the bot, and type "What is Flypoints?" the bot didn't reply to me, the console.log isn't showing as Ready! Logged in as ${readyClient.user.tag} in the vscode integrated terminal
index.js code:
const { token } = require('./config.json');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
// Message Create and Delete Section
client.on('messageCreate', message => {
if (message.content === `What is Flypoints?`) {
message.reply(`Flypoints is a system used after NovaEagle Flights`);
}
});
// Client Ready Zone
client.once(Event.ClientReady, readyClient => {
console.log(`Ready! Logged in as ${readyClient.user.tag}`);
});
client.login(token);```
How did you deploy the bot?
by deploying in a terminal
You typed in the terminal to startup the bot?
i used vscode integrated terminal
Like node .
i tried node index.js and node .
didnt show the console log
What is the name of the file you just showed?
With the code
it's index.js
const { token } = require('./config.json');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
// Message Create and Delete Section
client.on('messageCreate', message => {
if (message.content === `What is Flypoints?`) {
message.reply(`Flypoints is a system used after NovaEagle Flights`);
}
});
// Client Ready Zone
client.once(Event.ClientReady, readyClient => {
console.log(`Ready! Logged in as ${readyClient.user.tag}`);
});
client.login(token);```
the code is here for index.js
Please add the following code to your code base outside of any other event listeners and provide the full log output relevant to your issue.
client
.on("debug", console.log)
.on("warn", console.log)
- Note: if you initialize your Client as
botor other identifiers you need to use these instead ofclient - If the output is too long to post consider using a bin instead: gist | sourceb.in | hastebin
ok
you need the MessageContent intent to read message content
i know
then why isn't it on your intents

ContainerComponent discord.js@14.22.1
Represents a container component
can someone point me in the right direction
im trying to set a role to a holographic color and gradient colors
@lofty topaz please use #app-commands or the hide option for personal docs usage
documentation suggestion for @proud sparrow:
Role#setColors() discord.js@14.22.1
Sets new colors for the role.
// Set the colors of a role
role.setColors({ primaryColor: '#FF0000', secondaryColor: '#00FF00', tertiaryColor: '#0000FF' })
.then(updated => console.log(`Set colors of role to ${updated.colors}`))
.catch(console.error);
hmmm
@rose tangle, i did exactly the code in this message and im using the correct version (14.22.1) and i got a invaid role color error
when i set it to a holographic color though it works
you can only use the tertiary color with the hardcoded value of that enum in the docs example
Permissions - Role Object
read more
When sending tertiary_color the API enforces the role color to be a holographic style with values of: primary_color = 11127295, secondary_color = 16759788, and tertiary_color = 16761760.
those are the values of the enum in the example
.addFileComponents(FileBuilder =>
FileBuilder
.setURL(`attachment://${filename}`)
.setDescription('Project File')
)
this wrong?
what is filename
also a better question would be to share the error
rather than asking whether it's wrong
you already know whether it works or not
so it's a pointless question
TypeError: FileBuilder.setURL(...).setDescription is not a function
at C:\Users\pc\OneDrive\Desktop\swift sharecode\index.js:203:6
at resolveBuilder (C:\Users\pc\OneDrive\Desktop\swift sharecode\node_modules@discordjs\builders\dist\index.js:2224:12)
at C:\Users\pc\OneDrive\Desktop\swift sharecode\node_modules@discordjs\builders\dist\index.js:1795:75
at Array.map (<anonymous>)
at ContainerBuilder.addFileComponents (C:\Users\pc\OneDrive\Desktop\swift sharecode\node_modules@discordjs\builders\dist\index.js:1795:56)
at Client.<anonymous> (C:\Users\pc\OneDrive\Desktop\swift sharecode\index.js:200:2)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
doesn't look like there's a description field indeed
FileBuilder discord.js@14.22.1
ty got it working
when does the ApplicationEmoji#delete() promise resolve?
await client.application.emojis.fetch() // .pop().name === "indent"
.then(emojis => emojis.forEach(emoji => emoji.delete()));
console.log("All emojis have been deleted!");
for (const file of dir) {
// ... few more promises ...
await client.application.emojis.create({
attachment: buffer,
name: string // dir[0] === "indent"
});
}
All emojis have been deleted!
Uncaught _DiscordAPIError DiscordAPIError[50035]: Invalid Form Body
name[APPLICATION_EMOJI_NAME_ALREADY_TAKEN]: An emoji named indent already exists for this application. Applications can not have duplicate emoji names.
checking discord.dev, all other emojis upload just fine; i only receive an error for the first
forEach doesn't wait for promises to resolve
oh. thats news
i'll look into that
const deletePromises = await emojis.fetch().then(emojis => emojis.map((emoji) => emoji.delete()));
await Promise.all(deletePromises)
this is one way of doing it
or with a for of loop, or with Promise.allSettled... there's a lot of options, depends on what you want to do and your preferences
Promise.all()
The Promise.all() static method takes an iterable of promises as input and returns a single Promise. This returned promise fulfills when all of the input's promises fulfill (including when an empty iterable is passed), with an array of the fulfillment values. It rejects when any of the input's promises rejects, with this first rejection reason.
Promise.allSettled()
The Promise.allSettled() static method takes an iterable of promises as input and returns a single Promise. This returned promise fulfills when all of the input's promises settle (including when an empty iterable is passed), with an array of objects that describe the outcome of each promise.
freakin' sick
thank you so much
what is the intent to get GuildAuditLogEntryCreate event
GuildModeration
- Websocket intents limit events and decrease memory usage: learn more
- See what intents you need here
What is the different between message.author.tag with message.author.username? Or it had the same function?
tag includes the discriminator
So like it's only good for bots?
Yea
okay thanks
The first screenshott, that is a placeholder, right? How about the second? I want to make it like the second screenshot, and just don't know how
that's the value
TextInputBuilder#setValue() builders@1.11.2
Sets the value for this text input.
if using the builder
console.log(`Bot is ready ${client.user.tag}!`);
console.log(`Code by Bandarr.`);
console.log(`Bandarr - Code King :`);
client.user.setPresence({
status: "dnd",
activities: [{
name: "Bandarr - Code King :",
type: ActivityType.Watching,
url: "https://www.twitch.tv/Bandarr"
}]
});
});```
is any error here ?
Oh, yeah that's right. Thanks
are you getting any errors?
you can also define the presence when creating your client class as well rather than doing it when ready
oh...he left
i made a openai discord bot and when i was done he joins the channel and dosent speak/respond and most of the times the command does not work expect /join any ideas what happening?
When you say openai bot, do you mean it uses the openai API or that you vibe coded it?
yeah openai api
I got a question how would I make it so when there is an embed how would I make it a container is there a way I could make it remove the embed from the message then replace it with a container?
Also it told me I couldn't do an empty message so thats probably my solution, technically saying its impossible to do it.
Nvm I figured it out my self somehow I overthinked it just simply did embeds: [], components: [container], flags: MessageFlags.IsComponentsV2
How are you sending your prompt to the API ?
im kinda slow wdym
How can I make that
edit info look like
- edit info
- message
- message
const embed = new EmbedBuilder()
.setColor(EMBED_COLOR)
.setFooter({ text: EMBED_FOOTER })
.setTitle(`${CONST_EMOJIS.EDIT} Message Edited`)
.setDescription(
`User <@${oldMessage.author?.id}> edited a message in this thread\n\n- **Edit Info:** \n - __\`Old Message:\`__ ${oldMessage.content.slice(0, 500)}\n - __\`New Message:\`__ ${newMessage.content.slice(0, 500)}`
)
.setTimestamp()
need a better way I know via breaking lines
To use the Open AI API you need to hit the chat completion endpoint typically by building a prompt that it understands and can reply with the required info.
i followed a guide and just did excatly as it was written if possible i can send you the .txt and see for ur self cuz its my first time doing this
Are you getting any errors?
ill try to run the bot 1 sec
always shows this and when i make the bot join me in the voice it dosent speak/respond and i made sure it has every permission
Show your code for listening and reposnding to voice prompts ?
where do i find that?
In your code. Just because the bot has joined the voice channel doesn’t mean it’s listening to be able to reply.
its quite long where do i send it
cuz its not enough for 1 pic and its 2.4k letters
Maybe just show the error you get when you run that code?
its this
also i forgot to say this when i tell the bot to say anything it says out of quota
There’s your issue. Are you subscribed to open ai ?
Out of quota means you had no credits to use that endpoint.
i changed it another tts and it was another error so i just revert it back . also no
i just used it is that normal?
nope
Yea to use the TTS endpoint you’ll need pay as you go account with credit on it.
is there any free tts i can use ? cuz i got no money
Not with open ai sadly
so i cant make the bot speak unless i buy the open ai quota thing?
or the paid plan
Yea you’d need a subscription / payg account as your billed for usage.
Its cheap per request but is billed
alright ig thanks much for helping have a good day
No worries 😉
Why is it that every pic that I use as my bot avatar it seems super low resolution?
Just fyi, that's not the error you're getting, that's a warning saying some of your code will be outdated soon, which you should fix.
It's not the error you're having though.
anyone why this still pings?
i've commented it out on my client and it still pings, any leads?
If I have a PNG and I want to get a URL out of it, how would I do that? I previously would just upload the PNG as a file for an embed image, and it would work, but components v2 require it to be a URL;
Like if I have this.thingy = new AttachmentBuilder(icon, { name: 'rating.png' }); where icon is the file, how would I get the URL and then use it in the component
Really straightforward question but did you save and reboot your bot
Yes
Autosave is on
I believe it's supposed to be a boolean, so you would pass false
Which
Based on previous messages here it's not jdjt a boolean
Try it
Just do empty object. allowedMentions: {}
https://discord.js.org/docs/packages/discord.js/14.21.0/MessageMentionOptions:Interface#repliedUser consulting to the docs can be useful sometimes
still doesn't work whatsoever
i'm assuming this is a bug
Show your code
No
Yep
Pretty much all I had to do was update djs
Is there no way to have a poll and components in the same message?
Not ComponentsV2 components
The flag deletes the poll field of the message payload
sad :(
and @vivid iris, empty object shouldn't do it
if you don't want to mention replied user, do allowedMentions: { repliedUser: false }, if you also don't want to mention anyone in content then add parse: [] to it
that's all you should need
no nulls
are you sure? because empty object works for me if i dont want to mention anyone
replied_user? boolean For replies, whether to mention the author of the message being replied to, defaults to false
ah, right, it defaults to false if you pass the object
Got it that one was from an existing issue here I just copied theirs to see if it'd work on my end
is there a component builder website like those embed bu ilder websites?
how ot use attachment builder in discrd js
documentation suggestion for @jovial citrus:
AttachmentBuilder discord.js@14.22.1
Represents an attachment builder
Hey,
Is there a way to force an update for a containerv2 component? Using update with a string select menu doesnt seem to consistently update
export const updateConfigHandler = async (interaction: AnySelectMenuInteraction) => {
if (!interaction.guild || !interaction.inCachedGuild()) return;
const { customId } = interaction;
const config = await getConfig(interaction.guildId);
const questions = getQuestions(config);
const value = interaction.values[0];
const commonProps = {
customID: customId,
questions,
introText: getIntroText(interaction.guild),
};
if (interaction.isChannelSelectMenu() && value) {
const channel = await fetchChannel(interaction.guild, value);
const hasPerms = channel
?.permissionsFor(client.user as User)
?.has([PermissionsBitField.Flags.SendMessages, PermissionsBitField.Flags.ViewChannel]);
if (!hasPerms || channel?.type !== ChannelType.GuildText) {
const container = await getComponentForm({
...commonProps,
errorMessage: "I do not have permission to send messages in this channel.",
});
await interaction.update({
components: [container],
});
return;
}
}
const camelCaseName = customId.replace(/_([a-z])/g, (g) => g[1].toUpperCase());
// @ts-expect-error Type mismatch, but we know it's correct
config[camelCaseName] = interaction.values[0];
await updateConfig(interaction.guild.id, JSON.stringify(config));
const container = await getComponentForm(commonProps);
await interaction.update({ components: [container] });
};
Hello! I just wanted to ask if there is any way to obtain a message (user, guild, etc.) and return the api response...
I also need it to work with the library's own cache
-# I don't know If I explained correctly what I want to achieve
I don't think that's possible, you can use <Client>.rest but that won't cached
That's unfortunate, it would probably cause me problems with what I'm trying to do 🥀
I wish there was something like I wish there was something like <Client>.users.raw()
guys
when i need to use shards, and how
yes you can. message to update must be already a component v2 tho
guide suggestion for @robust flame:
Sharding: Getting started - When to shard
read more
It is - it doesn't always update with the latest selection
Will triple check it's not on my side though
you should catch error then and see what it says
How can we fetch the server tag? Is there an event for it?
you cant
you have to get tag through user
what are primary,secondary and teritiary colors? in guild.roles.create()
const res = await fetch(`https://discord.com/api/v10/guilds/${guildId}/members/${userId}`, {
method: "GET",
headers: {
"Authorization": `Bot (tokenhere)`,
"Content-Type": "application/json"
}
});
if (res.status !== 200) return false;
const m = await res.json();
return !!(m && m.user && m.user.clan && m.user.clan.tag);
in order to check if the user has the server tag of the specific guild
primary and secondary are for gradient, tertiary sets a holographic style
if thats enabled on the server, of course
why would you fetch it manually and not use guild.members.fetch() 
that also doesnt check if they have the tag of that guild
what about primaryGuild object?

Tyy :=)
Because I didnt used djs in that specific project, I used that method for a lua project
why would you do all that when it exists in djs 
that also doesnt fetch the server tag. only way to get tag is through user primaryGuild
We can get it from the API, but we cant get it through djs
As of v14.22, yes, you can
User#primaryGuild discord.js@14.22.1
The primary guild of the user
Oh sorry :/
Changing the users server tag affects which event?
^ GUILD_MEMBER_UPDATE
await message.guild!.editOnboarding({...})
if i did this directly, will it create a new option or replace the existing one?
Lads, how come when I send a message with one file attachment, it isn't found later?
I'm receiving a button interaction and the message has one file attachment like shown below. However, when I log out the ctx.message.attachments the file isn't found.
The message below has a container with a file component in it, which has the url attachment://....
When clicking the button below, it expects the ctx.message to have the transcript file attachment.
both userupdate and guildmemberupdate
the message doesnt have any attachments because its inside the componenetv2. youll have to get attachment through the component
think that will just return an error cuz you arent passing anything
yeah I just realized that. thanks tho!
Does the server update only affect that server when it receives the tag?
event will emit on every tag change
But thats not how it works GuildMemberUpdate is not triggered in the users global tag update
wdym?
something like this should work
client.on('guildMemberUpdate', async (oldMember, newMember) => {
if (!oldMember.user.primaryGuild?.identityGuildId !== newMember.guild.id && newMember.user.primaryGuild?.identityGuildId === newMember.guild.id) {
console.log(`${newMember.user.username} added server tag`)
}
});
Guild Member Update doesnt trigger on any tag changes
then try the userupdate
Okey
normally should be both events #djs-help-v14 message
also make sure you have the right intents
how do i disable all components (ButtonBuilder and StringSelectMenuBuilders) in an interaction (it's epheremal, if that matters)?
I believe i have the intents this event will require
-# GuildEmojisAndStickers was deleted
be careful with using all those partials. it could limit what info you get
Manually. It's fun. To disable all of them? There is no automatic way.
You can use .setDisabled(true) on each component, or create a function like
function build(disabled = false) {
return // All your components, use .setDisabled(disabled)
it wasn't deleted. hover over the strikethrough to see what it changed to, which is GuildExpressions
this doesn't provide any help for them by saying manually
i suggest reading #how-to-give-help for helping in the future
but this exists
i guess there's nothing to do with it
you can do ButtonBuilder.from(...).setDisabled(true)
Sorry 😓
Quick question... Is there any way to tell if a Role is self-assignable in onboarding? interaction is ChatInputCommandInteraction and guaranteed to be part of a guild
is that not just gonna make a whole nother disabled component
It creates a clone when using ButtonBuilder.from(...) and then disables it. That's a new component you can use if you're editing a message (instead of re-creating).
There was no problem in UserUpdate
how would i use that though? the component variables are out of scope (because they have to be in my case i'm pretty sure)
is there actually no way to loop through the interaction message components
Are you trying to disable all components after you process an interaction? (Guessing here to try and get some context)
yes, i'm making a submission thing and i don't want it to work after the "confirm" button is pressed
it gives a modal and after modal an epheremal message with 3 string select menus and a confirm button
The way I handle this is to create a function outside of export default {
// someCommand.ts
import {...} from "discord.js";
function generateSelects(disabled = false, ...data) {
return // all your components, use `.setDisabled(disabled)` on your StringSelectMenuBuilders
}
export default {
data: new SlashCommandBuilder()...,
async execute(interaction: ChatInputCommandInteraction) {
// Handle your modal
const msg = await interaction.reply({
components: [generateSelects()],
flags: [MessageFlags.Ephemeral, MessageFlags.IsComponentsV2]
});
// Handle interaction
await interaction.editReply({
components: [generateSelects(true)],
flags: MessageFlags.IsComponentsV2
});
}
}
Hi, im using Sapphire as a Framework but it should still concern DJS.
GuildAuditLogEntryCreate does not get emited on Message Delete but other stuff like adding roles does emit it. I dont have any action checks at all.
i mean, If i pass only one data in the prompts field, that will remove every other prompts.. ryt?
what is IsComponentsV2 for
yes i think. i havent worked with onboarding but you can probably fetch the onboarding and then add what you want
const board = await message.guild.fetchOnboarding()
await message.guild.editOnboarding({...board, })
Modals and such use v1 components (it's just not specified), when using V2 components ContainerBuilder, StringSelectMenuBuilder, etc, you have to include that flag
keep in mind theres no audit log for message delete if self delete
but it worked without it xd
... 😭 thanks..
How would i track that then?
Huh, interesting. I'm not an OG here so I only learned using V2 components (and I always wrap stuff with a Container) so I have to include it, lest I incur the wrath of the error messages
with the message delete event. but it doesnt produce audit logs so you cant if you just want the audit log
Alright, thanks. I guess deleting a message that is not mine does not produce a message delete event then? Or would i have to combine both to get the executor?
message delete event is always triggered on any message delete. you cant get executor from a message delete event
Alright, thank you!
did something similar, it worked! thanks :)
so its not good using partials really then ?
Monocraft font?! 😱
its a client mod, which is against tos
cool font
Every time I use Monocraft in VSCode I get bullied for it 😔
guide suggestion for @jagged rock:
Popular Topics: Partial Structures
read more
agony (Stylus)
ye i like keeping it simple i dont really modify anything i havew modifed my icons on vsc tho
mac's Minecraft, it's not monospace lol
i did use monocraft in vscode before lol
lets stay on topic please
can someone tell me what this is? 😭
ok bye bye
guide suggestion for @grizzled notch:
Popular Topics: Display Components
read more
use embeds their better
it's a container, part of components v2
everyone has their own use cases for it. there isnt something better or worse
hi guys, i have this category enum, how can i include it to commands?
define "include it to commands"
you mean like command categories?
if so, that's outside the scope of djs
you're free to do that however you want
ye
i dont understand 😢
i doing new bot with another way coding
djs doesn't have any command managing feature, much less category management
it only handles the connection to discord, not much else
ah ok
you're free to program such a system the way you'd like
you can ask in #1081585952654360687 about it
since it's a general programming question, not a question about how to do something with djs
thank you!
how to do this?
i mean discord status
tysm
I had this code: https://srcb.in/mrq7qRu6hX to log any message/attachment that is deleted into another channel. It works fine until I try to delete a message after the bot restarts. I'm not sure if it's actually impossible to detect a message deleted after the bot restarts. Still, when I try, it shows Cannot read properties of null (reading 'id') (line 22) or DiscordAPIError[10008]: Unknown Message. Is there any way to fix it? Or somehow detect any message deleted even after the bot restarts?
I've added if (!message.content && message.attachments.size === 0) return; just to make the console clear so it don't show any Unknow Message error
When Discord emits the event, they only send the message, channel, and guild ID of the deleted message, and not the content or other data of the message itself. This means that in order for that additional data to be present, the message has to be cached in d.js. As you may expect, restarting your bot clears the d.js cache
Oh... Okay, I get it. Thanks!
lol
Buttons don't have values. Check if it's a select menu before doing whatever you're doing
its a select menu
Then fix your types
idk which types to use
can you fix it?
Check .isStringSelectMenu() before trying to access values
BaseInteraction#isStringSelectMenu() discord.js@14.22.1
Indicates whether this interaction is a StringSelectMenuInteraction.
Check whether it is a string select menu by calling .isStringSelectMenu() on the interaction in your callback function before trying to access a property that does not always exist on interactions
im stupid
it will easy if you just fix my code :/
oh i fixed it
why GuildMember in newState or oldState in voiceStateUpdate can be null always
[help] execution error: TypeError: Cannot read properties of undefined (reading 'data')
const commandCategory: any = {};
for (const folder of commandFolders) {
const commandFiles = fs.readdirSync(`./src/commands/${folder}`).filter(file => file.endsWith('.ts'));
const commands = [];
for (const file of commandFiles) {
const { default: command } = await import(`../${folder}/${file}`);
commands.push({ name: command.data.name, description: command.data.description });
}
commandCategory[folder] = commands
}```
which type i need to use in ```const { default: command } = await import(`../${folder}/${file}`);```
Typing won't fix it being undefined
and how to fix
is anyone using new modal components?
how to fix?
Import something that exists? It's your file, I can't tell you
please, i tried all ways
(
shouldn’t it be
const command = await import(…)
.then(commandFile => commandFile.default);
but its not a d.js question but a general js syntax question
so next time you should use #1081585952654360687
for (const folder of commandFolders) {
const commandFiles = fs.readdirSync(`./src/commands/${folder}`).filter(file => file.endsWith('.ts'));
const commands = [];
for (const file of commandFiles) {
const command = await import(`../${folder}/${file}`).then(commandFile => commandFile.default);
commands.push({ name: command.data.name, description: command.data.description });
}
commandCategory[folder] = commands
}```
its right?
try it out and see, looks good to me
no it not working
also gives undefined
then delete your post in #986520997006032896 and make one in #1081585952654360687
I’ll continue helping there, as this issue is not d.js related and this channel is for d.js help
i did
Does Discord automatically reset the bot activity status when set with client#user#setActivity() ? cuz it seems to just clear every 24 hours for me.
Do you set the status in ready event? Specify it in the ClientOptions, otherwise during reconnects, it may reset
ClientOptions#presence discord.js@14.22.1
Presence data to use upon login
Default value: {}
Yeah I set it in the client ready event
Then specify it in the client option
Hi, I was using interaction.message.interaction.commandName to get the slash command name from a ButtonInteraction object (where the button is attached to the original response to the slash command) -- however, it's now marked as deprecated and recommends the use of interaction.message.interactionMetadata.
Does anyone know how I can achieve the same fetching of the command data on interactionMetadata? Doesn't seem to be included by default.
Yes, it is no longer exposed through interactionMetadata. The reason devs gave is because it's for internal use and may change any time.
So there's no other way anymore?
Hello, has someone experienced an issue where UserSelectMenu don't provide all the available users? I am searching for a specific username and it doesn't show up
question... how could one register a display name with special characters (since using URL doesn't work, even with the encoding [e.g. %20] apparently)
just pass the unicode name to the method, djs will take care of the rest. and has nothing to do with URL
This isn't discord js but the discord raw api and user oauth.
I have this code
async addUserToGDM(channel: string, user: DiscordUser): Promise<void> {
if (!this.oAuth.discord.client) return;
const request = await fetch(`${this.baseUrl}/channels/${channel}/recipients/${user.id}`, {
method: 'PUT',
headers: {
Authorization: `Bot ${this.oAuth.discord.client.token}`,
'Content-Type': 'application/json'
},
// eslint-disable-next-line camelcase
body: JSON.stringify({ access_token: user.token.key, nick: user.user.globalName })
});
const json = await request.json();
console.log(json);
}```
Based of this API Doc data https://discord.com/developers/docs/resources/channel#group-dm-add-recipient
I get 400 bad request with this returned
```json
{
"message": "Cannot execute action on this channel type",
"code": 50024
}```
This is how you get the channel id right? https://kathund.wtf/utyujrse.mp4
I'm not crazy this is how it should work right?
o7 embeds
Discord.js does not support oAuth try in #1081585952654360687 or DDevs
Ye I know I just mainly wanted a sanity check
that I wasn't going insane
You can’t add people to a dm channel anyways
then ask for that in one of those places; not in djs help
Need a group dm channel
Then whats with the oauth scope? Discord?
Or it is a group
Ask in ddevs
Can you post inv please i'm not in it anymore (I don't remember why I left at some point)
It’s in #useful-servers
that is a groupDM channel though
Ight thanks 👍
How to check if interaction is run in a DM or in a server where the bot isn't added in?
BaseChannel#isDMBased() discord.js@14.22.1
Indicates whether this channel is DM-based (either a DMChannel or a PartialGroupDMChannel).
check on the interaction.channel
Would’ve just use interaction.inGuild()
Would if could 🥺
BaseInteraction#inGuild() discord.js@14.22.1
Indicates whether this interaction is received from a guild.
returns null
then what Chewinsky said
ok thanks
oh sorry, I meant file display name
using the attachment URL is not allowed (attachment://)
The visible file name isn’t part of the url
Usually with attachment, you have the url and the name
Or ig it is
Ask in ddevs tbh
Pretty sure d.js encodes it for you
did, no answer ._.
even advaith responded, but he himself wasn't certain
For channel.send, you have separate name and attachment properties for each file/attachment
hm.... could you give me an example?
.send({ files: [ { name: "foo.txt", attachment: "./bar.txt" } ] });
wait, what if I already have a payload?
Wdym?
nvm, I was lost at my own spaghetti code lmao
Dw, it happens
I think my brain was telling me about the components (type 12 and 13) and the send.channel but those are two different things
my bad whoops
I guess time to refactor some stuff to make it more readible with JSDoc comments
thanks for the help tho, sir
It could also help to replace the number types with the ComponentType enum
how to detect when a user is boosting the server?
tag suggestion for @zinc forge:
The Discord API does not provide a dedicated event for guild boosts, but you can check for it in the guildMemberUpdate event:
client.on("guildMemberUpdate", (oldMember, newMember) => {
// Check if the member wasn't boosting before, but is now.
if (!oldMember.premiumSince && newMember.premiumSince) {
// Member started boosting.
}
});
an alternative is to have a system channel setup and listen for the system "user has boosted" message (messageCreate event)
it works only if member haven't boosted server yet
the example in the tag, yeah
and how to catch the user who boosted from this message?
the author is the user who boosted
it's a special case so it behaves differently
to be clearer, I'm talking about this message
How are components counted in terms of number? What counts towards it? Is it every component?
yes
v10: ComponentType
read more
damn ok
those are the component types, essentially every component there is
every one of them count towards the component count
nothing else (eg options in select menus or items in media galleries don't count since they're not components)
Tysm
dont containers count as 1 no matter whats inside?
no, the components in containers also count
and the container itself
confused by this wording then
oh I see - there was a limit inside as well
is there some way to get the number of components in a message?
nothing built in djs if that's the question, because it is possible by iterating
I dunno if this question is fit for this channel, but why does the official discord.js guide refer to itself as the "legacy" guide?
iirc because it's mostly a copy and paste of the original, legacy guide
but that's more of an internal categorization, it probably should be changed
is there like... a newer one?
the current one is the newer one
it's the contents what isn't particularly new
it's updated ofc, just not rewritten since some time ago
what does GuildMember#displayName return
Check the docs?
ok
GuildMember#displayName discord.js@14.22.1
The nickname of this member, or their user display name if they don't have one
thanks
is there a way to delete messages before theyre sent
like how automod blocks them? no
is there a way to configure automod with a bot then?
i basically just want certain members to be unable to send messages with certain words
Guild#autoModerationRules discord.js@14.22.1
A manager of the auto moderation rules of this guild.
AutoModerationRuleManager#create() discord.js@14.22.1
Creates a new auto moderation rule.
appreciate it
if a member has a role but that member is not in my bots cache will role.members not include that member? i need every member with a certiant role, not just cached ones
you'll need to fetch all members first
won't that take ages
or is there a way to filter for only members with that role
there is none
it'll take longer depending on the server size but no you can't filter before fetching
what we do internally is a filter on all members
also how large is the server
sooo.. if my server has 650k i assume that will take many mins right
no, that's not how that works
ah, how does it then
discord will just send you 650 events to your one request
maybe 651
someone have the discord v2 components documentation?
idk, maybe a minute, two
guide suggestion for @wary oxide:
Popular Topics: Display Components
read more
oops the bot broken
404
This page could not be found.
damn ok, and theres no way to get that shorter? the role only has like ~10 members so i dont want to waste all of that time
https://www.discordjs.guide/guide/legacy/popular-topics/display-components
here's the updated link
yes, we just roled out new guide on that domain
thanks
ya, i didn't even think about the urls changing...but of course they did...
is there new content or is it just a new look
new components
they will look new because they are new
so new new pages as in topics, like monetization
oh, you mean guide
There are no new pages
ah ok
If you see anything that doesn't look right with the guide, be sure to raise an issue!
so this is the fastest i could do it
you could have the guild members intent, fetch on start and then just check role.members
The description is gonna be prefixed w/ "undefined"
yea i fixed that, forgot how it worked for a second
Also, isn’t role.members a Collection?
That would make member an Array [id, guildMember]
It would be slightly faster to iterate over the guild.members yourself and conditionally add onto the description
Yeah but doesn’t that take a while if the user has many members in the server?
It won’t take longer than what he has
role.members is already a filter on guild.members cache
ah fair, forgot that
Can’t get any faster until you stream the results of fetching members
Since Discord sends them in multiple chunks for large servers
is it possible to automatically give a role if a user is using a specific guild tag
nvm found it at the server
How could I do a custom status for my discord bot without the playing presense like i've seen other bots like use the same status a user uses
Hello Good morning, i need help for reply and edit messge. how can i check if the reply is already exists and i need to edit it. instead of replying inside Events.InteractionCreate everytime?
interaction.reply({ embeds: [embed], components: [action], ephemeral: true });
Like hope this gives more context what im talking about
This bot Welcomer used the status protocol that we have access changing we are all familiar of using the second image
you could do interaction.editReply is that what you need?
Against tos
A bot is a bot not a user
Nvm
That should be possible in presence
so you're telling me the first bot used something that is against TOS that changed their status
ohh ok lemme try that.
thats what I was thinking to.
Do you mean a custom activity?
OH YES.
omg yess thank you so much
that was so confusing to figure how to do.
@sage elkthank you its working now.
Yea no problem
hello guys, i have translating system, which works only in string compatible places, like embed description or just interaction.reply. how can i translate slashcommandbuilder.setDescription to another language? or language checking and using condition
documentation suggestion for @robust flame:
SlashCommandBuilder#setDescriptionLocalizations() discord.js@14.22.1
Sets the description localizations for this command.
no this translation only for discord language
so you have more languages than what discord offers?
Hello! I'm having a hard time figuring out why my message isn't Ephemeral, when AFAICT I'm following the guide. For this code:
const { SlashCommandBuilder, MessageFlags } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
... ,
async execute(interaction) {
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
await interaction.editReply(`Hello it is me!`);
return;
},
};
It shows the "bot is thinking" message and then edits it, but it's not Ephemeral:
what is your d.js version
14.16.1
thats too old, please do npm i discord.js@latest
Ok one sec!
Huh, that did fix it, thank you
I guess I should have tried that first, but I didn't expect it to be broken mid-major version
yeah on your version “MessageFlags.Ephemeral” did not exist
Ahhhhhh, the switch over from ephemeral: true
yess
Got it. Thanks so much for the help!
Why wouldn't this display event image as fallback? When staff is not setting an image for event manually, it just sets nothing for event image (banner). URL is valid
const giveaway = await interaction.guild.scheduledEvents.create({
name: giveawayName,
description: giveawayDescription,
image:
giveawayImage?.url ??
"https://cdn.discordapp.com/attachments/736571695170584576/1422748982622289950/Giveaway_Default.png?ex=68ddcdbe&is=68dc7c3e&hm=d5dac383cabc6819480d7e783de542f26cf4acfbb7b6447a69b57963f035ad4a&",
scheduledStartTime: scheduledStartTime.toDate(),
scheduledEndTime: scheduledEndTime.toDate(),
privacyLevel: GuildScheduledEventPrivacyLevel.GuildOnly,
entityType: GuildScheduledEventEntityType.External,
entityMetadata: {
location: `By ${userMention(interaction.user.id)}`,
},
reason: `Giveaway created by ${interaction.user.tag} for ${giveawayName}.`,
});
I guess it asks for Base64 version
URLs expire now after a day. It’s valid now but it could be that when it expires it’s no longer valid. Discord isn’t a host. You could just put the image in local file storage then use a path
hi guys
const dropdownOptions = Object.keys(commandCategory).map(folder => ({
label: folder,
value: folder
}));```
how can i do rename for label? like admin="Administration"
because folder have 3 categories
utility, admin, info, i need rename for all
then give it to selectmenu
const selectMenu = new DJS.StringSelectMenuBuilder()
.setCustomId('category-select')
.setPlaceholder(`${i18n.twl(nowLang?.lang ?? "en", "help.placeholder")}`)
.addOptions(...dropdownOptions.map(option => ({
label: option.label,
value: option.value
})));```
is it possible to show a selectmenu inside a modal?
not yet, the update will be in the next release (no eta)
alright
Hey guys, is this the latest version of the discord guide https://www.discordjs.guide/guide/legacy ? cause I noticed that there is legacy in url, so I got confused
yes
Is it possible to make changes to a guild without a bot, by authorizing the application via user oauth2?
you could try, but doubt a bearer token can perform the same actions as a regular token
getting user token to do that would be breaching TOS, and to use app token your app would need to have a bot in the guild.
the things you can change with an admin's bearer token is command permissions for apps
So making requests to ie. Edit a guilds channels with that authentication would count as a selfbot?
Bearer token is not the same as regular token
Bearer token is obtained via OAuth2, and it works differently
including the fact that it has specified scopes it can work with, and there isn't really a scope to "use API with it instead of proper key"
what are you trying to do?
Im asking because my friend claims that he made a webpanel that does oauth2 for its application and allows to make edits to a guild via that, without a bot
Im revising whether we're not making a crticial mistake by accidentally making a selfbot / something illegal
"edits to a guild" is very broad
Edit channel names ie.
and like i said, you can edit app command permissions with a bearer token
How is that releveant? (No offense i just dont get it)
Like if they have the bearer token they can edit slash commands?
no, the permissions
Ah
you know how in your code during deploy you can only set defaults? and theat can only be on permission level
server admins can then go to server settings and overwrite those defaults, including ability to add specific roles/channels/members to the config
the latter part is completely impossible to do as a deploy default
I think you are talking about different things xd
Yeah, but thats just one thing you can do with a bearer token that you obtain when the user authorizes an app, but you cannot edit channel names in a guild for example
yeah
Noted, thanks chat
it is but you cant get interaction form it
i did it but cant get what user choosed
got new modal support?
Not yet
nope you can show it by json but get get interaction from it
show it by json?
you mean i have to send out raw payload
i think he means by raw api
but you cant get the interaction create submit event for it since itll be malformed
you can get in djs dev version i think
you can keep an eye on #announcements for when we release that
yes
What's an easy way to set the emoji of a string select menu option to a standard emoji? Something like:
new StringSelectMenuOptionBuilder() //
.setEmoji('💣')
just like that, or what do you mean exactly?
My bad I had another issue with the way I was creating the builders and missread the stack trace, the above works fine
how do i get the commands in a message that people can click on and then it runs it in their text bar smth like
</help:81440962496172032>
it won't "run in their text bar" though - they still have to fill in any options and hit enter
i see thanks sm
documentation suggestion for @worldly lantern:
chatInputApplicationCommandMention discord.js@14.22.1
Formats an application command name and id into an application command mention.
If you click the command, it will get put in their text input for chat. Like Mark said, any options would still have to be filled out.
container@pterodactyl~ Server marked as running...
up to date, audited 132 packages in 11s
13 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
(node:37) [DEP0040] DeprecationWarning: The `punycode` module is deprecated. Please use a userland alternative instead.
(Use `node --trace-deprecation ...` to show where the warning was created)
node:internal/process/promises:289
triggerUncaughtException(err, true /* fromPromise */);
^
ConnectTimeoutError: Connect Timeout Error (attempted address: discord.com:443, timeout: 10000ms)
at onConnectTimeout (/home/container/node_modules/undici/lib/core/connect.js:237:24)
at Immediate._onImmediate (/home/container/node_modules/undici/lib/core/connect.js:206:11)
at process.processImmediate (node:internal/timers:478:21) {
code: 'UND_ERR_CONNECT_TIMEOUT'
}
Node.js v21.7.3
this is not letting my bot to be online
Errors such as ECONNRESET, ConnectTimeoutError, SocketError: other side closed indicate a network issue
- Free or shared hosting providers often come with significant limitations
- Another indication of these issues are 'Unknown Interaction' errors.
done it 🙂
😮 how do you link a slash command?