#djs-help-v14
78874 messages · Page 23 of 79
like i'm trying to make a giveaway command and want to store the people and results.
please use #1081585952654360687 for non-discord.js questions
how do i get the new server tag from user?
is it possible?
possible, might be
not with discord.js though, since it's still undocumented by discord
👍 ty
did what?
that's cool, but how is it related to this channel?
sorry
Use editReply and specify the message
.editReply({ message: followUpMessage, content: …, … });
hello Can component v2 be used for python?
documentation suggestion for @tough dew:
ButtonInteraction#followUp() discord.js@14.19.3
Send a follow-up message to this interaction.
You're in the wrong server if you're asking about Python
lol sorry i don't have python server
I thought it just returns the Message
Yea, fetchReply does nothing on a followUp afaik
Hi everyone,
I'm encountering an issue where my bot returns the error "Cannot Send Empty Message" on certain servers...
I've double-checked the code, and there are no cases where an empty message is being sent (e.g., message.reply({})).
The command works perfectly fine on most servers, but on a few, it throws this error.
Could this be related to a missing permission? If so, does anyone know which one might be causing it??
No
It’s caused by either providing an empty object or an object with invalid keys

E.g. .reply({ embed: [ … ] })
embeds is misspelled
Could also be caused if you don’t provide a non-null/undefined content, embeds, stickers, files, or components
This would be much easier to track down with proper error handling
is there any way to know the type of an interaction without running isButton, isStringSelectMenu, etc
the interaction has a type property
Are Discord.js memory sweepers microtasks or macrotasks? For example, if I have a lot of async functioning queueing to microtasks, could it block proper sweeping of memory due to the way the NodeJS event loop works since microtasks happen first?
They are macrotasks. But are you sure you need/want sweepers if you have that many async functions queued? Sweeping adds quite a burden on CPU cycyles. Could limiting intents or makeCache be the better option for your issue?
Well I already use makeCache and also have limited intents as much as I can. Now that you mention it and with that understanding now, removing sweepers could be an option. The problem with that is I run into the issue of the memory ever-expanding overtime, to my knowledge, because my bot is pretty large (70k servers). Other option I am considering is moving the async microtasks that are getting queued to a worker thread or something like that so theoretically it wouldn't block the main event queue (assuming my understanding of that is correct). What are your thoughts?
if you're that concerned about memory and performance you might even fare better with @discordjs/core
Do you know if that'll work with @discordjs/voice?
Also what advantages would I get with that over regular discord.js 🤔
Ah Thanks man!
I found the issue : <>.reply({ embedName }) .. I forgot to write embeds: 
But embed: is also invalid
Auto correct* 
embeds: [...]
Might've not been clear that the example I gave was for an invalid use of reply

the advantages are the disadvantages really. discord.js is as comfy to use as it is because of not despite of the aggressive caching - that's what powers a lot of the convenience functions
no caching, whatsoever. you have to do that all yourself
you get a sophisticated rate limit handler, a wrapper for typesafe api calls, a websocket manager and a much smaller set of convenience functions and that's largely it.
so: you loose a lot of the comfort, but you gain all the agency
Thanks for the info :)
hi, is there any way to tap into the websocket in djs?
i want to monitor websocket connection close with status codes if possible
a hacky way would be sufficient, i want to expand the monitoring of my bot
(event) WebSocketShard#close discord.js@14.19.3
Emitted when a shard's WebSocket closes.
<Client>.ws.shards has all those
okay thanks
do those instances ever get replaced on reconnect? or do i have to only have to add the event listener once on startup?
for v2 components its there a way to put the thumbnail on the left instead of the right
no
ok
They don't get replaced
got it, thanks
webhooks dont support containers yet i presume?
They do
Just need to add withComponents: true as well as the IsComponentsV2 flag
cheers man
they dont
they are useless to bots
i need help
iam using componentv2
and what are you sending?
container
code
oh i think i missed message flags <_<
yeah, prob
thx for your time, im sorry
iirc 1 is actionrow and that is the only allowed topelvel component components[0] without the flag
can the client "ready" event be fired multiple times throughout the lifetime of a client object?
if i remember there is a guide for cooldown for / commands but i couldn't find the page. Can someone send me :
tysm
No, not anymore. But don't rely on that
Listening with .once to it is suggested
const row =
interaction.message.components[interaction.message.components.length - 1];
if (row.type == ComponentType.ActionRow) {
const ActionRow = ActionRowBuilder.from(row);
How to see that the action row have buttons? I'm trying to disable a button in the last row
Check the type of the first element in its .components
doing ActionRow.components[0].data.type == ComponentType.Button still gives me ActionRowBuilder<AnyComponentBuilder>
Do you want to find out if it contains buttons or do you want to typeguard/cast it so ts allows you to use it as buttonbuilder?
i want to typeguard it, i know it have buttons
Then just use the generic on the .from<...>() call
And use ActionRowBuilder, not ActionRow nvm, you shouldn't name your variables in PascalCase, those are classes
editing a component color function changed?
Components don't have colors regularly. A Container can have an accentColor and a Button can have a style causing it to look differently
The generic should be ButtonBuilder ?
Yes
it's not letting me..
const component = interaction.message.components.at(-1);
if (component && component.type == ComponentType.ActionRow) {
const actionRow = ActionRowBuilder.from<ButtonBuilder>(component);
Should i just cast components as APIActionRowComponent<APIButtonComponent> ?
Yes
Webhooks can send componentv2?
Yes
You need to pass withComponents: true in the options though
ok thx
WebhookMessageCreateOptions#withComponents discord.js@14.19.3
Whether to allow sending non-interactive components in the message. For application-owned webhooks, this property is ignored
Can someone send the link to the discord.js v14 guide where I can check: How to reply with an embed to a button.
interaction.reply({embeds:[embed]}) same as any other interaction
ButtonInteraction#reply() discord.js@14.19.3
Creates a reply to this interaction. Use the withResponse option to get the interaction callback response.
// Reply to the interaction and fetch the response
interaction.reply({ content: 'Pong!', withResponse: true })
.then((response) => console.log(`Reply sent with content ${response.resource.message.content}`))
.catch(console.error);
guide suggestion for @grizzled venture:
Message Components: Buttons
read more
const guild = await client.guilds.fetch('YOUR_GUILD_ID')
await guild.members.fetch()
const realMembers = guild.members.cache.filter(member => !member.user.bot)
i dont think theres other way
is there a flag or anything to turn off pings even if the container contains a user or role ping? for components v2
@languid summit u can fetch first then just add it on a database on howmany the members are
then use guildMemberAdd listener every userjoin it adds +1
If the guild is big the difference between with/without bots doesn't really matter though
tag suggestion for @vital vortex:
You can control which entities receive notifications via the allowedMentions option. You can:
- Set a default on the client
- Set for a specific message
- Use the
repliedUserkey to disable in-line reply mentions
{ ..., allowedMentions: { parse: ["users", "roles"] } }
so sorry for bothering but in .addTextDisplayComponents can i put 2 buttons?
No. A textdisplay is not a button
thanks
oh sorry i meant in SectionBuilder()
Then no. A section has exactly one accessory. You can use an actionRow below or above the section if you want more than one
Oh okay tysm for ur time
hi, why do i get 'MessageActionRow is not a constructor' ?
is there something else instead of it
ActionRowBuilder discord.js@14.19.3
Represents an action row builder.
Where did you get the code causing that?
Sounds like outdated v13 code
its my old code
oh okay i'll downgrade to v13
Version 14 has released! Please update at your earliest convenience.
- Update:
npm rm discord.jsnpm i discord.js - Update guide (use
CTRL+Fto search for the old method or property)
No, you should update your code to use v14 instead
it's a lot of code
v13 is outdated and unsupported
who cares if it still works
it says 404
search indexing is outdated sorry
https://discordjs.guide/interactive-components/buttons.html
hi!
here's a portion of logs from my bot's startup progress; it's been on a reconnect loop for shards even though they're ready. I was wondering if this is because of the "unavailableGuilds" thing, never seen this error before. some shards start with unavailableGuilds: 0 and the rest are as you see here. is this a common issue? I've also provided some debug logs that show the errors right before the reconnect loops. if you need any other information from the bot, i'll provide it!
(p.s this bot is on a custom clustering package but i just wanted to know if this was an error seen before due to discord.js reasons)
djs v14.9.3
Hi, I'd like to know why the v2 component guide documentation no longer works?
what a best way to give a one role to multiple members? (about 200)
can someone share with me the code of container with buttons inside
wasn't there something with the new version release, where you can put a horizontal line break or like create sub-sections inside of an embed? i just want to separate two halves of an embed and want it to look nice and clean
That’s not embeds, it’s components v2
https://discordjs.guide/popular-topics/components-v2.html
edit: weird, i took this link from another message and now it gives me a 404, guess the link changed
its called separator type 14
(here's the new guide link https://discordjs.guide/popular-topics/display-components.html)
Thanks!
thankssssssssss
there isn't any "bulk add role" method, so you'd need to iterate and add individually
the guide and documentation are different things, but on the assumption you're just talking about the guide, I assume you also encountered an old link as above
Yes
bumping this; do I have to drop this in #986520997006032896 ?
the unavailable guilds wouldn't be the cause of your issue, but rather another symptom
but yes opening a post there would probably be better
yup, but I wanted to know any common causes of why there would be unavailable guilds 
let me move this to that channel
how do i do prefix commands and does discord.js support them?
prefix commands are entirely just string parsing
you can access message content from <Message>.content, but beyond that, it's up to you to handle
While slashcommands are convenient for both user and developer. So why do you want to do prefix commands?
for what im doing i need to be in more control
holy fuck ok :)
why does every sub command I make it doesn't appear in /?
I restarted my discord, and deployed it
module.exports = {
data: new SlashCommandBuilder()
.setName('entertainment')
.setDescription('entertainment purpose command, used to have fun.')
.addSubcommand(sub =>
sub
.setName('facepalm')
.setDescription('Sends a facepalm Image API')
),```
More control than slashcommands? If anything you give up control by not using them
any issues when deploying?
care to share your deploy script?
have you logged what you're deploying to ensure this command is properly being sent?
im gonna have key/value pairs with an operator in between to define how they work, this is inspired off another bot
It's deployed, I have a log to tell me when it's deployed
Could you dm? for script
/command key:... operator:... value:... or if you want the full parse experience for you as dev: /command phrase:... and have them enter whatever you wanted in the prefix command and parse the string the same way
As said: if anything prefix commands are less flexible, as they only allow the latter of those two
no thanks
if you don't want to share here, you don't have to, but I don't do dm support
its slower and less stylish imo, and idk, i like parsing so idk
Great, then you won't need any help from us, good luck
it seems completely impossible to seperate the sync commands file from main
main needs the commands too
Huh? No, it's explained in the guide how to do it and many have done it. So not impossible
Yes, both files import the same commands
Then what could be the issues?
The deploy script is fine
I don't understand, no errors
stupid f*cking guide :(
that'd be the only thing that could have issues with everything else you've said
so if you won't share the code, I can't help any further
https://discordjs.guide/#before-you-begin ive read all of this before
ok
What's your issue with it? We're always looking for constructive criticism to make it better
i literally read all of it and i dont remember it showing that anywhere
yeah and also it uses ES6 and doesnt show other potential ways
oh wait, i dont have to sync my commands lol
i have create a whole new interaction wrapper :(
you only have to push them up when they change
^ im doing prefix
Yes with prefix commands you don't have to deploy anything.
However, if you ever plan on getting into more than 100 servers, then you're probably going to have to covert to slash commands. Discord won't accept your Privalaged intent application for the reason of using prefix commands
But if you don't, then do whatever you want. It's not against any rules, it's just an unsupported implementation
fuck discord lol
also with slash command you can do ephemeral responses
Keep this channel djs related, thank you
true
can I use djs to setup a kind of "teamspeak whisper" feature where x bots join voice channels and are there to just relay audio from one main channel?
Yes
A bot can join more than one VC in the same server?
No
Hence the "x bots"
Ah, My bad missed that
How do I get the first/initial message of a form channel thread/post?
ThreadChannel#fetchStarterMessage() discord.js@14.19.3
Fetches the message that started this thread, if any. The Promise will reject if the original message in a forum post is deleted or when the original message in the parent channel is deleted. If you just need the id of that message, use id instead.
thanks
that only works if the thread is started on a message afaik
Ah, is a post with no content body but media instead have to be handled differently?
correct
oh, not even just that, i mean if a thread is started ON a message
Im only dealing with fourm channels right now which I think must always have either a message or media
because then the message id is the thread id and we can do the fetch
in forum channels there is no easy way to figure that out, unfortunately
https://github.com/discordjs/discord-toolkit-bot/blob/main/src/events/threadCreate.ts#L23 we handle it by waiting for the first message on thread create for #986520997006032896's auto message - you need to wait for the first message to arrive to be able and send any messages in threads at all - majorly annoying because large file attachments can substantially delay that
not too sure what you are trying to do with the message, but that would be one way to go about it; waiting for it when the thread is created
(discord not implementing "jump to top" in the UI is crazy, btw)
Hmm my use case basically has to do with cleaning up/moderating duplicates in a forum, so the command is ran by a user a decent length of time after creation. Hypothetically I could listen for the first message and save them in my own db but that seems like a bad solution and doesn't solve it for any of the old existing posts
could also try after: 0
yup, that seems to work
thread.messages.fetch({limit: 1, after: 0})
fetchStarterMessage actually seems to be working for me, it's resolving the message both with text or with just media
Because im not doing anything automatically/on threadCreate I don't have to worry about the waiting issue
What is the best and most effective way to programme the bot in several languages? So that you have a /setup command with which you can specify the language of the bot for the server and then everything is translated (command names, buttons, responses etc.). So far I only know about user localisation and I understand how that works.
Is there an example/guide or ready-made handler for the other or do I have to build a solution myself?
Make a file for each locale with translations for each message and placeholders for the variables you want to add in and refer to the messages by key in the code
You don’t want to use interaction.locale?
BaseInteraction#locale discord.js@14.19.3
The locale of the user who invoked this interaction
Okay, are there any code examples or something?
that's outside the scope of djs
there are multiple i18n libraries out there though
does djs completely ignore the required argument to interaction.options.get(string, required)?
is it only for typing?
What do you mean by ignore?
not care about functionally
Or would it not be best:
for user interactions: take the user's language from the client
For user interactions where the bot then sends embeds to the server: the interaction Guild Language?
I mean, my bot will then only have 2 languages anyway
Im not sure why you think it would be ignored
Here it is throwing an error if you specify required, and its not found
oh ok
you get the user locale from the interaction, not from the client or the guild
and getting the language is one part of the system
the rest, which is the larger part, would be something like this, which is outside the scope of djs
guys why https://discordjs.guide/message-components/buttons.html is dead?
that's not the correct url
if your sidebar says message components instead of interactive components maybe you need to reset your cache, ctrl+f5
question:
Events.GuildMemberAdd does not seem to be "seeing" when new members actually join the server. all other event files trigger when they need to. i thought it would be a problem with the priviledged intents but i do infact have the GUILD_MEMBERS intent on, so it should be able to see when people join.
even weirder, to test this, i created another /command for my bot, which is /emit [eventType] [args] and used it to emit the event of a person joining (that I tagged). and it worked, and set the message correctly.
is there a situation where clicking the priviledged intents is not enough, and i need to do something more on the discord developers page to make it work?
TLDR:
Bot doesn't trigger and say hello when guildmember is added. but when i manually emit the event, it triggers, and the code runs smoothly without error. this means there's something going on in between discord emitting the event and my bot catching discord's emittion.
can you show your intents and listener's code?
👍 one second
hm thats when I search on https://discordjs.guide/
try this
thanks
and i found the bug by looking at my index file. i wasn't calling it correctly, when i'm trying to pass it to the client.on(event.name, (...args) => event.execute(...args)); part. so that fixed it.
honestly, just looking at it again from another angle really helped jog my memory in what needed to be done.
Is there a way to get user guild current guild tag rn I have auc
That's not yet documented by Discord
Any work around?
You can use REST
Client#rest discord.js@14.19.3
The REST manager of the client
REST#get() discord.js@14.19.3
Runs a get request from the api
how does discord.js implement stuff like interaction.options.getString() with the required argument type safely? i cant seem to do it and im losing my mind over it
discord.js is open source and freely accessible via github
im i able to find what i want in a reasonable amount of time?
because i am completely lost
you’ll need to search for it, which the docs can help with since everything in the docs has a link to the specific part you’re looking for on github
CommandInteractionOptionResolver#getString() discord.js@14.19.3
Gets a string option.
there’s a link there that directs to github
ok
coding isn’t meant to be something you make quickly, it takes time and effort
which includes searching the docs for what you’re looking for in that time
doesn’t necessarily have to be a short amount of time, but that comes with learning how to read the docs and navigate them
i dont think i can navigate an advanced github repo the dumbass i am
not true at all
you just have to learn how
Just to clarify, are you trying to understand its usage or how it works under the hood?
my editor says their implementation is also a type error
i don’t quite understand that
implementation of what
Can you show the error? Also what editor do you use?
Some people are able to add buttons and similar components to their embed. How do we do that, and which method should we use?
that would be in a container, which is part of the new componentsv2 update
Uh, I tried a lot but I couldn't do it. Do you have an example code or something, if there is one in JS of course?
thanks
@unique shoal wee dont have a way for show avatar user on ThumbnailBuilder Is it necessary to specify the link?
Why are you pinging me for this
is it at all possible (or might it ever be possible) to dynamically update command options if previous ones are set to certain selections?
no
is that a terrible idea
not a terrible idea, just not how it works
omw to discord suggestions somewhere somehow
won't work
command options are either static or dynamic
static are changed via deploy
dynamic are autocomplete
so what you want already exists
theyre talking about dynamic options, which dont exist
what doesn't exist, is the fact that discord client caches the autocomplete results
All options are static, only the choices for them can be dynamic
bleh
too late for me
at least, that was my interpretation
i read as a "tree" of options
but that can be kinda done via ac
is formatting for the switch from fetchReply -> withResponse the same
ahh right, yeah sort of
assuming user fills the options in correct order, which they have no obligation to
they return different objects
so it might kinda be achievable via autocomplete? im not sure if the client receives anything once an autocomplete option is selected
autocomplete results are cached locally for the "duration" of one command usage
so doing a backspace a backspace a backspace will not ddos your bot
you can access other options in the autocomplete interaction, but only the ones already filled will be, well, filled
so if user does options out of order there's nothing to read
can i supply predetermined autocomplete options similar to how i have static ones with normal commands
you can return whatever you want to an autocomplete
only limit is the 100 chars for name and value
and up to 25
does the client receive anything once one of those options is selected
autocomplete interaction is request for options to show to user
only thing after that is command interaction
value
which is when user actually submits the whole command
nothing inbetween
sadness
ye after user submit the options, the bot will receive its value, don't u think?
no, you don't submit options
you submit entire command with all its options
there is no "autocomplete submit interaction"
yes, I just want to say only abt options
but the question wasn't about submitting full command
yk what nvm
the question was if discord sends anything when user selects a value
which discord does not
i see
it is true for select components that have a max of 1
but not for command options, and for selects with more max, where only after user clicks out of the select there's a single interaction with all options selected
I am really blind I guess, but how do I collect the votes from a poll? https://discord.js.org/docs/packages/discord.js/14.20.0/PollData:Interface
Wrong type
Message#poll discord.js@14.19.3
The poll that was sent with the message
It does, if you look into the nested properties of it
<Message>.poll.answers.at(0).voteCount
thanks
Uhh my bot host site got ratelimited is there an eta for when it removes?
eu-ro-01.wisp.uno:9359 is erroring with The owner of this website (discord.com) has banned you temporarily from accessing this website. and You are being rate limited
varies - minutes / hours
Check the rate limit headers
It showed this only
All bots on that node got ratelimited 💀
client.rest.on("rateLimited", console.log)
Added in index.js that line
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 | paste.gg | sourceb.in | hastebin
if it hangs on login ^
I'm pretty confused on why didn't it update to DND and saying its not on any servers (0)
const { PresenceUpdateStatus } = require('discord.js');
function updatePresence() {
const count = client.guilds.cache.size;
client.user.setPresence({
status: 'dnd',
activities: [{
name: `${count} servers | /help`,
type: ActivityType.Playing
}]
});
}
client.on('guildCreate', updatePresence);
client.on('guildDelete', updatePresence);```
-# I just couldn't know how to fix this
are you missing the Guilds intent?
also, you don’t have client defined there 
Maybe it's about "client" isn't defined idk
but I have guilds intent
maybe? i mean it’s your code so you should know what’s defined and what’s not and what errors you have
nvm I have it defined

where is it defined? is this not the whole code?
yes it isn't the whole code
but it's pretty long
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
Someone know how i can use Buttons in an Embed with the new Comp's? Or is the update not out yet
embeds are not available to use along with components if you opt into the new system
if you have seen an "embed" with buttons inside, that's a container with an accent color
oh okay
container with text display(s) and an actionrow with buttons // section with button accessory (single button to the right of text)
Thank you
@crimson gale We cant add a Author, Timestamp / Footer & Stuff like this to an container?
correct
you can use the general timestamp format and emulate a footer with -# subtext prefix
API Reference - Message Formatting
read more
hmm
why did we not add those small stuff to the container also

-# (souji should send the “we just don’t know sticker”)
is there really no way to fetch past say 100 messages from a specific user? or is fectching messages just limited to channel
how can I remove some commands from being userinstallable?
-# some commands of mine won't work there so that's why
what's this database btw? 
I use MongoDB.
documentation suggestion for @ocean portal:
SlashCommandBuilder#setIntegrationTypes() discord.js@14.19.3
Sets the integration types of this command.
Ty
Ofc
I have a serious question,
Why does my bot say client is undefined? maybe for function like client.ws.ping
someone tried it on their djs bot and it worked..
what could be so wrong?
Sounds like a basic JavaScript scoping issue
which isn’t the first time you’ve been told that
ik but why not just the function itself?
I literally tried everything to get the same "undefined"
what function?
tried what?
what’s your code?
client.ws.ping returns undefined
that’s not your full code
haven’t we been down this road before?
you probably don’t have client defined
please stop showing single lines of code without any context
it helps no one
const { Client, SlashCommandBuilder, EmbedBuilder } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName("ping")
.setDescription("Returns ping and roundtrip latency for troubleshooting slow response."),
async execute(interaction) {
try {
const ping = interaction.client.ws.ping;
const embed = new EmbedBuilder()
.setColor(0xff0000)
.setTitle('🏓 Pong!')
.addFields(
{ name: 'WebSocket Ping', value: `${ping}ms`}
);
await interaction.reply({ content: null, embeds: [embed] });
} catch (error) {
console.log(error)
await interaction.reply({ content: `Error:\n\`\`\`${error.message}\`\`\``});
}
},
}```
you have interaction.client
not client
I tried both
you can’t use “both”
one wouldn’t be defined regardless
which you should know
where does it say undefined? log ping
there’s a lot of info missing here
Changed it to client.ws.ping
there are 3 different errors here
and the 3rd is basic javascript
log interaction.client.ws.ping please
Kk
if you don’t know how to log something, that is where my support ends
it shows undefined
okay, please log interaction
interaction what?
that’s it, just interaction
Kk
why did you delete it?
it looked fine, but i’m confused as to why <Client>.ws.ping is undefined.
does that mean its something none can solve 
no, not necessarily, but it just means that there’s another problem somewhere else
Should I delete and reinstall djs
for node module
what should I do at that moment?

might be simple but I can't figure out how to escape spoilers in markdown links.
so to escape ||this|| I would to \|\|this\|\|which renders as ||this||. so far so good.
but when I try to do the same in a link, it becomes ||this|| notice how the backslashes are visible.
either the link has visible backslashes or has a spoiler in the link. am I missing something?
I think backslash just doesn't work as an escape character inside a hyperlink. Not really a library thing though
yeah it's just a general "working with discord bots" question, figured someone here would have experience with this situation
You can probably but an nbsp or other invisible character between pipelines to stop it from formatting as a spoiler if you just want it to look correct
oooh that's a good idea
can bot see user connections?
No, you can only get that info through an OAuth2 grant
any way to resize images in the mediagallery components of a container?
How do some bots make choices that are fetched before you run the command?
SlashCommandStringOption#setChoices() discord.js@14.19.3
Sets multiple choices for this option.
and if you want them to be dynamically loaded, you can use an autoComplete interaction
This is what I want to do
Slash Commands: Autocomplete
read more
Thnx
I dont know how events work and i want to make one where each time someone sends a message, it reads and sees if its that message. Its gonna have a prefix “!” and will look for something like “!message”. Can someone help me?
send ur interaction obj again
Will <member>.createDM() fail if a user has their DMs closed, or will it fail on .send() ?
Just checking where my try-catch should go.
probably on .send, let me confirm that for u
Cheers
i think u dont even get an error, u can pass in true in <member>.createDM() to force the dm to be created and then send the msg
Ah I'm more handling the use-case for when the DMs are closed. Like, if .createDM() is used, will a dmChannel still be created? If so, then it should be able to send a message.
More just double checking when I should use my try-catch block, or if it's just outright better to put them both within the try block, and then just assuming it's closed if either fails.
yeah, u could just wrap it in a try catch and handle the error or u could pass in true into .createDM() and force ur client to create the dm even though they have their dms closed
All createDM() does is fetch the DM channel between your app and the user. If a user's privacy settings don't allow your app to DM them, then it'd throw an error on send(). Just as a side note if you're sending a DM to someone, you aren't required to call createDM() beforehand as d.js will do that internally if deemed necessary to get the DM channel. Of course, if you're doing something else with the DM channel, then you can disregard that last point I made
The force option in createDM() is also merely whether to bypass d.js' cache or not. It has no bearing on "forcing the DM to be created" or anything similar
Yeah, completely off memory, I needed to use .createDM() for something else on one of my bots and the functions I had afterwards were wonky without it. Just a bit habitual to use it beforehand I think.
Good to know nonethless, I'll just handle the try-catch logic on .send() then, but if errors come up then I'll assume I need to include .createDM(). There are very few scenarios I can imagine where the DMs would be off, since you would need to be able to DM the bot to get to this situation.
Thankyou both for being rubber duckys. :)
The image I sent before to show jö?
he said its fine and he's confused on why wasn't it working
^ or any alternative
For makeCache settings, is MessageManager and GuildMessageManager practically the same thing? Like if I set MessageManager to 0 to cache no messages, do I not need to set GuildMessageManager also to 0 since that's already being handled by MessageManager?
what does this do?
await interaction.deferReply({withResponse:true});
nothing still? also i think its the node module
GuildMessageManager extends MessageManager. Only MessageManager is a valid key for makeCache, the subclasses of it aren't
} else if (interaction.type === InteractionType.ApplicationCommandAutocomplete) {
const command = this.client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.autocomplete(interaction);
} catch (error) {
this.client.logger.error(error);
}
}
The property 'autocomplete' does not exist on type 'Command'.ts(2339)
any
hi, I updated my code to the latest version of discord.js v14.20.0 and now this line makes an unexpected error for me
Command is your own interface. Not one provided by djs
my code has not changed between version v14.19.3 and v14.20.0 and in the note patch, there is no mention of change
Still, both that code and that interface are made by you. So djs version is completely irrelevant for that
What does your Command interface look like? And what did you type client.commands to be?
import type { APIApplicationCommandOption, PermissionResolvable, AutocompleteInteraction } from 'discord.js';
import type Outra from './Outra';
interface CommandDescription {
content: string;
usage: string;
examples: string[];
}
interface CommandPlayer {
voice: boolean;
dj: boolean;
active: boolean;
djPerm: string | null;
}
interface CommandPermissions {
dev: boolean;
client?: PermissionResolvable | PermissionResolvable[];
user?: PermissionResolvable | PermissionResolvable[];
}
interface CommandOptions {
name: string;
name_localizations?: Record<string, string>;
description?: Partial<CommandDescription>;
description_localizations?: Record<string, string>;
aliases?: string[];
cooldown?: number;
args?: boolean;
vote?: boolean;
premium?: boolean;
player?: Partial<CommandPlayer>;
permissions?: Partial<CommandPermissions>;
slashCommand?: boolean;
options?: APIApplicationCommandOption[];
category?: string;
}
That is neither of the things I asked for
the client cmds, that’s it
No. That is neither typing client.commands nor is it the Command interface
this?
Did you write that code yourself? You don't seem to know where you typed client.commands nor where to find your interface named Command
Then it's indeed hard for you to fix that
Is it possible to delete sent ephemeral responses?
With .deleteReply() on the interaction
ty
No need to send the whole file, the single line answering one of my questions would've sufficed. And the other question still is not answered from that code
what question?
"did you write that code yourself?"
why does the button pages in guides shows 404 errors?
I meant the "Command interface" question
Did you go there through the search? The search index is outdated, use the menu on the left for the time being
alr that was a pain going there, also is there a way to make button handler?? i cant find that in docs
You can do it similar to the command handler. You already know the concepts if you did that
like this?
const buttonHandler = require('./handlers/buttonHandler');
for (const file of fs.readdirSync(path.join(__dirname, 'handlers/buttons'))) {
if (!file.endsWith('.js')) continue;
const btn = require(`./handlers/buttons/${file}`);
if (btn.customId && typeof btn.execute === 'function') {
client.buttons.set(btn.customId, btn);
}
}```
constructor(client: Outro) {
super(client, {
name: 'help',
description: {
content: 'cmd.help.description',
examples: ['help'],
usage: 'help <command>',
},
category: 'Info',
aliases: ['h'],
cooldown: 3,
args: false,
vote: false,
premium: false,
permissions: {
dev: false,
client: ['SendMessages', 'ReadMessageHistory', 'ViewChannel', 'EmbedLinks'],
user: [],
},
slashCommand: true,
options: [
{
name: 'command',
description: 'cmd.help.options.command',
type: 3,
required: false,
autocomplete: true,
},
],
});
}
Still not what I asked for... you have an interface named Command. Reading your code I even know where. But the fact that you don't seem to know is worrying to me
/home/container/index.js:30
await btn(interaction);
^
TypeError: btn is not a function
at Client.<anonymous> (/home/container/index.js:30:11)
at Client.emit (/home/container/node_modules/@vladfrangu/async_event_emitter/dist/index.cjs:287:31)
at InteractionCreateAction.handle (/home/container/node_modules/discord.js/src/client/actions/InteractionCreate.js:104:12)
at module.exports [as INTERACTION_CREATE] (/home/container/node_modules/discord.js/src/client/websocket/handlers/INTERACTION_CREATE.js:4:36)
at Client._handlePacket (/home/container/node_modules/discord.js/src/client/Client.js:384:33)
at WebSocketManager.emit (/home/container/node_modules/@vladfrangu/async_event_emitter/dist/index.cjs:287:31)
at WebSocketShard.<anonymous> (/home/container/node_modules/@discordjs/ws/dist/index.js:1273:51)
at WebSocketShard.emit (/home/container/node_modules/@vladfrangu/async_event_emitter/dist/index.cjs:287:31)
at WebSocketShard.onMessage (/home/container/node_modules/@discordjs/ws/dist/index.js:1091:14)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
Node.js v23.8.0```
```js
const btn = require('./handlers/buttonHandler.js');
else if (interaction.isButton()) {
await btn(interaction);
}```
whys this happening? i cant solve this problem
And that you client class is named Outra in one place but Outro in another doesn't make it better.
Your file exports a execute function
You have to call that
is there a way I can get vscode to provide autocomplete for djs?
Use jsdoc or typescript
thanks
how to? i thought this was gonna work
you dont know how to call a function?
Thats the core basics of js
And you even check for that function being present right here
no im just confused..
i cant literally communicate with like 80+ yr adults
-# 😭
confused about calling a function you exported? You check for your function being there
your btn.execute is what you need to call
And pass in the interaction or whatever your function expects
I'd recommend you brush up on your js knowledge, #resources
i just didnt understand what u said 
btn.execute(interaction)
Thats literally it
i tried that and
/home/container/node_modules/@discordjs/rest/dist/index.js:748
throw new DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData);
^
DiscordAPIError[50035]: Invalid Form Body
user_id[NUMBER_TYPE_COERCE]: Value "null" is not snowflake.
at handleErrors (/home/container/node_modules/@discordjs/rest/dist/index.js:748:13)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
at async SequentialHandler.runRequest (/home/container/node_modules/@discordjs/rest/dist/index.js:1149:23)
at async SequentialHandler.queueRequest (/home/container/node_modules/@discordjs/rest/dist/index.js:980:14)
at async _REST.request (/home/container/node_modules/@discordjs/rest/dist/index.js:1293:22)
at async UserManager.fetch (/home/container/node_modules/discord.js/src/managers/UserManager.js:101:18)
at async Object.execute (/home/container/handlers/buttonHandler.js:5:23)
at async Client.<anonymous> (/home/container/index.js:30:5) {
requestBody: { files: undefined, json: undefined },
rawError: {
message: 'Invalid Form Body',
code: 50035,
errors: {
user_id: {
_errors: [
{
code: 'NUMBER_TYPE_COERCE',
message: 'Value "null" is not snowflake.'
}
]
}
}
},
code: 50035,
status: 400,
method: 'GET',
url: 'https://discord.com/api/v10/users/null'
}
Node.js v23.8.0```
Thats a totally different error
You're trying to fetch a user somewhere but the id yoy pass in is null
it’s the index that redirects to the commands. You told me that this is not what you wanted...
ig its coming from this then js module.exports = { customId: 'hello_button', async execute(interaction) { const [ , slashUserId ] = interaction.customId.split(':'); const slashUser = await interaction.client.users.fetch(slashUserId); const clicker = interaction.user; await interaction.reply({ content: `${clicker.tag} clicked after slash run by ${slashUser.tag}` }); } }
time to cook 🔥
How to make like this
Im trying to make image thumbnail before the text and button in same section
Is not working how to do it?
because thats not an image thumbnail
Is what?
those are custom emojis inside a text display component, placed in a 2x2 grid
so for each pokemon image you see, 4 custom emojis are used
How to make it 2x2

Title text

Description
:follow1::follow2: **Title text**
:follow1::follow2: Description
Oh but
Emoji is in same line with the section
yes? you can put text after an emoji?
i do not see where the confusion is coming from here
4 emoji, 2 per line, 2 lines of text
a section component holds a text display component and an accessory (button or thumbnail)
Ha? How? Where?
^
But if i write a emoji with text the emoji small not big
…
How tl keep it big
4 small emojis make 1 big emoji
it... isn't?
[1][2]
[3][4]
you have to split your image into 4 pieces
_ _

Hello

world
upload them as 4 separate emojis
that's a cool but tricky tech
only downside is that on mobile clients between the lines there is like 1 pixel space between them
it's a very hacky workaround to make it work'ish
dv8 said so themselves 
i dont know if its worth it anymore but its that null is not compliant with the return type
and im using vscode, i tried replicating it, and it seems like its completely impossible to implement complicated return types
because TypeVar bound parameters cant get narrowed down
- they used 4 emojis
- shows grid
- what
- OH 4 EMOJIS WTF
Why would someone make such a movement for the sake of a message form?
i think you need to start actually reading what people say
I'm just beginning to understand. 😂
because its a nice workaround to have decent sized images on the left of your text
"nice" is debatable - horrible for screen readers and accessibility
imo the custom emojis syntax on discord is horrible for screen readers and accessibility in general 
-# (off-topic)
my best guess would be that the thumbnail variable is either undefind or that it needs to be as an attachment but im not sure but the error should be bc of the thumbnail accessory
how do i mention in components v2? is this enough?
await channel.send({
flags: MessageFlags.IsComponentsV2,
components: [container],
allowedMentions: {parse: ["roles"]}
});
Please show the error you're talking about
is it possible to make another ping of a role after i updated the message? because as far as i understand 1 message 1 ping
You don't need to add the allow mentions option to your message. By default, all mentions are parsed
You cannot trigger a push notification for a message that has already been sent
using “ghost pings” would work, but idk if users like that
u mean opening a thread and ping there?
no, sending a new message mentioning them again, then immediately delete that message after its sent
ah yea makes sense
but when i do follow up i still dont get a second ping - does it mean that followUp is not a "new" message?
it should as its a new different message
u see the message is not yellow like the first one. i just do this
const message = await interaction.followUp({
content: `${mention}`,
});
setTimeout(() => {
message.delete();
}, 5000);
this second mention is mentioning the bot not you
whereas the first one mentions you as well as possibly a role you may have
what you mean ? the bot is mentioning the role
mawhawk is a role that you have?
exactly
thats why i got mentioned in the fiorst message
now that I look at this it might actually be a discord issue
when i try to send a normal message it works with the mention but not with followup
yeah so the issue is then that with a followup it should also parse the mentions, which clearly doesn't right now
doing this - and it works xD
const message = await interaction.followUp({
content: `${mention}`,
allowedMentions: {parse: ["roles"]},
});
hm alr lol
seem like this is not the case by default
it is, but somehow not for followup messages
is it okay to forward your image to the discord devs server to ask there if this behaviour is intended (and a PR/issue is needed) or not?
yea sure
so you are sure its discord related then?
yeah, as d.js is just making it easier to send requests to discord's api and by the looks of it discord isn't handling the followup message mention parsing correctly
#djs-help-v14 message see this message from qjuh saying it should always parse all mentions on default
okay but anyway thx for your help ❤️
| [replaceComponents ERROR] ValidationError > s.nativeEnum(T)
0|moonveil | Expected the value to be a string or number
0|moonveil |
0|moonveil | Received:
0|moonveil | | undefined
how to fix this error
give the full error would be more helpful, now I can only tell you that somewhere it expects either a value of type string or number but it is given undefined
0|moonveil | [replaceComponents ERROR] ValidationError > s.nativeEnum(T)
0|moonveil | Expected the value to be a string or number
0|moonveil |
0|moonveil | Received:
0|moonveil | | undefined
0|moonveil |
0|moonveil | at _NativeEnumValidator.handle (/home/ubuntu/moonveil/node_modules/@sapphire/shapeshift/src/validators/NativeEnumValidator.ts:50:3)
0|moonveil | at _NativeEnumValidator.parse (/home/ubuntu/moonveil/node_modules/@sapphire/shapeshift/src/validators/BaseValidator.ts:126:2)
0|moonveil | at SeparatorBuilder.setSpacing (/home/ubuntu/moonveil/node_modules/@discordjs/builders/src/components/v2/Separator.ts:51:40)
0|moonveil | at Timeout._onTimeout (/home/ubuntu/moonveil/src/utils/replaceComponents.js
14)
0|moonveil | at listOnTimeout (node:internal/timers:581:17)
0|moonveil | at processTimers (node:internal/timers:519:7)
0|moonveil | [replaceComponents] Error editing message: TypeError: Cannot read properties of undefined (reading 'Caption')
0|moonveil | at Timeout._onTimeout (/home/ubuntu/moonveil/src/utils/replaceComponents.js:44:40)
0|moonveil | at listOnTimeout (node:internal/timers:581:17)
0|moonveil | at processTimers (node:internal/timers:519:7)
what is your code?
wdym?
what is line 26 of replaceComponents.js saying?
module.exports = function replaceComponents(message, {
timeout = 1 * 60 * 1000,
text = 'This menu has expired. Please use the command again.',
color = 0x2f3136
} = {}) {
if (!message || typeof message.edit !== 'function') {
console.log('[replaceComponents] Invalid message or no edit function');
return;
}
console.log([replaceComponents] Will edit message in ${timeout}ms);
setTimeout(async () => {
try {
console.log('[replaceComponents] Running timeout callback');
const expiredContainer = new ContainerBuilder()
.setAccentColor(color)
.addTextDisplayComponents(
new TextDisplayBuilder().setContent('#  Commands Expired')
)
.addSeparatorComponents(
new SeparatorBuilder().setSpacing(SeparatorSpacingSize.Small).setDivider(true)
)
.addTextDisplayComponents(
new TextDisplayBuilder().setContent(`*${text}*`)
)
thats a lot for just 1 line... (and not what I asked)
but I think you forgot to import SeparatorSpacingSize from the d.js package into your file
line 26 empty
this full code
const {
ContainerBuilder,
TextDisplayBuilder,
SeparatorBuilder,
ThumbnailBuilder,
MessageFlags,
SeparatorSpacingSize,
TextDisplayStyle
} = require('discord.js');
module.exports = function replaceComponents(message, {
timeout = 1 * 60 * 1000,
text = 'This menu has expired. Please use the command again.',
color = 0x2f3136
} = {}) {
if (!message || typeof message.edit !== 'function') {
console.log('[replaceComponents] Invalid message or no edit function');
return;
}
console.log([replaceComponents] Will edit message in ${timeout}ms);
setTimeout(async () => {
try {
console.log('[replaceComponents] Running timeout callback');
const expiredContainer = new ContainerBuilder()
.setAccentColor(color)
.addTextDisplayComponents(
new TextDisplayBuilder().setContent('#  Commands Expired')
)
.addSeparatorComponents(
new SeparatorBuilder().setSpacing(SeparatorSpacingSize.Small).setDivider(true)
)
.addTextDisplayComponents(
new TextDisplayBuilder().setContent(`*${text}*`)
)
.addTextDisplayComponents(
new TextDisplayBuilder().setContent('\n') // invisible spacer
)
.addTextDisplayComponents(
new TextDisplayBuilder()
.setContent('> gaeuly & moonveil')
.setStyle(TextDisplayStyle.Caption)
)
.setThumbnailAccessory(
new ThumbnailBuilder().setURL('https://cdn.discordapp.com/embed/avatars/0.png')
);
console.log('[replaceComponents] Editing message with expired container...');
await message.edit({
components: [expiredContainer],
flags: MessageFlags.IsComponentsV2
});
console.log('[replaceComponents] Message edited successfully!');
} catch (error) {
console.error('[replaceComponents] Error editing message:', error);
}
}, timeout);
};
next time use this @grizzled bison
are you on the latest d.js version?
alr
yes 14.20.0
@grizzled bison ~~this is at lest one of your issues use a separator
new TextDisplayBuilder().setContent('\n') // invisible spacer
)
```~~ NV this is not an issue
not true
I thought discord trimmed white space or is that only for conent
the error is saying two things are wrong:
.setSpacing(SeparatorSpacingSize.Small)
error 1: value of SeparatorSpacingSize.Small is undefined (idk how that is)
.setStyle(TextDisplayStyle.Caption)
error 2: value of TextDisplayStyle is undefined, that is because there is no such thing as TextDisplayStyle, use # in front of it to make the text as heading
@grizzled bison ^
I'm a little confused about which one is correct 
while considering TextDisplayStyle is not real it is likely that
wait ill try delete caption and spacing
> # header text with inline quote
You need to pass allowedMentions with that to ping
yea but Mafia said its enabled by default and it looks like its not by followup messages
no I said that, but looks like I was wrong then
#djs-help-v14 message I just read back this convo
Do you have any allowedMentions in your Client() constructor?
const client = new Client({intents: [Guilds, MessageContent, GuildMessages, GuildPresences, GuildMembers]})
And does the everyone role have permission to ping that particular role?
yes
Because interaction followUps don't use the bot's permissions, that would've been a likely reason
ah okay wait i need to check this right?
Yes. So there's the reason for your issue
Wait, no
ah okay so when I enable this for the bot it should wokrk?
Not that
that is for the everyone role you would need it for bot role
yea thats what i thought
No, neither. You'd need to set "allow everyone to mention this role" on the mawhawk role
ah makes sense
but that will make everyone be able to mentiont the role not just the bot. is that the goal?
Why are you asking me?
A followUp is not sent by the bot user
It is Not?! Interesting
It's a (interaction) webhook after all
The more you know. I kind of just assumed that follow-up used the same permissions as the bot user
I'm not 100% sure my statement still is accurate, it definitely was the case in the past. Double checking right now
v10: AuditLogEvent - MemberBanAdd
read more
how do i get all non-closed threads (even inactive ones)?
ThreadManager#fetchArchived() discord.js@14.19.3
Obtains a set of archived threads from Discord. This method requires the permission in the parent channel.
no i want NON closed
GuildChannelManager#fetchActiveThreads() discord.js@14.19.3
Obtains all active thread channels in the guild.
// Fetch all threads from the guild
message.guild.channels.fetchActiveThreads()
.then(fetched => console.log(`There are ${fetched.threads.size} threads.`))
.catch(console.error);
closed !== archived
oh whats the difference
inactive === archived
there is archived and there is locked. which one you mean by "inactive" is ambigous I guess
but since you talk about non-closed inactive that only makes sense if you mean not locked but archived
okay i double checked i want all non locked
then use those two methods, and filter all locked threads from the archived
oki ty
can we set image size in Mediagallerybuilder
no
has discord documented the gradient thing with roles?
No
any idea when it will be done?
Again, no.
Also not the best place to ask
You can follow the pr on their github
link?
You can check on their github (discord-api-docs)
has anyone else been getting this error?
/mnt/funsize/nodejsProjects/TTSBot/node_modules/@discordjs/voice/dist/index.js:531
throw new Error(`No compatible encryption modes. Available include: ${options.join(", ")}`);
^
Error: No compatible encryption modes. Available include: aead_aes256_gcm_rtpsize, aead_xchacha20_poly1305_rtpsize
at chooseEncryptionMode (/mnt/funsize/nodejsProjects/TTSBot/node_modules/@discordjs/voice/dist/index.js:531:11)
at /mnt/funsize/nodejsProjects/TTSBot/node_modules/@discordjs/voice/dist/index.js:720:21
Emitted 'error' event on VoiceConnection instance at:
at VoiceConnection.onNetworkingError (/mnt/funsize/nodejsProjects/TTSBot/node_modules/@discordjs/voice/dist/index.js:1898:10)
at Networking.emit (node:events:518:28)
at /mnt/funsize/nodejsProjects/TTSBot/node_modules/@discordjs/voice/dist/index.js:728:32
Node.js v20.11.1
it seems to only be happening in one vc in my server, I moved to a different one and it stopped
why webhook not working in this code
you need to add withComponents: true to the webhook
okay wait
If you are sending components as part of a webhook you'll need to use the
?with_components=truequery param otherwise they'll be ignored.
per the Discord docs
How can you get the maximum amount of Auto-Mod rule for a server?
Guys, what do I do if it takes 10 minutes exactly for the bot to rename a channel when a button is pressed?
you wait
The ratelimit is twice every 10 minutes
ah
Guys, is it possible to make my bot respond to a command with a server custom emoji or no?
yeah, just use the correct format
If i wanted my command to have a randomized response, can it pull from a website?
Whats the format?
tag suggestion for @grizzled venture:
- Custom emojis:
\:name:➞<a:name:id> - Twemojis:
\:name:➞ unicode representation - Emoji picker:
WIN+./CMD+CTRL+SPACE/CTRL+. - Right-clicking any emoji will not copy its id!
Ty
sure, but that's outside the scope of djs
discord is only concerned about you responding within 3s, whether with a full response or a defer
from where or how you pull your response doesn't concern them
Is there a certain way it has to be set up for a pull?
no but it's recommended that you defer first since you have to do this
and you don't know how much time the fetch and parsing it will take
Is there a way i could set like all of the random responses, and have it pick a random one each time?
I mean? Of course....but not with anything from DiscordJS...just with JavaScript
^^
(and it's not part of the library)
at most there's the AttachmentBuilder which helps by accepting local file paths to send them as attachments
Okay
I was just about to mention the attachment builder. For some reason it seems to break randomly when using Bun, though it's totally fine with Node. Any particular reason as to why?
@rose tangle The emoji is from the server. What am I doing wrong?
message.reply(If your item sells for \:robux: ${price.toFixed(2)}, you will keep \:robux ${afterTax.toFixed(2)} after a 30% tax.);
you have to use the <a:name:id> format
":name: ➞ <a:name:id>" means, if you have an emoji named "name", you can get the <a:name:id> format by sending a message in discord using the emoji, prefixed by \
you'll have to ask bun
i've seen an interesting function in the discordjs/core from the GuildsAPI that says getMembers
can i use that or no?
why not?
good question
I am so dumb.
message.reply(If your item sells for :robux: ${price.toFixed(2)}, you will keep :robux: ${afterTax.toFixed(2)} after a 30% tax.);
What is wrong with it?
that you are not using the <a:name:id>
you're using :name:
well because it says "GuildsAPI.getMembers is not a function"
this is the entire error:
TypeError: GuildsAPI.getMembers is not a function
at Object.execute (D:\JX1DX1 bot\src\commands\testing purposes\get-servers.js:15:39)
at D:\JX1DX1 bot\src\events\interactionCreate\commandHandler.js:20:30
at Array.forEach (<anonymous>)
at Object.execute (D:\JX1DX1 bot\src\events\interactionCreate\commandHandler.js:14:56)
at Client.<anonymous> (D:\JX1DX1 bot\src\index.js:51:47)
at Client.emit (node:events:519:35)
at InteractionCreateAction.handle (D:\JX1DX1 bot\node_modules\discord.js\src\client\actions\InteractionCreate.js:97:12)
at module.exports [as INTERACTION_CREATE] (D:\JX1DX1 bot\node_modules\discord.js\src\client\websocket\handlers\INTERACTION_CREATE.js:4:36)
at WebSocketManager.handlePacket (D:\JX1DX1 bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:351:31)
at WebSocketManager.<anonymous> (D:\JX1DX1 bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:235:12)
Node.js v24.2.0
I have. They've reviewed how the attachment builder works and can't locate anything runtime dependent that would potentially break it. Also, it's not a consistent issue. Sometimes it happens, sometimes it doesn't happen at all
Is there something i can see everything djs can do? Like an index?
huh? The name is !robux and the id is 1386370808275931146 and I am using :robux:
- it's not a static function, it's an instance method. you need an instance of GuildsAPI
- you're using discord.js, why do you want to use discordjs/core?
- my bad, did not know that
- i just wanted to see if i can get all the members of a separate guild
@rose tangle Discord keeps editing it wrongly. Tho this how it says:
it's outside discord.js' control how other runtimes work, if it didn't work on node then it'd be a djs issue, otherwise there isn't much that can be changed
if bun manages to find an issue that has a fix that is reasonable to implement in djs, maybe it could be implemented, but djs mostly targets node
documentation suggestion for @crimson thistle:
GuildMemberManager#fetch() discord.js@14.19.3
Fetches member(s) from a guild.
// Fetch all members from a guild
guild.members.fetch()
.then(console.log)
.catch(console.error);
do consider it'll take a long while in large guilds
since they come in batches through the gateway
I see. Alright, thanks 
I'd suggest finding an alternative
i assume that there's not a way of getting all the members from a guild that my bot is not in?
correct
shucks
Thank You
is it an animated emoji?
No, it’s 
then don't put the a
just <:robux:id>
if you send a message with \:name: it'll give you the correct format
how to check user tag?
not documented in API yet
thanks
👍
How can I synchronize prefix commands for music bots that use the same prefix as the Jockie Music bot?
how is that djs related?
how to set the container color
ContainerBuilder#setAccentColor() discord.js@14.19.3
Sets the accent color of this container.
Can my bot track when someone appears in the pending list (join applications)?
Thats not yet documented by discord
but is possible?
not with djs, it doesn't have undocumented features
is this verison bugged?? it always say client is undefined when it is not
15.0.0-dev```
I mean, that sounds like a js error, not a djs one
and this channel is for v14, not the in-development v15 version
how so?? everyone i asked was confused
and why are you using the dev version in the first place
I'd also be confused without the full error since I have no idea what it actually is, I'm just speculating it's the js one
is it like this to install stable djs?
npm install discord.js@lastest
nvm ill try
cya
literally just discord.js, don't need a special tag
you specifically specified the dev version in order to get the dev version
alright
but if the error is the js one then that won't solve your issue either way 
When will the primary_guild key will be able to sense update in updateevent?
Cuz via api it works but via presencedetect or memberupdate it doesn't work
d.js doesn’t support it yet that’s why
When will that thing come 😭
whenever it’s documented and finished
(by discord)
I tried to do it via api call and presence update bot got ratelimited for 50 minutes 💀
But it is present in user payload and I asked on ai it said d.js is unable to track update
how i can get the tag with djsv14?
@shut sphinx
.
now I am making a system like this, when the user gets the clan tag of the specified server, it will give him a role.
documented != present
oh oky
Same I was doing but we can't track changes sadly 😭
if i can get the guild tag i can do that but i cant get
if you plan to pull data constantly that'll easily get you ratelimited
the real way would be through a gateway event
maybe it currently works or maybe it doesn't, I'd advise just waiting for it to fully release
My bot got ratelimited yesterday 62 calls in 15 minutes including other calls so yeah
You can use rest api + presence update but you get ratelimited
what?
Yes you must use rest right?
Use that to get user payload
But still same thing it would lead to ratelimiting so try not to do that
right, I wasn't asking you to copy and paste your message
no i will do my special
I was asking you to elaborate in an understandable one
"make an api in d.py and transfer that api to d.js" makes no sense
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
nvm
Slash Commands: Advanced command creation
read more
@toxic moat please use #app-commands for personal use
sorry 
client.on('raw', async (packet) => {
if (packet.t !== 'PRESENCE_UPDATE') return;
const db = global.mongoClient.db('discordBot');
const guildTags = db.collection('guildTags');
const userTags = db.collection('userTags');
const data = packet.d;
const user = data.user;
const userId = user?.id;
if (!userId) return;
const newTag = user?.primary_guild?.tag || user?.clan?.tag;
if (!newTag) return;
const previous = await userTags.findOne({ userId });
const oldTag = previous?.lastTag || null;
if (oldTag === newTag) return;
await userTags.updateOne(
{ userId },
{ $set: { lastTag: newTag, lastUpdated: new Date() } },
{ upsert: true }
);
const logChannel = await client.channels.fetch('1386102430961373194').catch(() => null);
if (logChannel?.isTextBased()) {
const embed = {
title: '🛡️ Guild Tag Changed',
description: `<@${userId}> updated their primary guild tag.`,
color: 0x00b0f4,
fields: [
{
name: '👴 Old Tag',
value: oldTag || 'None',
inline: true
},
{
name: '🆕 New Tag',
value: newTag,
inline: true
}
],
timestamp: new Date().toISOString()
};
await logChannel.send({ embeds: [embed] });
}
for (const [guildId, guild] of client.guilds.cache) {
const tagDoc = await guildTags.findOne({ guildId, name: newTag.toUpperCase() });
if (!tagDoc) continue;
const member = await guild.members.fetch(userId).catch(() => null);
if (!member) continue;
const role = guild.roles.cache.get(tagDoc.roleId);
if (!role) continue;
if (!member.roles.cache.has(role.id)) {
await member.roles.add(role).catch(() => {});
}
}
});
Uhh its spamming same update
yeah, that's not the right one
tags have nothing to do with the presence
Why? On presenceupdate also it is spamming
also you're pretty much on your own supporting and maintaining undocumented features 
Only presence can only give tag info rn without bot going ratelimited
you are wrong
Then?
Also when I'm tracking normal presence like online to offline and other it is spamming logs
again, the tag has nothing to do with the presence. the tag is part of the inner user payload of a guild member update
And presence update emits for every guild your bot shares with the user (to answer the second part of your question)
Oh guildMember update
what amgelo said is also a good point - you are now in raw API, even undocumented raw API territory
you are on your own with this
Uhh ok gotta wait then
But why my normal presence uodate also spamming when user going offline to online
client.on('presenceUpdate', async (oldPresence, newPresence) => {
const userId = newPresence.userId;
if (userId !== '807961656306040854') return;
const channel = await client.channels.fetch('1386102430961373194');
if (!channel || !channel.isTextBased()) return;
const oldStatus = oldPresence?.status || 'unknown';
const newStatus = newPresence?.status || 'unknown';
if (oldStatus !== newStatus) {
const embed = {
title: '📶 Presence Status Changed',
description: `<@${userId}> updated their status.`,
color: 0x00b0f4,
fields: [
{
name: '📴 Old Status',
value: oldStatus,
inline: true,
},
{
name: '📶 New Status',
value: newStatus,
inline: true,
},
],
timestamp: new Date().toISOString(),
};
await channel.send({ embeds: [embed] });
}
});
What can I do for this issue?
Idk why is it spamming 😭
i would recommend re-reading the responses above
Oh mb so how can I resolve that?
specifically
tbf, the same is true for guild member updates, if the inner user changes - also gets emitted per shared guild
I forgot to read that sorry
Now what can I do for that about spam?
I haven't worked with presenceUpdate but I'd implement a debouncer
maybe there's an easier way, though it should be straightforward
probably limit your logging to one guild / log it on the guild it affects
There are like 116 guilds and each have unique users so like how can I limit to one guild?
If I use cache mechanism would that resolve this issue?
I think a better question would be, what are you specifically trying to implement
because this tries to log presence updates from one user, to a given channel, unless you plan to spy on someone, it'd be better if you fully describe what your expected feature is
any1 can help me with my error?
take a look at #how-to-get-help
Yes and that's happening like multiple times and as told above it will run in all servers the bot and user is so if the bot is in 50 servers and user also in all those so it will run 50 times so I'm asking how can I prevent that so it run once only instead of 50 times
so you do want to spy on someone?
or why specifically do you only need to filter one user
and send it to a specific channel
No
Its like the online offline dnd idle
it will be opt in so user have to opt in
Set opt in as true
Right now that's why I'm testing on myself only rn
so each user opts in for their presence to be logged in a given channel? why would they opt in to that?
Its me rn if I do this public the logs will blow out for now
See like this
Its not to spy on someone 😭
Just working on logs
^^
l0|moonveil | [UNCAUGHT send] CombinedError (2)
0|moonveil | Received one or more errors
0|moonveil | 1 ExpectedValidationError > s.instance(V)
0|moonveil | | Expected
0|moonveil | |
0|moonveil | | Expected:
0|moonveil | | | [Function: ButtonBuilder]
0|moonveil | |
0|moonveil | | Received:
0|moonveil | | | undefined
0|moonveil | 2 ExpectedValidationError > s.instance(V)
0|moonveil | | Expected
0|moonveil | |
0|moonveil | | Expected:
0|moonveil | | | [Function: ThumbnailBuilder]
0|moonveil | |
0|moonveil | | Received:
0|moonveil | | | undefined
0|moonveil | at _UnionValidator.handle (/home/ubuntu/moonveil/node_modules/@sapphire/shapeshift/src/validators/UnionValidator.ts:9:57)
0|moonveil | at _UnionValidator.parse (/home/ubuntu/moonveil/node_modules/@sapphire/shapeshift/src/validators/BaseValidator.ts:126:2)
0|moonveil | at SectionBuilder.toJSON (/home/ubuntu/moonveil/node_modules/@discordjs/builders/src/components/v2/Section.ts:150:34)
0|moonveil | at /home/ubuntu/moonveil/node_modules/@discordjs/builders/src/components/v2/Container.ts:236:61
0|moonveil | at Array.map (<anonymous>)
0|moonveil | at ContainerBuilder.toJSON (/home/ubuntu/moonveil/node_modules/@discordjs/builders/src/components/v2/Container.ts:236:32)
0|moonveil | at /home/ubuntu/moonveil/node_modules/discord.js/src/structures/MessagePayload.js:151:46
0|moonveil | at Array.map (<anonymous>)
0|moonveil | at MessagePayload.resolveBody (/home/ubuntu/moonveil/node_modules/discord.js/src/structures/MessagePayload.js:150:49)
0|moonveil | at TextChannel.send (/home/ubuntu/moonveil/node_modules/discord.js/src/structures/interfaces/TextBasedChannel.js:189:32)
how to fix this
Rn I have set specific channel
But servers will have ability to set own channel for their guild in future
I'm trying to understand what your feature is, to be able to suggest what would be a good approach
so each server can setup their own log channel for user presences?
it sounds like you tried to build a section without an accessory
sections need an accessory
if you don't set one, the section is pointless, hence why it's not allowed
just add the text displays directly in the container at that point
Ok basically I'm trying to use presenceupdate feature to like track like user activities about like they are doing coding in vs code going offline going online
It will be like fully customizable(not to spy on someone 😭)
I was trying to do it from yesterday but it is logging multiple times and as I got told that it would run for every server bot shares with user so how can I limit it to 1 user?
The user in code is me and the channel in code is for testing
but if each server would have their own logging channel, then it sounds like you do want the event to log for each server
I'm just looking for a way to make it run once instead of 50 servers
Rn for testing I wanna test it for once so first I can properly build it as rn it is sending 50 times so like logs are filling up a lot and unable to see properly as I showed in screenshot also
then filter by the guild/server
Presence#guild discord.js@14.19.3
The guild this presence is in
but later on you'll probably want to not filter, but instead use the guild to fetch their logging channel
Oh ok
Is there a link to the docs website?
to what part?
I shared the link to the docs of Presence#guild
discordjs.guide ?
there isn't a guide on how to log user presences
I have to use like
client.on('GuildMember')
Right?
you already shared code above though? I'm not sure what you're looking for
Nvm I'm tired for now will reread all messages in morning and will take help from friends also to figure out what I'm trying to do
how do i check if a message was sent by a webhook ?
Check whether it .webhookId is not null. Note this includes interaction webhooks, so you'd need to filter those out if you don't want them
wym interaction webhooks?
When you respond to an interaction you are doing so through a webhook
replys to commands and buttons etc. they uses a webhook
author bot true and discriminator 0000 should work
for now apps are not moved to the unique username system so should always have a non 0000 discriminator
so
if(msg.author.bot)
{
if(message.author.tag == 0000){
//dwadwdw
}
}
.discriminator, not .tag, and the 0000 should be in quotes since it's a string
.discriminator doesnt exist in author
Message.author is a User, so it does
not showing up in my IDE, let me restart rq
webhookId combined with not applicationId might be the better approach the more i think about it 
unless the hook was created by an app, then it might have that 
maybe hook and not interaction metadata?
this is surprisingly annoying
lmao, all g, im handling this under MessageCreate, would there be interactions attached to the messages?
oh yeah, just seen interactionMetadata, ill run that
There could be, if the message came from an interaction (like a user using any non-ephemeral command, for example)
i just created another sub command and the old one disappeared with no errors
why?
Hi Guys Onde Help
import { Client, GatewayIntentBits, Collection } from "discord.js";
import { config } from "dotenv";
import fs from "node:fs";
import path from "node:path";
config();
const client = new Client({
intents: [GatewayIntentBits.Guilds]
});
client.commands = new Collection();
function getAllCommandFiles(dirPath: string, arrayOfFiles: string[] = []) {
const files = fs.readdirSync(dirPath);
for (const file of files) {
const fullPath = path.join(dirPath, file);
if (fs.statSync(fullPath).isDirectory()) {
getAllCommandFiles(fullPath, arrayOfFiles);
} else if (file.endsWith(".ts") || file.endsWith(".js")) {
arrayOfFiles.push(fullPath);
}
}
return arrayOfFiles;
}
const commandsPath = path.join(__dirname, "commands");
const commandFiles = getAllCommandFiles(commandsPath);
for (const file of commandFiles) {
const command = require(file);
if ("data" in command.default && "execute" in command.default) {
client.commands.set(command.default.data.name, command.default);
} else {
console.warn(`[WARN] Comando inválido em: ${file}`);
}
}
const eventsPath = path.join(__dirname, "events");
const eventFiles = fs
.readdirSync(eventsPath)
.filter((file) => file.endsWith(".ts") || file.endsWith(".js"));
for (const file of eventFiles) {
const event = require(path.join(eventsPath, file));
if (event.default.once) {
client.once(event.default.name, (...args) => event.default.execute(...args, client));
} else {
client.on(event.default.name, (...args) => event.default.execute(...args, client));
}
}
client.login(process.env.DISCORD_TOKEN);
in my ts is return this error
Property 'commands' does not exist on type 'Client<boolean>'.
We highly recommend you extend the Client structure properly instead of just attaching custom properties like .commands to the regular discord.js Client instance.
- Using typescript, you might want to consider casting or augmenting the module type
Does djs have a helper function for mentioning commands?
Probably overwriting it. Show the command builder?
chatInputApplicationCommandMention discord.js@14.19.3
Formats an application command name and id into an application command mention.
cheers
the one that dissapeared after new one:
const { Discord, SlashCommandBuilder, EmbedBuilder } = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName('entertainment')
.setDescription('entertainment purpose command, used to have fun.')
.addSubcommand(sub =>
sub
.setName('facepalm')
.setDescription('Sends a facepalm Image (API)')
...```
the new one:
```js
const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('entertainment')
.setDescription('entertainment purpose command, used to have fun.')
.addSubcommand(sub =>
sub
.setName('nekos')
.setDescription('Sends a Nekos (API)')
)```
Put both subcommands on the same builder. You're probably setting them both to the same collection, which means the last will replace all previous ones
wow... no way to fix it?
they just gave you a way to fix it... 
??
huh
do you need help with something?
i want both /entertainment ...
why just 1
so put them in the same builder
as said
hows that
Call .addSubcommand twice. Once for each subcommand. On the same builder
isnt both gonna have the same code or what
Well then you check which subcommand it is and handle it accordingly
?
?
.addSubcommand(sub =>
// code
)
.addSubcommand(sub =>
// code
),
Without the first comma
how i can do like message that released on 14.19.0 version
what message
in data????????????
kk
what?
do you understand what to do here?
And if you're curious how this message was built, check out the source code!
wheres that gonna be
in your code?
lol
Put the second one under the first one, as they showed
like this one i didnt understand it
the source code is literally in that message
There's also a section in the guide:
https://discordjs.guide/popular-topics/display-components.html
like this?
module.exports = {
data: new SlashCommandBuilder()
.setName('entertainment')
.setDescription('entertainment purpose command, used to have fun.')
.addSubcommand(sub =>
sub
.setName('nekos')
.setDescription('Sends a Nekos (API)'),
// code
)
.addSubcommand(sub =>
sub
.setName('facepalm')
.setDescription('Sends a facepalm image (API)'),
// code
),
};```
i didnt really under what u were saying
thats what we were saying
remove the //code
it was an example
even the guide has a section on subcommands, which i believe i sent for you and shows how to put multiple subcommands
that also shouldn't really be the whole file. usually your command's functionality go in the same file unless your handler handles commands differently
im just basing it off of what our guide suggests
my code breaks everytime i cant code like that
why not?
lol what
mostly undefined
again what
i find it hard to believe you are following the guide properly
what is undefined here?
Create a custom type
import { Client, Collection, GatewayIntentBits, SlashCommandBuilder, CommandInteraction } from "discord.js";
export interface Command {
data: SlashCommandBuilder;
execute: (interaction: CommandInteraction) => Promise<void>;
}
export class CustomClient extends Client {
public commands: Collection<string, Command>;
constructor() {
super({ intents: [GatewayIntentBits.Guilds] });
this.commands = new Collection();
}
}
``` ands work
That wouldn’t propagate to structures that use Base (e.g. Message.client, Role.client, etc.)
Unless you cast it. You might be better off augmenting the module as per the second suggestion.
Imo, you should just manage it in a separate DI solution. It’s too easy to override an existing property on a class and mess up the entire lib
ah so you need to use files: [] for file builders to work, gotcha
do dropdowns not support custom emojis?
they do next to the label
just not inside the label itself
there's a separate emoji field
StringSelectMenuOptionBuilder#setEmoji() discord.js@14.19.3
Sets the emoji to display on this option
Use .setEmoji() to set a custom emoji I don't think u can set a custom emoji within the label
go to discord docs and read it which is the most simplest way of learning discordjs
hi guys, im wrong? when im reacting to one message, nothing in console
console.log(reaction.emoji.id)
})```
Do you have the proper intents?
You most likely also need the Message and Reaction partial.
was missing GatewayIntentBits.GuildMessageReactions, added but still dont work
post your client constructor
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildMessageReactions,
]
});
You most likely also need the Message and Reaction partial.
Popular Topics: Partial Structures
read more
whats that
works now, thx
another question, cant do ephemeral right?
return await reaction.message.channel.send({
content: 'Your discord account must be at least 6 months old to register.!',
flags: [MessageFlags.Ephemeral]
});```
Can't send an ephemeral, no
Those exist only as a response to an interaction
Hey yall, quick question:
Can you have a filter and lifetime options for sweepers and it will remove if the lifetime is reached or the filter matches?
Problem: I've just started using djs, but am receiving a network error whenever I try to run index.js (code below). I am using WSL Ubuntu on a windows computer. This is the same computer I use for work as a backend dev and don't experience network issues or performance issues during that.
import { Client, Events, GatewayIntentBits } from 'discord.js';
import { token } from './config.json';
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
client.on(Events.ClientReady, readyClient => {
console.log(`Logged in as ${readyClient.user.tag}!`);
});
client.on(Events.ShardError, error => {
console.error('A websocket connection encountered an error:', error);
});
console.log(token)
client.login(token).catch(console.error)
**Error Log: **
tsx index.ts in bash at 20:46:49
{EXPECTED TOKEN IS OUTPUT HERE}
ConnectTimeoutError: Connect Timeout Error (attempted address: discord.com:443, timeout: 10000ms)
at onConnectTimeout (/home/jack/src/personal/discord-community-playlist/src/node_modules/.pnpm/undici@6.21.3/node_modules/undici/lib/core/connect.js:237:24)
at Immediate._onImmediate (/home/jack/src/personal/discord-community-playlist/src/node_modules/.pnpm/undici@6.21.3/node_modules/undici/lib/core/connect.js:206:11)
at process.processImmediate (node:internal/timers:478:21) {
code: 'UND_ERR_CONNECT_TIMEOUT'
}
Steps I've taken so far:
- Ran
ping discord.comto check the connection. This was the output:
PING discord.com (162.159.138.232) 56(84) bytes of data.
64 bytes from 162.159.138.232: icmp_seq=1 ttl=57 time=4.19 ms
...
64 bytes from 162.159.138.232: icmp_seq=7 ttl=57 time=4.16 ms
^C64 bytes from 162.159.138.232: icmp_seq=8 ttl=57 time=8.90 ms
--- discord.com ping statistics ---
8 packets transmitted, 8 received, 0% packet loss, time 65155ms
rtt min/avg/max/mdev = 3.045/5.456/8.898/1.718 ms
- ran
sudo ufw statusit was offline - restarted my system
I'm unsure how to proceed
guys, why the bot remove completely the emoji button react? i want to remove only the reaction has triggered the client.on('messageReactionAdd')
if (!isSixMonthPassed) {
text.setContent('## Your discord account must be at least 6 months old to register!');
container.addTextDisplayComponents(text)
await userDM.send({
components: [container],
flags: [MessageFlags.Ephemeral, MessageFlags.IsComponentsV2]
});
return await reaction.remove()
};```
then use reaction.users.remove(user)
reaction.remove() removes all reactions to that emoji
oh ok thank, thats reactions is making me crazy
does forword message read as sent message ?
yes
its not content: '', it's empty how can i get to it's content
I believe it was messageSnapshots?
Message#messageSnapshots discord.js@14.19.3
The message snapshots associated with the message reference
Is a PrimaryEntryPoint application command supposed to trigger the interactionCreate event? If yes, does it trigger right after the command was executed or does it await the successful launch of the activity first?
Asking this because it is not triggering the event for me 🤔
You can create an application command with PrimaryEntryPoint type
https://discord.js.org/docs/packages/discord.js/14.20.0/ApplicationCommandType:Enum#PrimaryEntryPoint
e.g. this "Play" button, runs /Play after pressing
That depends on the configured handler
Oh I see
Thanks
Does anyone know why my app shows "The application did not respond" in a guild it's not a member of (user-installed), but works fine in a guild where it is a member? Nothing has changed - everything is the same. This issue suddenly started around 3 hours ago.
Does anyone know of a public API link or endpoint to get Guild Tag data from a user, such as: "Seeing when a user claims or changes their tag"?
tags are not yet documented so you will ahve to use raw api requests/events to read it - change emits guild member update per shared server
editReply but only up to 15m, if the message isn't ephemeral and the bot is in the server, it can edit the message directly with Message#edit()
could be that you have a lower node version in your server?
followUp returns the message, you can then pass that to editReply
InteractionEditReplyOptions#message discord.js@14.19.3
The response to edit
Default value: '@original'
i Create a new command but i hour i go to test the command is not showing.
did you run the deploy script?
i testing in local.
So I have a question about ratelimits, how many bans can I perform in a single guild until it hits ratelimit? Does anyone have a approximate number for me?
Ratelimits are dynamically assigned by the API based on current load and may change at any point.
- The scale from okay to API-spam is sliding and depends heavily on the action you are taking
- Rainbow roles, clock and counter channels, and DM'ing advertisements to all members are all examples of things that are not okay
i can send my index.ts to see more facillity ?
that doesn't answer the question though
I don't remember any deployment code in the documentation.
do you mean the guide?
if yes, then it is there
Creating Your Bot: Registering slash commands
read more
hmm....
In my index.ts there is a similar code
const client = new CustomClient();
client.commands = new Collection();
function getAllCommandFiles(dirPath: string, arrayOfFiles: string[] = []) {
const files = fs.readdirSync(dirPath);
for (const file of files) {
const fullPath = path.join(dirPath, file);
if (fs.statSync(fullPath).isDirectory()) {
getAllCommandFiles(fullPath, arrayOfFiles);
} else if (file.endsWith(".ts") || file.endsWith(".js")) {
arrayOfFiles.push(fullPath);
}
}
return arrayOfFiles;
}
const commandsPath = path.join(__dirname, "commands");
const commandFiles = getAllCommandFiles(commandsPath);
let sucessFiles = 0;
const errors: string[] = [];
for (const file of commandFiles) {
try {
const imported = require(file);
const command = imported.default ?? imported;
if ("data" in command && "execute" in command) {
client.commands.set(command.data.name, command);
sucessFiles++;
} else {
errors.push(`⚠️ Inválido (falta data/execute): ${file}`);
}
} catch (err: any) {
errors.push(`❌ Erro ao carregar ${file}: ${err.message}`);
}
}
// Exibe resumo dos comandos carregados
console.log(chalk.magenta.bold("[INFO]") + ` - Comandos carregados : ${sucessFiles}`)
if (errors.length > 0) {
console.log(chalk.green.bold("[ERROR]") + ` - Erro ao carregar os comandos : ${errors}`);
for (const e of errors) console.error(e);
}
const eventsPath = path.join(__dirname, "events");
const eventFiles = fs
.readdirSync(eventsPath)
.filter((file) => file.endsWith(".ts") || file.endsWith(".js"));
for (const file of eventFiles) {
const event = require(path.join(eventsPath, file));
if (event.default.once) {
client.once(event.default.name, (...args) =>
event.default.execute(...args, client)
);
} else {
client.on(event.default.name, (...args) =>
event.default.execute(...args, client)
);
}
}
```\
that doesn't do the same thing as the deploy script
it's missing the last half of it
the part that actually deploys the commands
this part you say
// Construct and prepare an instance of the REST module
const rest = new REST().setToken(token);
// and deploy your commands!
(async () => {
try {
console.log(`Started refreshing ${commands.length} application (/) commands.`);
// The put method is used to fully refresh all commands in the guild with the current set
const data = await rest.put(
Routes.applicationGuildCommands(clientId, guildId),
{ body: commands },
);
console.log(`Successfully reloaded ${data.length} application (/) commands.`);
} catch (error) {
// And of course, make sure you catch and log any errors!
console.error(error);
}
})();```
i can just write this part adaptate in main index.ts or best soluction is create a new file and run separete ?
it should be a separate file yes
i go to remove in my index.ts to best organization
you shouldn't remove this though, otherwise your commands won't reply at all
Just create a new file separate with the code
const { REST, Routes } = require('discord.js');
const { clientId, guildId, token } = require('./config.json');
const fs = require('node:fs');
const path = require('node:path');
const commands = [];
// Grab all the command folders from the commands directory you created earlier
const foldersPath = path.join(__dirname, 'commands');
const commandFolders = fs.readdirSync(foldersPath);
for (const folder of commandFolders) {
// Grab all the command files from the commands directory you created earlier
const commandsPath = path.join(foldersPath, folder);
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
// Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
if ('data' in command && 'execute' in command) {
commands.push(command.data.toJSON());
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
}
// Construct and prepare an instance of the REST module
const rest = new REST().setToken(token);
// and deploy your commands!
(async () => {
try {
console.log(`Started refreshing ${commands.length} application (/) commands.`);
// The put method is used to fully refresh all commands in the guild with the current set
const data = await rest.put(
Routes.applicationGuildCommands(clientId, guildId),
{ body: commands },
);
console.log(`Successfully reloaded ${data.length} application (/) commands.`);
} catch (error) {
// And of course, make sure you catch and log any errors!
console.error(error);
}
})();```
and run ?
well you'll need to adapt it to your own code
given you created your commands in a different way as the guide
Hello
I have question about the new enhanced roles system
is it available in discord js or not yet ?
I mean can I make roles with colors using my bot (let's say I want 150 new gradient colors)
it is not yet documented by discord
Ok
Thank you
i create a deplou command but not workin.
import { REST, Routes, SlashCommandBuilder } from "discord.js";
import config from "../config.json";
import fs from "node:fs";
import path from "node:path";
// Definindo o tipo do comando
interface Command {
data: SlashCommandBuilder;
execute: Function;
}
const commands: Command[] = [];
// Pega todos os arquivos de comandos dentro da pasta de comandos
const commandsPath = path.join(__dirname, "commands");
// Função para ler arquivos de forma recursiva
function readCommands(dir: string) {
const files = fs.readdirSync(dir);
for (const file of files) {
const fullPath = path.join(dir, file);
const stat = fs.statSync(fullPath);
if (stat.isDirectory()) {
readCommands(fullPath); // Chama recursivamente para subpastas
} else if (file.endsWith(".ts")) {
const command = require(fullPath);
if ("data" in command && "execute" in command) {
commands.push(command.data.toJSON());
} else {
console.log(
`[WARNING] Comando não possui 'data' ou 'execute': ${fullPath}`
);
}
}
}
}
readCommands(commandsPath);
// Criando instância do REST para fazer chamadas à API do Discord
const rest = new REST().setToken(config.token);
// Função de deploy
(async () => {
try {
console.log(`Iniciando o registro de ${commands.length} comandos.`);
// O método PUT é usado para atualizar todos os comandos de uma vez
const data = await rest.put(
Routes.applicationCommands(config.clientId), // Para comandos globais
{ body: commands } // Dados dos comandos
);
console.log(`Comandos registrados com sucesso: ${commands.length}`);
} catch (error) {
console.error("Erro ao registrar comandos:", error);
}
})();
and message to erro.
[WARNING] Comando não possui 'data' ou 'execute': C:\dev\AusTV\Ticket-Bot\src\commands\hello\hello.ts
Iniciando o registro de 0 comandos.
Comandos registrados com sucesso: 0
did i miss a change
import {
ActionRowBuilder,
ButtonBuilder,
ButtonStyle,
EmbedBuilder,
type Message,
} from "discord.js";
yeah I'm seeing this for
PermissionFlagsBits
RESTPostAPIChatInputApplicationCommandsJSONBody
Routes
ButtonStyle
Per your own error message, the file is missing either data or execute
but have data and execute i can show you.
import { SlashCommandBuilder, CommandInteraction } from 'discord.js';
export default {
data: new SlashCommandBuilder()
.setName('hello')
.setDescription('Saúda o usuário'),
async execute(interaction: CommandInteraction) {
await interaction.reply(`👋 Olá, ${interaction.user.username}!`);
},
};```
What could be the cause that my bot randomly went offline but showed no errors at all. Yes no hoster issues or anything
I'd put a log after you require the file then. Because that doesn't match the message
nvm this seems to be an issue on my editor
Como você diz?
pode me enviar um exemplo
console.log(command)
return this message
{
default: {
data: SlashCommandBuilder {
options: [],
name: 'hello',
name_localizations: undefined,
description: 'Saúda o usuário',
description_localizations: undefined,
contexts: undefined,
default_permission: undefined,
default_member_permissions: undefined,
dm_permission: undefined,
integration_types: undefined,
nsfw: undefined
},
execute: [Function: execute]
}
}
[WARNING] Comando não possui 'data' ou 'execute': C:\dev\AusTV\Ticket-Bot\src\commands\hello\hello.ts```
ID works too
Since you're exporting default you need to do require(fullPath).default to get the object you want. If you don't want to do that, use module.exports

yes