#djs-help-v14
78874 messages · Page 71 of 79
give your bot an admin and try again
if it works, then something is up somewhere, but completely on discord's side
if it doesn't.. well, exactly the same but slightly worse
I’m just trying to prevent errors ig, missing permission errors I feel can be easily checked for and prevented. I don’t think I’m missing any permissions as I remember having a chat about it here a while back
there are sometimes cases of state mismatch on discord's side, that's possible too albeit quite rare
okay, but
I can also update djs too. And yes I’m aware you can’t prevent all errors
it's not even about that, really
few people here looked, none can see from what you provided why would that be the case for sending a message
I did fetch the channel too
Ok, I can see if I’m missing anything else but I basically gave everything tbh
wdym
As in I gave all relevant pieces of code so I can’t see anything else. But I can check again when we reboot later
give the bot admin and try again
Hello, I'm at a loss, apparently my way of handling pings stopped working for some people using the desktop version of Discord. While investigating why my regex wasn't working, I wasn't seeing anything wrong, and I came across something interesting. I tried logging the bytes array, and sure enough, there were intruders.
The correct one was this :
3c403533373939363132303437313736353031383e
@spring cypress
And the incorrect one is this :
e281a83c403533373939363132303437313736353031383ee281a9
@spring cypress
Did someone notice any change in how discord sees pings?
- no there hasn't been any recent change in how discord formats/parses mentions
- given that you appear to be asking about your own custom regex, and I'm unsure at what point you'd receive message content as hex from discord.js, I'd guess this isn't related to discord.js
- if you are using discord.js (or frankly even if you're not), you may want to look into
MessageMentions.UsersPattern
Hmmm ok, thank you, I mean it's still weird because it started happening to several people recently but ok 
My regex is just ^<@!?\d+>$ so it should work (I think?), and apparently it's more or less the same that's used in the UsersPattern ? I didn't know about this though, thanks.
And I am using discord.js, I just tried to do new Buffer(message.content).toString("hex") just to see if there were additional characters that aren't displayed correctly, because I couldn't see what else could be different
SlashCommandBuilder discord.js@14.25.1
A builder that creates API-compatible JSON data for slash commands.
@mint eagle please use #app-commands for personal use of the bot
honestly that regex should work, yeah
even testing it against your incorrect string above also successfully matches only the mention (dropping the extraneous characters), so the problem likely lies elsewhere
I totally agree with you, and here I only noticed it because I wanted to match only a mention without any additional characters
Which is why I asked about if there was an update or something
Funnily enough, when the person for whom it didn't work tried on their phone, it worked 
Here, blue corresponds to the browser version (on my phone) and green to the mobile version

Can you detect an activity start with interactionCreate or some kind of similar event?
without action rows, how are you supposed to put multiple inputs in the same row in a modal now?
You still use action rows... I dont understand the question
Okay, I'm struggling a bit with what method to use on a ModalBuilder to insert a row
Not that Im aware of but I havent worked with that much
Like a row of buttons?
I was aiming to have two adjacent tiny text inputs
Sorry, Im mixing it up with containers
Adjacent text inputs arent a thing
no that would be presence update event
i can't fix this without downgrading to discordjs v13 should i even care about these "vulnerabilities"
no
Got'cha, thanks
Guys whats the best free or cheap Website to host bit 24/7
Ty
I will sleep soon, but do you think I should ask about this issue on another server? (discord devs?) or anywhere else? I don't really know where this could come from.
I guess a good way for me to check would be to open my client's devtools and see if the pings there also have impostor characters or not, but I don't have my pc until Monday 
Are you trying to ping the person in that bot response?
I'm just trying to grab the mention, but because it was failing my check for no apparent reason, I looked into it, and it appears that it's because of some random added characters..?
And those added characters are only there for people on pc or browser, not on mobile (I think)
Like, instead of getting <@....>, I get 0xe281a8<@....>0xe281a9
As in the person sending the mention?
As in it appears that something is added when someone pings someone else and the bot reads the message 
(so it fails when I try to match it with a regex and I'm sad)
I mean, an "easy" fix would be to add those characters to my regex as optional, but that doesn't sound like a very good idea if it's a bug or something already
I've heard discord has broken something with mentions adding some kind of invisible characters to the front of the message
Unsure if that's the case here or not but that's surely the message from Poketwo devs however that's the first time I've seen anyone mention it so I doubt it's exactly the case but keep aware
Yeah exactly this I believe, I'm hoping that discord will fix it?
Given how no one else is saying anything, I'm gonna say that's not true
Can you do me a favour and forward the messages here? Or just ping me since apparently that happens too
Potentially a new bug & not a ton of people use discord mentions
Also this seems like a mobile version bug only & not PC. This is confirmed to be fixed in discord canary
So I expect this to be rolled out to all versions soon or later too
Sure, here's a ping from my phone : @golden laurel
And from my browser : @golden laurel
is there a type that is compatible with Message#toJSON? APIMessage doesn't seem to fit that bill since it uses pascal_casing, while toJSON is outputting camelCasing
No
how would i remove a cooldown if the command ran unsuccessfully?
Cooldowns are custom implementation, so I'm not sure how to answer that
Simply... dont set it
Interesting, I see it in your mobile message! I CNR on stable, PTB, and canary on desktop, but I can reproduce on mobile alpha. This is unfortunate lol. But regardless, it shouldn't break how one uses a regular expression for mentions as the mention is still there fine. Would suggest you investigate into it
Would only break if you're using start/end qualifiers or something
Testing that a message is ONLY a mention
It breaks because I use regexs for the entire message, so if I'm expecting a mention at a specific place and there's something more, it rejects it.
But if it's fixed in the latest versions, then maybe it's temporary 
Canary isn't a mobile version
So you're saying twice that it doesn't happen on desktop but on mobile, and Jira confirms they can do that only on mobile too
The thing is :
The person who initially reported this to me said it didn't work on desktop, and it works on mobile
When I try it, it worked on my phone and not in my phone's browser
Someone else tried on their phone and it didn't work
So I don't know what to believe anymore 
But as long as it's fixed sooner or later, it's fine..?
And I can tell my users to use the ID instead of the mention in the meantime (since it works as well)
Of course, it would be best if it was possible to fix it or if the change was consistent
Browser has different versions too but at the end of the day.. it's not mobile app
Desktop app is just browser (that's what electron is, basically)
Anyway, it's a mobile thing
Hello little question is there a way to make a protection against self bots like the bot can recognize a self bot?
a self bot is just a program that listens for incoming messages with a specific pattern on a user account and responds with a rest call to the discord api
i'm not sure how you expect to discern those?
if you can find some good heuristics on it, sure, but it's not a native thing
or do you mean user-installed slash commands? (since that confusion happens quite often)
TypeError: guild.members.editMe is not a function
Are you joking me 😭
js await guild.members.editMe({ avatar: imageUrl || null, });
this was working few days ago now it's not
😭
have discord already updated it?
probably not using the right version of discord.js
mhmm maybe- lemma check rq
is there an event that fires when a user changes their guild tag?
was a mismatch
it's userUpdate
```js
const oldPrimaryGuild = oldUser.primaryGuild;
const newPrimaryGuild = newUser.primaryGuild;
if (oldPrimaryGuild?.identityEnabled === newPrimaryGuild?.identityEnabled &&
oldPrimaryGuild?.identityGuildId === newPrimaryGuild?.identityGuildId) {
return;
}
I’m talking about the commands that a bot could not do like making a raimbow role that changes color every second or banal kind of behaviors that an account could not do basic
recognizing implausible behaviour isn't trivial. that being said "changing role color every second" was typically done through bots, not automated user accounts
this might be more of a node question then a djs question but, is there some sort of tick/loop I can hook into? I essentially want to be semi frequently do xyz
for example, every 5 minutes or so update the bots status based on certain stuff
You could just use a setInterval, no?
how to track boosters using messageCreate
Check the message.type
I mean yes, but I was just wondering if there was a more official thing to hook into.
thanku
There's setInterval or using a cron job, which is a bit more robust. Either way, please use #1081585952654360687 if you have any questions on either, as it's a node question
no worries, thanks
Ok thank you for your answer and discord js does he do the components V2 of discord?
discordjs can send & build components v2 messages!
Thank
Hey, is there a utility method to get all the guilds a member is in AND where the client is part of?
Iterate through the client guilds
Yea that was plan B haha, but before I did that I was curious if there isn't already a build-in method for that
Thats pretty much the easiest way and isn’t something difficult
True
is this from your oauth connection? or normal bot querying?
normal bot querying
cool cool, isnt the "where the client is part of" inherent then, as you cant casually see other servers data
also if your bot is in big servers that may be fun because surely you dont want to cache everything
(and assuming you even have guild members intent to get more knowledge about them)
The idea was just 'How can I get all the guilds where a user and my client are mutually part of'. Sure I can iterate over the client guilds, but I was wondering if there is not a utility method for that.
ya, i wish discord themself gave us the api that normal users can use (there is a request on the github)
is there a builder for polls?
There is but it seem to be only available in the dev version of the builders
Is there any new information on this?
not really. pretty sure it's not something that d.js is vulnerable to either given what it is
if anything, i'd rather disable npm audit instead
okay thanks for the info.
when i restart my bot then and try delete messagges it doesnt log it ?
guide suggestion for @neat nimbus:
Partials
One example leveraging partials is the handling of reactions on uncached messages, which is explained on this page. Prior you had to either handle the undocumented raw event or fetch the respective messages on startup. The first approach was prone to errors and unexpected internal behavior. The second was not fully fail-proof either, as the messages could still be uncached if cache size was exceeded in busy channels.
```js
super({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.GuildVoiceStates,
],
partials: [
Partials.Message,
Partials.Channel,
Partials.Reaction
]
});
[ERROR]: Could not fetch partial message: DiscordAPIError[10008]: Unknown Message
[ERROR]: Could not fetch partial message: DiscordAPIError[10008]: Unknown Message ?
You cannot fetch an already deleted message
On bot startup old messages are out of cache so partial
?
```js
module.exports = async function (bot, con, cfg, m) {
if (!m.author || m.author.bot) return;
con.query(SELECT * FROM data WHERE id = ?, [m.guild.id], async function (e, row) {
m.guild.fetchAuditLogs({ limit: 1, type: 72 }).then(function (Logs) {
if (!row[0]) return;
SendAudit(m, 'messageDelete', new bot.djs.EmbedBuilder()
.setColor(row[0].color)
.setAuthor({ name: "Message Deleted", iconURL: bot.user.displayAvatarURL() })
.addFields([
{ name: "Author:", value: ${m.author.tag} (${m.author.id}) },
{ name: "Channel:", value: <#${m.channel.id}> },
{ name: "Deleted By:", value: Logs.entries.first().executor.tag },
{ name: "Content:", value: m.content ? m.content.substring(0, 1024) : "No content" }
])
.setTimestamp()
);
});
});
}
super({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.GuildVoiceStates
],
partials: [Partials.Message, Partials.Channel, Partials.Reaction]
});
I want to delete the message & give timeout the executed user and this bot is not inside the server but it spamming and this feature i wanted to implement in my bot
to secure my server
Looks like external app? Disable external app permissions
I know but i want it to stop with the help of my bot
.setDMPermission(false), this is removed right? what I should use now?
documentation suggestion for @radiant tulip:
SlashCommandBuilder#setContexts() discord.js@14.25.1
Sets the contexts of this command.
InteractionContextType#Guild discord.js@14.25.1
Interaction can be used within servers
I dont think you can stop external apps other than disabling the permissions for it
When my bot restarts, the messages are still in Discord, but the bot doesn’t pick them up or send the logs as not a delete message just yet?
The easiest solution is adding an AutoMod rule to block messages that contain @everyone
I am not sure on what the message object looks like on a user installed app
as i also mentioned in #1467545580732678308 message, there should be interactionMetadata on who caused the interaction to being with!
any idea?
As i already said theyre gone from the memory on startup. So unless youre not saving them anywhere you have to fetch them before they get deleted
what i mean is the message still in discord server and the bot restart but when i delete that message doesnt work
Doesnt mean its in discord thats it also in your bot
thats stupid
There isnt unlimited memory to save every single message there is
discord emits MESSAGE_DELETE with message id and channel id only
we can only emit it on discord.js with the message payload if we had that message cached before
you cannot fetch it, if the data is not cached, because it was deleted off discord's service
just stupid if i delete a message on discord it should still log
you don't listen
ik what your saying but still stupid
you don't
else you wouldn't be calling it stupid
where are we supposed to get data that's been deleted?
I have not got a clue just other bots i did for logs have never did thisa
there is literally no way to do this
you are misinterpreting what other bots do then
guess i just have to stay how it us
they generally have a huge message cache in things like redis, but that gets decently expensive
esp as there has to be some age cut of point where they may just give up and not store it anymore
I understand how it works technically now, I’m not disputing that. I just mean from a user perspective it feels frustrating like if the bot restarts for an update and someone deletes a message from a couple of hours ago, it doesn’t get logged. I get why that happens, I just think it’s annoying behaviour, that’s all.
Then implement a more persistent cache like Redis so that your cache is saved between restarts of the core application
true but dont want to make everyone setup a redis server just todo that
Then don't make everyone self-host your bot
fair
this only for messsage logs right?
I mean there's other things that the bot loses on startup. Like thread channels and guild members... There's a lot that can be lost on restart
Just depends on your application and what you want stored after restart
I have all role channel and message events and voice events to
sometimes i wish more people used @discordjs/core to realise how much cache powers all and have to implement stuff themself, but i know they will generally implement cache worse than djs does normally
Roles and channels (except threads/forum posts) are safe from restarting. Those are all sent to your app on startup (if you have the Guilds intent, which you should)
super({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.GuildVoiceStates
],
partials: [Partials.Message, Partials.Channel, Partials.Reaction]
});
```my intents
Forms i dont see a point
Then yes. At first glance of your event listeners, only message update/delete and guild member remove are going to possibly be partial
i ask them on poll of what they want
okay
you can try to manually fetch last 100 messages from each channel on startup fwiw
i think that should populate cache (i forgot ratelimits on it tho)
For 100 messages, it's not bad. But could still take a while depending on the number of guilds and channels
i was trying to go off whatever the max for one request was haha
lol this is the case of a thing id only do if its a one server bot (assuming based on the act of neeing to worry about self hosters)
Hi everyone! I have a question about the behavior of ActivityType.Streaming. I've noticed that the "Streaming" state (the purple dot/UI) is only triggered when providing a Twitch URL. If I use a YouTube or Kick URL, the default state is standard, or the "Watch" button isn't displayed. Is this a whitelist/strict limitation of Discord's own API, or is there a specific way for other platforms to trigger the streaming state in v14?
The former. Bots really shouldn't be streaming at all
yo, how do i mention a command?
ty
Can I still ask for help if I used Typescript? Not just JavaScript?
yes
Guys, i have a problem sending container:
DiscordAPIError[50035]: Invalid Form Body
data.components[0][MODEL_TYPE_CONVERT]: Expected an object/dictionary.
can you show your code please?
youre passing an array into an array into the components property of the reply options
either remove the array block around const container = [] into const container = new ContainerBuilder() or just pass container by itself into components, not [ container ]
Thank you very much, it worked
is discord.js@15 planned? does it make sense rn to upgrade my whole bot from 13 to 14 or should i wait for 15? i dont really have the time to do it twice
13 to 14, 15 probably won't be out for a long time
why do you think so? its been out 2022 (v13 was only there for like a year)
v14 still receives updates
and is still actively maintained
v15 will release when there is a need for it
And Discord API doesn't have any breaking changes that would prevent you from using new features
v13 did till the end too
v13 is no longer supported
since there is v14 now.. but it got updates till v14 launched so thats not really a mark for how long a version will stay
v15 is planned, at some point. it will release when there is a need for it
right now you can stick with using v14
there's no estimated time on when a new major release will happen
as stated in my initial message, im still running v13 and considering upgrading since i will finally have some time to spend on the bot. now what im asking is, is it worth upgrading now or in the next months, if theres already a v15.0.0 on github, so its already under development
yes its worth updating
again, v15 will release when there is a need for it
okay, so you dont know of any announcements of a discord v11 api or similar things.. gotcha
api v11 doesn't exist yet
thats what im saying
Besides going v13 to v15 would probably require you to sidetrack v14 as well
we're not discord so we don't know
im gonna rewrite the whole project anyway since the code i wrote back then is only hardly maintainable, so it would not really be a problem
iirc 13 has some unfixed bugs anyways
v13 was supported and updated for a while after v14s launch
Its not an immediate cutover
all that happens is the shards get ready then console.log(command?.name); is executed, logs is just heartbeat
yeah heartbeat logs are normal
status is never set, just set to the one that's in the constructor
basically nothing is happening besides heartbeat
you're probably ratelimited
wouldn't it say that i'm ratelimited?
const client = require("../index.js");
is it possible you have some circular import resulting in this code not executing?
it's executed because it is logging the commands
not sure if that logs on debug, but you shouldn't do what you're doing with commands anyways
setting already deletes missing commands, it's unnecessary to delete all of them individually beforehand
if you remove a command it will just stay
not if you use set...
which they do
alright, still confusing why nothing is happening
10 seconds is too frequent for a presence update
That method is always kinda unreliable
true but not like the presence info really needs to be up to date
could lower the interval
as in, make it longer?
yes mb
here is all that happens, it was just functional an hour or so ago, no ratelimit in the logs 🤷♂️
are you also listening to client.rest('rateLimited')?
just added, nothing in logs still
I say just place some logs and see if it reaches that line
await applicationCommands.set(commandsArray).catch(console.error);
stops here
yeah you're ratelimited then, that makes sense
interesting
You shouldn't be modifying your application commands on startup
how long is the ratelimit? never happened to me before
24 hours
could move it to a command, ty, was just a preference
shouldn't it at least error that i'm ratelimited?
Ya. The guide recommends having the deploy-commands.js (or any related scripts) be run only with human input as the data is rarely modified and the rate limit is so strict
the rate limit is so strict
weird how i've never gotten it, been using this for years
200 updates (add, remove, edit) ever 24 hours
By default discord.js just waits for rate limits, unless you set rejectOnRateLimit
alright thank you for the help everyone 👍
Hello, I am facing the following problem: I have a system that creates many rooms on Discord, but what happens is that it works perfectly during the day, but at a certain point it simply starts to “freeze” and creates rooms very slowly, but that's all. Can you tell me what might be causing this? It just happens, and I don't know anything about it. I've seen other servers with many more rooms being created simultaneously, and they don't have this problem.
you’ll want to contact discord at https://support.discord.com
unfortunately we’re not discord so there’s nothing we can do here to help. sorry
tks
I assumed he was talking about his discordjs bot that creates rooms
is there a way to change the background color of code blocks?
As in the color of the text?
This is the one that shows up when I try to post a message,
However this is what the background of the code block looks like in a different message I found (from a different bot)
This isn't Discord.js related
However it could be `` vs using a codeblock
ah, rip, inline block
doesnt seem to add the copy button unfortunately
Yes it only adds it on mobile, if you provide more context of these images maybe we can help, but in #archive-offtopic or #1081585952654360687 ig
Is there an updated documentation page on intergrating a music bot/commands?
Life Cycles
Two of the main components that you'll interact with when using @discordjs/voice are: - VoiceConnection – maintains a network connection to a Discord voice server - AudioPlayer – plays audio resources across a voice connection Both voice connections and audio players are stateful, and you can subscribe to changes in their state as they progress through their respective life cycles. Their individual life cycles with descriptions of their states are documented on their respective pages.
any reason why users wouldnt be able to see commands after I set setDefaultMemberPermissions, but they have the permission I set? the bot is in two servers, in one server users with the permission can use it fine, but in the second server they also have the permission but they cant see the command
How do you create a message like an embed and have a button in it?
Display Components
While you might be familiar with embeds in Discord, there are more ways to style and format your apps messages using display components, a comprehensive set of layout and content elements. To use the display components, you need to pass the IsComponentsV2 message flag (in docs: MessageFlags) when sending a message. You only need to use this flag when sending a message using the display components system, not when deferring interaction responses.
Containers
Components
can u do mobile status on bots with djs v14?
No
Hello, everyone!
I'm having a problem with my application: I have an embed (components V2) with buttons attached to manage various functions of my tickets (claim, unclaim, put on hold, close, etc.). The small problem is that after performing two actions (on the same button or on two different buttons), none of the buttons work anymore. Discord displays “Interaction failed” or simply nothing happens. Could you help me?
(it's not an embed, it's a container)
And we need way more info than that
Does your code error out and exit?
Yes, sorry, it's not an embed but a V2 component.
I don't have any output in the logs, but I can provide my code that handles interactions.
Well, does the code run
If it responds twice but no more, it means it either crashes or is coded to stop responding one way or another
The most intriguing thing is that I received a response to my third interaction just before turning off my bot, about five minutes after clicking a button
Out of curiosity, are you running your bot in cmd or PowerShell?
For development, yes, after the bot runs on a computer running Debian.
Is the issue occuring in cmd or PowerShell
Are you editing channel names when you perform those actions?
cmd
Yes, for example, when a ticket is claimed, the emoji in the chat room name changes
Then that's the issue
Channel name and topic changes are limited to roughly 2 times per 10 minutes.
If your channel changes are not going through, this might be why.
I'll try to change that and add a two-minute cooldown. Thank you both very much 🙏
It's 2 times per 10min
ten-minute cooldown so
5 min would also work
1 per 5 minutes?
Yeah
Guys my string select in my modal isn't sending. Any idea why? If required is false then it somehow works.
The label builder in question when required:
LabelBuilder {
data: {
component: StringSelectMenuBuilder {
data: {
type: 3,
custom_id: "1467823749339287553",
min_values: 0,
max_values: 1,
required: true,
},
options: [
StringSelectMenuOptionBuilder {
data: {
label: "Option 1",
value: "value-1",
description: undefined,
emoji: undefined,
},
}
],
},
type: 18,
label: "New Select Menu",
},
}
is it because of the min_values: 0 ? Because when it's required it has to be at least 1?
Maybe, you dont have to specify the min value in your code snippet
Yea, required and minValues: 0 doesn’t make sense
the docs didn't state that - I made a PR in the discord docs repo
required shouldn’t be part of select menus tbh
modal
In hindsight, it’d make sense if you chose a higher min values. For example, required: false min_values: 3 would mean no selection is allowed or you must select at least 3 items
yeah, but I'm talking about when it's required.
I just noticed this because users can configure their own modals with my bot and I had set 0 as the default for min values.
why can't my bot use component v2?
you didn't pass the flags probably
you gotta pass flags: MessageFlags.IsComponentsV2 and if ephemeral then flags: MessageFlags.IsComponentsV2 | MessageFlags.Ephemeral
Any one can help me
How to add select menus to a modal?
I cant find the dosc for this
Something a bit clearer. https://discordjs.guide/legacy/interactions/modals
Is there a way to write this using the module type in my nodejs app?
```javascript
const filePath = path.join(commandsPath, file);
const command = require(filePath);
documentation suggestion for @modern shell:
import()
The import() syntax, commonly called dynamic import, is a function-like expression that allows loading an ECMAScript module asynchronously and dynamically into a potentially non-module environment.
Use this ^, otherwise this is not d.js related, so might be best to use #1081585952654360687 in the future
Can any one write my a small code with a command Thats shows modal with stringselect function inside ?
I tryied but it says the .setlebel is not a function
And the same for .setlabel
check the docs. if thats still confusing try https://modal-builders.antouto.workers.dev/
guide suggestion for @flint lava:
Modals
Modals are pop-up forms that allow you to prompt users for additional input. This form-like interaction response blocks the user from interacting with Discord until the modal is submitted or dismissed. In this section, we will cover how to create, show, and receive modals using discord.js! This page is a follow-up to the interactions (slash commands) page. Reading that page first will help you understand the concepts introduced in this page.
I need stringselect
Not a textinput
please check the guide
Im new
please check the guide
Idk i dont understand im new to the disord.js libeay sory
the guide is very helpful for what you want to do
This
if language is an issue, translate the page to your native language
i understand that you’re new, but the guide is very helpful to what you want to do
Thanks
Hi 👋
For some reason i can't seem to run the Chat Input command twice, only once.
Code Snippets & Logs: https://pastebin.com/MpsBS4QB
Uh, i completely forgot to include the code snippet in the pastebin 🤦♂️
- If the code is required, ill send an additional pastebin.
Can you show your interactionCreate listener?
Do you maybe have client.once instead of client.on for your interaction create?
My thought too
How can I check if server hit ratelimit of adding emojis ?
you can't get your current ratelimits
you'll know if you've hit it once you try to do it
I mean when i am adding an emoji and the server is ratelimited i dont get any error
by default the request will be queued, if you want it to reject (throw an error if awaited) then you can specify it through your client options
ClientOptions#rest discord.js@14.25.1
Options for the REST manager
RESTOptions#rejectOnRateLimit discord.js@14.25.1
Determines how rate limiting and pre-emptive throttling should be handled. When an array of strings, each element is treated as a prefix for the request route (e.g. /channels to match any route starting with /channels such as /channels/:id/messages) for which to throw RateLimitErrors. All other request routes will be queued normally
Default value: null
can i make the menu option disabled? similer to button
StringSelectMenuBuilder#setDisabled() builders@1.13.0
Sets whether this select menu is disabled.
though you can only disable the whole select menu, not just one option
why does debug event doesn't log when i hit the limit ?
¯_(ツ)_/¯
you can listen through client.rest.on('rateLimited' though
still not working when i hit the limit
how are you sure you're hitting it?
Can you suppress notifications on componentsv2 messages? The SuppressNotifications flag doesn't seem to work.
tag suggestion for @tidal rune:
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"] } }
Does anyone have an idea how I can use the bitfield as flags?
// Sammle Permission-Overwrites const permissionOverwrites = [ { id: member.id, allow: [ PermissionsBitField.Flags.Connect, PermissionsBitField.Flags.Speak, PermissionsBitField.Flags.ManageChannels, 1n << 48n // SetVoiceChannelStatus (Bit 48) - direkt als numerisches Bitfield ], },
so if I want to do this, I can do this to prevent all mentions?
thank you!
Wait for it to be documented by Discord and added to discord-api/types
Feel free to define your own constant in the mean time
This flag just prevents the notification being sent. The mention still adds the red circle to the channel
Ah ok, so allowed mentions is what actually makes it not ping
Thank
because when i try to add any emoji manually I get error
and how do you know that's due to a ratelimit?
because this only happens after adding many emojis then then the bot stop adding anymore without any errors, and i try also and get error
getting actual ratelimit data would be more useful though, can you show how you added the rejectOnRateLimit option?
how can I check the time left? pretty sure it has been exactly 24h
at triggerClientReady (R:\xt\R:\xt\b\node_modules\discord.js\src\client\websocket\WebSocketManager.js:389:15)
at checkShardsReady (R:\xt\R:\xt\b\node_modules\discord.js\src\client\websocket\WebSocketManager.js:368:10)
at <anonymous> (R:\xt\R:\xt\b\node_modules\discord.js\src\client\websocket\WebSocketManager.js:198:16)
at emit (node:events:92:22)
at checkReady (R:\xt\R:\xt\b\node_modules\discord.js\src\client\websocket\WebSocketShard.js:184:12)
at gotGuild (R:\xt\R:\xt\b\node_modules\discord.js\src\client\websocket\WebSocketShard.js:158:10)
at <anonymous> (R:\xt\R:\xt\b\node_modules\discord.js\src\client\websocket\WebSocketManager.js:238:15)
at emit (R:\xt\R:\xt\b\node_modules\@vladfrangu\async_event_emitter\dist\index.cjs:2504:31)
at emit (R:\xt\R:\xt\b\node_modules\@vladfrangu\async_event_emitter\dist\index.cjs:2504:31)
how to fix
the warning tells you, change the name of the ready event to clientReady
thx
If you ping a role, do you need any permissions for that like mention everyone? (I’d imagine that’s only for mentioning the everyone role?)
anyone know how i can check the time ratelimit ends? for command updates
it has been 24h and still ratelimited ig
the rateLimited event emits with the ratelimit data
doesn't for me 🤷♂️
it emits but with no data, or...?
doesn't emit
can you show your listener?
no, the role just needs to be mentionable
if it isn't mentionable, you can still mention it if you have the mention everyone permission
since as its description says, "mention @everyone, @here and all roles"
const client = require("../index");
const { Events } = Discord;
client.on(Events.RateLimit, async (rateLimitData) => {
console.log("test");
});
"test" is never printed
it's client.rest.on
hm
there's also no Events.RateLimit
weird i've seen that used before
anyone can make an object with a property
maybe you saw RESTEvents.RateLimited
ofc
also weird that it doesn't error with client.on(undefined) lol
probably because node's doesn't either but I'd say that should throw, what would be the use case
still nothing
const client = require("../index");
client.rest.on("rateLimited", async (rateLimitData) => {
console.log("ratelimit", {
timeout: rateLimitData.timeout
});
});
are you sure that line is executing? exporting and requiring your client is known to cause issues with circular dependencies
are you sure that line is executing
all the others are executed such as the debug event
no reason for it not to execute
and you're triggering the ratelimit?
I mean you guys are saying it's a ratelimit, but yes it's hitting it
is this the same one from yesterday with the setting commands rate limit? Are you using the client's rest instance to do that?
yes same one
Are you using the client's rest instance to do that?
I don't get this, do you mean the variable "client"?
I mean whether you're trying to deploy the commands
yes that's being hit then it pauses
Our guide uses a separately declared REST constructor/instance to deploy commands
It doesnt use client/client.rest so yeah
yeah I don't use that
You could turn on rejectOnRateLimit and catch that error to make sure its still limited
Not sure why it wouldnt emit here though
one second
RateLimitError[/applications/:id/commands]
at onRateLimit (/home/container/node_modules/@discordjs/rest/dist/index.js:304:11)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async SequentialHandler.runRequest (/home/container/node_modules/@discordjs/rest/dist/index.js:1101:7)
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 ApplicationCommandManager.set (/home/container/node_modules/discord.js/src/managers/ApplicationCommandManager.js:171:18)
at async Client.<anonymous> (/home/container/events/ready.js:46:5) {
timeToReset: 30100,
limit: 2,
method: 'PUT',
hash: 'Global(PUT:/applications/:id/commands)',
url: 'https://discord.com/api/v10/applications/1001391997719949383/commands',
route: '/applications/:id/commands',
majorParameter: 'global',
global: false,
retryAfter: 30050,
sublimitTimeout: 30050,
scope: 'shared'
}
and it has been way more than 24h 🤔
That also says the limit is 2... not 200
Is there a new 2/30s limit? That's what this looks like
Have you spammed it so hard that you've been given stricter dynamic limits? idk
restarted the bot only like four times yesterday while applying changes
i've restarted it way more in the past
Probably going to have to go to ddevs with this one
ya
Any one have a tutorial for discord.js but not the official site
hey, i'm trying to write a bot using Typescript. i've got a bit of a weird setup, so i'll paste in my main.ts here: ```ts
// @ts-ignore
import {Bot} from "../../auth/modbot.ts";
// "Bot" has all my authentication information
import {Client} from "discord.js";
const client = new Client({intents: [/* here's where the problem starts... */]})
```i can't seem to import GatewayIntentBits from discord.js, WebStorm doesn't recognize it as an export. any ideas, or a full list of intents i could browse to manually add them as strings?
can you import from discord-api-types/v10?
What is wrong with the official site? It's probably the best one out there
i'll give that a shot
Ye i know but i need another one
is there a way to install the package without signing into github?
Nah
update: i'm getting npm error code 128. i did make this project before updating my version of npm, but deleting package-lock.json didn't fix it
discord-api-types should already be installed with discord.js
TS2035, doesn't show GatewayIntentBits there either with
import { GatewayIntentBits } from "discord-api-types/v10";
i have no idea then
somehow your setup is broken or idk
this is the raw values tho: https://discord-api-types.dev/api/discord-api-types-v10/enum/GatewayIntentBits
thanks for the enum, found an additional workaround in manually creating an IntentsBitField and invoking .add to add intents (i hope)
Any one can help me build a modal with a stringselectmenubuilder i cant understand the guide
Ye wait
Webstorm? If so, no solution. It's not going to like re-exports. Use another IDE or something
ya thats what they said #djs-help-v14 message
No we dont recommend ones other than our official one
Which part of the guide are you struggling with?
Yeah, is there something about this page you're not understanding? Happy to help
alright, new issue -- bot cannot send me a message (presumably because we don't share a server). is there a way to make it so it can send me DMs without adding it to a server? i'm planning on doing the latter anyways, but the former could help with what i plan to do with it (yet another automod bot)
It can respond to user interactions but otherwise no
I doubt there is, but i wouldnt recommend it whatsoever
Yes becouse if i make the string option and if im trying to run the bot its saying the .setvalue is not a function
Could you share the related code snippet?
I cant rn
Nobody can really help you then unfortunately
I would send tmrw
The only thing i can assume from what you've shared is that you literally have .setvalue() instead of .setValue()
Oh maybe
Ok… thanks
any one can help me with this ? i have require("doenv").config()and its givieng me this error
dotenv
You don't need dotenv in newer versions of node
so i have to do npm i dotenv@latest?
I don’t believe you saved the file, the white thing at the right of the filename
You don't need means you don't need to install it, or use it
No you can specify a .env file on newer node versions
how
I mean first you should save the file
i saved the file
But it’s node --env-file=.env index.js or whatever
?
index.js can also be like .
what do i have to do ?
node --env-file=.env deploy-commands.js
the same error
its giving me this
[dotenv@17.2.3] injecting env (0) from .env -- tip: 👥 sync secrets across teammates & machines: https://dotenvx.com/ops Started refreshing 1 application (/) commands. DiscordAPIError[50035]: Invalid Form Body application_id[NUMBER_TYPE_COERCE]: Value "undefined" is not snowflake. guild_id[NUMBER_TYPE_COERCE]: Value "undefined" is not snowflake. at handleErrors (C:\Users\ros99\Documents\first bot\node_modules\@discordjs\rest\dist\index.js:762:13) at process.processTicksAndRejections (node:internal/process/task_queues:103:5) at async SequentialHandler.runRequest (C:\Users\ros99\Documents\first bot\node_modules\@discordjs\rest\dist\index.js:1163:23) at async SequentialHandler.queueRequest (C:\Users\ros99\Documents\first bot\node_modules\@discordjs\rest\dist\index.js:994:14) at async _REST.request (C:\Users\ros99\Documents\first bot\node_modules\@discordjs\rest\dist\index.js:1307:22) at async C:\Users\ros99\Documents\first bot\deploy-commands.js:36:16 { requestBody: { files: undefined, json: [ [Object] ] }, rawError: { message: 'Invalid Form Body', code: 50035, errors: { application_id: [Object], guild_id: [Object] } }, code: 50035, status: 400, method: 'PUT', url: 'https://discord.com/api/v10/applications/undefined/guilds/undefined/commands'
Remove the dotenv line and make sure your files are saved
like i should remove the require('dotenv').config()?
^ yes
Also make sure it’s exactly application_id=1234 in your file, 1234 should be your app id
ok
application_id[NUMBER_TYPE_COERCE]: Value "undefined" is not snowflake.
at handleErrors (C:\Users\ros99\Documents\first bot\node_modules\@discordjs\rest\dist\index.js:762:13)
at process.processTicksAndRejections (node:internal/process/task_queues:103:5)
at async SequentialHandler.runRequest (C:\Users\ros99\Documents\first bot\node_modules\@discordjs\rest\dist\index.js:1163:23)
at async SequentialHandler.queueRequest (C:\Users\ros99\Documents\first bot\node_modules\@discordjs\rest\dist\index.js:994:14)
at async _REST.request (C:\Users\ros99\Documents\first bot\node_modules\@discordjs\rest\dist\index.js:1307:22)
at async C:\Users\ros99\Documents\first bot\deploy-commands.js:36:16 {
requestBody: { files: undefined, json: [ [Object] ] },
rawError: {
message: 'Invalid Form Body',
code: 50035,
code: 50035,
status: 400,
method: 'PUT',
url: 'https://discord.com/api/v10/applications/undefined/guilds/1467881360843608268/commands'
}
PS C:\Users\ros99\Documents\first bot> ^C
PS C:\Users\ros99\Documents\first bot>
PS C:\Users\ros99\Documents\first bot> node --env-file=.env deploy-commands.js
[dotenv@17.2.3] injecting env (0) from .env -- tip: 🔐 encrypt with Dotenvx: https://dotenvx.com
Started refreshing 1 application (/) commands.
DiscordAPIError[50035]: Invalid Form Body
application_id[NUMBER_TYPE_COERCE]: Value "undefined" is not snowflake.
at handleErrors (C:\Users\ros99\Documents\first bot\node_modules\@discordjs\rest\dist\index.js:762:13)
at process.processTicksAndRejections (node:internal/process/task_queues:103:5)
at async SequentialHandler.runRequest (C:\Users\ros99\Documents\first bot\node_modules\@discordjs\rest\dist\index.js:1163:23)
at async SequentialHandler.queueRequest (C:\Users\ros99\Documents\first bot\node_modules\@discordjs\rest\dist\index.js:994:14)
at async _REST.request (C:\Users\ros99\Documents\first bot\node_modules\@discordjs\rest\dist\index.js:1307:22)
at async C:\Users\ros99\Documents\first bot\deploy-commands.js:36:16 {
requestBody: { files: undefined, json: [ [Object] ] },
rawError: {
message: 'Invalid Form Body',
code: 50035,
errors: { application_id: [Object] }
},
code: 50035,
status: 400,
method: 'PUT',
url: 'https://discord.com/api/v10/applications/undefined/guilds/1467881360843608268/commands'
}
```
I don’t think you did what I said since that first line is there, injecting the dotenv. You probably didn’t save the file. #how-to-get-help and #rules atp about knowing JavaScript
It also just may not be there at all or an empty line
What does node -v output?
v24.12.0
This looks like your issue
application_id[NUMBER_TYPE_COERCE]: Value "undefined" is not snowflake

ye but i have it defined in .env
Could you share your deploy-commands.js
application_id=(id) like this
yeah
its 1;1 from dosc
const { REST, Routes } = require('discord.js');
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(process.env.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(process.env.USER_ID, process.env.GUILD_ID), { 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);
}
})();
process.env.USER_ID is undefined
ohhhh
its working thanks
np
is there any good article or something that i can read on components v2 with discord.js
how to use them
Display Components
While you might be familiar with embeds in Discord, there are more ways to style and format your apps messages using display components, a comprehensive set of layout and content elements. To use the display components, you need to pass the IsComponentsV2 message flag (in docs: MessageFlags) when sending a message. You only need to use this flag when sending a message using the display components system, not when deferring interaction responses.
can someone tell me what is causing this error? i have no clue at all since theres no refrence to path in my code, which makes me think its a issue with djs instead. i havn't ever had this error, and this exact code has worked before but dosn't sometimes??
- the channel is a fourm channel
- client.guild is defined
Known issue with the AttachmentBuilder right now unfortunately
I think thats it
dang ok, any way to fix? also is there a way to allow many attachments on a attachment builder?
No, you'd need multiple attachment builders
I think you can attach files without the builder though
dang alright
guess ill just wait for a update
really? how
I think this would work
```js
channel.send({
files:[
{
attachment: buffer,
name: "file.txt"
}
]
})
ok thank you
is there any easy way to get the buffer from a attachment? or do i gotta fetch the cnd content with like axios cuz thats how ive been doing it
I mean if your uploading data as an attachment you would have the data. I am not sure what your asking
ok so i can just add the discordjs attachment in there? i wasnt sure if it wanted like raw file info or not because the attachment has other stuff right
is this warning message in modal going to show every time someone opens it?
yes
buffer is a JS object https://nodejs.org/api/buffer.html#class-buffer
that is so lame i don't even have a text input in it-.-
Better for users
oh ok so buffer.from(attachment) would work then?
what is the type of attachment
discord attachment class
you would need to fetch the data from the URL
here, this is what i was going to do but it seems like a bit much for something like this so im jusst wondering if there is a simpler way
let data;
if (files) {
let data = await axios.get(files.url, { responseType: 'arraybuffer', timeout: 5000, maxContentLength: 500000000 });
}
files: files ? [{ attachment: Buffer.from(data), name: files.title }] : null,
oh wait i declared data twice lol
attachment accepts URLs as buffer resolvable
No need to do that
really? ok thats great
thanks
one other thing to not if you are reuploading Attachments is users can have higher upload limit than your app
hmm true, the modal limit is 500mb right? and discord bot message limit is less than that i presume?
let me check make sure i can limit file size i would hope
oh you cant change it with FileUploadBuilder?
no Discord does not provide a method to limit size before upload
The bots upload limit can very based on server
rip alright guess large files will have to go then
oh really, is it boost based? we def have the largest amount available then
ok 100 mb so still not enough but good i guess
Attachment#size discord.js@14.25.1
The size of this attachment in bytes
i scrolled past it lol
idk how i missed it, genuinely
Guild#premiumTier discord.js@14.25.1
The premium tier of this guild
to check the boost of the server
same as this right
yes
ok good
ok tysm for the help, sorry for being a little stupid lol
np
unfortunately this does not work unless i have done it wrong but idt since its the same error so i guess people wont be able to add attachments for the time being
Sorry, I dont know
i'm looking for a database for a bot i'm developing. i need data persistence and typescript compat, and i'm looking to run it on the same machine and connect via localhost for now, so something that i can run from node is ideal, but a minimum-uptime-power-cost server i can run as a standalone application would be a solid compromise. i'm not terribly worried about a learning curve, since i know a little SQL already. any recommendations?
not discord.js related please use #1081585952654360687
alright, thanks
is it possible to "listen" to a value change in modal?
or its just on submit
Submit only
hey how can i make like this model with menu
Modals
Modals are pop-up forms that allow you to prompt users for additional input. This form-like interaction response blocks the user from interacting with Discord until the modal is submitted or dismissed. In this section, we will cover how to create, show, and receive modals using discord.js! This page is a follow-up to the interactions (slash commands) page. Reading that page first will help you understand the concepts introduced in this page.
it not working i tryed
when i ask ai it told me that
That code snippet is not valid for discord.js v14 modals
That's not how that works mate
Why would ai know if d.js guide snippet works for d.js
~~Is there any guide on working with Components V2?
I'm looking at: https://discordjs.guide/ ~~
- NVM, i'm stupid.
Ai doesn't run your code
Node does
ya
#how-to-get-help says to share errors. not ai-hallucinated concerns
lol
?
i will try and let you know
it worked
Hi im struggling to make a simple stringselectmenu 😭
const userPurchases = await getPurchasesWithProductFromUserId(
user.id,
);
const stringMenu = new StringSelectMenuBuilder()
.setCustomId('retrieve_product')
.setPlaceholder('Select a product');
console.log(userPurchases, userPurchases.length); // [] 0
if (userPurchases.length === 0) {
stringMenu.setDisabled(true);
} else {
userPurchases.map((purchase) => {
stringMenu.addOptions(
new StringSelectMenuOptionBuilder({
label: purchase.storeProduct.name,
value: purchase.id,
}),
);
});
}
interaction.followUp({
flags: [MessageFlags.IsComponentsV2],
components: [
new ContainerBuilder()
.addTextDisplayComponents(
new TextDisplayBuilder({
content: `###  ${interaction.user.username}'s Downloads\n_ _`,
}),
)
.addActionRowComponents(
new ActionRowBuilder<StringSelectMenuBuilder>().setComponents(
stringMenu,
),
),
],
});
when the user has 0 products and the list is empty; it doesn't show a disabled stringselectmenu instead it errors with
@skye/client:dev: [] 0
@skye/client:dev: /Users/x/Projects/Skye/node_modules/.pnpm/@discordjs+rest@2.6.0/node_modules/@discordjs/rest/dist/index.js:762
@skye/client:dev: throw new DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData);
@skye/client:dev: ^
@skye/client:dev:
@skye/client:dev: DiscordAPIError[50035]: Invalid Form Body
@skye/client:dev: components[0].components[1].components[0].options[BASE_TYPE_BAD_LENGTH]: Must be between 1 and 25 in length.
Both the customid and placeholder are well under 25 characters which i don't seem to understand
you have too many options max of 25 per menu
but the addOptions shouldnt run since the list is empty and it should run stringMenu.setDisabled(true); ?
Than it would still throw bc looks like the validator is looking for it to have atlest one option
try adding a dumby option when it is disabled
Oh I see, so there always has to be an option in the select menu even if its disabled
Thank you very much
yes, np
BTW you should not be using actions row, use a Label
LabelBuilder discord.js@14.25.1
A builder that creates API-compatible JSON data for labels.
Im using v14.19 but ill upgrade if this is better
Thanks!
Action rows are deprecated by Discord in modals.
If you're using d.js for modals with select menus, you should be at least on version 14.23 when they were added
Can the bot automatically delete the Ephmeral reply so user don't need to hit the Dismiss message?
documentation suggestion for @pearl roost:
CommandInteraction#deleteReply() discord.js@14.25.1
Deletes a reply to this interaction.
// Delete the initial reply to this interaction
interaction.deleteReply()
.then(console.log)
.catch(console.error);
Thank you
Thank you
hello im starting out rn with discord.js and i cant understand what cooldown for commands should do i think it shold send a ephermal message with how much you should wait before executing this command but its not working for me can any one help me
thats mt interaction.js file in events//interaction.js
const { Events, MessageFlags, cooldowns, Collection } = require('discord.js');
client.cooldowns = new Collection();
if (!cooldowns.has(command.data.name)) {
cooldowns.set(command.data.name, new Collection());
}
const now = Date.now();
const timestamps = cooldowns.get(command.data.name);
const defaultCooldownDuration = 3;
const cooldownAmount = (command.cooldown ?? defaultCooldownDuration) * 1_000;
if (timestamps.has(interaction.user.id)) {
const expirationTime = timestamps.get(interaction.user.id) + cooldownAmount;
if (now < expirationTime) {
const expiredTimestamp = Math.round(expirationTime / 1_000);
await interaction.reply({
content: `Please wait, you are on a cooldown for \`${command.data.name}\`. You can use it again <t:${expiredTimestamp}:R>.`,
flags: MessageFlags.Ephemeral,
});
}
timestamps.set(interaction.user.id, now);
setTimeout(() => timestamps.delete(interaction.user.id), cooldownAmount);
}
// ...
module.exports = {
name: Events.InteractionCreate,
async execute(interaction) {
if (!interaction.isChatInputCommand()) return;
const command = interaction.client.commands.get(interaction.commandName);
if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
if (interaction.replied || interaction.deferred) {
await interaction.followUp({
content: 'There was an error while executing this command!',
flags: MessageFlags.Ephemeral,
});
} else {
await interaction.reply({
content: 'There was an error while executing this command!',
flags: MessageFlags.Ephemeral,
});
}
}
},
};
anyone
Not working for you how? You are very vague. Unless that code snippets you provided is taken from two different context, that is going to error, where are you getting your command and interaction object from for your cooldown logic?
guide
Can anyone help me
I dont understand the cooldown Logic where do i import it ?
What exactly isn't working and what part do you not understand? The guide isn't some magic code you can just copy-paste and import somewhere, it's a guide that you should follow and understand, then implement it to align with your project's setup.
I dont understand where i have to put the cooldown Logic
Does the guide not tell you that?
The guide puts the logic in the InteractionCreate event
But where is the interaction create event
where you coded it to be
or did you copy paste that without understanding as well, so now you're lost
I tried to understand everythink but i think i broke somethink and i tried to copy paste IT i was lost and im lost
client.on("eventName", function) create an event listener. Find the one you have for "interactionCreate"
And then create the cooldown system ?
Under IT ?
You put the logic there, yes
Thank you
Hello guys, i have problem (another). Im trying to send a message to a specified channel but what i get is:
"TypeError: Cannot read properties of undefined (reading 'channel')" at line 225.
All i want to get is: setup > selecting channels > sending a message to first channel and logs to second (logs will be done later)
the interactionCreate event only emits with 1 param, the interaction
it does not emit a message
why not use the specified channel you defined?
It just doesnt see it
how so?
you code doesn't even reference the channel variable after you define it
Hold on
Your issue is this line here, await message.channel.send({
As message is undefined because you initialized it in the event callback but since the event does not emit a message variable, it is still undefined
So message = container and then message.send?
No
Replace message entirely and do interaction.channel.send
it doesn't sound like they're trying to send to the interaction's channel, but rather the channel they're getting from the cache
which is to say, channel
Oh ya. Just do channel.send
I missed that you're defining a channel variable right above that
Now it says:
TypeError: Cannot read properties of undefined (reading 'send')
Collection#first() discord.js@14.25.1
Obtains the first value(s) in this collection.
setapp is a collection not a value
if (rendered?.buffer) {
const name = rendered.filename || `banner_${String(bannerKey)}.gif`;
embed.setImage(`attachment://${name}`);
files.push({ attachment: rendered.buffer, name });
}
sim what's wrrong?
file it's sended not in the embed
should to be in the embed????
So i need to extract channel ID?
getSelectedChannels returns a Collection of the selected channels
no need to get from the cache
if you extract the id, you'd effectively be using the channel object to get the same channel object
hm any1 h any idea?
Thank you, its working
is the fille being added to the message? What I mean by this IS rendered?.buffer true
where do i add the interactioncreate handler ?
anyone?
Wherever the path is for events
what ?
But it looks more like you have a typo (if you copied this from the code) on the first line of that.
Should be path.join(__dirname, "events")
it is on the top
...
idk i odnt under stand the handler meaning
sory if im annoying
Reading event files
Next, let's write the code for dynamically retrieving all the event files in the events folder. We'll be taking a similar approach to our command handler. Place the new code highlighted below in your index.js. fs.readdirSync().filter() returns an array of all the file names in the given directory and filters for only .js files, i.e. ['ready.js', 'interactionCreate.js']. In most cases, you can access your client instance in other files by obtaining it from one of the other discord.js...
I highly suggest reading the text on the guide, not just the code. It explains what the code does, and how to use it
ok i will try again
idk i dont understand it
what part of it?
like i understand whats a event handeler but i cant under stand where you put the cool downs in the interactionCreate file and where to add a new collection for cooldows 
@rose tangle im sooryyy for ping
then don't ping at all
combine the knowledge of the event handler with the cooldown guide page
any one can help why is my return interaction.reply my return is lighting red why
const { cooldowns } = interaction.client;
if (!cooldowns.has(command.data.name)) {
cooldowns.set(command.data.name, new Collection());
}
const now = Date.now();
const timestamps = cooldowns.get(command.data.name);
const defaultCooldownDuration = 3;
const cooldownAmount = (command.cooldown ?? defaultCooldownDuration) * 1_000;
client.cooldowns = new Collection();
if (timestamps.has(interaction.user.id)) {
const expirationTime = timestamps.get(interaction.user.id) + cooldownAmount;
if (now < expirationTime) {
const expiredTimestamp = Math.round(expirationTime / 1_000)
return interaction.reply({
content: `Please wait, you are on a cooldown for \`${command.data.name}\`. You can use it again <t:${expiredTimestamp}:R>.`,
flags: MessageFlags.Ephemeral,
});
}
timestamps.set(interaction.user.id, now);
setTimeout(() => timestamps.delete(interaction.user.id), cooldownAmount);
}
and it says that interaction.client;is not defined
why is my return interaction.reply my return is lighting red why
if you mouse over it, your ide will tell you why
and it says that interaction.client;is not defined
is this from your ide, or an error in your console?
is this in your interactionCreate handler like the guide mentions?
frankly, I worry you're still opting to copy-paste without reading and understanding the code
if this is the case, consider asking questions to help you understand the code and the guide's explanations rather than solely asking for direct solutions to issues caused by not understanding the code
it'll be much more useful in the long run if you actually understand the code you're writing
Thanks for helping i figiure it out by my self

Modals
Modals are pop-up forms that allow you to prompt users for additional input. This form-like interaction response blocks the user from interacting with Discord until the modal is submitted or dismissed. In this section, we will cover how to create, show, and receive modals using discord.js! This page is a follow-up to the interactions (slash commands) page. Reading that page first will help you understand the concepts introduced in this page.
hi @hollow dawn, please use #app-commands for personal usage 🙂
or use hide: true
i can't seem to import Routes from discord.js in my project, but can import REST just fine. what's the correct string to provide as a RouteLike to register commands for a particular server?
What's the issue with importing Routes?
And which IDE do you use?
WebStorm, grep through node_moules/@discordjs has suggested i should try importing discord-api-types/v10
WebStorm is known to have issues with DJS for some reason involving how the discord.js package re-exports the other packages (like @discordjs/builders and stuff like that
you can use d.js ways to register a command in a server
no need to do an almost-raw REST request
i poked around but couldn't find a method similar to client.applications.commands.set() that was guild-specific (what i use for setting global commands), what should i try?
exactly that method
guild.commands.set is the other
does commands.set() support an optional guild resolvable?
Sets all the commands for this application or guild.
if you check the second overload
couldn't figure out how to resolve to a guild from client alone from the docs, i'll look into ApplicationCommandManager
Client#guilds discord.js@14.25.1
A manager of all the guilds the client is currently handling - as long as sharding isn't being used, this will be *every * guild the bot is a member of
and this Manager's cache at .cache is a Collection
thanks, i'm probably just going to rely on GuildManager.fetch() to get the test server, this is mostly for deploying dev commands specifically to the dev server
then you shouldn't do that, really
you should not fetch a guild just for that
instead, use what i linked
ApplicationCommandManager#set() discord.js@14.25.1
Sets all the commands for this application or guild.
// Set all commands to just this one
client.application.commands.set([
{
name: 'test',
description: 'A test command',
},
])
.then(console.log)
.catch(console.error);
it can take a second parameter which is just the guild id
on top of that.. you shouldn't really fetch guilds at all unless you have pretty good reasons to. it comes with more issues than solutions
is client.users gonna fill up too when i fetch all members of one guild
yes
Hello!
im trying to use d.js with the latest version (14.25.1)
code:
const client = new Client({
intents: ['Guilds', 'GuildMessages', 'GuildMembers', 'MessageContent', 'GuildMessageReactions'],
partials: [Partials.Channel, Partials.GuildMember, Partials.Message],
allowedMentions: {parse: ["users", "roles", "everyone"]},
});
client.on('error', (error) => console.error(error));
client.on('warn', (s) => console.log(s))
client.on('debug', (e) => console.log(e))
await client.login(token);
// whaat I see in console
I start 5 instances but none works. I tested the code on windows, that worked perfectly. This is running on ubuntu
Anyone got a clue of what I can do?
just to show that it works on windows:
@marble plover u here aswell 😄 u are everywhere
Is it possible to capture when someone presses cancel on a modal using an interaction collector?
No it doesn't send any interaction event
Alright, thank you.
I actually found it out for anyone who wants to know. It seems that I cannot get a connection when using node:cluster
which to my opinion is very odd
oke nvm it's not that aswell cause I tried a minimal example:
if(cluster.isPrimary) {
for(let i=0; i<navigator.hardwareConcurrency; i++) {
cluster.fork({IS_LAST_CORE: i === navigator.hardwareConcurrency-1});
}
} else {
const client = new Client({
intents: ['Guilds', 'GuildMessages', 'GuildMembers', 'MessageContent', 'GuildMessageReactions'],
partials: [Partials.Channel, Partials.GuildMember, Partials.Message],
allowedMentions: {parse: ["users", "roles", "everyone"]},
});
client.on('error', (error) => console.error(error));
client.on('warn', (s) => console.log(s))
client.on('debug', (e) => console.log(e))
await client.login(process.env.DC_TOKEN)
}```
this works fine aswell on ubuntu, soo going to continue with research...
Okay I got new clue of why it works now, but it works in ubuntu using node:cluster and being in a docker container. not sure why it didnt work in the beginning but sure
Hey I want an option to upload files from a form[modal ] in my discord.js bot so that any user can upload files from the same form. Is it possible to do so?
Wdym by "same form"?
ActionRow discord.js@14.25.1
Represents an action row
Discord has added the new thing where you can give people roles through invites. They for some reason let people give admin roles like that which someone could use to nuke your server, is there any way to track roles given to people through invites? Or would I just need to scan them right after they join for unsafe roles
The new invite methods are not yet available to DJS... but the official docs show that the INVITE_CREATE event shows an array of role_ids attached to an invite... you can track that to instantly deactivate invites with suspicious roles on it
However, they do still limit the allowed roles that can be assigned the same way normal roles can be assigned (aka, can't assign equal or higher roles than your own)
Hey, i faced some issue while trying to make message commands, i realized they did not work at all, and the debug just shows everything is fine, for issues like this, is there anything else to check or something? or should i show you the code?
do you have the GuildMessages and MessageContent intents?
Yes
what do you mean "they do not work"
not responding or either it is the code
can you show the related code?
class CommandLoader {
constructor(client) {
this.client = client;
}
async loadPrefix() {
const baseDir = path.join(__dirname, 'commands', 'prefix');
if (!fs.existsSync(baseDir)) {
log.warn('Prefix commands directory not found');
return { loaded: 0, failed: 0, aliases: 0 };
}
const stats = { loaded: 0, failed: 0, aliases: 0 };
this.client.prefixCommands.clear();
this.client.aliases.clear();
const loadFile = (filePath) => {
try {
delete require.cache[require.resolve(filePath)];
const cmd = require(filePath);
if (!cmd.name || !cmd.execute) return;
this.client.prefixCommands.set(cmd.name, cmd);
stats.loaded++;
if (Array.isArray(cmd.aliases)) {
cmd.aliases.forEach(alias => {
this.client.aliases.set(alias, cmd.name);
stats.aliases++;
});
}
} catch (err) {
stats.failed++;
log.error(`Failed loading ${path.basename(filePath)}: ${err.message}`);
}
};
const walkDir = (dir) => {
const entries = fs.readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
walkDir(fullPath);
} else if (entry.name.endsWith('.js')) {
loadFile(fullPath);
}
}
};
walkDir(baseDir);
return stats;
)
...```
i dont really see where you respond to anything there.
i thought you mean to show how i loaded them
tag suggestion for @ocean portal:
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
have you done any debugging to see where your code stops and to know where it stops responding? 🐌
Yes
well where does it stop
ill run the server again to check, wait a moment
for the commands it doesnt show anything
what do you mean by that?
i checked the path and it is the correct one
that doesn't answer our question
running the command using debugging, unresponsive when used, no output in the console
im sorry
we asked you to put some logs and see where it stops logging
start putting them at the top of your listener to see if at least that executes
alright
then once you try to use the command, it'll stop logging at some point and you'll know where it stops working
i done that, still no outputs and unresponsive
the only thing that does work is slash commands
can you show your listener and the console.log line?
sure
Is it possible to create a voice channel and set the position directly when creating the channel? Or just after the creation with .setPosition?
Yes the former
// debug.js linked to commands and bot file
const fs = require('fs');
const path = require('path');
class Debugger {
constructor() {
this.enabled = true;
}
timestamp() {
return new Date().toLocaleTimeString('en-US', { hour12: false });
}
format(level, module, ...args) {
const time = `[${this.timestamp()}]`;
const mod = module ? `[${module}]` : '';
const msg = args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' ');
return `${time} [${level}]${mod} ${msg}`;
}
error(module, ...args) {
if (!this.enabled) return;
console.error('\x1b[31m%s\x1b[0m', this.format('ERROR', module, ...args));
}
warn(module, ...args) {
if (!this.enabled) return;
console.warn('\x1b[33m%s\x1b[0m', this.format('WARN', module, ...args));
}
info(module, ...args) {
if (!this.enabled) return;
console.info('\x1b[36m%s\x1b[0m', this.format('INFO', module, ...args));
}
debug(module, ...args) {
if (!this.enabled) return;
console.debug('\x1b[35m%s\x1b[0m', this.format('DEBUG', module, ...args));
}
}
module.exports = new Debugger();```
It’s still 2 api calls iirc tho
.channels.create({ name: …, position: …, … })
Hmmm, I would like an option when creating the channel, it doesn't go somewhere and then adjusts, lol
Nvm, it’s a single api call
I was using
const newChannel = await guild.channels.create({
name: channelName,
type: ChannelType.GuildVoice,
parent: templateChannel.parentId,
position: previousChannelPosition + 1
});
But it wasn't working, it just set it to a different position, sometimes in the start of the category
if you see helping me with this is just taking too long or boring ill just try and see other solution
because this probably wont work at all
you only shared the console.log line
which isn't that useful by itself
Are you using rawPosition?
this is how i linked it
const debug = require('./debug.js');
above in the main file
client.debug = debug;
after creating the client
do you wanna see how i loaded them? or the commands?
im suppose to use that one? rawPosition: ?
No
I’m talking abt the previous channel
I want to see your listener, where do you listen for MessageCreate, where do you execute the commands
you only shared a CommandLoader which stores your commands in a collection you created
not where you actually use that collection
ah, nope: let previousChannelPosition = templateChannel.position;
Try using rawPosition
Appears create doesn’t help you with position anymore, it just sets the raw position directly
Or maybe it never did I didn’t notice
const {
Client,
---- Collection, ----------
GatewayIntentBits,
Partials,
REST,
Routes,
ActivityType,
PresenceUpdateStatus
} = require('discord.js');```
after this
```js
client.prefixCommands = new Collection();
client.slashCommands = new Collection();
client.aliases = new Collection();
client.cooldowns = new Collection();```

yeah, that's how you create it
yea, It was what I was thinking. Tho, yesterday it was working, lol
do you actually listen to the messageCreate event somewhere?
you're creating those collections, they're not managed by djs
if you store commands in there (or anything else) they won't do anything by themselves
you must program a listener that will actually use them
client.on('messageCreate', async (message) => {
if (message.author.bot || !message.guild) return;
const prefix = await client.getPrefix(message.guild.id);
if (!message.content.toLowerCase().startsWith(prefix.toLowerCase())) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const commandName = args.shift().toLowerCase();
const command = client.prefixCommands.get(commandName) ||
client.prefixCommands.get(client.aliases.get(commandName));
if (!command) return;
if (!client.cooldowns.has(command.name)) {
client.cooldowns.set(command.name, new Collection());
}
const now = Date.now();
const timestamps = client.cooldowns.get(command.name);
const cooldownAmount = (command.cooldown || 3) * 1000;
if (timestamps.has(message.author.id)) {
const expirationTime = timestamps.get(message.author.id) + cooldownAmount;
if (now < expirationTime) {
const timeLeft = (expirationTime - now) / 1000;
return message.reply(`Please wait ${timeLeft.toFixed(1)} more seconds before using \`${command.name}\` again`)
.then(msg => setTimeout(() => msg.delete().catch(() => {}), 5000))
.catch(() => {});
}
}
sorry for late response, the code is too large
no worries, and yeah that's the important part
that's where you should place your logs and see where it stops executing
alright, thank you
I assume the next line is something like command.execute(message), it'll probably stop before that, you need to find where
alright, thanks
How can I collect these badges from the user's profile using TypeScript?
most badges are not available from the app api... but some of them, you can get with User#flags
And how can I access at least the user's boost levels even when fetching from anyone?
GuildMember#timeout() discord.js@14.25.1
Times this guild member out.
// Time a guild member out for 5 minutes
guildMember.timeout(5 * 60 * 1000, 'They deserved it')
.then(console.log)
.catch(console.error);
Should only be available from OAuth... and it's user#premium_type? but it doesn't show when it starts... only the tier
@umbral jetty please use #app-commands or hide:true for personal usage
Sorry
Okay, so how can I access an Orbs badge when a user completes a mission?
thats not available in the API
most badges are not available from the app api
Is it possible to access the user connections through the API?
through oauth, yes
Oh yea, thx
which discord.js does not support
It isn’t possible to create a channel and ser the position in the creation right? Only afterwards? I had the feeling that was, but probably just a confusion
It is possible to do it in the create call directly
Hmmm, yea I know, today morning I really thought it was working, but now it really doesn’t work
Every time I try to follow the official documentation my token never logs in. Youtube tutorials work but never really get my far enough along to understand the API. directly copied-and-pasted code from the docs straight up doesn't work. How is this allowed to happen?
what does your index file look like? and are you getting an error?
Its a bit hard for us to answer that based on what you've told, yeah. There's many things that could prevent a successful login, but if the code is directly from our guide, it shouldn't be the issue
Interesting,
Channel created: Staff #2
├─ position: 5
└─ rawPosition: 4
Well, it works, but Discord don't care than :D
that's why I'm so confused. my index file is (currently, for the sake of trying to get it exactly right the exact code from the starting doc. my token is correct. What other issues could be causing it to refuse to login? Like I said, it never had trouble logging in before I turned to discordjs's official guide. now it doesn't want to. I even made an entirely new project and reset my token just to try to make this work and it just won't.
// Require the necessary discord.js classes
const { Client, Events, GatewayIntentBits } = require('discord.js');
const { token } = require('./config.json');
// Create a new client instance
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
// When the client is ready, run this code (only once).
// The distinction between `client: Client<boolean>` and `readyClient: Client<true>` is important for TypeScript developers.
// It makes some properties non-nullable.
client.once(Events.ClientReady, (readyClient) => {
console.log(`Ready! Logged in as ${readyClient.user.tag}`);
});
// Log in to Discord with your client's token
client.login(token);
my config file should be correct as well. it all exists within the same file directory
When you say "refuse", what happens?
I get the error code "TokenInvalid"
Well then, its invalid
That error comes from Discord
can't be. direct cut and paste. even reset it just to make sure. nothing
Its possible that its not being imported from config directly. Have you tried logging it in index.js to make sure it matches
Or pasting it directly into client.login() to skip the import step
you might be onto something there. runs with the token directly pasted into the js file
Appreciate the patience. thin on my own. I'll make sure my config file is made right
My bot is in around 1300 servers now, and I kinda wanna become more familiar with sharding before I have to implement it. I have a test instance which is in like a few servers, if I use the sharding manager from the guide will this still “spawn”? So I can become familiar
if you set up Sharding Manager as the starting point of your app, it will pretty much already work
with your guild count, unless you change the defaults, it will ask discord for the shard count, which i'm pretty sure would be 1 shard. discord goes for 1k guilds per shard
that said, rest of your bot code will need adapting if you depend on certain assumptions
like guilds or channels simply "being there" in cache
Ok so it’ll still work then, I’ll give that a go and learn from there. Thanks. And yh exactly so I wanna start learning what I need to change etc
ShardingManager spawns each shard as separate process, so each one has it's own client and as such own caches
As from my understanding you also can’t use like client.channels.cache.get? You’ll need to like use broadcast eval
you can
it's just that the channel might be in another shard, if it's from a different guild (or you're doing stuff from different entry-point than guild stuff)
Wait, if I use that in the message create event, client.channels.cache, can I just assume that that channel will live in that client.channels.cache?
IMO, the most foundational tip i could give is to not grab all data to process it locally, but ask the shards that have the data to do it
It encourages a bit more thoughtful design into the scope of what you're trying to access
Definitely, will test and improve my skills for sure lol
e.g.: don't grab an entire channel via bEval just to call .send() on it, or entire guild just to check its .memberCount
Ah, return the member count itself
just ask the shard that has that channel to send something, or to return you the .memberCount directly
Gotcha, that’s super useful thanks
the former will also not work for a different reason, namely that stuff gets serialized
is #archive-sharding visible?
check my pin there
If that’s still valid is it possible to pin it here or maybe #1115775988857581668 ? That’s pretty good
(just note that since i wrote that, bEval stopped accepting string, no difference for the example itself though)
this channel is too generic for such stuff and certain overlord disallowed doing that
But I’m also aware that ig most people aren’t sharding lol
yeah
is there any fix i can add myself for the attachment builder issue?
by this i mean when you try to create a thread with files that are attachments it says there is no path variable or something like that
what version of discord js are you on?
14.18.0\
is is fixed in a newer version?
Try updating to latest and see if it goes away
hopefully
did not unfortunately
show full error please
TypeError: Cannot read properties of undefined (reading 'path')
at findName (/app/node_modules/discord.js/src/structures/MessagePayload.js:291:17)
at MessagePayload.resolveFile (/app/node_modules/discord.js/src/structures/MessagePayload.js:305:31)
at /app/node_modules/discord.js/src/structures/MessagePayload.js:273:85
at Array.map (<anonymous>)
at MessagePayload.resolveFiles (/app/node_modules/discord.js/src/structures/MessagePayload.js:273:56)
at GuildForumThreadManager.create (/app/node_modules/discord.js/src/managers/GuildForumThreadManager.js:65:8)
at Object.execute (/app/src/components/modals/bssHelp.js:98:78)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async Object.execute (/app/src/events/client/interactionCreate.js:164:21)```
its a error with djs i was told by monbrey
but its really causing issues in my bot and i just want to know if theres any easy way i can fix it myself, of course i could update the module in node_modules, but my hosting service pulls from discordjs's npm page so i would have to have the whole package locally which i guess wouldnt be a problem but
just tring to cover my bases what packages do you have installed?
discord.js includes multiple sub-packages, installing these separately can mess with internal code:
[0;31mnpm [0;0muninstall discord-api-types @discordjs/rest @discordjs/builders
[0;34myarn [0;0mremove discord-api-types @discordjs/rest @discordjs/builders
[0;33mpnpm [0;0mremove discord-api-types @discordjs/rest @discordjs/builders
some of them are useless i could probably get rid of them
oh ok, i will try removing api types and rest hopefully that fixes it
can i still import rest and routes from discord.js? because i used resst and apitypes to register commands and set my token
yes
ok great
mmm nope error still there
guess i will just have to remove file uploads from the modals which isnt to big of a deal i guess
should i open a bug report on the github? i dont see one explaining what i have, then again i am not sure exactly what is causing this so maybe its under a different name
I just tried to replicate you bug and could not on js will try to see if it happens in ts
client.on(Events.InteractionCreate, async (interaction) => {
if(!interaction.isChatInputCommand()) return
if(interaction.commandName !== 'ping') return
const modal = new ModalBuilder()
.setCustomId('modal')
.setTitle('Modal')
.addLabelComponents(label => label
.setLabel('File')
.setDescription('must be small')
.setFileUploadComponent(new FileUploadBuilder()
.setCustomId('file')
.setMaxValues(1))
)
await interaction.showModal(modal)
const submit = await interaction.awaitModalSubmit({time:15_000})
const file = submit.fields.getUploadedFiles('file', true)
submit.reply({
files: file.map((f) => f)
})
})
getUploadedFiles returns attachments, so you shouldnt need to make a new builder (assuming you can send Attachments in messages)
right, retest with updated code. edit previous message to reflect the change
ok, i will try and let you know
intresting, that works fine, so that means that its a issue with either how i pass the files argument for my message, or its a issue with the GuildFourmThreadManager.create() function
i will try changing my files argument to the map incase that changes anything somehow
the map fixed it!
although im not to sure why, but i am glad its fixed. maybe you know:
my old code was this
files: files && files.size > 0 ? [...files] : null,
// where files is a getUploadedFiles(), or a array of attachments
wait no it was a collection, but that should still work no? spread operator on a collection uses the values right
nope
getUploadedFiles returns a collection not an array
it uses entries im pretty sure, if it works at all
wow ok
i think it works on maps, i'm so use to maps so i assumed that was the same when i saw the snowflake attachment
Well Collection does extend map
true, idk im just happy its fixed lol
thanks so much to you guys for helping, glad i was able to get it resolved. especially you @wary coral ! 💗
Yeah its not values, its entries
oh dang ok, so it was giving the snowflake to
Just found out my discordjs version is out of date. Is there a way to force it to install v14? it only wants to install v13 despite me being on nodejs 18.19.1
Completely uninstall d.js and install, it defaults to only updating within the same major version that's installed
Why my bot getting a "Missing Access" error when trying to edit a message? I've already verified that it has the required permissions
DiscordAPIError[50001]: Missing Access
at handleErrors (/home/container/node_modules/@discordjs/rest/dist/index.js:762:13)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async SequentialHandler.runRequest (/home/container/node_modules/@discordjs/rest/dist/index.js:1163:23)
at async SequentialHandler.queueRequest (/home/container/node_modules/@discordjs/rest/dist/index.js:994:14)
at async _REST.request (/home/container/node_modules/@discordjs/rest/dist/index.js:1307:22)
at async GuildMessageManager.edit (/home/container/node_modules/discord.js/src/managers/MessageManager.js:255:15)
at async Paginator (/home/container/src/utils/helpers/Paginator.js:51:35)
at async interactionCreate.js (/home/container/src/events/guild/interactionCreate.js:103:7)
{
CreateInstantInvite: true,
KickMembers: false,
BanMembers: false,
Administrator: false,
ManageChannels: false,
ManageGuild: false,
AddReactions: true,
ViewAuditLog: false,
PrioritySpeaker: true,
Stream: true,
ViewChannel: true,
SendMessages: true,
SendTTSMessages: true,
ManageMessages: false,
EmbedLinks: true,
AttachFiles: true,
ReadMessageHistory: true,
MentionEveryone: false,
UseExternalEmojis: true,
ViewGuildInsights: false,
Connect: true,
Speak: true,
MuteMembers: true,
DeafenMembers: false,
MoveMembers: false,
UseVAD: true,
ChangeNickname: true,
ManageNicknames: false,
ManageRoles: false,
ManageWebhooks: false,
ManageEmojisAndStickers: false,
ManageGuildExpressions: false,
UseApplicationCommands: true,
RequestToSpeak: true,
ManageEvents: false,
ManageThreads: false,
CreatePublicThreads: false,
CreatePrivateThreads: true,
UseExternalStickers: true,
SendMessagesInThreads: true,
UseEmbeddedActivities: true,
ModerateMembers: false,
ViewCreatorMonetizationAnalytics: false,
UseSoundboard: false,
CreateGuildExpressions: false,
CreateEvents: false,
UseExternalSounds: true,
SendVoiceMessages: true,
SendPolls: false,
UseExternalApps: true,
PinMessages: false,
BypassSlowmode: false
}
How did you obtain these permissions?
eval const channel = client.channels.cache.get("");
channel.permissionsFor(channel.guild.members.me).serialize()
Is this interaction not a button on the message you want to edit?
Generally, you should be using ButtonInteraction.update to edit the message the button to avoid this sort of issue
yes, this message has buttons
thanks it works
hey, is cv2 only for embeds ? thx
That question doesn’t make sense. You can’t have components v2 and embeds in the same message
i dont really get how look cv2 tbh
i've never seen it for now
The guide has pictures
where is the guide pls ?
guide suggestion for @eager garnet:
Display Components
While you might be familiar with embeds in Discord, there are more ways to style and format your apps messages using display components, a comprehensive set of layout and content elements. To use the display components, you need to pass the IsComponentsV2 message flag (in docs: MessageFlags) when sending a message. You only need to use this flag when sending a message using the display components system, not when deferring interaction responses.
oh great, thx
I see the container look like a bit like embeds. So it ain't possible to concat embed + cv2 ig ?
They are separate animals
¯_(ツ)_/¯
yeah ok thats what i thought... Thx for you help mate
Np
okay i might be stupid but i am not able to find answer to my problem
i want to get user that triggered an interaction but get if from event CreateMessage
But they didnt send a message
So there is no messageCreate event fired
but the interaction created an reply
From the response to an interaction?
yeah
Message#interactionMetadata discord.js@14.25.1
Partial data of the interaction that this message is a result of
MessageInteractionMetadata#user discord.js@14.25.1
The user that invoked the interaction
okay thank you im trying this rn i couldnt find this
yeah this works, thank you
i just didnt see this in docs
Display Components
While you might be familiar with embeds in Discord, there are more ways to style and format your apps messages using display components, a comprehensive set of layout and content elements. To use the display components, you need to pass the IsComponentsV2 message flag (in docs: MessageFlags) when sending a message. You only need to use this flag when sending a message using the display components system, not when deferring interaction responses.
We have #app-commands or the hide option for personal usage
hi, how can i get the accessory button interaction from a message component collector ?
yeah sorry i noticed it right after sending the cmd
It'll just be a normal button interaction
You can look at interaction.component if needed
oh ok, nothing changes
so i dont need any action row or else ?
Not in an accessory
k thx, and is there any way to set a default value for a StringSelectMenu ?
@crimson gale
@fleet ridge
savage publicity won't make people come to u
The default is in the string select menu option
couldn't ping mod role so
Yo, sorry didn't read the spam bot message you're good
what do u mean
StringSelectMenuOptionBuilder#setDefault() builders@1.13.0
Sets whether this option is selected by default.
oh i meant StringSelectMenuBuilder, which is the one you put in cv2
The select menu is the same as it has been. When creating a string select menu. You need to create options for that menu. In the options is a Boolean value to set whether or not it's a default
Hey! Question about source. Is there a reason why skipLibCheck: true is missing in the tsconfig? I'm having trouble building because of this
You'll want to ask in #djs-in-dev-version
Okay, thanks for the direction!
ok thx
Unlike other select menus, the string select menu does not have a default defined in the object itself. String select menus have the default defined in the option structure
Hopefully this reword is a little bit more clear
oh ok so i can't set a default value
You can, but it's a Boolean value in the string select menu option
example
const menu = new StringSelectMenuBuilder()
.setCustomId('menu')
.addOptions(
new StringSelectMenuOptionBuilder()
.setLabel('option 1')
.setValue('option 1')
.setDefault(true), // set option as default
new StringSelectMenuOptionBuilder()
.setLabel('option 1')
.setValue('option 1')
.setDefault(false) // set option as Not default
)
@eager garnet this help?
oh yeah thx a lot i get it, i just need to put through StringSelectMenuOptionBuilder
i was trying with pure object so... thx :p
If you're using the raw objects you can just defult: true
const removeButton = new ButtonBuilder()
.setCustomId('disable')
.setLabel('Disable button')
.setStyle(ButtonStyle.Danger);
const removeDisabledButton = // Same button as above but disabled with custom id 'disabled'
const row = ActionRowBuilder().addComponents(removeButton);
const reply = await interaction.reply({
content: 'text',
flags: MessageFlags.Ephemeral,
components: [row],
withResponse: true,
});
const collectorFilter = (i) => {
i.user.id === interaction.user.id;
};
try {
const confirmation = await reply.resource.message.awaitMessageComponent({ filter: collectorFilter, time: 60000 });
if (confirmation.customId === 'disable') {
console.log('ok') // logs nothing when button clicked
const disabledRow = new ActionRowBuilder().addComponents(removeDisabledButton);
await confirmation.update({ content: `disabled button`, components: [disabledRow] });
}
} catch {
const disabledRow = new ActionRowBuilder().addComponents(removeDisabledButton);
await interaction.editReply({ content: 'text', components: [disabledRow] });
}
Any idea as to why the button click isn't even logged?
I don't see where row is defined to show what components are in it. You could use a regular collector to get better real time information, such as the interaction data that the filter sees
oh yeah that's above the reply
forgot to add it again while adding the comments in the snippet I sent
I would still suggest using a regular component collector to get more data as you're debugging, then you could go back to await
Also, I don't see where you put a max in your current collector, that may have something to do with it
Hey curious questions, Can you use a container builder in @discordjs/rest and send it via
body: {
components: [component],
flags: [MessageFlags.IsComponentsV2]
}
)}```
question about archived threads due to inactivity, if I give the bot Manage Threads permission, can the bot send a message normally in that thread without needing to manually unarchive it?
try it and see, if it doesn't work then call toJSON on it first
from what I can see a user can, so a bot probably can as well
okay thanks, that's what I thought as well
I tried it out, and from what i'm getting for an error, its for some reason talking about my thumbnail and components
Is this wrong formatting?
row.addComponents(
new ButtonBuilder()
.setCustomId('approve')
.setLabel('Approve')
.setStyle(ButtonStyle.Success),
new ButtonBuilder()
.setCustomId(`deny`)
.setLabel('Deny')
.setStyle(ButtonStyle.Danger),
new ButtonBuilder()
.setCustomId('more_options')
.setLabel('More Options')
.setStyle(ButtonStyle.Secondary)
);
return row;
});```
The docs are not clear at all when it comes to this, I can send the whole containerbuilder if you want
please do send the whole thing... from what it sounds like, you are using a section component somewhere but youre not adding an accessory
sections are required to have an accessory... which is either a single thumbnail or a button
const embed = (title) => {
const container = new ContainerBuilder()
.addTextDisplayComponents((text) =>
text.setContent(`## New Appeal Submission n\**Username:** ${userData.username} (${userData.discordId})\n ${logs}`)
)
.addSeparatorComponents((s) => s)
.addSectionComponents((section) => {
section.addTextDisplayComponents(
(t) => t.setContent(`**What reason were you given for your ban?**\n${appealData.reason1}`),
(t) => t.setContent(`**What action(s) or word(s) of yours led to this ban?**\n${appealData.reason2}`),
);
section.setThumbnailAccessory((thumb) => { return thumb.setURL(userData.avatar)})
return section;
})
.addSectionComponents((section) => {
section.addTextDisplayComponents(
(t) => t.setContent(`**Why do we have a rule against this type of behavior?**\n${appealData.reason3}`),
(t) => t.setContent(`**To show why you should be unbanned, what steps have you/will you take to reform your behavior and ensure this wont happen again?**\n${appealData.reason4}`)
);
return section;
})
.addSectionComponents((s) => s)
.addTextDisplayComponents((textt) =>
textt.setContent(title)
)
.addSeparatorComponents((s) => s)
.addActionRowComponents((row) => {
row.addComponents(
new ButtonBuilder()
.setCustomId('approve')
.setLabel('Approve')
.setStyle(ButtonStyle.Success),
new ButtonBuilder()
.setCustomId(`deny`)
.setLabel('Deny')
.setStyle(ButtonStyle.Danger),
new ButtonBuilder()
.setCustomId('more_options')
.setLabel('More Options')
.setStyle(ButtonStyle.Secondary)
);
return row;
});
return container.toJSON();
}```
yup, there it is... a section with no accessory... pass the text display by itself without wrapping in a section
yeah youre missing two accessories (buttons or thumbnails), you should just use a regular textdisplay if you dont need more accessories 🐌
So just remove the section componets for one of them and just use regular text display components?
you also appear to have a typo and did a .addSectionComponents((s) => s) when you probably meant to do .addSeparatorComponents((s) => s)
remove whichever ones dont include accessories
Bless, thank you two, that worked beautify now
Is there any solution about this situation?
I have created a modal that contains let user fill the information and send attachment to my server. I use an AI to scan that file and send user back the result of data in that file
The problem i got is when the attachment sent to server, it took a few time (~10-15s) to process. Since the user clicked submit in the modal, after 3 seconds it responds "Somethings went wrong, try again".
I have tried the interaction.awaitModalSubmit() but seem like not work for me, so how do i can do that like make the modal wait longer until the data is processed and sent to user?
Use deferReply immediately on the ModalInteraction then editReply when ur ready to reply
awaitModalSubmit is for collecting a modal submission
well i understand it, thanks for you support!
Hello everyone, I am a bit unsure about my approach and wanted to share it.
Several users have asked me if I could make a method to remove the data of all the members who left.
So my approach is to basically fetch everyone in my list and filter those for which there is an error, and it seems to be working when I test it
const guildMembers = await ctx.bot.db.fetchPlayersFromServer(server);
const toDelete = (await Promise.all(guildMembers.map(x => ctx.getGuild().members.fetch(x.uid).then(() => null).catch(e => e.status == 404 ? x : null)))).filter(x => x);
But, uh, won't there be a problem if I try this on a larger guild ? Like a rate limit ? So is there a better approach that this one ? (I don't have the guild members intent enabled)
Hey, is there a solution if I use commands with
const data = await restClient.put(Routes.applicationGuildCommands(client.user.id, guild.id), {body: uniqueCmdList});
The process will be completed after a few seconds.
yes, deleting all the messages of any specific user in a server is nearly guaranteed to rate limit your application and generally shouldn't be implemented in any (public) application... discord's bulk delete endpoint only works for up to 14 days back and beyond that, message related endpoints generally have more strict rate limits
There's also no need to fetch each member individually. Fetch all members using a single call, then cross-references the lists locally
^
calling guild.members.fetch() at/near startup will load your members cache for a guild... then the gateway will keep it updated from there... so you never need to perform another fetch again
I'm not looking to delete any messages, just local data related to the members.
But, in order to use guild.members.fetch(), don't I need to have a special intent enabled ?
youll need the GUILD_MEMBERS intent to get gateway events on member join/leave anyways
I don't use this event, I basically keep the data until the server owner wants to purge it for all those who left
(and also because it was a pain to apply for the message content intent and I would hate to do that procedure again)
I don't want to call that a bad design but its certainly contradictory to the way Discord is designed
The events exists for you to automatically and efficiently manage your cache
i'm not sure i understand your question
You could still have both - receive the events for a guild member leaving, set a flag in the database that they've left, and then purge from the database on request
Without any fetching required
Thats how I'd be implementing a feature like that
Hmm, so it's either I have the intent and I can fetch the entire guild, and easily compare it to my internal list, or I don't have the intent, and I risk hitting the rate limit ?
(Even if I had the intent, I think I would still fetch in case someone left while the bot was offline even if it doesn't happen really often)
you can't fetch a member if they aren't in the server anymore
yeah but thats how theyre managing it
fetch throws = purge
oh i see... i missed that part...
You also risk hitting the global errors limit lol
Thats less likely but still
the guild members intent is generally also far easier to get than the message content intent... so if you got that one, you shouldnt have that hard of a time getting the members one
though just putting it out there, specifying ids with <Guild>.members.fetch({ user: <id array> }) allows you to fetch multiple members in 1 call and doesn't require the GuildMembers intent
so you could just attempt to fetch the members you have data for and cross reference just those
Hmm I see, thanks. It's actually been a while since I did that (it was in 2022), but if you say so, maybe it's worth a try. Or else I'll just keep using the current method, which is letting the mods delete data for users one by one xD
Oh! Is there a length limit on that? 
you could also have some kind of lastSeen value on a user object in your db, so that if it exceeds a certain threshold, you can add them to a "check if they're gone" queue and purge it if they are
not as far as I know, but it's over the gateway so it's still beholden to timing out if the chunks take too long
It's worth a try actually, but wait how does it behave if there's members that are not here anymore? Does the entire request fails?
(I can't test right now, in an hour I will be able to)
I'm looking at the docs, and it doesn't seem to be written
it just doesn't send a member for them
cross referencing would be the same as if you had fetched all members
Oh so in theory it would be perfect, it just maybe depends on how many I'm fetching
When I add commands with put, it adds the command, but after a few seconds it stops and I don't see any commands on my servers.
did you re fresh your client?
your code adds commands to a single guild, not globally
yes i know.
that's intentional
^
What do you mean? I use the REST client.
they are referring to refreshing your discord app
reloading it
Do I have to do that too?
sometimes the commands don't cache into the client, so reloading is needed for them to show up
CTRL + R
Ah, okay, I thought code technically, yes, I pressed CTRL+R to reload.