#djs-help-v14
78874 messages · Page 36 of 79
primary guild will be part of User int he next release
Haii, to add more presences, do i just include them after each , like in ``` client.user.setPresence({
status: 'online',
activities: [{ name: Serving ${client.guilds.cache.size} servers, type: 0 }],
more...more
Before closing completely with `});`, or how should I go about setting more than one which would change?
You can’t have more than one?
I cant ? I've seen several bots that change their status during a set period of time 
Sure you can do that… that’s not a problem. But afaik you can’t have multiple statuses.
there is a reason why it's setPresence (singular) and activities (plural)
import {SlashCommandBuilder} from 'discord.js';
export default {
data: new SlashCommandBuilder()
.setName('get-txt')
.setDescription('s'),
async execute(interaction) {
}
}
export const data = new SlashCommandBuilder()
.setName('get-txt')
.setDescription('s');
export async function execute(interaction) {
interaction.reply({content: 'Hello'})
}```
Hello guys, according to ES6 Modules, which syntax is better? I mean, which is the best optimized and the one suggested for discord.js?
does Discord validate if the role is actually from the guild, or do we have to validate it ourselves? (in slash command)
There’s gonna be little to no optimisation using either. Use whatever you prefer. Using Const means you can import using {} but using default means you have to (import(…)).default. Up to you
Like role option? Discord side
Alright thanks. Whad do you use? Which is the most common used?
yea, role option, does it also validate that from discord's backend?
I use const myself as I couldn’t be bothered about all of the .default stuff. But I’ve used both
Discord will send a role, so yes
Thank you
Also, what about the role mention? Is it also validated if provided as a mention inside a string option?
If you have a string option and @ a role then discord obviously won’t pass that no. You’ll have to pass it yourself
thats not what i mean....
Then what did you mean, you said mention inside a string option
what you mean by discord obviously won't pass*
won't i get that string in my app?
Yes, ofc you will. But to get the actual role instance you’ll have to get the id from the @ then do all of the passing yourself
How do i get interaction user's id?
interaction.user.id
does fetch look into the cache before actually fetching it from discord?
I am doing this right now btw,
channel = client.channels.cache.get(unResolvedchannel.id) ?? client.channels.fetch(unResolvedchannel.id);
Fetching one does, for the most part. Fetching many will always be an API request
Fetching one does?
you mean, channels.fetch looks into cache before requesting from discord?
Fetching one checks cache
k
Personally I always use the ES6 method, much cleaner imo
But ultimately it's just syntactic sugar, when you import you get it as an object anyway
Hi, if I use
const linkedRole = interaction.guild.roles.cache.find(role => role.name === "Linked");
A) The bot's only in 2 servers, does it fetch roles automatically on startup / build the cache
B) What happens if the role isn't already looked up/cached? Will it fetch and do I need to await this?
Do you have the guilds intent?
If yes, they're already cached
Yeah, I gave it a few intents 
.cache.find() doesn't fetch anything
Ty for the caching tip, what do you mean about this?
Same way trying to access 5th element of an array will not make a request to internet to ask what should be there
Ohhh of course, I see. Thanks!
If I was to use this code, for example, in a bot that has 500 servers, will it fetch all of the roles and the memberlist of all of those roles in all of the 500 servers?
Because surely that's better to do if the server can handle it, I'm not bothered about a bit of a slower startup
Infact, cache.get might not work for me, as I need to check how many members were in a role at the time of running the command, not at startup/cache time
Roles are cached on ready, when the guild payload is sent. Members would need to be fetched in bulk once per guild, and then the cache would be continuously updated as new data is received from the API
I need to implement sharding for my bot and I have a shared MongoDB database for guilds and I saw shard id is calculated with server id >> 22 % shards so how should I go about this should I store the shardid as an attribute of each server
so are you trying to implement sharding or are you trying to save shard ids to db?
djs does sharding automatically for you. Use the key in client options
I see
Mainly just figuring how to prevent extra requests to the database and wasting bandwidth for guilds that aren’t even in the shard
ShardingManager discord.js@14.21.0
This is a utility class that makes multi-process sharding of a bot an easy and painless experience. It works by spawning a self-contained ChildProcess or Worker for each individual shard, each containing its own instance of your bot's Client. They all have a line of communication with the master process, and there are several useful methods that utilize it in order to simplify tasks that are normally difficult with sharding. It can spawn a specific number of shards or the amount that Discord suggests for the bot, and takes a path to your main bot script to launch for each one.
more of a #1081585952654360687 question 
Ok thank you
Hi,
When adding multiple select menus to a message, how to show a label next to each of them ?
The placeholder doesn't fit this need because it disappears when an item is selected.
Thanks
you cant
with the use of components v2 you can set labels above the select menus with a text display component
Oh right, above, because a select menu must be alone. So above is possible ? Not just above the first select menu, but above each select menu ?
sure
add the text display, add the select menu, add the second text display, add the second select menu
you know role id?
I could hardcode the Role ID but I just used name to make it easy
You can use await client.guild.fetch(), then use that guild object to fetch the role. fetch checks whether you have it in the cache; if you do, it will use the cache, otherwise it will fetch it from Discord's servers. This way, both cache and data issues can be solved.
but you do need to know role id.
Actually no. You can do as he did. Using id is just more precisely because it’s unique
the role is cached because they have the Guilds intent
their questions were only whether it'll fetch separately and if a manual fetch is needed, both were already answered
lets not complicate, ask amgelo he will surely solve this
My only concern was the role counts realistically. I did consider doing { force: true }, but didn't want to hardcode IDs.
Further down in the code, I'm assigning a user a colour - either Red, Yellow, Blue, Green, and I wanted to get the role with the least amount of users in it.
Because it's not majorly important to be cardinally correct, I'm just relying on the cache at startup to tell me the approximate amount of members in the role and doing this:
async function getAssignmentCounts(interaction, client) {
// For each of the teams in the setup array
const teams = client.config.teams;
const assignmentCounts = {};
for (const team of teams) {
// Get the role, and the member count
const role = interaction.guild.roles.cache.find(r => r.name === team);
if (role) assignmentCounts[team] = role.members.size;
else assignmentCounts[team] = false;
}
return assignmentCounts;
};```
you have the GuildMembers intent so you'll first need to fetch all members
then role counts will always be kept up to date
Does the order of the intents matter? If not, then I'm probably caching a whole lot anyway.
I do have GuildMembers and Guilds enabled.
the order doesn't matter, and yeah I noticed you have it, that's why I'm saying you only need to fetch all members
Oh so I still need to manually fetch all members?
if you didn't have it then you'd need to fetch per role
yeah, discord doesn't send all members on start, regardless of intents
If the bot's only in 2 servers can I just recursively fetch all members
Or wiser to hardcode the ID of the server I need to know about maybe?
well that's just your choice, how you want it to work
only in some guilds or in all of them
The only purpose of it being in the 2nd guild is to check their roles for eligibility
So realistically it's probably wise to fetch every member so that I have both the role count info and the user role info from the other server
I'm assuming just this impl is fine?
That's just in my ready event for ease
you can just iterate over the guilds cache
otherwise yeah
if you want all members from all your guilds
in order to have the role counts
Will that reliably have both on startup?
the ready event is emitted after everything is ready
I went for this but it logs undefined D:
I'm fairly sure the first await is useless but it's not in a promise so I wanted to be sure it was finished
- forEach doesn't await for their callback promise to finish
- you're wrapping in { } so if you want to return something you need to explicitly have a
returnstatement
and forEach doesn't return anything, hence the undefined
you most likely meant map
Oh shoot, of course. I forgot about returning in nested functions, whoops.
So if I leave the forEach in the background it'll be fine?
The console log's only there for the next 10s to make sure the code worked
you most likely want to map and await the promises with Promise.all
or use a for of loop instead which does wait for the inner block to finish
Looks like it's working now! Thanks.
I used
const guilds = await Promise.all(client.guilds.cache.map(async (g) => {
await g.members.fetch();
return g;
}));```
And just logged it out temporarily underneath
just to be clear for the future in case you want to implement it in some other bot, you only need to fetch once because you have the GuildMembers intent: the bot will receive member update events to update the roles cache
if you didn't have it then you would've needed to fetch every time you wanted the role count
well, djs has a ratelimit manager and also looks up for cache so, it did be fine to fetch all, but again...it is really bad way.
Yeah so just fetching on ready only is fine right?
For future impl's.
How can I check if a member was moved by someone or they moved on their own? (voice)
the cache isn't checked for requests for many objects (eg just fetch())
That worked, thanks.
But now, when the user submits, I can no longer replace the message contents with an embed ?!
why all so obsessed with cache ?
it does check for cache
it is
the answer was ambiguous
guild.members.fetch(id) will check cache
guild.members.fetch() will not check
member.fetch() also doesn't check because that's against the entire idea
it isn't because there's no way to know if you have all objects cached
and if they're up to date anyways
Correct. ComponentsV2 is an irreversible action. You can alternatively do a .followUp or convert your response to a CV2 message
why you even need to cache whole guild's memeber, it seems like such a over caching
because some might need it
i need it, for example
you can also re-use memory instead of needing another instance per member
With the second option, how to get an embed-looking result ?
i am waiting 👍
waiting? for what
example
role changes
thanks for waiting
Jack's issue in the first place requires that, I'm not sure why that isn't an example
Almost everything in an embed can be recreated with markdown
You can use # headers for titles and -# subtext for footers
Header
-# subtext
discord doesn't send amount of members per role, you need to know all members
But the card look ?
and in order to keep track of old state you need a cache
A container?
Popular Topics: Display Components - Container
read more
Is ContainerBuilder backwards-compatible with EmbedBuilder ?
no
they are completely different things
you cannot compare them, besides look and the settable color
😭
ComponentsV2 and Embeds (and even the content field) are mutually exclusive
like Samtino also mentioned, "almost everything can be recreated"
Yeah, but that's so much migration work
namely it doesn't have author, footer or fields replacements
huh?
just do it when you need it, no need to change all at once
tell me which role was added to a member without having oldMember
role updates?
It won't contain oldMember if they aren't cached. The event does not contain the whole user object because users are not cached by default
uh
it does contain the entire object
what it doesn't contain is the old data
or the changes explicitly
it just sends the state after update
AuditLogs 👍
you'd also need an extra intent for that
and permission
in general update events don't have the old state
you need a cache for that
discord only sends the new state
you can stop now. some people need cache, and if you don't understand why they would ever need that, there's no need to push for weird solutions that don't solve anything at all
yea you do need cache for that....
How to check whether an interaction has been switched to components V2 ?
it's not interaction either
interaction is just a way to create a message
That's not what I asked for @sharp ginkgo
it's the message that contains components
hm? why not
How to check from a CommandInteraction object ?
Like there's replied, is there something like replyIsV2 or something
again
I asked specifically for the message flag for IsComponentsV2...it sent the base enum
interaction has nothing do to with flags on message
Well, it affects what you can do with editReply
which means you need to check the message
again - not relatead to interaction
but to message it edits
Okay, so how to get the message from the interaction ?
i am not explicitly saying: check message flags
from interaction?
or interaction response?
Interaction
you can't edit that well, depends, sometimes you can (button), sometimes you can't (contexts)
so not what you want
how do you have the interaction but not know whether you replied with cv2 tho
If you set withResponse: true in your reply, then you can check the InteractionCallbackResponse to see if the message contains the IsComponentsV2 flag
But you should really be in more control of your interaction flows so that you never have to check this state, it should be assumed
In order to improve my development experience, I created functional functions that work regardless of state, such as this one :
respond = async (
interaction: CommandInteraction<'cached'> | MessageComponentInteraction<'cached'> | ModalSubmitInteraction<'cached'>,
payload: InteractionEditReplyOptions | InteractionReplyOptions = {},
isResetPayload: boolean = true
): Promise<Message> => {
if(isResetPayload)
payload = {
...payload,
content: payload.content || (payload.embeds || payload.files || payload.components ? '' : '** **'),
embeds: payload.embeds || [],
files: payload.files || [],
components: payload.components || []
};
if(interaction.deferred || interaction.replied)
return interaction.editReply(payload as InteractionEditReplyOptions);
else if(interaction instanceof MessageComponentInteraction)
return (await interaction.update(payload as InteractionUpdateOptions)).fetch();
payload.flags = [MessageFlags.Ephemeral];
return (await interaction.reply(payload as InteractionReplyOptions)).fetch();
},
But this non-reversible backwards-incompatible V2 thing, is killing me
yeah major bumps aren't meant to be reversible or backwards compatible
the point of them is that they're breaking
Yeah, but at the very least, downgrading should be possible.
discord says otherwise, and I think they have a good point but that's unrelated either way
Does that mean embeds will also become deprecated ?
honestly I'm not sure what's the use case where such a method is needed, but as we said you'll need the original message (which you can fetch or get depending on your interaction type), then check if it has the flag, you could also just pass it
also? nothing has been deprecated
and no, discord hasn't shared any plans to do that
Yeah, I was asking about the future.
Because if Discord is really treating this as versioning (I thought "Components V2" was just a brand name), then there's potential for "V1" to eventually get deprecated, as that's what happens to versioned stuff.
it's unmaintained but not deprecated
deprecation usually happens if it's harder to keep it working, but a lot of their infra still uses embeds, like url embeds
Discord did not name it “components v2” afaik, it was either an intern project name or the community named it like so
the official announcement was titled “new components for messages” as well
and ofc the message flag, but ig that wasn’t a smart move to call it IS_COMPONENTSV2
but they had to distinguish those somehow
it's the project name, but the flag sticked around for some reason
Well, if "V2" isn't a thing, then the "major bump" argument no longer holds, actually
it's meant to be a major bump, but it's not named after it
doesn't need to be named after its versioning in order to be breaking
I guess breaking anytime is the Discord standard operating procedure indeed
some libraries even can't implement it yet because it's breaking to them since they coded everything around the fact that action rows were the only top level component
which discord actually debunked a long time ago (mentioning that more components could eventually arrive)
I mean, it's breaking if you choose to use it
if you don't want to, don't use it, simple
I don't have a choice, they didn't provide a feature that solves my issue without it
which issue?
Labeling each select menu.
if it's a short description you could use the placeholder
otherwise yeah you do need to switch
the cost of better features is that you have to code around them
^
The placeholder doesn't fit this need because it disappears when an item is selected.
you're out of luck then, switch to cv2 and their features/limitations
Where is this coming from?
the docs never mention "components v2"
only for the flag name
how do I get an ID of a slash command right clicking isn't working
right clicking the name here just does nothing
https://media.discordapp.net/attachments/381870553235193857/1405618005580185750/image.png?ex=689f7b47&is=689e29c7&hm=a73ef8e3c01a51150a4502fc2f842b6c926f93f0158ed0a5325e0bbe65dbbf2d&=&format=webp&quality=lossless
Select a command in the message box and right click its name
So, from a Message object, how do I check whether it was switched to V2 ?
Also, if I call deleteReply from an interaction, can I then use reply again ?
Check if it has the flag
No
(await interaction.fetchReply()).flags.has(MessageFlags.IsComponentsV2) ?
If you're performing the flag check on a reply you sent, shouldn't you already know whether it has the flag or not without needing to fetch it again?
^ As mentioned above, I'm doing functional programming
Okay, well in that case, then yes, that would be what you'd use
Okay thanks
can we embed to html
like this
export type BitFieldResolvable<Flags extends string, Type extends number | bigint> =
| RecursiveReadonlyArray<Flags | Type | `${bigint}` | Readonly<BitField<Flags, Type>>>
| Flags
| Type
| `${bigint}`
| Readonly<BitField<Flags, Type>>;
How to reliably check whether the V2 flag is present with this diversity of types ?
MessageFlagsBitField#has() discord.js@14.21.0
Checks whether the bitfield has a bit, or multiple bits.
message.flags.has, if that’s what you mean
Whats the best way to add a shard number field to a json logger like pino?
maybe tie it to the client
cuz its not like a global value im guessing
Can use like message.guild.shard, since the shard is attached to the guild. So whatever has the guild property will have a shard
Guild#shard discord.js@14.21.0
The Shard this Guild belongs to.
okay but i dont really want to pass the shard id at every logger call, id rather want to initialize the logger at program start with the shard id
maybe by passing the shard id as an env or argv
Not possible unless you can do like shardLogger.get(message.guild.shardId). Since each guild will have a shard
what would work is put the logger on the client
client.logger = logger(client.shard.ids[0]) or something
You can pass it in like an “extra” section or something
But imo having like a map of 5 loggers for 5 shards then getting one is a bit pointless
still wondering why client can have multiple shard ids, its an array
Because you can have multiple shards?
okay i guess depends on the sharding method
I very much doubt it would be different really
im pretty sure for me the array only has one id on each client in each shard
but theres also a strategy where you shard on one worker where it would probably show multiple ids
I mean I’m no expert on sharding, but you should have one client which will spawn multiple gateway instances. So regardless client.shard.ids should be all shard ids
no im using the ShardingManager, which will start up a file on multiple threads , so theres one client for each shard
causes me headaches sometimes cuz i have to use shard.broadcastEval to access some values
Yes, but to my knowledge the main client will still have the shard ids for each shard. I’m interested in this too since one day I’ll have to shard so I’ll be happy if someone more knowledgeable would say what is and isn’t
hyg
hyg?
here ya go
its only one id
slow mode mad annoying
this is literally a help channel why would they restrict messages
Oh, right. But I suppose that means ids is 8 since it’s 8 shards? I would’ve thought it would be different but… yh. Will be nice to see why it’s an array then and how it all works
no it means its the 8th shard
Ahhh, ok right. Ig that’s right then, interesting
like we said before, you can also shard on one client with multiple gateways, where it would probably show mutliple shard ids
I suppose it would? That’s cool either way
yea
actually having a bigger problem than the shard ids right now
Maybe you could use some class with a map of loggers then use like getLogger(<shardId>)
i think id rather just use client.logger, i have the client accessible in most contexts
but i was just wondering if it could work with just import logger
if i could pass a seperate env or argv to each shard then that could work
I believe there’s options to do it when you make a sharding manager, to pass argv
yea but not a different one to each
ShardingManagerOptions discord.js@14.21.0
The options to spawn shards with for a ShardingManager.
Ah true
my pino logger is not logging debug logs
import pino from 'pino';
import path from 'path';
export const pinoTransport = {
targets: [
{
target: 'pino-pretty',
options: {
colorize: true,
translateTime: 'SYS:standard',
ignore: 'pid,hostname',
},
},
{
target: 'pino/file',
options: {
destination: path.resolve(`logs/${new Date().toISOString().split('T')[0]}.log`),
mkdir: true,
},
},
],
};
const logger = pino({ level: process.env.LOG_LEVEL || 'info', transport: pinoTransport });
logger.info(`[Pino] Logger initialized at level: ${process.env.LOG_LEVEL || 'info'}`);
logger.debug('[Pino] Debug');
export default logger;
now my other problem is that i dont log debug logs
this is only inside a shard, if i run this file standalone it logs fine
or maybe its to do with docker idk
its not the shards, the first logger initialization is from main.js where i set up all the shards and it still doesnt log debugs
can anyone help me with adding a raid-protection into my moderation bot?
how should i detect raids? how does other bots does this?
we have 2 server where 300+ users joining since 5 days, newly created accounts
Generally, the built-in stuff in discord is pretty robust, including the settings to require verified email, etc. Otherwise, you'd need to tailor it based on what you want to filter, such as by account age
Heya, can I get a user's tag? clan tag thing
Not yet, will be in the next release
bots like wick and beemo have their own algorithms that filter raid accounts. you'll have to write your own
[2025-08-14 23:47:30] TypeError: The "options.env" property must be of type object or one of undefined, null, or worker_threads.SHARE_ENV. Received type symbol (Symbol(nodejs.worker_threads.SHARE_ENV))
at Worker (unknown)
at new Worker (node:worker_threads:155:35)
at spawn (/home/container/node_modules/discord.js/src/sharding/Shard.js:141:27)
at spawn (/home/container/node_modules/discord.js/src/sharding/Shard.js:123:15)
at spawn (/home/container/node_modules/discord.js/src/sharding/ShardingManager.js:227:27)
at processTicksAndRejections (native:7:39)``` what could be causing this error?
does this happen when your bots starts up? or randomly? can u show the options you set for sharding pls
when my bot starts,
const client = path.resolve(__dirname, './client.ts');
const manager = new ShardingManager(client, {
mode: 'process',
token: TOKEN,
respawn: true,
});``` im using bun but that shouldn't be the problem cause if i run it locally it works just fine
what's that TOKEN you're passing?
is it smth like
const TOKEN = options.env.TOKEN
?
if yes, seems like .env isn't an object
export const TOKEN = Env.Required('token').ToString();
https://gitlab.com/mloetta/Komono/-/blob/main/src/libs/env.ts?ref_type=heads heres how the env lib is
not a djs issue then it seems.
pls use #1081585952654360687
will try to fix it there
ah sure
Was the import or type Interaction removed? It tells me that there isnt such expor for Interaction
If you are looking for the parent class of all interactions, it’s now BaseInteraction
Oh ok
ForumChannel#setAvailableTags() discord.js@14.21.0
Sets the available tags for this forum channel
Yo, is there a way to know if a user was moved by someone or if they moved themselves (voice channel)?
you can check audit logs
which is at best a correlation, move audits just have the number of members moved, iirc
is there some convenient way of editing replies to interactions without keeping interactions in memory somewhere? I'm sending an ephemeral reply that I later want to edit when a button inside the ephemeral reply is pressed, but editing it as a message does not work, and I'm not sure how I'd get access to the interaction object again...
each button press is its own interaction and specifically buttons and select menus have the "update" response type that will update the message the button or menu is on
I see, thanks!
as per usual you have to respond within 3 seconds or 15 minutes* after defer (there is also a deferred update variant)
👍
i have invited beemo after 2 days, he's ignoring these accounts for 3 days now
You'd have to ask their support
Hi,
On a non-string select menu with a default value and a submit button, how to distinguish between the user not editing the value and the user removing the value ?
Thanks
if the user doesn't edit it then you won't receive a select menu interaction
Yes, but if the user clicks the X mark to remove the value, I also don't receive a select menu interaction
execute: async (client, interaction, subId, page) => {
if (!interaction?.message || !subId || !page) return interaction.reply({
embeds: [newEmbed().setDescription(`This button is not ready to be clicked.`)],
flags: MessageFlags.Ephemeral,
});
interaction.showModal(
new ModalBuilder()
.setCustomId(`dashboard_add_confirm:${interaction.user.id}:${subId}:${page}`)
.setTitle(`Add ${page.charAt(0).toUpperCase() + page.slice(1)}`)
.addComponents(
new ActionRowBuilder().addComponents(
new TextInputBuilder()
.setCustomId(`title`)
.setRequired(true)
.setMaxLength(100)
.setStyle(TextInputStyle.Short),
),
new ActionRowBuilder().addComponents(
new TextInputBuilder()
.setCustomId(`content`)
.setRequired(true)
.setMaxLength(2000)
.setStyle(TextInputStyle.Paragraph),
),
),
);
},
why might this be producing the error "ValidationError: Expected a string primitive"?
have you set the min values to 0?
your text inputs are missing labels
Oops, thanks !
oh lmao 😭
why does discord.js not actually specify what field or whatever is wrong in the error message 😭
it should but it's kinda hard to read
builders v2 uses zod v4 which supports better error formatting
but since builders v2 is breaking it won't be used in djs until v15
I see
How many rows can a V2 message have ?
Thanks
the only component amount limit is 40 components per message
either top level or nested
Alright, thanks !
What version is MessageFlags.IsComponentsV2 added in?
14.19.0 as per #announcements but it's recommended to use latest
or at the very least 14.19.3 which has a couple of fixes for that release
When creating a voice channel, will the "topic" option set the "channel status" or does "topic" only work for text channels which is their channel descriptions?
Given how setting status is undocumented, serious doubt topic will set it
Especially as the status also isn't valid at the time of creation but when someone in it sets it, and is a status not a topic
And setting it has a separate endpoint to do it
Right Click (Desktop) / Long Press (Mobile) > Apps > some command
How do i make those command?
Other Interactions: Context Menus
read more
How would I get the last message sent in a channel by my bot or should I just save it in a variable?'
Hello does someone know how can i embed to html to have the same as how discord show embed
you'll want to store it yourself
so just a let variable on top of the listener?
are you asking how to design a webpage component to look like a discord embed?
if so, that's not something you'd use the discord api for, much less discord.js, so this would be better suited elsewhere
#1081585952654360687 / #useful-servers
how you store it is really up to you
if storing in memory is enough for your use case, then sure
all I want to do is put like a post it note that is always the last message in the channel
so everytime someone sends a message, old one gets deleted, new one gets sent
then assuming you don't want it to break when your bot restarts, it sounds like you'll want something more persistent than a variable
that being said, you'll want to keep in mind "stickied message" features always have the potential to be incredibly spammy on the api and encounter rate limits, especially depending on the activity in the channel
Yeah thats the other thing I was going to ask
how would I avoid hitting rate limits and because of that the system breaking?
avoid them completely without affecting the feature and regardless of channel activity?
you don't
such a feature is not possible to make reliably though
I want to do it as reliably as possible
by the time your message arrives, another one could've been sent
What if
I'd make a debouncer so it only actually works some seconds after the last message received
I wait a little when a message is sent to see if another one is sent and repeat that process until a message hasnt been sent for a bit
yeah that's a debouncer
few seconds maybe
Honestly, I would CRON it. Run every 10 minutes and check if bot authored last message.
nice, the guy who asked me to do it only now just randomly said nvm
I am running 14.21.0 and still get this
and from where are you importing MessageFlags?
and ^^ (though the fixes are unrelated to your issue)
can you npm ls discord-api-types
│ └── discord-api-types@0.37.93 overridden
├─┬ @discordjs/voice@0.18.0
│ └── discord-api-types@0.37.93 deduped
└─┬ discord.js@14.21.0
├─┬ @discordjs/builders@1.11.3
│ └── discord-api-types@0.37.93 deduped
├─┬ @discordjs/formatters@0.6.1
│ └── discord-api-types@0.37.93 deduped
├─┬ @discordjs/ws@1.2.3
│ └── discord-api-types@0.37.93 deduped
└── discord-api-types@0.37.93 deduped```
is there a way to better do what the discord.js guide base code does and in a more professional way cause I have just been using that for my base code for a while
Forgot i had a override there - it was the issue
what the discord.js guide base code does
what base code? there's multiple code examples
to better do (...) in a more professional way
why? are you having issues?
cause I have just been using that for my base code for a while
and what's the problem with that?
can someone help me my bot wouldnt come online
- just the base index.js
- no, just figured it be better to make it myself in a better looking, more professional way
- nothing, just thought it'd be more professional to make it better and custom
Any errors?
in the code no
in the terminal
i tried nodemon and it crashed
please read #how-to-get-help, we need more details than just that
and what would be better looking or more professional? are you looking for a framework?
nevermind, ill just keep using the base code
show your code
also not a discord.js issue
ik but i dont know where should i o
Yeah that but I'll help him fix it and if he has more issues he can go elsewhere
do you know javascript? it looks like you just copied and pasted non sensical code
^
i js know the basics i tried following a tutorial and failed so i copied it
srry im in high school
you need to learn javascript before using a library like discord.js
the guide has some resources you can use to learn js more in-depth
there's also a few in #resources
I have a server focused on more JS help if you'd like an invite
gimme
Can I send him an invite to speakJS without getting banned for DM advertising?
thanks to all of u
you could just ask first if they're interested, though I'm not a mod
i am intressted
sent
one q in the Subcommands cant i make it one command instead it of its creating 2 commands? like if the user choose custom it shows options for the customs only but for default it shows another strings?
can I get a user bio with djs ?
no
ah
that's how it already behaves though? both have different options
discord doesn't allow it, it's not a djs limitation
i see
ContainerBuilder#setAccentColor() discord.js@14.21.0
Sets the accent color of this container.
this only works with the number right not like the emebd builder
Is it possible to know how many boosts a user gave on a server? 1 or 2?
I’m surprised it doesn’t accept ColorResolvable
the type signature doesn’t have that. At least
correct
resolveColor discord.js@14.21.0
Resolves a ColorResolvable into a color number.
aw darn
you can use this if you want a string
in case it's user input or something
oh i did some parseint stuff
if it's a hardcoded value I'd just use the number
yeah that's basically what that does
do u think in the future it will be like embeds
you can click the discord.js@14.21.0 to go to the source code
probably not, since djs has moved away from extending builders classes from @discordjs/builders in discord.js (they're two different packages), and that "string color resolution" only worked like that, the base EmbedBuilder in /builders has never accepted strings
i see alright. just thought it made working with colors a heck of a lot easier but it isn't too much trouble to write your own parser
checked the code it's basically the same thing im' doing so
yeah and djs also provides one which I don't think will be removed
oh right i can just call it and pass it in anyways
yeah setColor(resolveColor(...))
^^
@outer plume since you commented on it, that's the reason why
no, you only get when they started boosting (premiumSince)
The Discord API does not provide a dedicated event for guild boosts, but you can check for it in the guildMemberUpdate event:
client.on("guildMemberUpdate", (oldMember, newMember) => {
// Check if the member wasn't boosting before, but is now.
if (!oldMember.premiumSince && newMember.premiumSince) {
// Member started boosting.
}
});
and that event for detecting when it starts
Ooo: thanks for the ping 
is it possible to escape backticks inside of an inline code block?
it isn't as far as I'm aware but that isn't djs related
\ `

where should I ask it?
Do shard IDs start from 0 or 1 or are they Discord-like IDs?
0
Thanks.
Hi there!
Does someone know why is this event: GuildAuditLogEntryCreate is not working?
import { AuditLogEvent, Events } from 'discord.js';
export default {
name: Events.GuildAuditLogEntryCreate,
async execute(interaction) {
console.log(interaction);
}
};
I tried it to test: creating and deleting a channel, a message and a role. And no one has execute log and nothing. I have a switch later but it does not matter because it does not execute log neither.
I attach bot permissions.
Those are permissions of the default invite, not the bot
People inviting the bot might uncheck the boxes, or even be unable to check them in the first place
I am the only one using it in a test server. BTW where should I check It then? Because audit log is not working. And the bot has those rights on the server
Do you have the GuildModeration intent?
SyntaxError: Unexpected end of JSON input
at <parse> (:0)
at json (unknown)
at parseResponse (/home/container/node_modules/@discordjs/rest/dist/index.js:264:30)
at processTicksAndRejections (native:7:39)
I have this in console, I have no idea why and where and when it happened, any ideas what is it?
Do you use a rest proxy?
? im using discord.js
Yes. I know that. I was asking about your configuration. Show your client constructor if you're unsure
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
],
partials: [
Partials.Channel,
Partials.Message,
Partials.User,
Partials.GuildMember,
Partials.Reaction,
],
presence: {
status: "dnd",
activities: [
{
type: ActivityType.Watching,
name: "/dating",
},
],
},
just this
bot usually worked fine and then this just happened randomly
That error means that a response from discord wasn't valid JSON although having a 200 status code.
so is it issue on my end or
I don't have enough information to tell you that. I told you what I can from what you showed
#697138785317814292 message
can it be this
that's entirely unrelated
i was js curious
because i can't debug this error ^^^
no way of knowing how or where it happens
does it happen frequently?
i think this is first time it happened
but it logged that error 10-15 times in a row
are you hosting it on a vps or?
dedicated server
do you have any kind of proxy setup?
i mean its normal
normal installation of server
as i said it worked perfectly before
Where do I configure It?
const channel = await client.channels.fetch(channelId);
if (!channel || !channel.isSendable())
return interaction.reply({ embeds: [badChannel] });
const message = await channel.messages.fetch(messageId);
message.edit({embeds: []})
So, I have to make a round trip three times and use the rate limit from a bucket just to edit a message…
I already know the messageId and channelId. Can't I just request to edit it directly, without the object overhead?

oh sh*t, I do need to fetch message.
i am using message as a database, to cut a bit of storage 🌹
are you hosting on an arduino nano so you have no ram and no storage
also I'm pretty sure using discord as storage is against the dev tos
64mb ram and 1gb storage 😊
I just need to update a few fields in the embed when the command is invoked. I grab the last message, modify the relevant fields based on the previous fields data, and then build a new embed to edit the message.
I am really really low of storage, and a bit of cut is fine
I don't know, I have a production bot with lots of caches and it uses around 50 mbs, its db is around 3 mbs
if you're storing text it's really compresable
1 gb should be more than enough for most bots
hi
I have a slash command that accepts an attachment as an argument, but I can't find a way to access the full name of that attachment
the original name contains Korean characters, but the attachment object doesn't
when I try to download this file via the attachment link, I get a file named «69.zip»
{
attachment: Attachment {
attachment: "https://cdn.discordapp.com/ephemeral-attachments/.../69.zip?...",
name: "69.zip",
size: 9032489,
url: "https://cdn.discordapp.com/ephemeral-attachments/.../69.zip?...",
...
},
}
however, if I send the file in a chat and download it from there, the file name «살아남은 왕녀의 웃음 뒤에는_69화.zip» remains. even though the link to the file in the chat also does not contain these Korean characters.
so how does the discord app know which file name to use when downloading the file locally, and is it possible to restore the original file name (before removing non-ascii and other prohibited characters)?
Hi, just looking at the documentation, is there any way to see whether a guild has an entitlement from events such as messageCreate?
For example, a way to check from a guild which entitlements it has (there is no Guild.entitlements or anything from what I can see)
Well, specifically is there a way to achieve this without using the entitlement events I suppose or will I need to go down that route :P
I believe entitlement is only sent with interactions. You can fetch the entitlements for your application and check if there is any for the particular guild
EntitlementManager#fetch() discord.js@14.21.0
Fetches entitlements for this application
Just seen ClientApplication.entitlements, what is the cache populated by? Do you happen to know whether this would be populated by the time the bot is ready (ie before an interaction has been sent in that guild)
Ah this wouldn't work, nor would ClientApplication.subscriptions I dont think
It would be added as it is recieved, whether it was fetched or recieved from an event
Okay, so the recommended way to implement this would be listening to the entitlementCreate and entitlementUpdate events (for any bot that also uses other events)
What is your goal?maybe I can help you better that way.
Just trying to add subscriptions to my bot to be compliant with the monetization terms. The bot has some features tied to other events (for example presence update) which should only work if they have a subscription. I need to be able to check whether they have a guild subscription from that event (in this example from a presence update event)
Just to be sure, you want to check subscription or entitlement? Because those two are different things
What's the difference? Sorry I am clearly uninformed here, I just want to know whether there is an active subscription to my application for that guild
Ah subscriptions is a subscription to the guild. Sorry for the confusion, I am referring to entitlements.
Sorry, where do I do that?
in your client constructor where you do new Client
Ah thanks, I Will check It 😼
quick question can u send component v2 in the dms
sure
there's no restrictions for dm messages
alr thx
it worked, thanks!
Now, I have this in a separated file:
import translate from '../translation/es.js';
import interpolate from '../auxiliar/interpolate.js';
import logEmbed from '../auxiliar/embeds.js';
import { AuditLogEvent, Events } from 'discord.js';
export default {
name: Events.GuildAuditLogEntryCreate,
async execute(auditLog) {
console.log(auditLog);
const { action, extra: channel, executorId, targetId } = auditLog;
const executor = await client.users.fetch(executorId);
const target = await client.users.fetch(targetId);
let message;
switch (action) {
case AuditLogEvent.MessageDelete:
message = interpolate(translate.events.GuildAuditLogEntryCreate.messageDeleted, { target: target.tag, executor: executor.tag, channel: channel });
logEmbed.description = message;
logEmbed.fields[0].value = executor.id;
break;
case AuditLogEvent.MemberKick:
message = interpolate(translate.events.GuildAuditLogEntryCreate.userKicked, { target: target.tag, executor: executor.tag});
logEmbed.description = message;
logEmbed.fields[0].value = executor.id;
break;
}
await channel.send({ embeds: [logEmbed] });
}
};
2n question: how do I import client from index.js (following https://discordjs.guide that guide).
3rd question: I have not tried "channel.send" but, how do I configure in which channel do I send the message?
Then you can just fetch the entitlements on ready, and with entitlement intents, the cache will be updated with the respective event and you can just query the cache for the guilds entitlement
you can import client through your event handler, by simply passing your client as argument: event.execute(...args, client) and then you can use async execute(auditLog, client) { as well in your event execute function
You don't import client at all. It's a property on the parameters of your event
(event) Client#guildAuditLogEntryCreate discord.js@14.21.0
Emitted whenever a guild audit log entry is created.
The second parameter is a Guild, which has a .client property you can use
And to your third question: client.channels.cache.get(channelId) and you get the channel you want
The collection of Client.applications.entitlements.cache is keyed by what?
To achieve the ability to get the entitlements of a guild would you have to filter / find in that collection?
Entitlement id
Yes
oh okay
Okay one more question, if you fetch will it only return active entitlements (non expired ones)
EntitlementManager#fetch() discord.js@14.21.0
Fetches entitlements for this application
FetchEntitlementsOptions discord.js@14.21.0
Options used to fetch entitlements
You can fetch by guild id etc.
And also decide what to exclude
Thanks :)
Hey there ✌️
I'm having weird errors today and Discord seem super laggy...
Everything was fine for months and we didn't push any changes into production... 
I'm having a lot of those DOMException [AbortError]: This operation was aborted at new DOMException (node:internal/per_context/domexception:53:5) at AbortController.abort (node:internal/abort_controller:391:18) at Timeout.<anonymous> (/home/Bots/ArtyBot/node_modules/@discordjs/rest/dist/index.js:680:47) at listOnTimeout (node:internal/timers:581:17) at process.processTimers (node:internal/timers:519:7)
Version 14.15.2
Anyone with the same errs ?
what is the entitlement intent? cant see on GatewayIntentBits
thanks @worthy drift and @steel trail 🙂 I will come back
With official troller answer, it gets the console.log but not with Qjuh one... or I implemented it wrong 🙂
None, you always get those events
Okay thanks I believe I misunderstood his/her/their earlier message
thats a really old version. try updating to 14.21.0 to see if that resolves
Sorry, that was my bad. I misremembered
no worries :)
Can't right now because of the new components system... 
there aren't breaking changes with that
There are breaking type changes
How do I edit a message component (V2) from a modal interaction? According to TS I cant do .update on the modal interaction
Is there any way to know how many boosts a user has given in a server?
documentation suggestion for @queen vale:
ModalSubmitInteraction#isFromMessage() discord.js@14.21.0
Whether this is from a MessageComponentInteraction.
Thanks!
I've never used node.js before (I've made a button for a website, that's about it). Figured a bot would be a cool way to learn how to use JS. I'm completely unable to install, or remove discord.js because a dependency that discord.js does actually have. I'm very confused
it says it added it successfully though?
So I can disregard the error?
it's only notifying you about the possible security vulnerabilities, which are on code that djs doesn't use
Mootools? Doesn’t npm install <> also install packages which aren’t installed but in the package.jsom?
I'm just doing a global install if that matters
installing globally generally isn't a good idea unless it's a cli tool
okay yeah, I'm not sure what you installed but that isn't djs
looks like you installed a package called "discord"
thought it was another "vulnerability" djs does have in one of its dependencies, which comes from code djs doesn't use at all
Would you happen to have a link to instructions to set up a proper environment then?
My Google is being absolutely useless and refusing to give me any source that says more than "install node.js"
What’s the issue
tbf you really just need discord.js, nothing else
but if you want a guide there's an official one
start a post in #1081585952654360687 i'll help you with basics and setup
nvm, it seems that you already have node set up. djs guide is good. and check #resources for learning how to use js
Skill. I've never used JS before and decided a discord bot would be a good option to learn
Thanks
-# Will in a bit. Need groceries
oh. you're on windows. uhhhhh. i can try to help then i guess
I'd recommend just following the guide if you're really stuck, it should help with most of the stuff
but it does assume you already have some level of understanding of js and node
he needs help setting up node. djs is out of the question for now...
from their questions I understood they already have node, given npm works
they're asking how to setup an environment for djs
shi you're right
i wonder where that "discord" lib came from when they typed "discord.js"
that is how I learned how to use js/ts. so yes, it's a good idea.
I updated my message #djs-help-v14 message
Hi,
Can a slash command be directly replied with a modal ?
Thanks
sure
ChatInputCommandInteraction#showModal() discord.js@14.21.0
Shows a modal component
not really help but a question, but what is the type of interaction?
async execute(interaction) {
// interaction.guild is the object representing the Guild in which the command was run
await interaction.reply(`This server is ${interaction.guild.name} and has${interaction.guild.memberCount}members.`);
},
can be any?
oh yeah i forgot to mention i was using typescript
Can't answer that without knowing what handling you're doing before this
https://discord.js.org/docs/packages/discord.js/14.21.0/ModalBuilder:Class
https://discord.js.org/docs/packages/discord.js/14.21.0/ButtonBuilder:Class
where do i find the documentation of this class where i can see the supported methods? the only thing shown is .from
sorry, but what kind of handling?
Where is this execute function being called?
Under the dropdown on the left-hand side, select builders instead of discord.js
Then look for the same classes
bruh, lol thank you man
its a normal slash command builder using the handling from the discord.js guide website, i just converted some of the code to be typescript compatible
import { SlashCommandBuilder } from 'discord.js';
module.exports = {
data: new SlashCommandBuilder()
.setName('server')
.setDescription('Provides information about the server.'),
async execute(interaction) {
// interaction.guild is the object representing the Guild in which the command was run
await interaction.reply(`This server is ${interaction.guild.name} and has ${interaction.guild.memberCount} members.`);
},
};
ChatInputCommandInteraction then
oh ok thanks
I'd recommend making a generic Command type to let you type your exports object
is there something like you can associate some data with a button? like a user's email so i know who clicked the button in a button interaction event?
interaction.user.id tells you who clicked the button in a ButtonInteraction event
you're supossed to add some kind of id in the customId and then store data like that in your own database
i know that, i meant custom data
or the user id yeah since that'd make more sense for an email
customId is a thing to identify the button tho? so in the event i would listen for the customId
the only data you can append is the customId, but it's not big enough to store much data, and you shouldn't store anything sensitive either, it's not a secret
Cool. It should be pretty easy, I already have experience with the discord API.
-# Gonna go create discord.asm
yes, i understand. i think for such things interaction event is not useful
for an email it'd make much more sense to have in your db a relation from the user's id to their email
i would need to use the other way which has timeout so i can know the context of where this button was clicked
consider this:
you are asking user to verify so he clicks a button but in case of an interaction event i would know what the user's details are to link to his discord id
yeah, it should be fine to implement with the approach I said
you extract the user id like TAEMBO said, query your db to get the details and you're done
should defer before querying given the response overall may take longer than expected
got it, another question theres no way to accept images in the modal?
the only thing you'd need to store in the customId would be whether it's the reject or confirm button, and the "confirmation session" id maybe (though not if you use collectors)
then how would i listen for the button interaction with a random id
quick question theres no way to accept images in the modal?
you can only listen to interactions overall, you don't listen to interactions with a single id
there isn't
currently modals only support text inputs, and select menus in the future
to respond to the interaction.isButton i need to know which button was clicked and i do that with id == "do this", right? so this would fail in case the custom id is not known
well you can do anything you want with the customId
you can split it, you can check if it starts with something, you can serialize it...
ah
you know how your customIds look like so you'll know how to handle it
yep. makes sense
I'm not experienced with interaction at all and its shown can someone please assist me without having a closed answer, explain what i did wrong please
https://sourceb.in/eHUB1rqOGq
tag suggestion for @untold locust:
DiscordAPIError: Interaction has already been acknowledged[InteractionAlreadyReplied]: The reply to this interaction has already been sent or deferred.
You have already replied to the interaction.
- Use
<Interaction>.followUp()to send a new message - If you deferred reply it's better to use
<Interaction>.editReply() - Responding to slash commands / message components
Is something else also handling this slash command?
Can you add console.logs before each usage of interaction.reply to see where it errors?
Line 105 and 111 based on your errors
hi, sorry, maybe not djs related
i have a type for slash command:
import type { SlashCommandBuilder } from "discord.js"
type Command = {
data: SlashCommandBuilder,
execute: (...args: any[]) => void
}
but when trying to create a command, getting this typescript error:
but without addStringOption it works fine
you can use SlashCommandOptionsOnlyBuilder | SlashCommandSubcommandsOnlyBuilder
because the SlashCommandBuilder gets narrowed down to one of the two depending on whether you have "normal" options or subcommands
oh thanks
and all three are mutually exclusive: if you add options it'll turn into SlashCommandOptionsOnlyBuilder which isn't assignable to SlashCommandBuilder, which is your issue
I'm trying to register commands with my discord bot and for some reason they aren't registering. I've waited hours - restarted my client - restarted my bot - checked on my phone... nothing I do gets them to register.
This is my command I am running to register them...
require('dotenv').config();
const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const bot = require('../config/bot.json');
module.exports = {
name: 'createcommands',
execute(message) {
const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_TOKEN);
(async () => {
try {
// Convert Map to array of command objects
const slashCommands = [];
if (message.client.slashCommands) {
message.client.slashCommands.forEach((cmd) => {
let object = {};
if (cmd.name) object.name = cmd.name;
if (cmd.description) object.description = cmd.description;
if (cmd.options) object.options = cmd.options;
slashCommands.push(object);
});
}
console.log(`Registering ${slashCommands.length} slash commands...`);
// Create guild commands
const result = await rest.put(
Routes.applicationGuildCommands(bot.id, bot.serverId),
{ body: slashCommands },
);
// Create global commands
const globalResult = await rest.put(
Routes.applicationCommands(bot.id),
{ body: slashCommands },
);
console.log(`Successfully registered ${result.length} guild commands!`);
console.log(`Successfully registered ${globalResult.length} global commands!`);
message.reply(`Successfully created ${result.length} slash commands!`);
} catch (error) {
console.error('Command registration error:', error);
message.react('❌');
message.reply({content: `There was an error: ${error.message}`});
}
})();
message.reply({content: 'Created the commands!'});
}
}
Is there something wrong with this command?
why are you registering both in the guild and globally? that'll just cause duplicates
choose one or the other, not both
Okay, I only need this in one server so I will do the guild commands
apart from that I think it looks fine, after you choose one, log its data and show its output
I was having issues with guild commands registering so I was trying to get them to register at all
make sure to delete the global commands
If you have duplicate commands on your server, you registered both global and guild commands.
You can remove the duplicates by resetting either the global or guild commands
- Resetting global commands:
rest.put(Routes.applicationCommands(clientId), { body: [] }) - Resetting guild commands:
rest.put(Routes.applicationGuildCommands(clientId, guildId), { body: [] })
I will. Already have a command for that. I logged everything and no errors - they just don't register.
modify it so it only has one or the other and show that code
and also log the data you receive (result or globalResult)
require('dotenv').config();
const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const bot = require('../config/bot.json');
module.exports = {
name: 'createcommands',
aliases: ['startslash', 'create-commands'],
description: 'Allows Erin to create the Slash Commands.',
execute(message) {
const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_TOKEN);
(async () => {
try {
// Convert Map to array of command objects
const slashCommands = [];
if (message.client.slashCommands) {
message.client.slashCommands.forEach((cmd) => {
let object = {};
if (cmd.name) object.name = cmd.name;
if (cmd.description) object.description = cmd.description;
if (cmd.options) object.options = cmd.options;
slashCommands.push(object);
});
}
console.log(`Registering ${slashCommands.length} slash commands...`);
// Create guild commands
const result = await rest.put(
Routes.applicationGuildCommands(bot.id, bot.serverId),
{ body: slashCommands },
);
console.log(`Successfully registered ${result.length} guild commands!`);
message.reply(`Successfully created ${result.length} slash commands!`);
} catch (error) {
console.error('Command registration error:', error);
message.react('❌');
message.reply({content: `There was an error: ${error.message}`});
}
})();
message.reply({content: 'Created the commands!'});
}
}
|-----------------------------------|
Logging In...
|-----------------------------------|
Erin's Helper Bot#1301 is
logged in and ready!
|-----------------------------------|
Error Logs...
|-----------------------------------|
Bot is ready! Loaded 74 slash commands.
|-----------------------------------|
Slash commands loaded successfully
|-----------------------------------|
✅ 74 slash commands ready for registration
💡 Use "++createcommands" in Discord to register all commands
🎯 Commands will be available after registration
Registering 74 slash commands...
Registering 74 slash commands...
It stops at the first log
sounds like you're ratelimited then
can confirm by logging on the rateLimited event: client.rest.on('rateLimited', console.log)
iirc the limit is 100 daily commands
you have 74 so you shouldn't be able to register all of them twice per day
When does the day reset?
I have an issue: I can only change the channel name once. If I try to change it again, the name doesn’t update, and I don’t get any error — really strange.
const newName = `closed-${channel.name}`;
//await channel.setName(newName);
let ch = interaction.guild.channels.cache.get(channel.id)
console.log(ch)
ch.setName(newName).then(() => console.log('done')).catch(() => console.error);
ddevs (#useful-servers) would be a better place to ask, I'm not even sure if all of them count if you changed only 1's data for example
channel name edits are heavily ratelimited, you may not be able to edit one's name after a while
^^
Hm... I moved it to my ready event (cause I was planning to anyway) and I'm not seeing anything about the rate limiting.
config stuff
module.exports = { ...
const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_TOKEN);
(async () => {
try {
// Convert Map to array of command objects
const slashCommands = [];
if (client.slashCommands) {
client.slashCommands.forEach((cmd) => {
let object = {};
if (cmd.name) object.name = cmd.name;
if (cmd.description) object.description = cmd.description;
if (cmd.options) object.options = cmd.options;
slashCommands.push(object);
});
}
console.log(`Registering ${slashCommands.length} slash commands...`);
// Create guild commands
const result = await rest.put(
Routes.applicationGuildCommands(bot.id, bot.serverId),
{ body: slashCommands },
);
console.log(` Am I rate limited?`); // i see this
client.rest.on('rateLimited', console.log); // but not this
console.log(`Successfully registered ${result.length} guild commands!`);
} catch (error) {
console.error('Command registration error:', error);
}
})();
...
Entire console... Actually I'm not seeing either of those now...
if you see the "Am I rate limited" then that's not consistent with what you had before
thank you ❤️
also if you are ratelimited then that rest.on line will never reach
or well, not when you want to
it would be reached after it has expired, which is not what you want
If it doesn't reach - wouldn't that stop the load in its tracks and I wouldn't see the successful log after it?
^^ before it only logged "Registering slash commands", which suggests it stopped before the rest.put
if you see "Am I rate limited" then it's now proceeding after that, maybe you aren't ratelimited anymore
Is there a way for me to know if it’s a rate limit, or do I just have to assume it and handle it with a cooldown?
@rose tangle
and you shouldn't deploy on start anyways, just do it when you actually change commands
you have 74, it sounds like you're well past the dev stage where you needed to deploy constantly
otherwise if you get ratelimited it may block your bot from fully starting (since the promise won't resolve)
you can make another promise that will resolve in a given time and Promise.race both to see which finishes first (should be longer than your rest timeout, which is 15s default), or you can configure your Client to make it reject the promise instead of waiting, so you can try {} catch {} it
RESTOptions#rejectOnRateLimit discord.js@14.21.0
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
new Client({ ..., rest: { rejectOnRateLimit: ... }});
Thanks man, appreciate it
I figured it out - I am not rate limited. I got rate limited for a minute but I ran the command again (cause you were right - it shouldn't be in my ready event so I went back to having a command) and I'm not rate limited - it just never logs after creating the commands.
config stuff
module.exports = {
name: 'createcommands',
aliases: ['startslash', 'create-commands', 'cc'],
execute(message, client) {
const rest = new REST({ version: '10' }).setToken(token);
(async () => {
try {
// Convert Map to array of command objects
const slashCommands = [];
if (message.client.slashCommands) {
message.client.slashCommands.forEach((cmd) => {
let object = {};
if (cmd.name) object.name = cmd.name;
if (cmd.description) object.description = cmd.description;
if (cmd.options) object.options = cmd.options;
slashCommands.push(object);
});
}
console.log(`Registering ${slashCommands.length} slash commands...`);
// Create guild commands with automatic retry handling
const result = await rest.put(
Routes.applicationGuildCommands(bot.id, bot.serverId),
{ body: slashCommands },
);
console.log(`✅ Successfully registered ${result.length} guild commands!`);
message.reply(`✅ Successfully created ${result.length} slash commands!`)
} catch (error) {
console.error('Command registration error:', error);
message.react('❌');
message.reply({content: `There was an error: ${error.message}`});
}
})();
message.reply({content: 'Created the commands!'});
}
}
if it isn't ratelimited then it should log the successful message
console.log will never error
if it doesn't log it then it really sounds like you are ratelimited, that's how it'd behave
the request would be queued to run only after the ratelimit expires, and only then the promise will resolve
Does that mean I'll get rate limited again whenever it rolls over?
Cause I can't see how long the rate limit is. Nothing logs
where did you place your rateLimited listener?
oops - it got lost - okay now it is logging the rate limit
Thanks! At least now I know what is going on.
So, I have a question, Basically every time that I make this report command run, It spits out an error message, Which I will show, And it makes 3 copies of the same command, What do I do?
I used AI btw 😭
- Error means you're taking too long to respond to the interaction. Defer the reply if you're going to do things like send a message before responding.
- Duplicate messages might be because you have multiple instances of the bot running. Check your console windows.
the error can also be caused by multiple things trying to respond to the interaction, so I'd definitely focus on the latter issue
especially since the error points towards deferReply being called somewhere
I am using PM2 as a server hoster, Could that be why there could be multiple operations?
It also seems that the image I try to send through the bot does not work
"Not work" how?
So, everytime I put the image file into the query, It just doesn't show up
How are you trying to send it?
this is more of an #1081585952654360687 but that does seem right
if you run pm2 ls it should show a list of all the processes its managing (which would explain the unknown interaction errors)
tag suggestion for @lilac basin:
Common causes of DiscordAPIError[10062]: Unknown interaction:
- Initial response took more than 3 seconds ➞ defer the response *.
- Wrong interaction object inside a collector.
- Two processes handling the same command (the first consumes the interaction, so it won't be valid for the other instance)
* Note: you cannot defer modal or autocomplete value responses
Two processes handling the same command
I'm wondering, does anyone know how long an attachment link/url will work when using a slash command? Normally when uploading files discord hosts them indefinitely, but I'm not quite sure whether that's the case for attachments in slash commands
7 days iirc
Alright thank you 🙏
Would you say it's viable/reasonable to instantly make my bot reupload and save the url of its own reupload for longer access?
you should use an actual cdn or have the files locally and upload them when needed
What do you mean exactly with "should" here? I was kinda hoping discord could handle it for me, would simplify things lol
attachments haven't always expired, that's a relatively recent change
Well yeah but that's only for ephemeral or slash command ones, no?
people used discord as a cdn, like for bots or other stuff, so they wanted to avoid that and introduced expiration
Like I can still view random images from many years ago.. so I don't see anything like expiration?
ephemeral attachments last much less yeah but it's not only for those cases
the client has a token it uses to refresh the url
the images exist, only the urls stop working
Dym expiration of access rather than removal of the file?
something like that, you still have access, just the url isn't valid anymore
Yeah okay that's expected
I mean I should be able to refetch it if I have the message id, no?
yeah if you fetch it you get a valid one, the point is mostly to avoid hardcoding urls and making it harder to use discord as a cdn
fair, it's not much harder but yeah
it's still easier than setting up a separate cdn (even if it fits within free tier) 😭 (in the case that the attachments go via discord anyway)
you could just save the images locally and upload
or whatever file you have
meh tbh that's messy as hell
though I'm thinking of something, if I enable usage of the command in DM only, and make the user upload the image separately, I should also jsut be able to forward it, no?
shouldn't need more than 5 extra lines
oh no I mean it's locally messy, not in terms of code, and it will clash with selfhosting systems like coolify
not sure, better ask ddevs for that #useful-servers
o
thanks for the help 🙏
Hello,
with GuildAuditLogEntryCreate on AuditLogEvent.MessageDelete action, how do I get the channel and the original message that has been deleted?
I tried this for the channel:
const { action, extra: channel, executorId, reason, targetId, changes } = auditLog;```
as it is suggested on the guide but it does not work. It throws ```[object object]```
don't stringify that and it wil indeed be an object
you won't get the content from either, as the content is gone at that point in time and the event just provides the channel and message id so the subscribed client can clean up and evict that data fro memory
so unless the message was cached before (in the same session), you are out of luck
thanks you!
this event: MessageDelete and GuildAuditLogEntryCreate with AuditLogEvent.MessageDelete are not the same, right?
Should I make a specific event for messageDelete to get what I want?
I fixed my problem with both events and with chatGPT, thanks for your help souji 🙂
Hello, I have a small discord app that sends different text based emotes like: ᯠ_ ̫_ᯄ੭ by doing a slash command like /catsighflat
I have been able to make this work in any server even if the bot isn't there, but I would like for this to also work in private DMs.
What is the thing that I would need to change? I already gave the intent for private messages ts const client = new Client({ intents: [ GatewayIntentBits.DirectMessages, GatewayIntentBits.DirectMessageTyping, GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, ], });
And added the dm_permission: true to the command body, any other thing I need to add for it to work on private messages?
This is the way I am registering the commands:
try {
console.log('Started refreshing application (/) commands.');
await rest.put(Routes.applicationCommands("CLIENT_ID"), { body: commands });
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}```
And this is the way I am listening for interactions:
```ts client.on(Events.InteractionCreate, async interaction => {
if (!interaction.isChatInputCommand()) return;
if (interaction.commandName === 'catsigh') {
await interaction.reply('/ᐠ - ˕ -マ Ⳋ');
}}```
For each one of the commands
where you can use the command is part of contexts and not shown here (it needs to be in the command itself)
#setContexts if using builders
{
name: 'catsigh',
description: '/ᐠ - ˕ -マ Ⳋ',
dm_permission: true
}, ``` You mean the body for the commands I suppose like this?
yes, contexts
Application Commands - Contexts
read more
https://discord.js.org/docs/packages/discord.js/14.21.0/InteractionContextType:Enum being the enum you can import
(i'd recommend that over just using random numbers, so you still know what means what lateron)
dm_permission has been deprecated, contexts should be used instead as linked by souji
So the equivalent would be?: ts const commands = [ { name: 'catsigh', description: '/ᐠ - ˕ -マ Ⳋ', InteractionContextType: 2 },
no, InteractionContextType is not a property of a application command object
I recommended that you use the builder
it would be more like contexts: [InteractionContextType.Guild, InteractionContextType.BotDM] etc
documentation suggestion for @glossy lion:
SlashCommandBuilder discord.js@14.21.0
A builder that creates API-compatible JSON data for slash commands.
Okey, I was able to figure it out and it works, thank you very much :D
Hey guys ! Can someone tell me why I am not getting the guildId when I delete a channel and retrieve the GuildAuditLogEntry ?
First check that it was not a DM
!channel#isDMBased()
and then is has guildId
channel#guildId
GuildChannel#guildId discord.js@14.21.0
The id of the guild the channel is in
Why would dm channel be in audit log
I assumed that we are looking at the channelDelete event then getting the GuildAuditLogEntry. so type check
sure
but the question isn't really "why is channel.guildId not there", but it reads more like "i already accessed channel.guild.fetchAuditLogs()"
unless it is really badly formed and forces an XY problem
@safe pasture could you clarify where your issue is by sharing your code and error
Here's my code :
export async function execute(client, auditLogEntry) {
console.log(auditLogEntry);
switch (auditLogEntry.action) {
case 10 :
await prisma.guildEvent.create({
data: { guildId: auditLogEntry.target.guild.id, type: "CHANNEL_CREATE", label: `Salon créé: ${auditLogEntry.target.name}`, meta: { channelId: auditLogEntry.targetId, type: mapChannelType(auditLogEntry.target?.type) } }
}).catch(() => {});
break;
case 12 :
await prisma.guildEvent.create({
data: { guildId: auditLogEntry.target.guild.id, type: "CHANNEL_DELETE", label: `Salon supprimé: ${auditLogEntry.target.name}`, meta: { channelId: auditLogEntry.targetId, type: mapChannelType(auditLogEntry.target?.type) } }
}).catch(() => {});
break;
}}
and the error :
GuildAuditLogsEntry {
targetType: 'Channel',
actionType: 'Delete',
action: 12,
reason: null,
executorId: '256892994504884224',
executor: User {
id: '256892994504884224',
bot: null,
system: null,
flags: null,
username: null,
globalName: null,
discriminator: null,
avatar: null,
banner: undefined,
accentColor: undefined,
avatarDecoration: null,
avatarDecorationData: null
},
changes: [
{ key: 'name', old: 'test42' },
{ key: 'type', old: 0 },
{ key: 'permission_overwrites', old: [] },
{ key: 'nsfw', old: false },
{ key: 'rate_limit_per_user', old: 0 },
{ key: 'flags', old: 0 }
],
id: '1406666904453779550',
extra: null,
targetId: '1406639192116560023',
target: {
id: '1406639192116560023',
name: 'test42',
type: 0,
permission_overwrites: [],
nsfw: false,
rate_limit_per_user: 0,
flags: 0
}
}
[17:52:05.028] ERROR: uncaughtException
err: {
"type": "TypeError",
"message": "Cannot read properties of undefined (reading 'id')",```
Guild object is include in the event
(event) Client#guildAuditLogEntryCreate discord.js@14.21.0
Emitted whenever a guild audit log entry is created.
is it possible to add file to message with interaction.editReply?
export async function execute(client, auditLogEntry, guild) {
const guildId = guild.id
}
Ohhh, okay ! thanks for the help !
Yes. Add it to files in the edit reply options
.addChannelTypes(ChannelType.GuildText, ChannelType.GuildAnnouncement, ChannelType.AnnouncementThread, ChannelType.PublicThread, ChannelType.PrivateThread)
```Is there a better way to just only show text channels?
GuildTextBasedChannelTypes discord.js@14.21.0
The types of guild channels that are text-based. The available types are:* ChannelType.GuildText* ChannelType.GuildAnnouncement* ChannelType.AnnouncementThread* ChannelType.PublicThread* ChannelType.PrivateThread* ChannelType.GuildVoice* ChannelType.GuildStageVoice
Hey, how can I get a user's tag?
Oh mark responded already no worries
For the next release, which has tags, will there be an event when someone equips a guild tag?
yes, an already existing one - user update
also, it's not "tag", but "guild tag" if anything, as "tag" is a property that has existed for years on a User
No, that is the best why to only have text based channels appear
DiscordAPIError[50001]: Missing Access
at handleErrors (/root/FAHAD/OutBotGamesV3Main/node_modules/discord.js/node_modules/@discordjs/rest/src/lib/handlers/Shared.ts:148:10)
at processTicksAndRejections (node:internal/process/task_queues:95:5)
at SequentialHandler.runRequest (/root/FAHAD/OutBotGamesV3Main/node_modules/discord.js/node_modules/@discordjs/rest/src/lib/handlers/SequentialHandler.ts:417:20)
at SequentialHandler.queueRequest (/root/FAHAD/OutBotGamesV3Main/node_modules/discord.js/node_modules/@discordjs/rest/src/lib/handlers/SequentialHandler.ts:169:11)
at _REST.request (/root/FAHAD/OutBotGamesV3Main/node_modules/discord.js/node_modules/@discordjs/rest/src/lib/REST.ts:210:20)
at GuildMessageManager._fetchMany (/root/FAHAD/OutBotGamesV3Main/node_modules/discord.js/src/managers/MessageManager.js:112:18)
at TextChannel.bulkDelete (/root/FAHAD/OutBotGamesV3Main/node_modules/discord.js/src/structures/interfaces/TextBasedChannel.js:349:20) {
requestBod
your going to need to elaborate. Please share your code and what your trying to do
Guys, im trying to put a proxy on my client
How do i do it exacly
Hello, I'm a beginner in front-end programming. Learn html css js. If there is someone who helps me create projects together and cooperate in projects.
sorry, you are in the wrong server.
okay huh this might just be a discord issue, but if i simply type the following *
// like this
`*`
on discord, it works
HOWEVER
in an embed field value, having an/multiple asterisks (*) inside a single-backtick codeblock breaks (and escapes) the codeblock
I have tried putting text around/between the asterisks inside the codeblock and even backslashes for both the asterisk and backticks (and even the backslashes themselves) but nothing does it right
any ideas ?
Is there a way to use footer and author in Discord.js v14?
uhh yes?
same way that has always existed
EmbedBuilder#setAuthor() builders@1.11.2
Sets the author of this embed.
EmbedBuilder#setFooter() builders@1.11.2
Sets the footer of this embed.
unless you mean a container, in which case - no. embed is not a container
i have also noticed the embed rendering on desktop and mobile are not the same, discord why 🫠
Why? Because theyre entirely different devices, aspect ratios, resolutions...
Probably codebases
no but it's different for such stupid things (such as markdown)
*text * on desktop gives *text *
but on mobile it gives *text *
(and many more cases)
yes, I meant to try adding display_avatar.url
nothing we can do about that
then no, this is not an embed
container has nothing to do with embeds
aight thank you
container is merely a, well, container for new components
Create it as an emoji in server and then use, ez
But yeah, if you are feeling crazy; you can even mask it as circular and then make it an emoji to use as container’s author else it will be in square
creating an emote out of an avatar just because someone joined sounds like a quite bad of an idea
It is
I’m just giving ideas if they want to make it work out
they can also just use an embed
those weren't removed
Creating then deleting though; in another server
and the button is under it anyway
that's just spamming api
Yeah but no problem because we users also spamming api and the limit is so short so it is okay
no its not okay
spamming the api is never okay
You can upload emojis in row as user, so why not as bot
or you can just not do that
and use an embed
why are we even discussing this
I'm using embed, I just tried doing it with a container because it looks better than with embed, but thanks for the suggestions
for the amount of things you have in it right now, it should look almost identical as an embed
There are so many reason an emoji per user is a bad idea, if nothing else the 50 per server / 2000 per app limit immediately caps how scalable that solution can ever be
Rate limits aside
Embed is obsoleted 
But yeah, that’s the idea if you wanted to make profile pictures inside containers for now
Embed is not obsolete
As evidenced by this very discussion where its the better solution for a specific use-case and still is the web standard for embedding content from websites (its original intended purpose)
Emojis sometimes don’t tell what you want to say 😔
then use better words
the ones you actually want to use
Anyway, lets all move on
Embeds were never actually intended for use in bots as fancy formatting
ل
hello there! do you need help with something?
bro are you ok
My close button in my ticket system doesn't reply. Here is the code to the handling of my ticket system.
Also there is nothing in the terminal.
Help me out 
Where are you loading this file? You also have 0 logging in this file to debug it
index.js
Can you share a snippet of the loader?
ofc
const eventsPath = path.join(__dirname, 'events');
const eventFiles = fs.readdirSync(eventsPath).filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const filePath = path.join(eventsPath, file);
const event = require(filePath);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
} else {
client.on(event.name, (...args) => event.execute(...args));
}
}```
I will mention everything works fine except the closing part of the ticket system.
Ya I'm on mobile, I can't read that...it's hard to follow
You should start by adding some debug logging and seeing where the interaction flow is stopping
Alr
Any recommendations on what debug logging I should add?
I put a try catch in there and nothing came to the terminal.
console.log("Interaction ID:", interaction.customID)
Or just console.log("got to here") type logging to see at what point it stops working.
Just kinda put them everywhere. You can delete them when you're done, but if you don't know why it's not working, it's helpful to figure out WHERE it's not working
Alr
Weird
Still nothing in the console. I put like 6 of them in.
Then it's failing even earlier than you thought. Did you put one with at the start of your execute function?
I found it, it make it to my first if (interaction.isButton()) thing.
Then it stopped.
Line 47 on your pastebin. You check if (interaction.IsStringSelectMenu()) and the rest of your code is nested in that
So it's impossible for any buttons in there to run...because they can't be both a select menu and a button
So does that mean my current setup won't work?
Well at least you'll need to move your button code to outside of that if (interaction.IsStringSelectMenu()) check
But you're also checking if it's a button way too much...you have 4 of them
Lemme test rq.
Code structure is more of a quality of life thing...but it would probably be beneficial to do some refactoring of this.
You're doing a lot of stuff in your interactionCreate event file...making a handler to send the interaction event to other files would make it a lot easier to maintain.
Adding more buttons or modifying existing ones would be much more organized. Like src/buttons/deleteTicket.js
And would prevent bugs like this, where you're trying to handle a button interaction inside of a select menu handler
How would I make a handler like this?
Also is there any benefit to have a src folder before the buttons one?
src is simply just good practice to separate your actual code away from configuration files/folders. It also matters more when you have secondary services running alongside your main app...but that's besides the point
But actually implementing this is up to you...but you can copy the automatic command loader from the discord js guide and modify it to be for buttons...in the API, they're almost the same thing
Ok
And also thanks for the help.
Ofc
0|Complexo | RATE LIMIT: {
0|Complexo | global: false,
0|Complexo | method: 'POST',
0|Complexo | url: 'https://ptb.discord.com/api/v10/channels/1403628284201275432/threads',
0|Complexo | route: '/channels/:id/threads',
0|Complexo | majorParameter: '1403628284201275432',
0|Complexo | hash: '7ced0bc5b612b6797114f6ffc4b5fe04',
0|Complexo | limit: 50,
0|Complexo | timeToReset: 160928,
0|Complexo | retryAfter: 161050,
0|Complexo | sublimitTimeout: 161050,
0|Complexo | scope: 'shared'
0|Complexo | }
What can i do? 😢
Can nirn-proxy help me with that? Should i buy a proxy?
you're ratelimited, you have to wait
No a proxy will not get around a rate limit...
in the future don't make many requests, change your code to avoid hitting it
Hello,
const serverChannels = await guild.channels.fetch();
const channel = serverChannels.filter(c => c.type === ChannelType.GuildText).find(x => x.position == 0);
await channel.message({ content: translate.logs.noChannelFound, flags: MessageFlags.Ephemeral });
how to make that message ephemeral?
only interaction replies can be ephemeral.
ouch, thanks you!
const member = await guild.members.fetch(memberId);
does discord return roles with it? or do i have to fetch for it separately?
It does return roles with it.
will discord throw error, if i try to set role which the user already has?
no
But it doesn't hurt to check beforehand.
what if i don't want to cache any member?
await guild.members.fetch(memberId); will fetch the member.
But what about the roles of member?
well, idk how explain
yes, that includes which roles they have
documentation suggestion for @wooden carbon:
GuildMember discord.js@14.21.0
Represents a member of a guild on Discord.
you can see all of the things that that would return here
So, when fetching a member, Discord returns roles as an array of role Id.
Does Discord.js look into the roles cache and grab the full role objects to put them into the member's roles cache? I think that’s what happens.
But if I turn off all the cache, what happens? Will it still fetch the roles? I don’t actually need the full role objects, just the role IDs returned by Discord, along with member fetch are enough for me.
kind of yes
dont turn off the guild cache
yea
which is where roles come from
ok but i don't want member to be cache they are kinda useless for me
so dont cache them, thats fine
the roles arent related
the caching of them isnt anyway
btw, I wonder how much ram will consume to cache single guild?
fuck all
lol
How much will it consume to cache all excluding members? for a single guild
a couple of fuck alls
I dont know how many guilds your bot is in
gpt 😅
yeah thats what I said
😄
to cache a single guild*
realistically you don't need to worry about this until you have a large application
i am hosting bot on 64mb ram 💀
the problem then is that node itself will reserve about that much
64mb*
why so tiny?
idk
I'm at a usage of ~120mb with a few thousand members cached, no cache limited and constantly playing something in voice, so I would say it doesn't really matter unless you reach a massive user/server base
is there a way to make a user select menu within a role, so for example i have a role called vips so the selectmenu would only show the users with the role
no
ok ty
you can do it with auto complete in slash
Anyone else's .setPresence on clientuser no longer working? As in it doesn't show what I ask it to set + no errors or anything
How often are you changing it?
Have you confirmed the code is being reached and executed? console.log() statements before and after?
It's only being changed once every two minutes to update a certain value. It was all working fine before somewhere last week and suddenly it stopped. To add it did for two different bots of mine running a different codebase/ framework set up
what did I do wrong?
error: https://sourceb.in/tJ6O46D2Cm
code: https://sourceb.in/mWYBaFkbFK
section requires an accessory of either a thumbnail or a button
if you don't want an accessory, don't use a section
just use text display directly
ty<3
I have a error in my closing portion of my ticket bot. The error is TypeError: Cannot read properties of undefined (reading 'send') the code for handling of my ticket system is in the link below. https://sourceb.in/CN9CDuaMyg
Could you provide the full stack trace of the error
This? ```node:events:497
throw er; // Unhandled 'error' event
^
TypeError: Cannot read properties of undefined (reading 'send')
at Object.execute (C:\Programming + Coding\DiscordBots\Bot\src\events\ticket-system.js:215:45)
at Client.<anonymous> (C:\Programming + Coding\DiscordBots\Bot\src\index.js:42:44)
at Client.emit (node:events:531:35)
at InteractionCreateAction.handle (C:\Programming + Coding\DiscordBots\Bot\node_modules\discord.js\src\client\actions\InteractionCreate.js:101:12)
at module.exports [as INTERACTION_CREATE] (C:\Programming + Coding\DiscordBots\Bot\node_modules\discord.js\src\client\websocket\handlers\INTERACTION_CREATE.js:4:36)
at WebSocketManager.handlePacket (C:\Programming + Coding\DiscordBots\Bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:351:31)
at WebSocketManager.<anonymous> (C:\Programming + Coding\DiscordBots\Bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:235:12)
at WebSocketManager.emit (C:\Programming + Coding\DiscordBots\Bot\node_modules@vladfrangu\async_event_emitter\dist\index.cjs:287:31)
at WebSocketShard.<anonymous> (C:\Programming + Coding\DiscordBots\Bot\node_modules@discordjs\ws\dist\index.js:1190:51)
at WebSocketShard.emit (C:\Programming + Coding\DiscordBots\Bot\node_modules@vladfrangu\async_event_emitter\dist\index.cjs:287:31)
Emitted 'error' event on Client instance at:
at emitUnhandledRejectionOrErr (node:events:402:10)
at process.processTicksAndRejections (node:internal/process/task_queues:84:21)```
Yes, that is it.
Looks like your general support channel is undefined
I think it is though.
On line 205 interaction does not have that property.
Don't I have it defined on line 57?
but you wouldnt get it via "const generalSupportChannel = interaction.generalSupportChannel" you need to either get the actual id of it and save it somewhere or if the name is unique get it by name
Well you have it on line 205 in the same if statement as 215 where the send error is. It is defined as a property of interaction which the property is undefined
Ok, so how would I fix this?
i have a system that manage around 3600 threads inside a channel everyday, its a game
Add your own cooldowns to prevent hitting rate limits
theres no way to prevent getting rate limit? im already using nirn-proxy, but it doesnt change a lot
Write better code? I don't know your code and am not writing it for you.
Like someone else said above. Proxy does not prevent getting rate limited. That would defeat the purpose of rate limiting
Are you trying to get the channel where the button is pressed?
documentation suggestion for @solemn arch:
ButtonInteraction#channel discord.js@14.21.0
The channel this interaction was sent in
do u think discord can increase the tolerance? by sending them a ticket
what are you doing specifically?
you shouldn't hit that ratelimit in the first place
@rose tangle
yeah but that's just a general description, I wanted something more specific
i assume creating editing deleting
or a combination
It's a game that works as follows: let's say you and I want to go 1v1 in Valorant, so we go to the bot and click "Play". When both players click, it will create a thread within a text channel. Upon confirmation, the bot will add a mediator to the thread who will be responsible for creating the match and monitoring possible cheating. That's basically it. The problem is that there were about 200 simultaneous matches and +3,500 per day.
maybe you could re-use channels or do they need to be empty?
Why not reuse threads for matches that are finished? By clearing the chat? Or do you need to keep the chat
lol
they need to have no messages and no people inside it until both join it, thats it
Try this on line 205.
const generalSupportChannel = interaction.channel;
You were calling interaction.generalSupportChannel which doesn't exist
Purge messages and remove prev users
if you don’t need history, that’s a better option
Thanks
Next time check the documentation to validate the properties exists linked by the bot above
ok
console.log(orderInfo.CoachPic);
const embed = new EmbedBuilder()
.setColor('#0c941c')
.setTitle(`Welcome ${orderInfo.CustomerName}!`)
.setAuthor({ name: 'Clash School', iconURL: client.user?.displayAvatarURL() })
.setThumbnail(`${orderInfo.CoachPic}`)```
here the thumbnail is not working, not sure why. this is the pic btw
`https://www.clashschool.com/wp-content/uploads/2020/01/BRADDERS-1.png`
I logged it btw
Could define not working? Did an error occur or did the thumbnail not appear
thumbnail didn't appear
I know nasa images blocks Discord. Is it possible that the site you link also blocks it
https://discord.js.org/docs/packages/discord.js/main/GuildChannel:Class
I can't find method for creating invites
logically it should be in channel.
GuildInviteManager#create() discord.js@14.21.0
Create an invite to the guild from the provided channel.
// Create an invite to a selected channel
guild.invites.create('599942732013764608')
.then(console.log)
.catch(console.error);
logically it should be on guild :P
nah
it should be in channel caz, invites are created based on a channel
so, channel.createInvite() or something seems resonable
that does also exist
documentation suggestion for @wooden carbon:
BaseGuildTextChannel#createInvite() discord.js@14.21.0
Creates an invite to this guild channel.
// Create an invite to a channel
channel.createInvite()
.then(invite => console.log(`Created an invite with a code of ${invite.code}`))
.catch(console.error);
why is it not on guildchannel then 
logically, GuildChannel also includes category 😄
'cause not all guild channels can be invited to, just the text based ones 
and invites can only be in text or voice based
then you can still add it to guildchannel and omit it from categories 
also #justiceforcategories
if(channel.isTextBased()) channel.createInvite
Seems like i also need to exclude Dm thingy, but is there any combined type guard ?
f
HELP!!!
IT DOESN'T EXITS ON ANYTHING
Property 'createInvite' does not exist on type 'DMChannel | PartialDMChannel | NewsChannel | StageChannel | TextChannel | PublicThreadChannel<boolean> | PrivateThreadChannel | VoiceChannel'.
that's the whole union
well, there is only one way if("createInvite" in channel)
further below it should say on which exact element it isn't
probably DMChannel | PartialDMChannel
and I think VoiceChannel as well like mentioned above
i typ gaurd dm thingy still show err
pretty sure you can create an invite in voice channel
yep you can
no idea, it was mentioned above so I assume so ¯_(ツ)_/¯
the error should tell you exactly on which it isn't present
this should be faster though
sometime ts is such a biatch
I mean it's there to avoid making a runtime mistake
if you did receive a dm channel then it would've errored
if ("createInvite" in channel)
channel.createInvite({
maxAge: 0,
maxUses: 0,
unique: true,
reason: "Making your discord public :D",
});
well well, this is a problem it will create invite each time
oh nvm
unique false should do the magic
is it possible to get the string that the user has selected during autocomplete?
say, my field_1 is autocomplete too and user chooses "text1"
now when he goes to field_2 which is also an autocomplete, I want to be able to customise the option based on what he selected for field_1. is this possible?
guide suggestion for @fading girder:
Slash Commands: Autocomplete - Accessing other values
read more
consider that options are cached
tyy
if the user types text1 and you'll reply with some options, it'll show those same options if they type text1 again
regardless of what they've typed in other options
there's no way around that
okay got it
Hey, whenever I get guild's data from cache or by fetching it, it seems that I'm missing the description property though my guild has the description set in settings. It was working when I was making this feature, but now for some reason it has stopped
from cache or by fetching it
how are you fetching it?
It is in the screenshot
Originally I was getting the data from the cache but after I noticed that the description property is blank then I changed it to fetch
so you're not fetching it at all
since fetch used this way checks cache first
Oh yeah you're right actually
i always forget about that, now it works
I got this error
Error: Used disallowed intents
If you are using the GuildMembers, GuildPresences, or MessageContent intents, you need to enable them via Developer Portal > Your app > Bot > Privileged Gateway Intents
/**
* @param {import('../init').bot} bot
* @param {import('../init').con} con
* @param {import('discord.js').GuildChannel} oldChannel
* @param {import('discord.js').GuildChannel} newChannel
*/
module.exports = async function (bot, con, oldChannel, newChannel) {
if (!newChannel.guild) return;
con.query(`SELECT * FROM data WHERE id = ?`, [newChannel.guild.id], function (e, data) {
if (!data[0]) return;
con.query(`SELECT * FROM logging WHERE logType = ? AND guildId = ?`, ['Channel', newChannel.guild.id], function (e, logs) {
if (!logs[0]) return;
newChannel.guild.fetchAuditLogs({ limit: 1, type: 11 }).then(function (AuditLogFetch) {
var Entry = AuditLogFetch.entries.first();
newChannel.guild.channels.cache.get(logs[0].channelId)?.send({
embeds: [
new bot.discord.EmbedBuilder()
.setColor(data[0].color)
.setAuthor({ name: `Action Logs - Channel Updated`, iconURL: newChannel.guild.iconURL({ dynamic: true }) })
.addFields(
{ name: `Actioned By:`, value: `${Entry.executor.tag || "someone"}` },
{ name: `Before Changes:`, value: `\`Name:\` ${oldChannel.name}\n\`Type:\` ${oldChannel.type}\n\`ID:\` ${oldChannel.id}\n\`Created:\` ${oldChannel.createdAt.toLocaleString()}` },
{ name: `After Changes:`, value: `\`Name:\` ${newChannel.name}\n\`Type:\` ${newChannel.type}\n\`ID:\` ${newChannel.id}\n\`Created:\` ${newChannel.createdAt.toLocaleString()}` },
)
.setTimestamp()
.setFooter({ text: newChannel.guild.name, iconURL: newChannel.guild.iconURL({ dynamic: true }) })
]
});
});
});
});
}```
Ok