#djs-help-v14
78874 messages · Page 62 of 79
for some reason my bot wont show any commands when going into DMs even after trying to set it up to show in DMs
ive tried changing the .applicationGuildCommands to .applicationCommands
ive added the channel message and reaction partials
ive tried using .setContexts in my command
it still doesnt work, how can i fix this?
Have you redeployed commands since setting contexts, and reloaded the app?
yes
Can you show one of the commands
Partials are not relevant here, but global deployment and contexts should be sufficient
tried it with the ping command
yeah I think that should work if correctly deployed globally
it shows nothing when i go into dms but works fine in servers
Can't replicate - I just deployed that exact SlashCommandBuilder and it appears in DMs
Typescript Error caused by this code:
const { token } = require('./config.json');
const client = new Client({ intents: [GatewayIntentsBits.Guilds] });
client.once(Event.ClientReady, (readyClient) => {
console.log(`Ready to Start! Logged in as ${readyClient.user.tag}`);
});
// Log in to Discord with your client's token
client.login(token);```
It would help a lot if you told us *what *TypeScript error was caused by this code
is there anything i can do?
Just make sure you've done everything. Set the context, THEN deploy globally, THEN reload your Discord app to make sure caches are cleared
we can't get rid the gaps on container right
You can check integrations installed in guilds to make sure the commands are there
What do you mean by "gaps"?
How have you built that container?
here
.addTextDisplayComponents(
textdisplay =>
textdisplay.setContent(
`> Ends: <t:${duration}:R> (<t:${duration}:F>)`,
),
textDisplay =>
textDisplay.setContent(`> Hosted by: <@${interaction.user.id}>`),
textDisplay =>
textDisplay.setContent(
`> Entires: ${giveaway.getDataValue('participants').length}`,
),
textDisplay => textDisplay.setContent(`> Winners: ${winners}`),
)
Just use a single text display if you dont want them split
the commands still show up in servers, but when i go to dms it isnt there
Then it hasnt been correctly deployed with that context
how would i deploy it correctly?
Very hard for me to answer that since I don't know how you're doing it now, but if its not showing up, I can tell you that it hasnt been
im using the deploy-commands.js setup from the guide
Here's how I tested it:
Slightly cut down from the guide but basically the same
you mean by adding \n right
If thats how you want to format it
alr ty for the tips
it looks similar to mine, but mine hasnt worked and im not sure why
You could try fetching commands to see whats been deployed, client.application.commands.fetch() and log that
okay
i just got this
gotta await it
oh alright
where would i put it though?
Ready event should work, client will be logged in there
ready event can be async?
tried it there, still didnt work
yes it can, what do you mean it didnt work
still got the pending promise
still arent awaiting it then
its awaited
you're awaiting the console.log, which isnt a Promise
You arent awaiting the fetch, so its logging the Promise
oh
that worked
i believe this is the ping command
Yep, looks correct, and it appears to be deployed to the correct contexts
You're trying to use it in the bots DMs, not DMs with someone else right?
im trying to use it in someone elses dm
Ahh. then you need to have it installed as a User application type, not into Guilds
It looks like the command has been deployed to be available that way, but you also need to install it that way
how would i go about that?
You'll also need the third context type, PrivateChannel
Which is missing
When you install the bot via its link, if its enabled for user installs you can select to install it that way
that made it work, thank you so much!
Sorry, I should have thought to ask which DMs sooner
did we have method to update textDisplay
documentation suggestion for @warm charm:
TextDisplayBuilder#setContent() discord.js@14.25.1
Sets the text of this text display.
i mean i already have container have textdisplay, now i need to update it to new text
Ya. You update the content of the text display and then edit the message in question by sending the entire Container object back with the modifications you wanted
alr imma try that
what is ExpectedConstraintError?
the error is threw when embed.addFields
I created a test.js
it's not thrown by using it, it's thrown by using it incorrectly
ik, but idk what incorrect
how do you use it in the first place
an array contains foods' data that user have
and map() to format the foods
[food name] `[amount]` (Saturation: `[Saturation]` <:drumstick:1430440392536490065>)
-# my English is not good
how do you use the addFields()
oh! will the value too long causing this problem?
{name: "[food category]", value: itemsText}
yes,
> itemsText.length
1046
How to get optimal prefix command?
My bot feels slower to reply than other bots
There is no optimal prefix command
Unless you're doing some sort of really terribly inneficient string manipulation
// ----- Register Prefix Commands ----- //
const prefixCommandsPath = path.join(__dirname, './commands/prefixs');
fs.readdirSync(prefixCommandsPath).forEach(folder => {
const folderPath = path.join(prefixCommandsPath, folder);
if (!fs.statSync(folderPath).isDirectory()) return;
const commandFiles = fs.readdirSync(folderPath).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(path.join(folderPath, file));
if (command?.data && command?.execute) {
client.commands.set(command.data.name, command);
} else {
console.log(`[WARNING] Lệnh ${file} thiếu "data" hoặc "execute"`);
}
}
});```
no, none of this makes any difference
and even if, it's unmeasurably small, compared to the fact that you connect to discord via internet
Huh?
you can check a string billions of times per second
doesnt' change anythign if you still have 150 ms ping to discord
my bot has ping 300ms
even more then
and this is precisely and exactly why it's slower than other bots
so what to do
run it somewhere else
or ignore the problem, it doesn't particularly matter
I am hosting the bot on a VPS Linux server in Singapore.
then run it elsewhere
For example?
rest of the world
Anywhere else on the planet
maybe besides japan, i guess
In the US would generally be best for Discord server proximity
230ms for singapore
Yes
Hey, I'm using @discordjs/core on the latest npm version (2.4.0), and trying to use per-method auth, specifically for UsersApi#getCurrent. However, the function type looks like this: getCurrent({ signal }?: Pick<RequestData, 'signal'>): Promise<discord_api_types_v10.APIUser>; even though the PR to add per-method auth was merged almost a year ago. Am I missing something here?
Actually, it seems like #10682 is not published to @discordjs/rest on npm either
It is a breaking change, which would require a major
core@2.0.0 was Sep 3 2024, so a breaking change would require a 3.0 to release I guess
Not sure why we haven't done one for this though tbh, I don't really maintain core
cc: @golden laurel time to bully people into a core release
What happened
Oh
Cause it depends on breaking changes from other packages really
ahh
k release those too then
Ah, good to know. My use case is OAuth2 using OAuth2APIand UsersAPI from core, which is currently not possible without a custom auth param. Looking forward to a release!
Does discord support dropdowns in modals yet? (With auto complete?)
ty ty
Am I being stupid rn?
const container2 = new ContainerBuilder()
.addSectionComponents(s => s
.addTextDisplayComponents(td => td
.setContent('User Join Channel'))
.addActionRowComponents(ar => ar .setComponents(welcomeMenu)))
.addSectionComponents(s => s
.addTextDisplayComponents(td => td
.setContent('User Leave Channel'))
.addActionRowComponents(ar => ar .setComponents(goodbyeMenu)));
Error:
Interaction error: TypeError: s.addTextDisplayComponents(...).addActionRowComponents is not a function
You have a closing ) at the wrong place, you can't add action rows to sections, you want to add it to the container
Also sections need an accessory
If you just want a menu below textdisplay add the textdisplay directly to the container, no section needed
Ah
I assumed it was the same because of the button accessory
Thanks 🫡
wait if i dont have partials in client options for guildmember for example, and member is partial, i wont receive event for it at all ?
or i will but i have to fetch them
Yes, because discord sends the id for delete events and the new member for update events. You can’t fetch a member which left though
so i wont receive that event if they're partial and i dont have partial for it, right?
Yh you won’t
kk ty
how can i solve this problem?
i have nearly 15 bots and i have to make every bot to be connected voice channel
that sounds like a network issue
Errors such as ECONNRESET, ConnectTimeoutError, SocketError: other side closed indicate a network issue
- Free or shared hosting providers often come with significant limitations
- Another indication of these issues are 'Unknown Interaction' errors.
or a firewall one
Error [VoiceConnectionTimeout]: Connection not established within 15 seconds.
Make sure you have provided the GuildVoiceStates intent to the client:
import { Client, GatewayIntentBits } = from 'discord.js';
const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildVoiceStates]
});
No, not what I was looking for... ip discovery failing is usually a firewall/vpn/proxy blocking UDP ports

Matriz
let Matriz: number[][] = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
];

im not too sure what this has to do with the discord.js library
The game '#' in Discord.js
yeah no, please troll elsewhere
Using array
i'm sure all i did should work but for some reason sapphire is yelling at me with 0 context, for sending the message i do enable the componentsv2 flag
message.channel.send({
components: [
embed
],
flags: [
MessageFlags.IsComponentsV2
]
})
https://pastebin.com/1FCYrCqW
Errors are in the provided message.txt
Embeds are not a component
it's a container
its just called embed becuase it was an embed before and i just turned it into a container
because they look cleaner
You have one or more sections without an accessory
oh
i didn't think they were required, thanks for the help!
Sections are required to have an accessory and one text display
If an accessory is not needed. Just add the text display on its own
Yup, that was the issue, thanks for the clarification and sorry for being dum
All good
What is the max character limit in the new modal label's descriptions?
documentation suggestion for @coarse storm:
Component Reference - Label
A Label is a top-level layout component. Labels wrap modal components with text as a label and optional description.
How do i slice embeds properly? For example i have some search results (for example a string[]) and i need to fit them into an embed (and then pagify it)
i need to make sure i wont go over the field limit, field value length limit and the embed character limit
there's no built-in function for that
yes i know, im asking for solutions
this is for help with the library itself
though tbh it sounds like you already know the solution, just trim the content according to those limits
ive tried a lot and its kinda hard, im just looking for the best solutions out there
you can ask in #1081585952654360687 but it's just String#slice()
String.prototype.slice()
The slice() method of String values extracts a section of this string and returns it as a new string, without modifying the original string.
hmmmm i never actually thought about that, but its not good enough for my case
ill ask elsewhere
https://discord.com/channels/222078108977594368/1447330163422658621 for anyone interested
why it does not reach the console.log({ btn }) or bellow
uploadInteraction is a ButtonInteraction
collectors don't work well with non fetched ephemeral replies iirc
try adding withResponse: true
The fetchReply option when replying to an interaction will be removed in v15.
- {..., fetchReply: true}
+ {..., withResponse: true}
```This returns an [InteractionCallbackResponse](https://discord.js.org/docs/packages/discord.js/stable/InteractionCallbackResponse:Class)
Use `<InteractionCallbackResponse>.resource.message` to get the message
then i do response.resource.message.awaitMessageComponent?
yeo
um how do i make my bots commands available in dms - like when dming sm1 else i can run a command
I made a bot that puts users, based on their id, into a queue.
The queue is a simple array. I added a check if the user is in queue, and dont add them if they are.
Added that bot to two different servers (guilds)
And every server had their own queue somehow.
So thats awesome, but does somebody know why?
I didnt implement "per guild" separation, its just a simple array.
So not knowing whats going on is kinda scary
anyone know why getBoolean('blacklist') gives this error when the reject command is used? TypeError: Cannot read properties of undefined (reading 'getBoolean')
const blacklist = interaction.option.getBoolean("blacklist")
interaction is probably not actually an instance of an interaction
the rest of my subcommands work fine
(and they all use interaction)
Make your app user-installable via the developer portal, then add the PrivateChannel context to your command(s)
Start logging stuff then
just found the issue, classic typo. put option instead of options
Ah, yep, there you go, not sure how I missed that, good deal
yea not sure how i missed that either lol, thanks
your ide should be on fire
We'd need to know how you actually implemented this queue system and what you specifically mean by "every server had their own queue" to be better able to help imo
nah for some reason vsc dosnt mark stuff like that. not sure why, probably the way my file is setup thoug
or just the way vsc works. probably should switch to jetbrains but oh well
ok, I expected there to be some obvious magic that someone knows about, because how I implemented it, it makes 0 sense
Ive used a million singletons and a singleton holds the array
If User A joins the queue on server A, then joins the queue on server B, it should not put him in, cause he is already in
But it puts him in what seems to be a different queue and I dont know why, maybe its a bug after all
Can you share the code for all of this?
I can share the important parts
from a button handler
await interaction.deferReply({ flags: MessageFlagsBitField.Flags.Ephemeral });
const playerAddedToQueue = queues.addPlayerToQueue(region, interaction.user);
and adding them to an array
public addPlayerToQueue(region: string, user: User, partySize: number = 1)
const queue = this.state.queues[region];
if (queue.players.find(player => player.id === user.id)) {
return false;
}
queue.players.push(this.mapUserToPlayer(user, partySize));
really nothing to it
region is the same for both cases
ok I found it, does indeed not work, just looks like it 
man I was starting to get excited about not having to implement guild separation 
everything is tied to a discord message, and the message was just overridden
so while nothing broke, it was only working for the last guild that set everything up
can i make a upload file field in forms to only accept a certain file
what would be the point of uploading it?
Its for my dsl plugin file
you mean a certain file type then?
Yes cause i want it to only accept .fsx file
there isn't
though tbf you can't really rely on that anyways, I can rename my .png to .fsx
so you'll still need some kind of validation
Yay i made valudation to verify it content but i still wanted to prevent it but i will keep it how i have it
Then they don't have one
Is it better to transfer to typescript or just stay on javascript?
Not really a yes/no or a discord.js question\
If you want the benefits of type-safety, switch to TypeScript
const workFilesUpload = new FileUploadBuilder()
.setCustomId('work_files')
.setMinValues(1)
.setRequired(true)
.setMaxValues(10);
const workFilesLabel = new LabelBuilder()
.setLabel('Upload portfolio files (images, pdf, video)')
.setDescription('You can upload up to 10 files')
.setFileUploadComponent(workFilesUpload);
this is my current code. once ran and a button is interacted, it gives me this error:
application handler error TypeError: (intermediate value).setLabel(...).setDescription(...).setRequired is not a function
at Object.execute (/workspaces/nuhuh/events/dashboard/application.js:93:22)
at Client.<anonymous> (/workspaces/nuhuh/handlers/eventHandler.js:17:50)
at Client.emit (node:events:531:35)
at InteractionCreateAction.handle (/workspaces/nuhuh/node_modules/discord.js/src/client/actions/InteractionCreate.js:101:12)
at module.exports [as INTERACTION_CREATE] (/workspaces/nuhuh/node_modules/discord.js/src/client/websocket/handlers/INTERACTION_CREATE.js:4:36)
at WebSocketManager.handlePacket (/workspaces/nuhuh/node_modules/discord.js/src/client/websocket/WebSocketManager.js:352:31)
at WebSocketManager.<anonymous> (/workspaces/nuhuh/node_modules/discord.js/src/client/websocket/WebSocketManager.js:236:12)
at WebSocketManager.emit (/workspaces/nuhuh/node_modules/@vladfrangu/async_event_emitter/dist/index.cjs:2504:31)
at WebSocketShard.<anonymous> (/workspaces/nuhuh/node_modules/@discordjs/ws/dist/index.js:1190:51)
at WebSocketShard.emit (/workspaces/nuhuh/node_modules/@vladfrangu/async_event_emitter/dist/index.cjs:2504:31)
at WebSocketShard.onMessage (/workspaces/nuhuh/node_modules/@discordjs/ws/dist/index.js:1007:14)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
anyone know what makes it error? any help would be great
your error doesn't match the code shown
is this application.js line 93?
if so, is it possible you haven't saved your code?
never mind, i forgot to restart the bot
thanks though
is V2 modal file temporary like the file upload option?
File upload stores them for a week im wondering if the V2 modal file upload does the same
It survives as long as the interaction does
back again :p | from the FileUploadBuilder, how would i get the url/download the image(s) that were uploaded onto it?
interaction.fields.getUploadedFiles(customId)
That will give you a Collection of Attachments that you can derive the .url property from each and fetch yourself
https://discord.js.org/docs/packages/discord.js/14.25.1/ModalSubmitFields:Class
Here's the whole interaction.fields class for all relevant methods for modal submits
perfect, thank you both!
Is there any plans for Modal Discord System to be able to add images in the formular?
More of a DDevs question... Discord.js doesn't have any control over stuff like that
But I have not heard what they plan to add but I know they are working on stuff
Hello, I've been trying to create a similar discord embed that adds a right button on the title like next.js does on their Release channel but can't find how they are doing that, any hints? Is that even an embed?
Display Components
While you might be familiar with embeds in Discord, there are more ways to style and format your apps messages using display components, a comprehensive set of layout and content elements. To use the display components, you need to pass the IsComponentsV2 message flag (in docs: MessageFlags) when sending a message. You only need to use this flag when sending a message using the display components system, not when deferring interaction responses.
Thanks!
My bad 😭 I was just asking if anyone has any idea, I think discord dev like to follow news
Is there anyway to have a message show content in iOS notifications when using IsComponentsV2?
Since content is not allowed with IsComponentsV2 flag
No. Discord needs to fix the notification implementation of their app
why does my bot save old menu select selection
This is a Discord app issue...not anything to do with DiscordJS

hi there, do you need help? if not, please head to #archive-offtopic
I have a question: in the modal generator of the selection menu, instead of collecting only one piece of data, is it possible to select several?
Select menus can receive multiple selections, yes
Yes you can make it select more values in forms
You can set a min and max number of values the user is allowed to submit as well
Thank you so much. 😀
to remove all permissions on a role would i do role.setPermissions(0n) ?
Yes (and there's an example in the docs showing that)
It’s saying cannot read properties of null (reading ‘username’)
It would help to know from which line
interaction.options.getUser('user') can be null though
It doesn’t state 😭
Errors do state
Show the error stack
Okay so you arent logging the error stack 
Its recommended not to stringify errors
- console.log(`Error handling /balance... ${error}`);
+ console.error("Error handling /balance...", error);
Log it like that
Oki
Great - line 27
Which is as I guess interaction.options.getUser('user').username
Option wasn't supplied and is null
oh but it is at the bottom of the command?
The command has the option but it's optional. If someone doesn't select the option, getUser will return null
ohhhh... how would I make it so it can send something different then? So if they don't choose to enter it, it sends smth else?
You already do this on line 14
Optional chaining (?.) and null collescing (??)
define the user once and then go from there. will be less confusing
ah okay! I followed a economy bot tutorial so I could understand databases but they only used normal replies but I wanted to make embed replies 😅
oh... i just realised.. since I alr defined targetUserId could I change everything to be that instead?
Well its an id, not the user
But using that style, yes, you could do targetUser = interaction.options.getUser("user") ?? interaction.user
Then whenever you need to, you have access to either targetUser.username, targetUser.id or anything else
You're not passing an array of embeds
set embed inside array
omg I can't believe i forgot the brackets! I need to sleep lol
tysm guys!!! 💀
Quick question tho! For like a new command to get currency, how would you make it random?
make what random?
if currency amount, just do random math 🤷
Yh it was the currency amount
thanks I didn’t know there was a random math function :D
Math.random()
The Math.random() static method returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1, with approximately uniform distribution over that range — which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user.
btw whoever manages the djs bot /docs is not working
Thanks guys 💕
Hi, can anyone tell me how to change the status of a voice channel ?
That API is not documented and therefore not supported by discord.js
Oh, okay... That is surprising, I use a bot that can changes the status
That's weird, no ?
maybe python
the api not being documented isn't the same as it not existing
it being unsupported does not mean it's impossible
Oh, okay.. I'll see how else i can do it, thanks for help 👌
Should be fixed now
quick question? what are the default interaction types (server, bot DM, any DM)?
Depends on the contexts your app is installed for at the time of deployment, I think its Guild and BotDM for the Guild install and PrivateChannel for the User install
what error do you get
You did not enable MessageContent in the Discord developer portal
edit: since prior messages was deleted. Discord add this restriction on Sep 1st 2022
https://discord.com/developers/docs/change-log#message-content-is-a-privileged-intent
years ago
ooooooooh, is there somewhere in the discord docs that documents this?
I have tried searching but can't find it, ty btw
documentation suggestion for @nimble obsidian:
Application Commands - Contexts
Commands have two sets of contexts on the application command object that let you to configure when and where it can be used: - integration_types defines the installation contexts that a command supports - contexts defines the interaction contexts where a command can be used Details for both types of command contexts are in the sections below.
huh looks like it's no longer there
yeah no idea to where they moved it
only integration types seems to be documented
Defaults to your app's configured contexts
https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-structure
and
By default, newly-created apps only support installation to guilds.
https://discord.com/developers/docs/resources/application#setting-supported-installation-contexts
contexts used to default to all of them, no idea if it's still the case
https://github.com/discord/discord-api-docs/pull/7583 looks like they simply removed it
I just new on discord.js version 14.25.1 how to set label using label builder
That's not a LabelBuilder. That's a TextInputBuilder...which is correct that TextInputBuilder#setLabel is deprecated
LabelBuilder#setLabel() discord.js@14.25.1
Sets the label for this label.
LabelBuilder#setTextInputComponent() discord.js@14.25.1
Sets a text input component to this label.
Tsym !
are discord tags in discord js, like i waana get my user's tag BOLT
documentation suggestion for @uncut tangle:
User#primaryGuild discord.js@14.25.1
The primary guild of the user
documentation suggestion for @uncut tangle:
User#primaryGuild discord.js@14.25.1
The primary guild of the user
shoud have a .tag property which would be the guild tag
alr thanks
primary guild for me shows null
or wait nvm
mb, thanks for help
How to make this type ui inside selection menu or buttons
guide suggestion for @devout widget:
Display Components
While you might be familiar with embeds in Discord, there are more ways to style and format your apps messages using display components, a comprehensive set of layout and content elements. To use the display components, you need to pass the IsComponentsV2 message flag (in docs: MessageFlags) when sending a message. You only need to use this flag when sending a message using the display components system, not when deferring interaction responses.
hey all .. what do I have to do to get all members on a server with all the information about user status, etc.
Using guild.members.fetch() doesn't give me this
FetchMembersOptions#withPresences discord.js@14.25.1
Whether to include the presences
Default value: false
ah awesome.. sorry next time I scroll down a lil more
is there a limit to how many options can have an emoji? because my string select menu is casuing the bot to fail to send a message when there is 125 emojis
each for one option
const rows = Array.from({ length: 5 }, (_, i) => {
const options = Array.from({ length: 25 }, (_, j) => (
new StringSelectMenuOptionBuilder()
.setLabel(`Option ${i * 25 + j + 1}`)
.setValue(`FID:${id}:select:${i * 25 + j + 1}`)
//.setEmoji('🤖')
));
if (i === winnerMenu) {
const winnerOption = Math.floor(Math.random() * options.length);
options[winnerOption]
?.setValue(`FID:${id}:select:${i * 25 + winnerOption + 1}:win`)
.setLabel(`Option ${i * 25 + winnerOption + 1}`)
.setEmoji('💎');
console.log(i * 25 + winnerOption + 1)
}
the commented line causes the bot to error 500
no matter the emoji I put there
select menus can only have 25 options
how is this relevant?
Whats exactly your error message
Error starting first-to-win drop: HTTPError: Internal Server Error
at handleErrors (/home/discordbots/xxx/node_modules/@discordjs/rest/src/lib/handlers/Shared.ts:136:9)
at SequentialHandler.runRequest (/home/discordbots/xxx/node_modules/@discordjs/rest/src/lib/handlers/SequentialHandler.ts:417:26)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
at async SequentialHandler.queueRequest (/home/discordbots/xxx/node_modules/@discordjs/rest/src/lib/handlers/SequentialHandler.ts:169:11)
at async _REST.request (/home/discordbots/xxx/node_modules/@discordjs/rest/src/lib/REST.ts:210:20)
at async TextChannel.send (/home/discordbots/xxx/node_modules/discord.js/src/structures/interfaces/TextBasedChannel.js:190:15)
at async _FirstItemDropBuilder.start (/home/discordbots/xxx/src/app/utils/itemDrop.ts:453:21)
at async chatInput (/home/discordbots/xxx/src/app/commands/admin/item-drop.ts:151:9)
at async <anonymous> (/home/discordbots/xxx/node_modules/commandkit/src/context/async-context.ts:36:24)
at async _AppCommandRunner.runCommand (/home/discordbots/xxx/node_modules/commandkit/src/app/commands/AppCommandRunner.ts:151:13) {
requestBody: {
files: [],
json: {
content: undefined,
tts: false,
nonce: undefined,
enforce_nonce: false,
embeds: [Array],
components: [Array],
username: undefined,
avatar_url: undefined,
allowed_mentions: undefined,
flags: undefined,
message_reference: undefined,
attachments: undefined,
sticker_ids: undefined,
thread_name: undefined,
applied_tags: undefined,
poll: undefined
}
},
status: 500,
method: 'POST',
url: 'https://discord.com/api/v10/channels/1363229717511012439/messages'
}
just some discord nonesense
told u it's 500, the error stack doesn't help at all
could you please provide the full context of your code and discord.js version
full context? it's at least 1k lines
^14.18.0
like the fuction you are executive
so .send?
try updating to latest v14.25.1
yes
sure, let me try that first
function generateFirstDropComponents() {
const winnerMenu = Math.floor(Math.random() * 5)
const rows = Array.from({ length: 5 }, (_, i) => {
const options = Array.from({ length: 25 }, (_, j) => (
new StringSelectMenuOptionBuilder()
.setLabel(`Option ${i * 25 + j + 1}`)
.setValue(`FID:${id}:select:${i * 25 + j + 1}`)
.setEmoji(':robot:')
));
if (i === winnerMenu) {
const winnerOption = Math.floor(Math.random() * options.length);
options[winnerOption]
?.setValue(`FID:${id}:select:${i * 25 + winnerOption + 1}:win`)
.setLabel(`Option ${i * 25 + winnerOption + 1}`)
.setEmoji(':gem:');
console.log(i * 25 + winnerOption + 1)
}
const menu = new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(
new StringSelectMenuBuilder()
.setCustomId(`FID:${id}:select:${i}`)
.setPlaceholder("Choose an option")
.addOptions(options)
);
return menu;
});
return { embed, components: rows };
}```
I am skipping irrelevant code btw, so dw if there are some variables missing
const { embed, components } = generateFirstDropComponents();
const message = await channel.send({ embeds: [embed], components })
if (!message) {
throw new Error("Failed to send drop message.");
}```
note: it works without this line .setEmoji(':robot:') so the rest of the code is very irrelevant to the issue I am facing
and the updated djs version also fails
same error or did it change at all
same
are you trying to add a Unicode emoji?
what do u mean?
like is it part of the default set or a custom emoji?
default
it's just broken cuz of discord formatting
do u want the .toJson()?
and it errors on that code?
on the .send
Are your label and value strings 100 or less characters?
it sends without the .setEmoji('🤖') line so yes
weird. if your try to do .setEmoji({id: '🤖'})
wow inlicode realy not liking emojis today
rawError: {
message: 'Invalid Form Body',
code: 50035,
errors: { components: [Object] }
},
code: 50035,
status: 400,
method: 'POST',
url: 'https://discord.com/api/v10/channels/1363229717511012439/messages'
}
pretty sure it should be in "name"
well that is a different error. but that is bad advice on my part you chould just be able to pass the emoji
it's a different error cuz u put in in "name" not "id"

if you put it in name does it give you 500
yes
I am at a loss it could just be a Discord bug right now.
Maybe worth asking on DDevs
where
btw this works:
const options = Array.from({ length: 25 }, (_, j) => {
const menu = new StringSelectMenuOptionBuilder()
.setLabel(`Option ${i * 25 + j + 1}`)
.setValue(`FID:${id}:select:${i * 25 + j + 1}`)
if (j % 2 === 0) {
menu.setEmoji('🤖')
}
return menu;
});
Discord Developers. find the link for it in #useful-servers
if (j % 10 !== 0) {
menu.setEmoji('🤖')
}
THIS ALSO WORKS
so only adding emojis to all 25 causes an issue?
if (j % 12 !== 0) {
menu.setEmoji('🤖')
}
pretty sure
wait nevermind:
if (j !== 24 && j !== 23) {
menu.setEmoji('🤖')
}
this works
but this doesnt:
if (j !== 24) {
menu.setEmoji('🤖')
}
😭, I will just put 23 options per page and ignore this shit
any thoughts on this mafia?
strange, Def sounds like a Discord bug
yeah definetely, but how could they make it so buggy?
oh and @wary coral it's only an issue with 125 options, if I do 100 with full emojis it works
actually let me check what is the exact number
lol, ok. I wonder does the issue also occure with cv2
if (i !== 4) {
menu.setEmoji('🤖')
}
if (i === 4) {
if (j < 19) {
menu.setEmoji('🤖')
}
}
this works, but 20 doesnt
what is cv2?
Display Components
While you might be familiar with embeds in Discord, there are more ways to style and format your apps messages using display components, a comprehensive set of layout and content elements. To use the display components, you need to pass the IsComponentsV2 message flag (in docs: MessageFlags) when sending a message. You only need to use this flag when sending a message using the display components system, not when deferring interaction responses.
oh components v2, yeah no idea
but since the limit is 119 emojis, it errors on 120 it might mean it's some bug with .length where they forget to do +1
don't u agree? @wary coral
I don't know. the issue seems to be on Discords side as they give a 500 error and I can't find written emoji limits for select menus
yeah, definetely on their side based on the error lol, don't we have discord devs here?
maybe but it outside the scope of discord.js. I did raised the issue to the maintainers
oh u did? thank you so much, saved me some troublew
im puzzled, how do you make the same webhook send github notifications to different forum threads, like in #1006698887605653565?
/webhooks/{webhook.id}/{webhook.token}?thread_id={threadChannel.id}
https://discord.com/developers/docs/resources/webhook#execute-webhook
alr so i've added the thread_id parameter, now i cant make it a github webhook
/webhooks/{webhook.id}/{webhook.token}/github?thread_id={threadChannel.id}
https://discord.com/developers/docs/resources/webhook#execute-githubcompatible-webhook
Are your trying to use this in code?
oh so you first do /github and then pass the thread_id option
no im configuring it in the github repo settings
that works, thanks
np
if you set channeltypes in a selectchannelmenu and there are no such channeltypes in the guild. what happens?
does it error or discord handles that?
😭 why would it error bro?
you could... try it and see. else, this is a question for ddevs, the library has nothing to do with it
hello guys,
what should i use for this fields ? i tried to search about it on discord.js.org, discordjs.guide and the discord.js package.
i don't get it how can i get the values and fields to save them into a data ?
documentation suggestion for @light ibex:
ModalSubmitFields discord.js@14.25.1
Represents the serialized fields from a modal submit interaction
cuz there wont be any channels to display in the menu
try to search for a channel "syder-is-the-best-developer", there shouldn't be any results
yh but thats with search
thank you
You also can't use .trim on that because those return a collection, not an entry
If you are expecting a single result, do .first().trim()
😭 it won't error bro
have you tried my question then?
why would I?
then why are you assuming something if you havent tried it?
can u hold a spoon in your mouth while petting a cat?
based on your experience u will say u can, but u haven't tried it, have u?
if you got nothing useful to say dont reply
I said something useful, it won't error
that was literally your question, wasn't it?
you didnt. stop it
I did say it won't error, here is proof
stop with the nonsense
mods deal with this guy 
but this guy is trolling rn, asking for help and then ignoring it
just, stop
sure
How can I edit container components the same way I edit embeds?
Also, how can I modify the components inside a container like updating the options in a select menu without causing duplicates?
As shown in the image, whenever I try to edit the select menu inside the container, it ends up duplicating the menus.
Sounds like you're appending the component to the array instead of putting it in the same spot inside the container
that what i'm i talking about, how can i put select menu insde the container ?
this what i did
You need to reconstruct the container and then slice the new component in
so how can i do this ?
In your for loop on line 75 you're iterating through the components in the message, not the components inside the container. You want to be looping through message.components[0].components instead and then replacing the row you find there
- message
- container
- action row
- select menu
- action row
- container
There's the createComponentBuilder function if you want to use the splice function Mafia mentioned. You'll probably want to do that instead of just pushing the new row in once you've found the old one
OKay Thank you 🤍
@wary coral in-case u wondered why I needed 125 emojis, am making a drop system with one of the types being find the emoji
why
interaction.guild.channels.cache.get('1448028434058973366').setName('A')
it's slow ? is that bcuz rate limit ?
You are prob calling it too often and getting rate limited
Bots have a special rate limit for editing name and topic of channels
2 edits / 10 min
how about create channel ?
I mean, everything have a rate limit. Not as bad as editing channel name tho
ok ty
hello
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
// GatewayIntentBits.GuildMessages,
// GatewayIntentBits.GuildVoiceStates,
GatewayIntentBits.MessageContent,
// لو ما تحتاج Presences فعلاً، حاول تشيل:
// GatewayIntentBits.GuildPresences,
],
partials: [
Partials.Channel,
Partials.Message,
Partials.User,
Partials.GuildMember,
],
makeCache: Options.cacheWithLimits({
// لا نحتفظ بأي رسائل في الكاش تقريبًا (أنت تعتمد كثير على DB أصلاً)
MessageManager: 0,
// عدد الأعضاء المخزّنين لكل Guild
GuildMemberManager: 40000, // عدّل حسب حجم السيرفرات
// الكاش العام للمستخدمين
UserManager: 500000,
// لو ما تحتاج presence في الذاكرة:
PresenceManager: 0,
}),
sweepers: {
messages: {
interval: 600, // كل 10 دقائق
lifetime: 300, // امسح الرسائل الأقدم من 5 دقائق من الكاش
},
users: {
interval: 1800, // كل 30 دقيقة
filter: () => user => !user.bot, // مثال: امسح المستخدمين العاديين من الكاش
},
},
});
what's wrrong in guild cache size exists only 2
that it's me and bot
in guilds there like 20 members
on the assumption you're asking about the guild member cache, not the guild cache, members aren't cached on ready
you'll need to fetch them with <Guild>.members.fetch()
though if you just want the number of members, <Guild>.memberCount also exists and doesn't require any fetching
✨
why is there guild.roles.cache and no .fetch?
is there any way to put inline fields inside a container?
nope
documentation suggestion for @keen widget:
RoleManager#fetch() discord.js@14.25.1
Obtains a role from Discord, or the role cache if they're already available.
// Fetch all roles from the guild
message.guild.roles.fetch()
.then(roles => console.log(`There are ${roles.size} roles.`))
.catch(console.error);
bruh
Because you don't fetch from a cache. A cache is local
how did u answer me that fast
You can fetch from the RoleManager which contains a cache
sorry, I am blind
theres no way to simulate it?
no
Not without casing formatting errors
How could I not see it in the freaking docs ...
yeah, i imagined
discord sucks
Phones just hit different
embeds are still existent, they're not going away
i dont think i can send an embed + container
you cannot, no
i cant use embed in my case, ill find a way to do what im trying to do
ty for ur help
I meant rolemanager class for both
am not that brainrot to not know such basics
also while we speak about that, are roles cached on ready?
with the Guilds intent, yes
okay and is it same endpojnt as guilds?
just seperated in djs for memory management freedom
I'm not totally sure what answer you're looking for here so just to explain a few things
the reason guilds, roles, channels, etc. are cached on ready with the Guilds intent is that with this intent, discord sends the guildCreate event immediately after the gateway's ready event for every available guild your bot is in
djs's clientReady event emits after having received these
djs does not fetch anything on ready via rest, so there isn't an endpoint of any sort involved
there are separate endpoints for fetching a guild and fetching a guild's roles
though I believe fetching a guild does also provide its roles, and djs would cache these roles
however djs also relies on the Guilds intent for many of its features, so in most cases we actually recommend you don't fetch guilds
oh I thought u need to fetch all guilds when starting, u cleared one thing up I was wrong about, and yeah I was wandering about that if fetching a guild returns roles
What is the recommended file/code structure for me to accommodate modal submission logics? Inside the slash command file that triggered it?
Examples are welcome
there's really no "official" recommended code structure
it pretty much depends on what you like and what you need
pretty much the only built-in helper for that in djs is the awaitModalSubmit method, which is easy to use
hey, i want to build a embed but it seems like addComponents is now deprecated, whats the new way to make modals? my current approach is this:
let modal = new ModalBuilder()
.setCustomId(`settings_edit_modal_${selected}`)
.setTitle("Edit Settings");
switch (selected) {
case "message_xpp":
const enabled = new TextInputBuilder()
.setCustomId("enabled")
.setLabel("Enabled")
.setStyle(TextInputStyle.Short)
.setValue(String(settings.messageXpEnabled))
.setRequired(true)
.setMinLength(4)
.setMaxLength(5);
modal.addComponents( // <-- deprecated
new ActionRowBuilder<TextInputBuilder>().addComponents(enabled)
);
}
you add a label which contains the text input
ModalBuilder#addLabelComponents() builders@1.13.0
Adds label components to this modal.
LabelBuilder#setTextInputComponent() discord.js@14.25.1
Sets a text input component to this label.
ty, will have a look
How many of you use visualization tools like json crack to understand json data and other types of that like XML and such?
Sounds unrelated to discordjs
Never did tbh. I usually just figure it out from observation and context, if no docs are available
const { SlashCommandBuilder, PermissionFlagsBits } = require('discord.js');
const { UserProfile } = require('../../schemas/UserProfile');
module.exports = {
async execute (interaction) {
if (!interaction.inGuild()) {
interaction.reply({
content: "This command can only be used inside Chonsa!",
ephermeral: true,
});
return;
};
const addAmount = interaction.options.getNumber('amount');
try {
await interaction.deferReply();
let userProfile = await UserProfile.findOne({
userId: interaction.options.getUser('user').id,
});
if (!userProfile) {
userProfile = new UserProfile({ userId: interaction.options.getUser('user').id });
}
userProfile.balance += addAmount;
await userProfile.save();
interaction.editReply(
`${addAmount} was added to <@${interaction.options.getUser('user').id}>'s' balance\nNew balance: ${userProfile.balance}`
)
} catch (error) {
console.log(`Error handling /daily...`, error)
}
},
data: new SlashCommandBuilder()
.setName('add')
.setDescription("add currency to someone's balance")
.setDefaultMemberPermissions(PermissionFlagsBits.Administrator)
.addUserOption((option) => option
.setName('user')
.setDescription("Who's balance are adding to?")
.setRequired(true))
.addNumberOption((option) => option
.setName('amount')
.setDescription('How much would you like to add?')
.setRequired(true)),
}```
that's not a djs error
It’s not?!?
Oh… oops okay - I thought it was 😅
"cannot read properties of undefined (reading 'X')" means somewhere you're doing undefined.X
the fact that it says 'findOne' means it's one of your findOne calls
the only usage there is UserProfile.findOne
so UserProfile is undefined
oh okay.. I thought I defined it.. I'll look into it - thx
There's a difference between defining a variable and a variable having a value of undefined - the latter of which is your case
const myVariable = undefined;
// Variable `myVariable` has been defined and can be referenced, but its underlying value is of type "undefined"```
How would I make a command have like 4 different replies all using luck / Math.random()??
you can use interaction.followUp for that
interaction.followUp?
or do you mean a random reply based on 4 possible replies?
a random reply based on those 4 possible ones
that isnt really djs related and just basic js. you can put those 4 replies in array and then get random
oh okayyyy I thought it would be
thx tho!
if it has to do with discord, it's djs related
if it doesn't, then it's not
does discordjs support per server profiles for bots yet ?
GuildMemberManager#editMe() discord.js@14.25.1
Edits the current application's guild member in a guild.
thx
@unique shoal guild.editMe says not a function
@queen goblet guild.members.editMe
i see wahts wrong
i wasnt on the updated version of djs
hey y'all I need some help. I'm trying to make a work command for my bot. I have the cooldown system finished, now I am trying to figure out how to calculate the timestamp at which the user will be able to work again. Here is my code to reject the user if the cooldown isnt finished:
if (!bot.cooldowns.work(cmd.user)) {
let remaining = Date.now()-user.workedAt;
let embed = new EmbedBuilder()
.setTitle(`Chill out`)
.setDescription(`You can work again at <t:`)
}```
I just need to know how to calculate the time at which the user will be able to work again.
dont think thats djs question
I'm not great at date math.
Cooldowns
Spam is something you generally want to avoid, especially if one of your commands require calls to other APIs or takes a bit of time to build/send. This section assumes you followed the Command Handling part of the guide. First, add a cooldown property to your command. This will determine how long the user would have to wait (in seconds) before using the command again. In your main file, initialize a Collection to store cooldowns of commands: 1. now: The current timestamp.
wouldnt you just calculate the current time from the time you have saved
We agree that in a v2 component with simple text containing a link, we can't use YouTube's auto-embed feature, right?
Correct. I don't believe links in TextDisplay components render an embed
Okay, that's what I thought, unlucky
Try it bro
const { SlashCommandBuilder, PermissionFlagsBits } = require('discord.js');
const UserProfile = require('../../schemas/UserProfile'); // got error here bro
module.exports = {
async execute(interaction) {
if (!interaction.inGuild()) {
return interaction.reply({
content: "This command can only be used inside Chonsa!",
ephemeral: true,
});
}
const addAmount = interaction.options.getNumber('amount');
try {
await interaction.deferReply();
let userProfile = await UserProfile.findOne({
userId: interaction.options.getUser('user').id,
});
if (!userProfile) {
userProfile = new UserProfile({
userId: interaction.options.getUser('user').id,
balance: 0
});
}
userProfile.balance = (userProfile.balance || 0) + addAmount; //safe math
await userProfile.save();
await interaction.editReply(
`${addAmount} was added to <@${interaction.options.getUser('user').id}>'s balance\nNew balance: ${userProfile.balance}`
);
} catch (error) {
console.log(`Error handling /add...`, error);
}
},
data: new SlashCommandBuilder()
.setName('add')
.setDescription("add currency to someone's balance")
.setDefaultMemberPermissions(PermissionFlagsBits.Administrator)
.addUserOption(option =>
option.setName('user')
.setDescription("Who's balance are adding to?")
.setRequired(true))
.addNumberOption(option =>
option.setName('amount')
.setDescription('How much would you like to add?')
.setRequired(true)),
};
Can you elaborate on that (connecting through a socks5 proxy)? I am trying to do the same thing in my client, but I get an error about this.dispatch is not a function:
const proxyAgent = new SocksProxyAgent('socks5://127.0.0.1:40000');
//in client
rest:
{
timeout: 20000,
agent: proxyAgent
},
ws: {agent: proxyAgent},```
I have been looking at `https://discordjs.guide/legacy/additional-info/proxy`
Thanks for anything you can do to point me in the right direction 🙂
❌ Failed to register commands: DiscordAPIError: Maximum number of application commands reached (5).
at RequestHandler.execute (C:\Users\zeinf\Documents\Projects\tryhard\main\tryhard-main\node_modules\discord.js\src\rest\RequestHandler.js:350:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (C:\Users\zeinf\Documents\Projects\tryhard\main\tryhard-main\node_modules\discord.js\src\rest\RequestHandler.js:51:14)
at async ApplicationCommandManager.set (C:\Users\zeinf\Documents\Projects\tryhard\main\tryhard-main\node_modules\discord.js\src\managers\ApplicationCommandManager.js:162:18)
at async module.exports (C:\Users\zeinf\Documents\Projects\tryhard\main\tryhard-main\handler\slash.js:68:9) {
method: 'put',
path: '/applications/1069217203800518727/commands',
code: 30032,
httpStatus: 400,
requestData: {
json: [
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object]
],
files: []
}
}```
what even is the limit at this point? I barely have like 40 commands, even less
100 slash commands, 5 user context menu, 5 message context menu
You're exceeding the context menu command limit
add like sub command
ahhh I see thanks!
correct
You can bypass this by using guild and global commands to double it to 10
I'm exceeding the user one
wow I didnt know about user context menus, thats kinda neat
can I do multiple operations in 1 API call to guild members? like changing nickname & adding a role ?
You can do multiple edits on a single member via member.edit
GuildMember#edit() discord.js@14.25.1
Edits this member.
Assuming you know their roles beforehand
Does anyone know why this is happening?
Idk if am doing something wrong or
with the image not showing
is the Buffer.from(..., 'base64') necessary? I can imagine that's what's messing it up
I have to buffer it as am building the html
Like this
How can put an attachment on addMediaGalleryComponents
please someone help me
in the same way as you would have with embeds previously: you attach the file to the message (with the files option) and reference it with an attachment:// url in the component
Media Gallery
A Media Gallery is a display component that can display a grid of up to 10 media attachments. Each media item can have an optional alt text (description) and can be marked as spoiler. You can use the MediaGalleryBuilder and MediaGalleryItemBuilder classes to easily create a Media Gallery component and its items:...
const pizzaChartAttachment = new AttachmentBuilder(pizzaGraficoBuffer, {
name: 'pizza_chart.png'
});
const graph1media = new MediaGalleryBuilder().addItems((mediaGalleryItem) =>
mediaGalleryItem
.setDescription('alt')
.setURL('attachment://pizza_chart.png')
.setSpoiler(false)
);
...
.addMediaGalleryComponents(graph1media)
```
this way?
on the assumption you're also sending the attachment alongside the component, yes
i forgot it 💀
But I don't want to send the images if they're not inside the container, how do I do that?
don't include them in the files array
so.. i need include them in the attachment array?
no, if you don't want to send an attachment, don't include it at all
but it gives error
components[1].components[3].items[0].media.url[UNFURLED_MEDIA_ITEM_REFERENCED_ATTACHMENT_NOT_FOUND]: The referenced attachment ("attachment://linha_chart.png") was not found
components[1].components[6].items[0].media.url[UNFURLED_MEDIA_ITEM_REFERENCED_ATTACHMENT_NOT_FOUND]: The referenced attachment ("attachment://pizza_chart.png") was not found
then it sounds like those will be referenced in the media gallery
is it possible your media gallery itself isn't in the container?
const linhaChartAttachment = new AttachmentBuilder(linhaGraficoBuffer, {
name: 'linha_chart.png'
});
const pizzaChartAttachment = new AttachmentBuilder(pizzaGraficoBuffer, {
name: 'pizza_chart.png'
});
const graph1media = new MediaGalleryBuilder().addItems((mediaGalleryItem) =>
mediaGalleryItem
.setDescription('alt')
.setURL('attachment://linha_chart.png')
.setSpoiler(false)
);
const graph2media = new MediaGalleryBuilder().addItems((mediaGalleryItem) =>
mediaGalleryItem
.setDescription('alt')
.setURL('attachment://pizza_chart.png')
.setSpoiler(false)
);
const separator = new SeparatorBuilder().setDivider(true).setSpacing(SeparatorSpacingSize.Small);
const exampleContainer = new ContainerBuilder()
.setAccentColor(30206)
.addTextDisplayComponents((t) =>
t.setContent(`### Analytics Influenciador <@${influencerId}>`)
)
.addSeparatorComponents(separator)
.addTextDisplayComponents((t) =>
t.setContent(
`**Convites do período**\n` +
`**+${selectedInvites.data.total - selectedInvites.data.left}** ` +
`(+${selectedInvites.data.total}, -${selectedInvites.data.left}, +${selectedInvites.data.fake} novas)\n\n` +
`**Clientes:** ${totalUsers}`
)
)
.addMediaGalleryComponents(graph1media)
.addSeparatorComponents(separator)
.addTextDisplayComponents((t) => t.setContent(`## Jogadores qualificados:`))
.addMediaGalleryComponents(graph2media)
.addTextDisplayComponents((t) => t.setContent(dataString));
await interaction.editReply({
components: [buttonsRow, exampleContainer],
flags: [MessageFlags.Ephemeral, MessageFlags.IsComponentsV2]
});
}```
you're saying that after adding the files option back, the media gallery appears outside the container?
inside the container and outside
have idea what i can do?
well this code shouldn't produce that behavior
afaik if an attachment is referenced elsewhere via an attachment:// url it should only appear there
furthermore with components v2, components should be the only thing available in the message
I'm also unable to reproduce this behavior with your code
so this sounds more like an issue with your discord client
What should I do?
for some reason...
.setButtonAccessory((button) =>
button
.setCustomId("dice_start")
.setStyle(ButtonStyle.Primary)
.setEmoji("🎲")
.setLabel("Start rolling")
)
using .setButtonAccessory((button) returns validation error for a default emoji. I have to use the buttonbuilder instead
in terms of your code? add the files option back
as for fixing your discord client? contact discord if you like
that's expected behavior
the base ButtonBuilder from @discordjs/builders doesn't resolve strings to emoji objects, but rather just accepts an APIMessageComponentEmoji object
using a component-building callback in SectionBuilder will use this base ButtonBuilder, so you'd need to call resolvePartialEmoji yourself
or of course just pass a APIMessageComponentEmoji object
okie dokie. just double checking it's not a bug
thanks
Can someone answer my question [#1448496950067462287]? I can't post it here because my question won't be clear if I send it here.
it's true, <InteractionResponse>.editReply() doesn't exist
I imagine you were looking for modalInteraction.editReply() (or response.edit() I suppose)
whats the difference between editReply() and edit()?
I thought you edit interactions through interaction.editReply()
you do, but you called response.editReply(), not modalInteraction.editReply()
response.edit() just calls modalInteraction.editReply() internally
what is the actual difference between interaction and interactionResponse?
they seem to have pretty similar methods
the InteractionResponse is a helper object that's intended to represent your response to the interaction (the message itself)
it does also have a few unresolvable issues relating to collectors so it'll be removed in the next major version
I see, thank you so much
btw the .edit() worked :)
I'm showing a modal, and having a collector set to two minutes to accept any requests. Once the time is up, it sends an embed saying time is up. However, when the user closes the modal, the collector still keeps running. Is there a way for the collector to stop when the user closes the modal, and have it throw a different exception than "Collector received no interactions before ending with reason: time"
No
I see, thanks
when a bot sends a message, can I make it ping specific mentioned users and make it not ping the others? for example
to <@userA> <-- ping this person
<@userB>, <@userC> has entered the chat. <-- do not ping these people
You can control which entities receive notifications via the allowedMentions option. You can:
- Set a default on the client
- Set for a specific message
- Use the
repliedUserkey to disable in-line reply mentions
{ ..., allowedMentions: { parse: ["users", "roles"] } }
thank you!
In regards to this, normal discord has the option to add @silent at the start of the message to not ping anyone
Does that also work for bots?
Suppress notifications flag
Since that's what being set when you do the @silent as a human
Thanks
Hey is it possible to block forqarded messages?
Message#messageSnapshots discord.js@14.25.1
The message snapshots associated with the message reference
oh no wait isnt there a message flag for it
i think this also has snapshots of messages when someone replies to a message
MessageFlags#HasSnapshot discord.js@14.25.1
This message has a snapshot (via Message Forwarding)
yeah better to check the flag
Thanks bro
what is InviteGuild on InviteCreate / InviteDelete events and is there a typecheck to check if its a Guild?
Represents a guild received from an invite, includes welcome screen data if available.
If you want the full guild, use .fetch() on it
I'm listening to the InviteDelete event to track when invites are deleted / created in the guild so i should already have the full Guild right?
Just wondering how do I typeguard it, is there anything like inCachedGuild etc
you... dont have the full guild, thats the point
InviteGuild is NOT a Guild object, it has partial data of a guild that is transmitted via the event.
I'm having an issue with my bot when I run npm start. It only outputs this and the bot doesn't come online.
Can you show your index.js?
Only guess is your token is invalid (or being read wrong) and your ClientReady never fires
Does the .env need to be BOT_TOKEN = XXX OR BOT_TOKEN=XXX?
Both should work but I personally do BOT_TOKEN="XXX"
Does the quotes do anything special?
Try adding a .catch() to client.login()
So client.login().catch()?
No. But can help with some long strings with weird characters
.catch returns a callback function with an error message. You'll want to log said error
I also want to point out that I'm completely new to JS and kinda learning as I go.
Learn about try-catch functions or the Promise#catch method then
Working with Promises is crucial for JavaScript
has this always been the case? when would it be a partial when an invite is being deleted from the guild?
partial, any time it is not cached and the event is received
I understand that there is limitations when it comes to videoes being displayed in embed messages. But shouldn't work in inline messages? Tho?
Only if there aren't embeds already. Discord won't add link embeds in that case
Why not use a media gallery in a components v2 container instead?
Oh wait, that's logging messages? Use forwards instead
No! It is a silly fun command called "snipe", so the message doesn't exist (it is deleted, and the bot send the message)
Snipe commands are widely considered a violation of user privacy. If a message is deleted it should stay that way.
- Logs for moderation purposes are fine
- Bringing back a deleted message by just anyone to expose or humiliate a user is not
Ah, I understand that but it is relatively private server for 80 friends, and the server is set to private.
and the bot is only for this server. (Guild specific server)
Doesn't matter
We won't help with that
Alright, but may I get the source of violation line? Because I have seen a relatively big bot such as "Apollo" using it and I got surprised.
Just because another bot does it doesn't make it okay. We won't support this. End of story
We are also not Discord. So we can choose to not help you simply because we believe the commands are an invasion of people's privacy
Regardless of Discord's thoughts on the matter
Let's keep this channel djs related, move off-topic elsewhere
👍
what is CacheType for?
In what context?
so for example i specify that interaction is of type ChatInputCommandInteraction. But i can also specify that it's of type ChatInputCommandInteraction<'cached'>. What does that change?
If the interaction originated in a cached guild or not
This is a help channel. Not the place to look for work
it refuses to deny what the client shows on forum channels as "Create Posts", i thought it was just CreatePublicThreads but denying that doesn't seem to work
ohh its send messages
that makes sense somewhat
beat me to it
looked at requests when setting it on the client
is there a helper function of sorts to sanitise some string into a channel name
No, you would need to write that yourself. I believe
alr
is there not a ContainerBuilder.from() method that allows me to build a container from a JSON?
no, but you can do so by setting container in new ContainerBuilder(container.toJSON())
I see, thank you!
is there any error with the api? i am trying but it says invalid token where i tried resetting the token 3 times
const { Client, GatewayIntentBits } = require('discord.js');
require('dotenv').config();
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
]
});
client.on('ready', () => {
console.log(`✅ Bot logged in as ${client.user.tag}`);
});
client.login(process.env.DISCORD_TOKEN);
env =
DISCORD_TOKEN=OTEyOTIyMjk3MjU2NTM0MD........
anybody?
nvm i dont know i did nothing and it worked now
check it with console output
@fading shard
Maybe your IDE auto safe magics
the bot is responding with response 3 but removing balance when that should only happen in response 1 or 2
because response is only within the range of 0 to 3 inclusive. array indexing starts at 0, not 1
Ohhhhhhh okay. So I should change 1 to 0 then 2 to 1, etc?
yeah
Alright thank you!!!
If I ever did more than 4 responses though how would that work?
why do you need if (response ===) anyways
the code in all of them is the exact same
you're not doing something particularly different on each random "roll"
Dude anyone can use all the permutations and combinations and get your key
already reset done 
The part they shared is the public part anyone could easily find themselves. So no
Ahh, that I wasn't aware of
Thanks
The response changes and in response 0,1 it removes balance & 2,3 adds balance
for how long are embed buttons able to register interactions when sent as a standalone message? would bot reboot make them inaccessible?
the response is always "${auditions[response]} you have lost ${response2.toLocaleString()}" though
I just noticed one half adds and the other adds though, so that's correct
you'd only need the if for that
The other 2 responses do say different things
there's no expiration for buttons
It says you’ve gain or lost
ah, maybe you could just store successes and fails separately, then you choose whether it succeeded or failed, and choose a message from each
so you don't end up with a ton more checks or repeated code
Oh how would you do that?
what part?
Store the successes and fails then grab them
you have a single array for both successes and fails, and you then have to figure out manually which is which
I suggest storing them separately so you don't need to figure that
you already know depending on the if {} branch you are whether it's a success or a failure
or storing them separately but not as strings, but as objects that contain whether it's a success or a failure (and the message), but that's not as straightforward and might be a bit harder if you're not familiar with objects
So like const success = [successes] ?
if successes were the strings that mean success then yeah
const successes = ['', ''];
const failures = ['', ''];
// succeeded would be randomly rolled
if (succeeded) {
// give money
const message = // choose randomly from the successes array, you already know how
editReply(message);
} else {
// take money
const message = // choose randomly from the failures array, you already know how
editReply(message);
}
Alright thank you so much!!
is there a method to check if bot can send messages in channel? because now i would have to check if bot has the send message, view channel flags right? (and embedlinks for embeds?)
Are bot guild profiles supported in discord.js yet?
this #1040031099860045854 message
for changing banner, pfp and bio by server
oh okay thanks
hey
does anyone know how can i fix the encryption error in discord.js
Unhandled promise rejection: Error: No compatible encryption modes. Available include: aead_aes256_gcm_rtpsize, aead_xchacha20_poly1305_rtpsize
at chooseEncryptionMode (file:node_modules/@discordjs/voice/dist/index.mjs:476:11)
at file:node_modules/@discordjs/voice/dist/index.mjs:668:21
this happened while i was testing my bot in a vc
please ping me if responding
Update /voice
to what version
thanks! ill try it
But best case would simply be: latest
this is the discord.js server. this is not a place for recruiting people
await interaction.showModal(reasonModal);
const modalSubmit = await interaction.awaitModalSubmit({ time: 60_000, filter: i => i.user.id === interaction.user.id }).catch(_ => {});
if (!modalSubmit) return;
await modalSubmit.deferUpdate();
const reason = modalSubmit.fields.getTextInputValue('reasonInput');
so i have this piece of code responsible for working with a modal. interaction here is of ButtonInteraction type. 2 questions:
- is there any point in applying such filter here?
- i've noticed that this can be abused by constantly triggering and closing the modal, calling the
awaitModalSubmitfunction every time. Should i protect my code from that and if so, how?
no theres no point in such filter since modal is only shown to interaction user. and yes you should add cooldowns systems or something to prevent abuse in your apps
anyone knows?
not related to djs but what's the format to show / commands like this
- yes, awaitModalSubmit will await any modal submit, so you could open modals from two completely different commands at the same time, and once one submits, if the other didn't have a filter it'll also trigger, also applies to two users with open modals of the same command
- you can add a max: 1 so it only runs for one submit, or you can append the interaction id to the customId and check that in your filter, so only modals sent for that command resolve that await
there isn't
I don't think you need embed links for embeds though
though it is worth a try
i swear djs errors used to be so much more helpful?? this is so frustrating
i heard errors will get much better in v15
Received an undefined when expecting a (I think string) at test.ts@112:31
showing unknown
But yes. v15 should have better error messages...but it's largely undocumented so different problems
you gotta click on it
Threads don't cache automatically...it'll still work though
ok ty
kinda right yea, but the real issue was that i forgot that section components require an accessory component
so i have to do this jank instead
Hmm...I remember there being a specific error for that. It still wasn't a great error but a unique one
Like "received 2 errors, expecting value of ButtonBuilder and received null, expecting value of ThumbnailBuilder and received null"
ok, so I want to like an embed where if no user is mentioned, it replaces the user with something else.
Before:
User held hands with same user
After:
User held hands with themselves... sad
well you can do something like that in many ways. the most obvious way would be; if no user then do
Ok I see it... I have
**${interaction.user.username}** is holding hands with **${user.username}**
so if I can do like
if(user.username === interaction.user.username){
msg = "with themselves... sad"
} else {
msg = interaction.user.username
}
would that work?
then you can do something like this
**${interaction.user.username}** is holding hands with ${user ? user.username : 'themselves'}
this is basic js and not really djs related
sure but checking for same id is better instead of name
In this case it doesn't particularly matter if it's id or not
As it's only relevant for the instant of the command use
But overall, yeah. Usernames can change while ids cannot
works, I did the
if(user.username === interaction.user.username){
msg = "with themselves... sad"
} else {
msg = user.username
}
Why aren't you comparing id instead of username? Not that it really makes a difference since usernames are unique
they arent using the user mention or id in the response so yh doesnt matter
i dont get it, there's no max property on AwaitModalSubmitOptions and the filter doesnt work either..
const modalSubmit = await interaction.awaitModalSubmit({ time: 60_000, filter: i => i.customId === 'dfafadasd' }).catch(_ => {});
the actual modal's customId here is "reasonModal", but it still goes through
Because you can only ever collect 1
whats this different than role.members.size? #discord-dev-news message
How would you await 2 submits if your code is stuck waiting for a second one before anyhow proceeding, and with the fact that you cannot chain modals
It's an api endpoint, while what d.js has had for years - role.members - is just a filter on member cache
oh okay didnt know good to know
It's also a good idea to not swallow errors
That looks more like an issue with your runtime, considering it doesn't seem to resolve the class used and claims it's anonymous
sorry I figured it out 😭
Did you define editReply somewhere?
await interaction.deferReply(); ?
You are supposed to use await interaction.editReply(...) then
oh oops yh
Can bots listen to audio in voice calls?
Like a speech to text or something in stages
bots can do voice. but they can only connect to one channel at a time
https://discordjs.guide/voice
How can I make ComponentsV2 never allow mentions?
You can control which entities receive notifications via the allowedMentions option. You can:
- Set a default on the client
- Set for a specific message
- Use the
repliedUserkey to disable in-line reply mentions
{ ..., allowedMentions: { parse: ["users", "roles"] } }
One channel per guild
const container = new ContainerBuilder()
.setAccentColor(parseInt(getRandomColor().replace("#", ""), 16))
.addMediaGalleryComponents((gallery) =>
gallery.addItem((item) =>
item.setURL('')
)
)
.addSeparatorComponents((separator) => separator)
.addTextDisplayComponents((textDisplay) =>
textDisplay.setContent(itemList)
)
.addSeparatorComponents((separator) => separator)
.addActionRowComponents((row) =>
row.setComponents(
new ButtonBuilder()
.setCustomId("buy_item")
.setLabel("Xác nhận mua")
.setStyle(ButtonStyle.Success)
)
);
await message.channel.send({ components: [container.toJSON()], flags: MessageFlags.IsComponentsV2 });```
Why doesn't addMediaGalleryComponents work in Container Builder?
i dont see addItem in the docs, only addItems
(though one would imagine your editor would catch that)
might wanna try it:
- gallery.addItem((item) =>
+ gallery.addItems((item) =>
And image url?
Oh thank you
assuming your image provider renders properly when just sending the link, the url should be fine
how do I make it so that I can get the actual message content itself instead of the modal interaction?
im trying to edit a specific field of the messageComponent
response.message?
the debugger had it flagged as null
you'll want to specify withResponse: true in the reply options so that it resolves with an InteractionCallbackResponse as opposed to InteractionResponse (which predates the withResponse option)
you can then access <InteractionCallbackResponse>.resource.message
I see, thank you!
how would I go about editing the message since InteractionCallbackResponse doesn't have an edit method?
but InteractionCallbackResponse.resource.message does
ah I see, my bad
just know resource and message are nullable
-# though in your case it should be fine
thanks 🙏
though side note ephemeral messages are still only editable through the interaction webhook, so while you can use <Message>.edit() for non-ephemeral messages, you'd need to use <Interaction>.editReply() for ephemeral messages
so it would be modalInteraction.editReply() instead of response.resource.message.edit()?
I believe Message.edit fails w/o proper permissions
Def can’t edit w/o View Channel
yes
think so since i believe it requires the same permissions as create message (+MANAGE_MESSAGES if its not its own message)
-# can't edit another user's message, that doesn't come into play here
misread docs (and a logic error 😭)
-# (it's talking about flag editing requiring MANAGE_MESSAGES)
With Components v2. When creating a StringSelectMenuBuilder is there a limit on the number of options you can add. Or is it just limited by the global limit of 40 components?
options are not components
but as with all selects, the limit is 25 options per select
👍
how do I use followUp() on InteractionCallbackResource?
I dont see that method on the docs page
You don't. Because a callback resource is used to see the message data of an interaction response... You would need to use the interaction itself that created the resources
how do I get the interaction itself that created the resources? This is what I have currently
modalInteraction
ModalSubmitInteraction#followUp() discord.js@14.25.1
Send a follow-up message to this interaction.
🤦♂️ I feel so dumb, I've really been having a hard time with InteractionCallbackResource vs InteractionResponsevs Interaction
thank you
You pretty much only ever need an an interaction response if you need to read the data on the message itself. But sending, editing, and deleting of messages is done using the Interaction itself
Ok,so if i have this code:
.addTextDisplayComponents(
new TextDisplayBuilder().setContent("text")
)
.addSeparatorComponents(new SeparatorBuilder().setSpacing(SeparatorSpacingSize.Small).setDivider(true))```
How do i make that there is showed the server picture at size 1024?
There's 2 ways to show an image in a container.
- Use a SectionComponent and add an accessory ThumbnailComponent
- Use a MediaGalleryComponent
Neither of which however have any sizing control. Thumbnails are more designed for square images and MediaGalleries are better suited for large images or multiple images
Ye,i want square,but i tryed already to use SecionComponent ,and failed
Section
Sections represent text (one to three Text Display components) with an accessory. The accessory can either be an image (thumbnail) or button. If you do not want to send an accessory, use a Text Display component instead. You can use the SectionBuilder class to easily create a Section component:...
You most likely didn't add a TextDisplay...as a Section is required to have 1-3 TextDisplay components
So i need to use this:
.setThumbnailAccessory(
(thumbnail) => thumbnail.setDescription('alt text displaying on the image').setURL('attachment://image.png'), // Supports arbitrary URLs such as 'https://i.imgur.com/AfFp7pu.pna' as well.
);
?
As i found in the example
- What error did you get if it "failed"
- Can you show the whole container? Or the whole Section at the least?
Hi! There is no api for quests, right?
Correct
Bots do not have access to the quest related endpoints
Does anyone know how to create this type of "embed" with a dropdown wider than a regular embed?
guide suggestion for @pure steeple:
Display Components
While you might be familiar with embeds in Discord, there are more ways to style and format your apps messages using display components, a comprehensive set of layout and content elements. To use the display components, you need to pass the IsComponentsV2 message flag (in docs: MessageFlags) when sending a message. You only need to use this flag when sending a message using the display components system, not when deferring interaction responses.
I'm using discord-player to search and play the song in queue,
but the music is choppy.
should I use @discordjs/opus, opus or opusscript to play sound?
or what should I do?
better to post in #998942774994927646
discord-player enables volitions of TOS we cant help you with a project utilizing it
Is there an event that triggers when the user.primaryGuild of a server member changes?
userUpdate
okay, rewriting the music system tmr :D
its not specifically the discord-player part thats against the tos, its music bots as a whole
what if u pay for ur music license 🤔
then youre okay
Should I just use discord.js? Or should I use the discord.js@builders thing?
it depends what do you want to do
Wdym?
Workspace: selfbot-v1
what are you make?
CompV2 bot
Wdym?
Your workspace is called selfbot-v1
Are you making a self bot?
That doesn't answer my question
discord.js full supports cv2. builders is just package to make Discord API compatible objects in a programmer friendly way
more to what we are asking is what does you bot do
If you're making a gateway connected bot, you probably want to use discord.js but if you're building an oauth app or http-only bot, then you probably don't need the whole discord.js package
I’m learning how to use CompV2.
guide suggestion for @last ore:
Display Components
While you might be familiar with embeds in Discord, there are more ways to style and format your apps messages using display components, a comprehensive set of layout and content elements. To use the display components, you need to pass the IsComponentsV2 message flag (in docs: MessageFlags) when sending a message. You only need to use this flag when sending a message using the display components system, not when deferring interaction responses.

Why would you care?
Yes
Selfbots are against Discord's ToS and we wont help with them
I know and I needed help with my CompV2 bot.
sure , but that is why we care
And also you don’t even use discord.js for a self bot.
No, I don't because that is against Discord's ToS and I don't want to get banned. discord.js does not support Selfbots
Ok
hi all, is it ethical to make a bot where it detects something from an api and it dms all of our admins / managers / whoever has admin perms (there’s around 15 total) considering there’s new ratelimits ?
It depends on what you mean by "something" but it is more of a question for ddevs than here
let’s just say if it detects data from an API randomly, it’ll dm our team
If it's an external api, and the recipient expects that information, it should be fine as long as you respect the ratelimits
yes, external. how could i “respect” the ratelimits?
Ratelimits are dynamic and adjust based on usage, ig if you do not message frequently it should be fine. DMs are more regulated than other routes to prevent spam
interesting ok, i’ll give it a shot, thanks.
It'd be recommended to ping a shared role or something, so it's only one message
How could I detect if a users ID is another server’s channel where their ID and username would be held and then block them.
What?
That's just an if statement comparing two strings. How you get those values depends on a lot of things that you haven't provided much context for
What context do I need to provide?
Does this help?
You'd be better off using a database as a scalable solution, as you're either holding a lot of stuff in memory and/or making a lot of API requests to get those messages
MessageManager#fetch() discord.js@14.25.1
Fetches message(s) from a channel. The returned Collection does not contain reaction users of the messages if they were not cached. Those need to be fetched separately in such a case.
// Fetch a message
channel.messages.fetch('99539446449315840')
.then(message => console.log(message.content))
.catch(console.error);
If you do need to fetch a message, and then after that, it's just an if statement to compare strings
Do you control this bot at all, or is this someone else's bot that you want to read messages from?
It would be like comparing the ID of the person who pressed the button to if their ID is in either of those 2 channels.
I don’t control the bot in that screenshot.
why do you need to know that information?
There's interaction.user.id
To tell me if they are marked or not.
Looking at the screenshot there'd be over 15k messages for you to look through every time, I would say that your idea falls kind of flat due to that
Compare that to the message content
Sometimes our team doesn’t read the channel, dms are much better. but if it doesn’t work out i’ll have to use this method.
Ya. Sending out DMs in bursts risks your bot being permanently blocked from DMing at all
Plus, it just has much stricter rate limits
yeah, i’ve noticed recently. before the new ratelimits we’re a thing, dming our team was actually possible. but unfortunately discord implemented a new ratelimit feature. also wondering , what can you have in modals now, heard they got updated?
Rate limiting has always been a thing. They might have adjusted it for you due to suspicious behavior
They are all dynamic and take many factors into account. They don't publish any information on how exactly it's done
(like why they don't tell you how an anticheat works)
SelectMenus and textdisplays, additionally to the textinputs that already existed before
can you upload images as well?
File Upload, right, forgot that one
probably. we make multiple bots for our needs because of ratelimits
is that all (select menus, files and text displays)?
And Text Input. That's all. For now
All kinds of select menus
I see okay thanks
@verbal plinth secondly, if you're not doign it manually, why write the POST /path -> 404 instead of just the method call and the error you get back from it
@topaz bluff, I discovered my error. When I was creating the file(s), I never saved them when I finished. Now that the file(s) are saved the bot turns on.
Also, is there a difference the Bot > Bot Permissions or OAuth2 > OAuth2 URL Generator? Can I put the permissions integer in the code and have it automatically read the permissions it needs?
url generator merely gives you an URL with permissions already filled in
and no, a random integer does not have capacity to scan your entire code and figure out how discord works and what your code would need permission wise
I just copied this from my log, which I log with client.rest.on(RESTEvents.Response). I don't see what's wrong with it, since it provides all the important information.
it leads to wrong beliefs
you could have also just said that it comes from you doing .send(). otherwise i just thought you're using postman or raw fetch()
do you know which call could have caused it? or are you just seeing it in logs
we encountered the problem on a channel.send(), we could provide the complete url but I dont think that will help much.
in the message we send a basic embed, nothing special if you thought about that.
I'm talking about on the dev site where you select permissions, it gives you that integer at the bottom. Can I put that in my code and have it assign the perms pre-selected without having to save the URL somewhere.
After sending the message, we get an error from DiscordAPI "Unknown Message", the stacktrace points back to the channel.send()
Maybe it helps mentioning that we also provide nonceStrings in the call to prevent unnecessary messages
to be fair this does not sound like something that has any relation to discord.js itself
ye we now looked into other logs and it seems that discord.js isnt the problem
it was just the first idea 😅
setting makeCache as
ThreadManager: 0,
ThreadMemberManager: 0,
GuildTextThreadManager: 0,
GuildForumThreadManager: 0,
doesnt distrubt bots ability to reply message commands right? (yes i still support them)
and what are default cache settings, where can i find them
this cant be it?
so by default there is no limit to caches except message caches?
correct
what about this?
maybe if they're in threads but I'm not so sure
worth testing
yeah ig gotta test this out
what hosting paltform is best for big bots and all in one bots
That's not a topic for this channel, but we do have a list of recommended hosts in #resources
can i edit a message like this , to avoid cache/fetch
await client.rest.patch(
Routes.channelMessage(jtc.panelChannel, jtc.panelMessage),
{ body: result.panelJSON }
);
does rest manager also handles ratelimits?
cause im thinking to reduce my messageManager cache or disable it. its either pulling all panel channel ids and set them in keepoverlimit in makecache or this
yes you can edit like that, and the rest manager is the only place where rest ratelimits are handled
you only need the channel cached to do that though
MessageManager#edit() discord.js@14.25.1
Edits a message, even if it's not cached.
why do i need channel cached tho, cant the endpoint take channel id and message id and discord does it internal magic
i need channel cached if i wanna do it by discord.js messageManager#edit, put not for direct rest request right?
correct
I meant that you don't need the message cached, which is what you were suggesting with this
you only need the channel
yeah, cause i cant mess with channel cache. but there tiny chance for channel to not be cached, so i can save a request by this
thanks a lot for your help
what would the tiny chance be?
is there no edge case where a guild/channel is not cached?
if you have the Guilds intent then they're always cached
or well, channels where you're in obv
if you receive a command from a guild you're not in you don't get much data from discord
which includes the channel
hmmm, ig i could use this too
setting messageManager cache as 0 wont break the bot right? i dont call messages.cache.get anywhere now
afaik the only dangerous ones are the ones mentioned in the guide
oh, then im safe. ig i could reduce my ram a lot now.
thanks again
if you're comfortable with raw api calls and don't want cache then you can just use /core
it's pretty much just the ws and rest manager wrapped in a nicer api but with no cache
well i need some cache, and rewriting whole codebase is not the thing i wanna pick up rn.
yeah that'd require you to rewrite everything, fair enough then
❌ Uncaught Exception: Error: Expected token to be set for this request, but none was present
at _REST.resolveRequest (D:\Dodi games\Games\node_modules\@discordjs\rest\dist\index.js:1346:15)
at _REST.queueRequest (D:\Dodi games\Games\node_modules\@discordjs\rest\dist\index.js:1306:46)
at _REST.request (D:\Dodi games\Games\node_modules\@discordjs\rest\dist\index.js:1272:33)
at _REST.post (D:\Dodi games\Games\node_modules\@discordjs\rest\dist\index.js:1246:17)
at TextChannel.send (D:\Dodi games\Games\node_modules\discord.js\src\structures\interfaces\TextBasedChannel.js:182:38)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)```
What's your DJS version?
Because this looks like an old bug that's been fixed already
v14 and am jest tryn to set new banner heres the code:
if (interaction.customId === "banner") {
try {
await interaction.reply("الرجاء ارسال بنر صوره او رابط..");
const filter = (m) => m.author.id === interaction.user.id && (m.attachments.size > 0 || /^https?:\/\/\S+\.\S+/.test(m.content));
const response = await interaction.channel.awaitMessages({ filter, max: 1, time: 60000 });
if (response.size === 0) {
return interaction.editReply("لا يوجد اي تعديلات.");
}
const bannerURL = response.first().attachments.size > 0 ? response.first().attachments.first().url : response.first().content;
await client.user.setBanner(bannerURL);
await interaction.editReply("تم تغير بنر البوت بنجاح ✅");
} catch (e) {
await interaction.editReply(`ERROR: ${e.message}`);
}
collector.stop();
}```
which specific version?
14 has many versions
discord.js": "^14.16.3",
that’s quite outdated, try updating
can you check if a user is dm-able without dming them?
ty
If i do:
.setThumbnailAccessory(
(thumbnail) => thumbnail.setDescription('alt text displaying on the image').setURL('SP'),
); ```
Is it correct?
.setURL('SP'),
You're setting the url to the string 'SP', not the variable
So,i needa do
.setURL(SP)?
Did it fix it?
why i am getting the membercount field undefined ? or null ?
it's casuing me the issue in welcome message
/**
* Get the member count for a guild
* @param guild {Guild} - The guild to get the member count for
* @returns {Promise<number>}
* @description Get the member count for a guild
* @example
* await this.client.util.safeMemberCount(guild);
*/
public async safeMemberCount(guild: Guild): Promise<number> {
try {
// Use cached count if valid
if (guild.memberCount && guild.memberCount > 0) {
return guild.memberCount;
}
// REST fallback
const fresh = await guild.fetch().catch(() => null);
return fresh?.memberCount ?? 0;
} catch {
return 0;
}
}```
Shouldn’t have that try catch block tbh, you alr have Promise.catch
Blindly ignoring errors is bad in of itself
I’m assuming you are using this in the guild member add event?
If they typings you use for the parameter array correct this should never be undefined nor null. Showing the code where you use that would help
/**
* Parse a string
* @param content {string} - The content to parse
* @param member {GuildMember} - The member to parse the content for
* @returns {Promise<string>}
* @description Parse a string
* @example
* await this.client.util.parse(content, member);
*/
public async parse(content: string, member: GuildMember): Promise<string> {
const guild = member.guild;
const mention = `<@${member.user.id}>`;
const memberCount = await this.safeMemberCount(guild);
const joinedTimestamp = member.joinedTimestamp ?? Date.now();
return content
.replaceAll(/\\n/g, "\n")
.replaceAll(/{server:name}/g, guild.name)
.replaceAll(/{server:member:count}/g, String(memberCount))
.replaceAll(/{member:name}/g, member.displayName)
.replaceAll(/{member:mention}/g, mention)
.replaceAll(/{member:id}/g, member.user.id)
.replaceAll(/{member:created_at}/g, `<t:${Math.floor(member.user.createdTimestamp / 1000)}:R>`)
.replaceAll(/{member:joined_at}/g, `<t:${Math.floor(joinedTimestamp / 1000)}:R>`)
.replaceAll(/{member:tag}/g, member.user.tag);
}
Can you log the error if guild.fetch() throws?
You really shouldn't have to fetch it in the first place. What made you make that function in the first place?
it was giving undefined values or null in guild.memberCount
That also shouldn't happen if that parameter is a GuildMember. Can you show where/how you call that parse function?
if (config.embedData.description) {
embed.setDescription(await this.client.util.parse(config.embedData.description, member) || '');
}
This is gonna take forever if we keep going like this. This doesn't show any sign of what member is defined as... what djs event does this come from and what properties of what parameter are those? Or is this a result of calling a function/getting from some cache and not from event parameters?
That still doesn't answer my question
Hey, is it possible to use the main branch version of core and http? The straight-forward way of pulling from a git repo with npm does not work due to the monorepo as far as I'm aware. Are there any updates on when to expect a major release for core and http?
Alternatively you could console.log(member) and we'll be closer
wait let me try
There are dev releases on npm
also there is only core. There is no http package
Ah, I mean rest of course
i need help understanding something, in march i checked my bots total users using the client.guilds (8.980k servers) and it was 300k+ i checked couple days ago 23k, with 8.293k servers, how did i go from 339.4k users across total guilds, to 23k users in near the same amount of guild spread just missing a few hundred servers from possible dropped servers, unless my counter is broken now?
GuildMemberAdd job 927811764895227945-1084336014455230464-1765710374114 failed for guild 927811764895227945: Cannot read properties of undefined (reading 'toString')
membercount is still undefined
Maybe your bot just left a server that had a lot of users?
yes, but,
where does 23k users come from 8k servers? that makes no sense it should still be in the min 100k range
thats like 2 users to a server which makes 0 sense
unless theres been a overhaul with how users get broadcasted? i honestly dunno why the numbers lower than server count, i would understand if it said 400 servers and 23k then that would feel average mix
Why are you calling toString() on something? That's not the log I asked for
How do you calculate that member count per guild?
interaction.client.shard.broadcastEval(c => c.guilds.cache.reduce((acc, guild) => acc + guild.memberCount, 0))
i am calling it on guild.membercount
public async parse(content: string, member: GuildMember): Promise<string> {
const guild = member.guild;
const mention = `<@${member.user.id}>`;
const memberCount = await this.safeMemberCount(guild);
const joinedTimestamp = member.joinedTimestamp ?? Date.now();
return content
.replaceAll(/\\n/g, "\n")
.replaceAll(/{server:name}/g, guild.name)
.replaceAll(/{server:member:count}/g, memberCount.toString())
.replaceAll(/{member:name}/g, member.displayName)
.replaceAll(/{member:mention}/g, mention)
.replaceAll(/{member:id}/g, member.user.id)
.replaceAll(/{member:created_at}/g, `<t:${Math.floor(member.user.createdTimestamp / 1000)}:R>`)
.replaceAll(/{member:joined_at}/g, `<t:${Math.floor(joinedTimestamp / 1000)}:R>`)
.replaceAll(/{member:tag}/g, member.user.tag);
}```
i already did but got ntng no err
Error in parse for member 1426071500892405781 in guild 927811764895227945: Cannot read properties of undefined (reading 'toString')
Stack: TypeError: Cannot read properties of undefined (reading 'toString')
at Util.parse (file:///root/Xieron/dist/Structures/util.js:350:73)
at Util.buildGreeting (file:///root/Xieron/dist/Structures/util.js:123:61)
at Job.task (file:///root/Xieron/dist/Queue/GuildMemberAdd/GuildMemberAdd.js:231:64)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
As soon as you have an unavailable guild that will cause the result from that shard to be NaN
I don't see you calling toString() here nor do I see you doing the log I asked
You're not calling it on guild.memberCount, you're calling it on the result of your function
Would I need to filter and fetch a collection from each shard?
You should simply check for unavailable in that reduce call
acc + (guild.available ? guild.memberCount : 0) or guild.memberCount ?? 0
i directly tried member.guild.memberCount.toString()
And that's still not what I asked to log. I gave you two options what you could do/show me. You chose neither
sorry i quite can't understand what you are asking for can you please tell me in simple words ?
is actually possibile customize the same bot, but in different server, discord bot has differnt description and logo ?
Won't get simpler than that 👆
wait let me do it