#djs-help-v14
78874 messages · Page 51 of 79
There’s no variables being put into any part of the modal
He means this is the temp:
const { ModalBuilder, TextInputBuilder, TextInputStyle, ActionRowBuilder } = require('discord.js');
module.exports = {
customId: 'test',
async execute(interaction, args, client) {
const modal = new ModalBuilder()
.setCustomId('test_modal')
.setTitle('test Modal');
const input = new TextInputBuilder()
.setCustomId('test_input')
.setLabel('Enter some text')
.setStyle(TextInputStyle.Short)
.setRequired(true);
modal.addComponents(new ActionRowBuilder().addComponents(input));
await interaction.showModal(modal);
}
};
That’s pretty standard
The legacy way
You can define the modal where you use it
That’s usually where you start before you try factoring it
Ohh so i need define it in the cmd file
That’s the easiest way
And suitable for most cases
You’d only factor it out into another file if it’s used in multiple places
Alright so i can delte this file and do the form in the cmd file
Yea
And should i do the logic in the cmd file?
Whatever you need to do before you show the modal
Or decide not to show modal
i dont know if its extension of the discord rich presence made by crawl but how do you get your status to say "Playing Code" instead of "Playing Visual Studio Code"
Alright
Probably fork the extension? 
how do you do that? is there docs?
after completing the steps you will get your status to "Playing Code"?
No. That will just make it so you can modify the source code yourself
Fork the repo, change extension code to detect VSC and make a special case for it, then install it into VSC
The repo doesn’t hold your hand on the inner workings, but you can prob figure it out by inspection
👍
(Even easier w/ AI tbh)
@stable sun is this good
.addOptions(
(optionBuilder) => setLabel('Warning').setValue('warning').setDescription('Issue a warning to a user'),
)
You forgot the optionBuilder.
Ohh
Thx
Hi, I'm getting this error when trying to edit an interaction reply after some amount of time:
757 | if (status >= 400 && status < 500) {
758 | if (status === 401 && requestData.auth) {
759 | manager.setToken(null);
760 | }
761 | const data = await parseResponse(res);
762 | throw new DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData);
^
error: Invalid Webhook Token
requestBody: {
files: [],
json: [Object ...],
},
rawError: {
message: "Invalid Webhook Token",
code: 50027,
},
code: 50027,
status: 401,
method: "PATCH",
url: "https://discord.com/api/v10/webhooks/****/messages/%40original",
is there a way to get around this?
Get around tokens expiring? no
is it possible for me to get the message from its id and edit it that way?
Only if it isnt ephemeral, and you have a bot user in the guild
that's a bit limiting but fine i guess. thanks!
Thats necessary for the permissions model
@stable sun this is my Form now:
const modal = new ModalBuilder().setCustomId('open-case').setTitle('Open Moderation Case')
.addLabelComponents((labelBuilder) => {
return label
.setCustomId('case-category')
.addStringSelectMenuComponent((menuBuilder) => {
return menuBuilder
.setCustomId('case-category')
.setPlaceholder('Select case category')
.addOptions(
(optionBuilder) => optionBuilder.setLabel('Inquiry').setValue('inquiry').setDescription('General inquiry'),
(optionBuilder) => optionBuilder.setLabel('Discipline').setValue('discipline').setDescription('Disciplinary action'),
(optionBuilder) => optionBuilder.setLabel('Urgent').setValue('urgent').setDescription('Urgent case'),
(optionBuilder) => optionBuilder.setLabel('Executive').setValue('executive').setDescription('Executive decision'),
)
})
.setLabel('Select the category for this case:')
.setDescription('Choose the appropriate category for the moderation case.')
})
.addLabelComponents((labelBuilder) => {
return label
.setCustomId('select-user')
.addUserSelectMenuComponent((menuBuilder) => {
return menuBuilder
.setCustomId('select-user')
.setPlaceholder('Select a user')
.setMinValues(1)
.setMaxValues(1);
})
.setLabel('Select the user involved in this case:')
.setDescription('Choose the user who is the subject of this moderation case.')
});
await interaction.showModal(modal);
What do you say good our not good?
LGTM
That’s mb
Obv no custom id on labels
It doesn’t accept input, the inner menu or text input does
Either use label or labelBuilder, not both
Not good: (labelBuilder) => { return label
Alright
A new one
set, not add
This is why you should log errors to console, not to Discord
The error stack will tell you exactly where something happened
Yeah i will get it now
[05:20:40] [Command ] [Slash] Command "open-case" executed by mihivx (1427480488511279124) in Mein Test Bot server (1428234467272687641)
Error showing modal: ValidationError > s.object(T)
Expected the value to be an object, but received function instead
Received:
| [Function]
at _ObjectValidator.handle (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:2070:9)
at _ObjectValidator.parse (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:972:90)
at C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\builders\dist\index.js:1176:164
at Array.map (<anonymous>)
at StringSelectMenuBuilder.addOptions (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\builders\dist\index.js:1175:28)
at C:\Users\user\Documents\VSCode\random bot\Synapse-Base\commands\Moderation\open-case.js:18:26
at resolveBuilder (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\builders\dist\index.js:2461:12)
at LabelBuilder.setStringSelectMenuComponent (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\builders\dist\index.js:1580:27)
at C:\Users\user\Documents\VSCode\random bot\Synapse-Base\commands\Moderation\open-case.js:14:18
at resolveBuilder (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\builders\dist\index.js:2461:12)
[05:20:58] [Database] Backup settings changed: Interval=24h, Retention=7d
This is the error
Something to do with the select menu options
Not sure what though, havent used these new ones
Idk but i looked at the old its much better and easier but i want learn the new one
@stable sun this is now the error.
(node:37) DeprecationWarning: The ready event has been renamed to clientReady to distinguish it from the gateway READY event and will only emit under that name in v15. Please use clientReady instead.
yes, do you have a question about that deprecation warning?
Yes how to fix it
by using clientReady instead of ready
I stopped my bot it doesn't run anymore
But where
wherever your ready event is
What error do you receive?
After renaming it to clientReady in ready event and index.js it doesn't show an error but my bot doesn't work anymore it just says
Logged in as
Could you share the code for open-case.js?
tag suggestion for @toxic moat:
If you aren't getting any errors, try to place console.log checkpoints throughout your code to find out where execution stops.
- Once you do, log relevant values and if-conditions
- More sophisticated debugging methods are breakpoints and runtime inspections: learn more
Apparently it’s typed to receive callbacks, but resolveBuilder is never used
Applies to the other method spliceOptions
Just go back to manually instantiating the StringSelectMenuOption for now
#1428631452248969227 help me please
Hey. Is there a way to know in advance if a bot can DM someone ? If not, would the send method throw an error that I should catch and do some fallback strategy there ?
No.
Just handle rejections
So .send would throw an error, go it
Yea
Thank you for you guidance
Is it possible to send an ephemeral message in a GuildText channel when it's not a reply ? If the bot doesn't mention anyone in the message who would see it ? And if I mention 1 person would they see it ? 2 persons ?
No, ephemeral messages can only be created through interactions
That's what I thought yea. Makes sense ngl
Hey can anyone tell me which verison of discord js supports all the new components v2
It supports all of em?
Lemme see thanks tho 🙂
Does sharding only affect the number of guilds in a shard, or is it also influenced by the number of members in individual guilds?
For example, will a server with two million members automatically be assigned its own shard?
number of guilds
So if ur bot was in 100 2m+ member guilds they could technically all be on the same shard?
unlikely
if you want to do load balancing based on guild size, that's on you to implement in the sharder
Anyone got a bot with new components v2? I wanna test em out but my bot crashes when I add them
if you want to solve that, providing the error may help
Tried solving it and I gave up
then what do you hope as result from posting here, if you don't want to fix it?
I was asking if someone already got a bot with them and can share it
so instead of fixing the mistake and learning from it you want someone else's work, got it
this is a help channel, please only use it to get help with your own projects, thanks
Mb sure

can anyone tell me the ratelimit to edit the bot's profile on the server (avatar, banner, etc)?
you can look it up on github there are templates there that uses components v2
documentation suggestion for @steady vale:
GuildMemberManager#editMe() discord.js@14.23.2
Edits the current application's guild member in a guild.
oh, wait, rate limit
rate limits are dynamic and based on API load
if you want to cycle through avatars, just don't, tbh
It's not that, it's that the function to change avatar is unlimited and free in my bot, so I wanted to know what the limits are to add cooldown
Is the rate limit per-guild?
Probably yes
Then you could just show the user that they hit Discord's rate limit.
You don't have to implement a cooldown for something that's limited by Discord anyway.
Thanks
Got any recommendation?
just search discord components v2
This uses webhook ig
Yes but you can copy and paste the output into your code to use
Thanks
Global error or is it just me?
TypeError: Class extends value [object Object] is not a constructor or null
at Object.<anonymous> (/home/sistemas/Bots/Palitoo Studios - Pureza/Pureza BOT - Pureza/node_modules/discord.js/src/structures/BaseChannel.js:15:27)
at Module._compile (node:internal/modules/cjs/loader:1706:14)
at Object..js (node:internal/modules/cjs/loader:1839:10)
at Module.load (node:internal/modules/cjs/loader:1441:32)
at Function._load (node:internal/modules/cjs/loader:1263:12)
at TracingChannel.traceSync (node:diagnostics_channel:322:14)
at wrapModuleLoad (node:internal/modules/cjs/loader:237:24)
at Module.require (node:internal/modules/cjs/loader:1463:12)
at require (node:internal/modules/helpers:147:16)
at Object.<anonymous> (/home/sistemas/Bots/Palitoo Studios - Pureza/Pureza BOT - Pureza/node_modules/discord.js/src/structures/GuildChannel.js:5:25)```
What are you trying to do?
My bot automatically sends rankings to each staff area + automatic reception.
After a while with the bot running, this error starts to appear and the bot kind of freezes.
Looks like the error comes from using the key word extends on an object that "is not a constructor or null" were do you use Class <name of class> extends <object extended> in your code
Comes from my Extended Client.js - Responsible for the Client connection
any where else?
Only in him
and Client is coming right from the import/require? nothing is done to it before?
yes
is there more to you error?
None, just this one
could you share your Extended Client.js
The issue is sothing to do with your require and export of the class but I am not sure why
I might be going done the wrong road. From my googling it occurs when a circular dependency exists ex: file A calls file B witch calls file A. so it may be unrelated to "Extended Client.js"
re: deleted
we do not provide support for selfbots
Am I allowed to ask for bot help but not in coding
?
Like how to fix this, if I'm not allowed I'll delete it
dude
if you post a question, actually read the answers
before moving on into another place and posting the same thing again
or - before posting it in the first place - read the error message
remove a bot, so you don't have 50 bots on the server anymore, then you can invite one again
I did read it but didn't understand it at all
you can only have 50 apps/bots on your server
Thought the issue was with my bot, thanks for the help tho
Yeah, thanks
Hey, could it be that “bio” is not set in editMe()?
I tested it several times. Avatar, banner, and name were set immediately. The bio was not.
Did you try reloading the discord app? Potentially it’s a cache thing with the app?
Yes, I did. But it didn't work. Now, after about 20 minutes, it's showing the new bio 😄
http://pastebin.com/nVmVmGAp
why does only event type and initiate vote show?
i can only call interaction.reply() and .editReply() once on an interaction? So if i want to edit more times i need to make a followup and base on the new message?
You can only call .reply once, but you can call edit reply multiple times
I believe only until 15 mins is up, since that’s how long an interaction token is valid for
hi, why i can't use TextDisplayBuilder? I have djs v14.23.2, but it's doesn't work
in console i got DiscordAPIError 50035 (Invalid Form Body)
what about .update()? Im getting the InteractionAlreadyReplied error after calling .update() multiple times
You can only call .update once too, then use edit reply after
You need a container. Use https://discord.builders if it’s easier for you to make it there then c+v it into ur code
import { TextDisplayBuilder, ContainerBuilder } from 'discord.js';
const components = [
new ContainerBuilder()
.addTextDisplayComponents(
new TextDisplayBuilder().setContent("text"),
),
];
but in context of receiving buttons from a collector that was attached to a message I need to use update(), since the collector retrieves a button interaction which I only retrieve and consume once?
Yes, you can only use update once. Same as .reply, deferReply deferUpdate
They are not highlighted in my code editor (VSC) as a used class (they should be highlighted green, but they glow blue, like a regular constant)
If you do that does it error? Maybe ur djs isn’t at the latest version maybe? I’d say try it and then go from there
components[0][UNION_TYPE_CHOICES]: Value of field "type" must be one of (1,).
DiscordAPIError[50035]: Invalid Form Body
components[0][UNION_TYPE_CHOICES]: Value of field "type" must be one of (1,).
at handleErrors (/home/Lexis/node_modules/@discordjs/rest/dist/index.js:762:13)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async SequentialHandler.runRequest (/home/Lexis/node_modules/@discordjs/rest/dist/index.js:1163:23)
at async SequentialHandler.queueRequest (/home/Lexis/node_modules/@discordjs/rest/dist/index.js:994:14)
at async _REST.request (/home/Lexis/node_modules/@discordjs/rest/dist/index.js:1307:22)
at async TextChannel.send (/home/Lexis/node_modules/discord.js/src/structures/interfaces/TextBasedChannel.js:195:15)
As I thought, an error occurred
When I check the library version on the hosting, it says 14.23.2, just like in package.json
What’s your new code?
I made some changes to my code and used site u sent me and got a new error:
components[0][MODEL_TYPE_CONVERT]: Expected an object/dictionary.
DiscordAPIError[50035]: Invalid Form Body
components[0][MODEL_TYPE_CONVERT]: Expected an object/dictionary.
at handleErrors (/home/Lexis/node_modules/@discordjs/rest/dist/index.js:762:13)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async SequentialHandler.runRequest (/home/Lexis/node_modules/@discordjs/rest/dist/index.js:1163:23)
at async SequentialHandler.queueRequest (/home/Lexis/node_modules/@discordjs/rest/dist/index.js:994:14)
at async _REST.request (/home/Lexis/node_modules/@discordjs/rest/dist/index.js:1307:22)
at async TextChannel.send (/home/Lexis/node_modules/discord.js/src/structures/interfaces/TextBasedChannel.js:195:15)
at async Object.execute (/home/Lexis/slash_commands/text_test.js:79:9)
at async Client.<anonymous> (/home/Lexis/index.js:99:9)
here my actual code:
const {
SlashCommandBuilder,
TextDisplayBuilder,
ButtonBuilder,
ButtonStyle,
ActionRowBuilder,
StringSelectMenuBuilder,
StringSelectMenuOptionBuilder,
ContainerBuilder,
MessageFlags
} = require('discord.js')
module.exports = {
data: new SlashCommandBuilder()
.setName('test')
.setDescription('test'),
async execute(interaction) {
const components = [
new ContainerBuilder()
.setAccentColor(4149449)
.addTextDisplayComponents(
new TextDisplayBuilder().setContent("Example components:"),
)
.addTextDisplayComponents(
new TextDisplayBuilder().setContent("# Test header\nButtons"),
)
.addActionRowComponents(
new ActionRowBuilder()
.addComponents(
new ButtonBuilder()
.setStyle(ButtonStyle.Primary)
.setLabel("test1")
.setCustomId("36acfad8d418474084daed1d0d06bef2"),
new ButtonBuilder()
.setStyle(ButtonStyle.Secondary)
.setLabel("test2")
.setCustomId("212dc1a845d54912cdff8446cdb3d321"),
),
)
.addTextDisplayComponents(
new TextDisplayBuilder().setContent("\nSelect menus"),
)
.addActionRowComponents(
new ActionRowBuilder()
.addComponents(
new StringSelectMenuBuilder()
.setCustomId("99fca274f90a4070beb7086fdf335bfc")
.setMaxValues(3)
.addOptions(
new StringSelectMenuOptionBuilder()
.setLabel("Test selection")
.setValue("44c530edcff948c5e63764303419e252")
.setDescription("test")
.setDefault(true)
.setEmoji({
name: "😜",
}),
new StringSelectMenuOptionBuilder()
.setLabel("Other selection")
.setValue("c0f60f084fc44e99ec904a89f83ffaf6"),
),
),
)
.addActionRowComponents(
new ActionRowBuilder()
.addComponents(
new StringSelectMenuBuilder()
.setCustomId("0eee4ad1eb8b480dc4a7b448445e666f")
.setPlaceholder("TEST SELECT")
.addOptions(
new StringSelectMenuOptionBuilder()
.setLabel("TEST SELECT OPTION")
.setValue("6574da11b26146a58f3995d155c32a80"),
),
),
),
];
await interaction.channel.send({
components: [components],
flags: MessageFlags.IsComponentsV2
})
}
}
ephemeral status is reserved only for command interactions, so there is no way to make a message sent by the bot ephemeral?
Ephemeral messages require an interaction, yes.
components is an array, you're then wrapping it in another array (on your send, components: [components])
TextDisplay doesn't require a container
you mistyped the flag, it's IsComponentsV2, not isComponentsV2
all enum values are in PascalCase
I already fixed it
I always use the command node --env-file=.env index.js to start my app. Is there a way to stop me having to add --env-file=.env to the command every time?
That's a question for #1081585952654360687
Oh I just learned what scripts are, fancy
Oh Yh ofc my bad
Then what are my actions?
#djs-help-v14 message ? wdym?
I have an issue where when getting who deleted a message to show it in my bot's mod logs, it's not always right
Let me show you guys the code real quick
client.on("messageDelete", async (message) => {
try {
const logData = await logSchema.findOne({ Guild: message.guild.id });
if (!logData) return;
const logChannel = message.guild.channels.cache.get(logData.Channel);
if (!logChannel) return logData.delete();
setTimeout(async() => {
const fetchedLogs = await message.guild.fetchAuditLogs({ limit: 1, type: 72 });
const deletionLog = fetchedLogs.entries.first();
const executor = deletionLog?.executor || 'Unknown';
const embed = new MessageEmbed()
.setTitle("Message Deleted")
.setColor("RED")
.addFields([
{ name: "Content", value: `${message.content}` },
{ name: "Author", value: `${message.author.tag}` },
{ name: "Deleted by", value: `${executor}` },
{ name: "Channel", value: `${message.channel}` },
])
.setThumbnail(message.author.displayAvatarURL({ dynamic: true }))
.setTimestamp();
logChannel.send({ embeds: [embed] });
}, 2000)
} catch (error) {
console.error("Error logging message delete: ", error);
}
});
what do you mean by not always right?
Like sometimes it shows someone who didn't delete it
your issue is here const deletionLog = fetchedLogs.entries.first(); you are not check to see if it is the right log
How do I do that?
I'm assuming it's getting the last log right?
sorry I missed the line above
Yeah
I am setting a limit so it should get the one I need, and the type too
really tho it is a race condition. the log has not been created or another has been added at time of fetch
Even tho it still shows a wrong one, not the one who deleted
Not just once, multiple times which is so weird
I am saying it fetched the wrong log. bc the right one had yet to be created or to that affect
So what's my fix then?
A delay definitely won't work at all
add a wait to the fetch log then get say 10 logs then fitter for the message id
This doesn't guarantee it. Logs are not created when a user deletes their own message or a bot does it. So you blindly getting the first one could very well be incorrect log
Discord api is a pain in the ass tbh
Any work arounds then?
Do I need to change the code if the container is not needed there?
You could add further checks, like checking if target channel is same as the message channel and target id as author
But this just narrows it doen
Yeah doesn't help that much
It's the only thing I can do tho
no additional changes are needed. A Text Display builder can just be added to the components array on a message or reply
And this
client.on("messageDelete", async (message) => {
try {
const logData = await logSchema.findOne({ Guild: message.guild.id });
if (!logData) return;
const logChannel = message.guild.channels.cache.get(logData.Channel);
if (!logChannel) return logData.delete();
setTimeout(async() => {
const fetchedLogs = await message.guild.fetchAuditLogs({ limit: 1, type: 72 });
const deletionLog = fetchedLogs.entries.first();
const executor = deletionLog?.executor || 'Unknown';
if(message.channel.id !== deletionLog..extra.channel.id) return;
if(message.author.id !== deletionLog.target.id) return;
const embed = new MessageEmbed()
.setTitle("Message Deleted")
.setColor("RED")
.addFields([
{ name: "Content", value: `${message.content}` },
{ name: "Author", value: `${message.author.tag}` },
{ name: "Deleted by", value: `${executor}` },
{ name: "Channel", value: `${message.channel}` },
])
.setThumbnail(message.author.displayAvatarURL({ dynamic: true }))
.setTimestamp();
logChannel.send({ embeds: [embed] });
}, 2000)
} catch (error) {
console.error("Error logging message delete: ", error);
}
});
Anything extra I should add?
components[0].components[4].components[0].options[BASE_TYPE_MIN_LENGTH]: Must be 3 or more in length.
DiscordAPIError[50035]: Invalid Form Body
components[0].components[4].components[0].options[BASE_TYPE_MIN_LENGTH]: Must be 3 or more in length.
at handleErrors (/home/Lexis/node_modules/@discordjs/rest/dist/index.js:762:13)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async SequentialHandler.runRequest (/home/Lexis/node_modules/@discordjs/rest/dist/index.js:1163:23)
at async SequentialHandler.queueRequest (/home/Lexis/node_modules/@discordjs/rest/dist/index.js:994:14)
at async _REST.request (/home/Lexis/node_modules/@discordjs/rest/dist/index.js:1307:22)
at async TextChannel.send (/home/Lexis/node_modules/discord.js/src/structures/interfaces/TextBasedChannel.js:195:15)
at async Object.execute (/home/Lexis/slash_commands/text_test.js:79:9)
at async Client.<anonymous> (/home/Lexis/index.js:99:9)
could you share you code in its current state?
Please check with docs what properties exists. There's no channel or message property on GuildAuditLogsEntry
GuildAuditLogsEntry discord.js@14.23.2
Audit logs entry.
I'll log it I guess, or yeah docs. Thanks
ofc
await interaction.channel.send({
components: components,
flags: MessageFlags.IsComponentsV2
})
also for the fetch type recommend you use the enum AuditLogEvent.MessageDelete
I ment for components
For channel, <log>.extra.channel and target author is well <log>.target.id
const components = [
new ContainerBuilder()
.setAccentColor(4149449)
.addTextDisplayComponents(
new TextDisplayBuilder().setContent("Example components:"),
)
.addTextDisplayComponents(
new TextDisplayBuilder().setContent("# Test header\nButtons"),
)
.addActionRowComponents(
new ActionRowBuilder()
.addComponents(
new ButtonBuilder()
.setStyle(ButtonStyle.Primary)
.setLabel("test1")
.setCustomId("36acfad8d418474084daed1d0d06bef2"),
new ButtonBuilder()
.setStyle(ButtonStyle.Secondary)
.setLabel("test2")
.setCustomId("212dc1a845d54912cdff8446cdb3d321"),
),
)
.addTextDisplayComponents(
new TextDisplayBuilder().setContent("\nSelect menus"),
)
.addActionRowComponents(
new ActionRowBuilder()
.addComponents(
new StringSelectMenuBuilder()
.setCustomId("99fca274f90a4070beb7086fdf335bfc")
.setMaxValues(3)
.addOptions(
new StringSelectMenuOptionBuilder()
.setLabel("Test selection")
.setValue("44c530edcff948c5e63764303419e252")
.setDescription("test")
.setDefault(true)
.setEmoji({
name: "😜",
}),
new StringSelectMenuOptionBuilder()
.setLabel("Other selection")
.setValue("c0f60f084fc44e99ec904a89f83ffaf6"),
),
),
)
.addActionRowComponents(
new ActionRowBuilder()
.addComponents(
new StringSelectMenuBuilder()
.setCustomId("0eee4ad1eb8b480dc4a7b448445e666f")
.setPlaceholder("TEST SELECT")
.addOptions(
new StringSelectMenuOptionBuilder()
.setLabel("TEST SELECT OPTION")
.setValue("6574da11b26146a58f3995d155c32a80"),
),
),
),
]
Alright, thanks @proud arrow @wary coral appreciate the help fellas
I think the issue is here.
components[0].components[4].components[0].options
new StringSelectMenuOptionBuilder()
.setLabel("Test selection")
.setValue("44c530edcff948c5e63764303419e252")
.setDescription("test")
.setDefault(true)
.setEmoji({
name: "😜",
}),
If I had to guess it is the emoji
Yep
Thx for help, I delete the maxValues
when using Unicode emojis just add it like this .setEmoji("😜")
I missed that, lol, you had less options than the max selectable defined
k, I gotcha
String Select in modal working right now in djs?
yes, #announcements
It's just that my classes aren't showing up there either. Any idea what might be causing this?
Have you updated your package?
yep, on host all updated, v14.23.2
What classes are not showing up?
Any idea on how my bot adds or removes multiple roles? Its supposed to add one role and remove one role. Other roles ( ids ) werent even saved on db
could you share you code? Is this a recording the change or updated the members roles issue?
Just wanted to add onto this, we're on the same project. We inputted an array into the roles.remove function but somehow it removed roles that weren't in that array.
you mean in the audit log?
Yeah
audit log is unreliable as the event only emits when a log is created not when it is updated
Does that mean it could've been another bot that removed the roles and not our bot?
Sorry if I'm not understanding correctly!
I think it would be better if I send you the source code.
Do you mind if I sent it to you in DMs since we operate a public bot
Hope it's not an inconvenience! 🙏🏻
That is a true statement but not what Mafia was talking about.
How Audit Logs work is that when an action to get logged occurs (deleting a role), a AuditLogCreate event is emitted. But the problem is that, if the same action occurs in a short period of time, Discord updated the existing AuditLog entry without emitting a new event
is it possible to check if a command has server set permissions on the server integration page?
Through the bot endpoints? No I don't think so
With OAuth? Yes
I see. We're still figuring things out but that's a huge clue because the code we have simply don't add/remove roles outside of the roles specified in the database.
Thank you so much for both your help and Mafia's help, we appreciate it a lot! We'll come back if we run into a dead end again. Tysmmmm!!
hi, am getting error with _Rest i don't know why that's happen
when trying to change my app's avatar using command
i getting this error:
throw new Error('Expected token to be set for this request, but none was present');
^
Error: Expected token to be set for this request, but none was present
at _REST.resolveRequest (C:\Users&&&\Desktop&&&\node_modules@discordjs\rest\src\lib\REST.ts:313:11)
at _REST.queueRequest (C:\Users&&&\Desktop&&&\node_modules@discordjs\rest\src\lib\REST.ts:255:44)
at _REST.request (C:\Users&&&\Desktop&&&\node_modules@discordjs\rest\src\lib\REST.ts:210:31)
at _REST.put (C:\Users&&&\Desktop&&&\node_modules@discordjs\rest\src\lib\REST.ts:191:15)
at GuildMessageManager.react (C:\Users&&&\Desktop&&&\node_modules\discord.js\src\managers\MessageManager.js:255:28)
at Message.react (C:\Users&&&\Desktop&&&\node_modules\discord.js\src\structures\Message.js:872:33)
at C:\Users&&&\Desktop&&&\avatar.ts:27:13
at Generator.next (<anonymous>)
at fulfilled (C:\Users&&&\Desktop&&&avatar.ts:5:58)
at processTicksAndRejections (node:internal/process/task_queues:105:5)
import { Message, Attachment } from 'discord.js';
export const name = 'avatar';
export const execute = async (message: Message) => {
const args = message.content.split(' ').slice(1);
const attachment = message.attachments.first();
try {
let avatarUrl: string;
if (attachment) {
avatarUrl = attachment.url;
}
else if (args[0]) {
avatarUrl = args[0];
if (!avatarUrl.startsWith('http')) {
return message.reply('❌ Please provide a valid URL or attach an image file!');
}
}
else {
return message.reply('❌ Please provide a URL or attach an image file!\nUsage: `!avatar <url>` or attach an image with the command');
}
await message.client.user.setAvatar(avatarUrl)
message.react('✅')
} catch (error) {
console.error('Error changing avatar:', error);
}
};
what version of discord.js are you using?
14.16.3v
waiiitt is there a new updates ?
current version is v14.23.2
shi am dumas
lemme just update it and see if got an error again
@wary coral , @halcyon bison deserves a cookie 🍪 , really thanks.
-# sorry for mention 🙂
can i add textdisplay in label comp?
No
so only like this
const modal = new ModalBuilder()
.setCustomId(`reportUserModal_${reportedUser.id}`)
.setTitle(`Report ${reportedUser.user.username}`)
.addTextDisplayComponents(
new TextDisplayBuilder().setContent("**Zneužití** této akce může vést k **moderátorským** akcím ‼️")
);
Yea
Why would you put it in a Label?
to put it under select menu
then just add it after the label containing the select menu
how
also can there be 2 text displays?
add the label to the modal first, then add the text display
call addLabelComponents before addTextDisplayComponents
yes
oh
Label components also have description, so if your use is not too fancy, you can use that
like this
modal.addLabelComponents(selectMenu, label);
modal.addTextDisplayComponents(
new TextDisplayBuilder().setContent(
"**Zneužití** této akce může vést k **moderátorským** akcím ‼️"
)
);
await interaction.showModal(modal);
},
};
on the assumption selectMenu is the select menu in question, that's not a label component
add that to the label with <LabelBuilder>.set*SelectMenuComponent()
const selectMenu = new LabelBuilder()
.setLabel("Typ reportu")
.setStringSelectMenuComponent(
new StringSelectMenuBuilder()
.setCustomId("typ")
.setPlaceholder("Vyber typ reportu")
.addOptions(
new StringSelectMenuOptionBuilder()
.setLabel("N-word")
.setValue("nword")
.setDescription("Pokud zprava obsahuje N-WORD")
.setEmoji("⚫"),
new StringSelectMenuOptionBuilder()
.setLabel("Spam")
.setValue("spam")
.setDescription("Pokud si myslíš že je zpráva spam")
.setEmoji("📰"),
new StringSelectMenuOptionBuilder()
.setLabel("NSFW")
.setValue("nsfw")
.setDescription(
"Pokud zprava obsahuje sexualní nebo jiny nsfw content"
)
.setEmoji("🔞"),
new StringSelectMenuOptionBuilder()
.setLabel("Hate speech")
.setValue("speech")
.setDescription("Pokud zprava obsahuje nenávistné projevy")
.setEmoji("💢"),
new StringSelectMenuOptionBuilder()
.setLabel("Harrasment")
.setValue("harrasment")
.setDescription("Obtěžování")
.setEmoji("😠"),
new StringSelectMenuOptionBuilder()
.setLabel("Jiné")
.setValue("jine")
.setDescription("Jiný důvod")
.setEmoji("❓")
)
);
``` i know thx
nice thx
imagigation
Will Channel Select Menus autoupdate the selectable options if i create new channels?
probably, but it's nothing inside djs' control
discord populates that menu, it's a built-in component
you should ask in ddevs since it's an api question #useful-servers
Thanks
but I'd say you should just try it and see, would be faster than waiting for a reply
seems like it doesnt
I retarted the client with CTRL+R and its still the same after creating a channel beforehand
yh it probably doesnt update in realtime
there is an enum for RESTEvents but is there one for ClientEvents? Either im blind or there really isnt one. Cant seem to find anything in docs either
is there any docs for how to support usernames & tags?
like i can do !whois koalanate
!whois @torn orchid or !whois 1203401516069822477
?
can you be more specific?
so for my whois command
i want to be able to do !whois [username]
why not just use a User slash command option?
alr
How can I know the server guild tag? Is it exposed?
it's exposed by the api but undocumented, so djs doesn't have it
how can access to raw guild data? do i need to query discord manually?
yes
Client#rest discord.js@14.23.2
The REST manager of the client
REST#get() discord.js@14.23.2
Runs a get request from the api
thanks Amgelo 
I have problems with the modal:
This is my error:
Error showing modal: ValidationError > s.nativeEnum(T)
Expected the value to be a string or number
Received:
| undefined
at _NativeEnumValidator.handle (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:2788:9)
at _NativeEnumValidator.parse (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:972:90)
at TextInputBuilder.setStyle (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\builders\dist\index.js:1365:47)
at C:\Users\user\Documents\VSCode\random bot\Synapse-Base\commands\Moderation\open-case.js:62:26
at resolveBuilder (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\builders\dist\index.js:2461:12)
at LabelBuilder.setTextInputComponent (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\builders\dist\index.js:1625:27)
at C:\Users\user\Documents\VSCode\random bot\Synapse-Base\commands\Moderation\open-case.js:58:18
at resolveBuilder (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\builders\dist\index.js:2461:12)
at C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\builders\dist\index.js:2646:48
at Array.map (<anonymous>)
[01:58:12] [Database] Backup settings changed: Interval=24h, Retention=7d
TextDisplayBuilder doesn't have a Paragraph property. you're probably thinking of TextInputStyle
TextInputStyle#Paragraph discord.js@14.23.2
Multi-line input
Ohh yes
It dont work with TextInputStyle to
what's the error?
Error showing modal: DiscordAPIError[50035]: Invalid Form Body
data.components[2].component.label[TEXT_INPUT_COMPONENT_LABEL_IN_LABEL_COMPONENT]: Cannot set label on a TextInput in a Label component
at handleErrors (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\rest\dist\index.js:762:13)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
at async BurstHandler.runRequest (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\rest\dist\index.js:866:23)
at async _REST.request (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\rest\dist\index.js:1307:22)
at async ChatInputCommandInteraction.showModal (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:399:22)
at async Object.execute (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\commands\Moderation\open-case.js:72:9)
at async validateAndExecute (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\utils\Handlers\InteractionHandler.js:377:17)
at async Client.handleInteraction (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\utils\Handlers\InteractionHandler.js:428:21) {
requestBody: { files: undefined, json: { type: 9, data: [Object] } },
rawError: {
message: 'Invalid Form Body',
code: 50035,
errors: { data: [Object] }
},
code: 50035,
status: 400,
method: 'POST',
url: 'https://discord.com/api/v10/interactions/1428896635450167449/aW50ZXJhY3Rpb246MTQyODg5NjYzNTQ1MDE2NzQ0OTpYUHU3TzBRMTVlU0JYWVhWaVhPQUd3S1o4cXFlc0hUNGdTcFRlNmdyaDV6OENPMHN5b0JpWlhXeFhBc2dCbEt0QWlRVVVEcG45bHJabU5pMUt5bmJxcTNyWjh0ZnN2NjVCTldHYmJrM21BTVY0Y1UxQjB2UVlQRXJiQ1pSNktwRw/callback?with_response=false'
}
well i guess i havent learned how the new modal components work haha. look at the error
Yeah i sow it now.
Does anyone know when discord.js will be updated?
regarding what?
releases happen when we need to fix bugs or cover new features
How can i make post in a forms channel with the bot?
ForumChannel#threads discord.js@14.23.2
A manager of the threads belonging to this channel
documentation suggestion for @toxic moat:
GuildForumThreadManager#create() discord.js@14.23.2
Creates a new thread in the channel.
// Create a new forum post
forum.threads
.create({
name: 'Food Talk',
autoArchiveDuration: ThreadAutoArchiveDuration.OneHour,
message: {
content: 'Discuss your favorite food!',
},
reason: 'Needed a separate thread for food',
})
.then(threadChannel => console.log(threadChannel))
.catch(console.error);
hi can i ask a doubt could i can make a modal that just shows only text? without any of the box or things?
Code
Error:
[02:47:59] [Error ] Component execution error: interaction.fields.getUserSelectMenuValues is not a function
[02:47:59] [Error ] Command Error esfrmmve7zo:
[02:47:59] [Error ] Error Details: (No Detail available)
Where did you get getUserSelectMenuValues() from?
The Open-Case cmd
No, I'm asking who/what told you that that's the name of the method you'd use
VSCode.
ModalSubmitFields#getSelectedUsers() discord.js@14.23.2
Gets users component
Well, not sure where it got that from, but this is the actual method name
im guessing they are talking about copilot
Yeah
do not blindly listen to copilot...it does not have real time access to the djs documentation...actually read the docs before trying to do something
I'm too stupid to understand the docs. That's where the function is, and then I don't understand what comes next.
Like this
getSelectedChannels<Type? extends ChannelType = ChannelType>(customId: stringrequired: true = falsechannelTypes?: readonly Type[] = []) : ReadonlyCollection<Snowflake, Extract<NonNullable<CommandInteractionOption<Cached>['channel']>, { type: Type extends ChannelType.AnnouncementThread | ChannelType.PublicThread ? ChannelType.AnnouncementThread | ChannelType.PublicThread : Type; }>>
What means
<Type? extends ChannelType = ChannelType>(customId: stringrequired: true = falsechannelTypes?: readonly Type[] = []) : ReadonlyCollection<Snowflake, Extract<NonNullable<CommandInteractionOption<Cached>['channel']>, { type: Type extends ChannelType.AnnouncementThread | ChannelType.PublicThread ? ChannelType.AnnouncementThread | ChannelType.PublicThread : Type; }>>
look at properties
not raw types
hey guys, any documentation on how to use the new modal components? Specifically file upload?
The file upload component is not currently available in Discord. JS
not the one in your editor...the actual website...to find the props youre looking for, first you would start on the ModalSubmitInteraction, which has a fields property. that fields property has all the methods you need such as getSelectedUsers
it's not included in that?^
check the date...that was before file upload was announced
rip thats a shame
ok thanks guys, I'll wait for the good news then
Thanks i know now how to read the docs
you need to add this component
And it will be
read the conversation just 3 messages above your message
Error:
Error saving new case to database: TypeError: Cannot read properties of undefined (reading 'id')
at Object.execute (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\components\modals\open-case.js:19:26)
at Client.handleInteraction (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\utils\Handlers\InteractionHandler.js:453:41)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
Code:
const user = interaction.fields.getSelectedUsers('select-user')[0];
const category = interaction.fields.getStringSelectValues('case-category')[0];
const reason = interaction.fields.getTextInputValue('case-reason');
Im getting the category and the reason but the user is undefined like you can see in the err
Collection is not an Array
Yeah i sow it now
Collection#first() discord.js@14.23.2
Obtains the first value(s) in this collection.
Yuh i still have problem get the id
and how are you getting it
did you update your code?
Yeah i delted the [0] at the end if it was this
so what is it now?
first?
as a value or a method?
Method
im getting <@1187167862448717967 >
How can i clean it
that doesn't look like what you're getting
but what you're making it to be
how are you using this variable
because that is not an id
const user = interaction.fields.getSelectedUsers('select-user').first();
that does not return what you says it does
so this is not the line of code that is using it
console.log(`Selected User ID: ${user}`); this line prints this
and here
const newCase = new Case({
userId: user,
category: category,
reason: reason,
openedBy: interaction.user.id,
openedAt: new Date(),
caseStatus: 'Open'
});
Ahh i need put .id after user
yes...because user is an object
Ohh
User discord.js@14.23.2
Represents a user on Discord.
Alright thanks and sorry if this questions are dumb but im trying to give my best
we were all there at some point
Thanks
Error:
[03:57:02] [Error ] Command Error xpp01ilsw8:
[03:57:02] [Error ] Error Details:```
Code:
https://srcb.in/qGGke5xko7
ReferenceError: "x" is not defined: learn moreTypeError: Cannot read properties of undefined/null (reading "x"): learn more
you have a section with 6 textDisplay's...you are only allowed to have a maximum of 3
you should instead combine these into a single textDisplay
Ohh
Alright thanks
(that's not the cause of the error but it will cause that issue if you fix the current one, read Jo's reply for your actual issue)
So i need to define textDisplay ?
yeah
on your line 57 you're using a variable called textDisplay but there's no such variable
looks like you forgot to wrap it on a callback like you did on the others, (textDisplay) => ...
or like Samtino said, just merge all your subsequent text displays into one
Yeah i sow it now thanks for the help guys
How can i get the Link from the thread im creating here
forum.threads
.create({
name: `Case - ${user.username} (${newCase.caseId})`,
message: {
components: [forumContainer],
flags: MessageFlags.IsComponentsV2,
},
reason: `Moderation Case Opened - Case ID: ${newCase.caseId}`,
})
.catch(console.error);
Do you need a link or are you just trying to send a mention like this #djs-help-v14
Its a button so a link
It should look like this
ThreadChannel#url discord.js@14.23.2
The URL to the channel
forum.url?
no theards
Nop it wrong
A forum post is a thread
create() returns a Promise that resolves to the thread channel that was created
So you need to get that resolved value to access the url property from it
When i do .then(threadChannel => console.log(threadChannel)) afther i created the theard i get this
<ref *2> ThreadChannel {
type: 11,
guild: <ref *1> Guild {
id: '1428234467272687641',
name: 'Mein Test Bot server',
icon: '5eb9ccb7dcedc66c152721e5d120ee35',
features: [],
commands: GuildApplicationCommandManager {
permissions: [ApplicationCommandPermissionsManager],
guild: [Circular *1]
},
```
And more...
Yes, that's the ThreadChannel data for the thread you just created
ThreadChannel discord.js@14.23.2
Represents a thread channel on Discord.
I have it now
Thx @clear garnet and @topaz bluff.
any way to stop this error message from cropping up
DiscordAPIError[50027]: Invalid Webhook Token
Don’t use interactions after they expire
Is there any way to detect new member is pending for enter..?
I read the docs and found Events.GuildMemberAvailable but I think its not working
documentation suggestion for @fervent osprey:
GuildMember#pending discord.js@14.23.2
Whether this member has yet to pass the guild's membership gate
If this is changed, it'll will fire member update event
what are the possible reasons to get an Unknown Interaction error on ModalSubmitInteraction.reply?
tag suggestion for @chrome chasm:
Common causes of DiscordAPIError[10062]: Unknown interaction:
- Initial response took more than 3 seconds ➞ defer the response *.
- Wrong interaction object inside a collector.
- Two processes handling the same command (the first consumes the interaction, so it won't be valid for the other instance)
* Note: you cannot defer modal or autocomplete value responses
Common causes of DiscordAPIError[10062]: Unknown interaction:
- Initial response took more than 3 seconds ➞ defer the response *.
- Wrong interaction object inside a collector.
- Two processes handling the same command (the first consumes the interaction, so it won't be valid for the other instance)
* Note: you cannot defer modal or autocomplete value responses
Oops can't delete it...guess you get it twice
Apps > Delete message fyi
Oh wait that's gone
Nvm then

is guide not updated with latest changes to modal things like select menu things and input changes ?
because TextInputBuilder marked deprecated and guide still shows old method
https://discord.com/channels/222078108977594368/1411723956020445298 it's being worked on
ohh ok thanks
That's only a generic error message. What's the actual error message in your terminal?
TypeError: Cannot read properties of undefined (reading 'getSelectedUsers')
and yes I am using modal collectors, and also waited for 5 minutes
ReferenceError: "x" is not defined: learn moreTypeError: Cannot read properties of undefined/null (reading "x"): learn more
well I did not mean that, I don't need the error ephemeral come in if the 5 minutes expired
my modal collector is set to expire after 5 minutes
getSelectedUsers is undefined because I did not type in anything in the user bar for 5 minutes
Ohhhh I see
You don't want the second message sent at all... unfortunately I haven't worked with collectors very much or for a long time. You should share a snippet of your code and someone who knows more than me can help from there
// previous code
const report = await interaction.awaitModalSubmit({ filter: i => i.user.id === interaction.user.id && i.customId === 'report', time: 300000 }).catch(async(err) => {
console.error(err)
return interaction.followUp({ content: 'There was an error while recieving this modal or the modal timer of 5 minutes has expired.', flags: MessageFlags.Ephemeral });
});
if (report) {
const user = report.fields.getSelectedUsers('user').first()
const reason = report.fields.getTextInputValue('reason')
// ...```
well you don't want to return something in that catch
or at least not something truthy, like an interaction response (the followUp)
your if (report) will always be true
since that awaitModalSubmit can either fail or succeed, if it succeeds it returns the interaction, if it doesn't it returns the followUp message (since you're returning it on your catch)
both possible results are truthy when evaluated in an if()
I want to edit the message, but I want to indicate that this is a v2 component, but TypeScript complains.
message.edit({ content: null, components: [container], flags: MessageFlags.IsComponentsV2 });
(property) MessageEditOptions.flags?: BitFieldResolvable<"SuppressEmbeds", MessageFlags.SuppressEmbeds> | undefined
However, if I // @ts-ignore, everything works fine.
But if I don't set any flags at all, the API returns an error that the body is invalid.
You either have mismatching d.js and discord-api-types versions or you have a faulty d.js installation
What’s ur d.js version? npm ls discord.js
I updated it, it was an old version, thanks
Have discord.js added support for components v2? if so how would I use it?
Display Components
While you might be familiar with embeds in Discord, there are more ways to style and format your apps messages using display components, a comprehensive set of layout and content elements. To use the display components, you need to pass the IsComponentsV2 message flag (in docs: MessageFlags) when sending a message. You only need to use this flag when sending a message using the display components system, not when deferring interaction responses.
read more
What is limit in new modal components
Is there a documentation about the new update for modals? (select menus)
40 components overall that includes nested one's
Not yet, you can look at docs for now
So i can have 40 text inputs / select menus?
do components v2 use the standard 2000 character message length limit or is it changed?
4000 i think
is that intended ? or a bug ?
My bad, i thought you asked for cv2. For modals the limit is still 5
Oh okay thx
this is the selection menu (this.selector_pages[this.selector_page_index]) im trying to pass to the components_row below
data: {
type: 3,
custom_id: 'empty_selector',
placeholder: 'You dont have any accounts yet!',
disabled: true
},
options: []
}```
`this.components_row = [this.selector_pages[this.selector_page_index]]`
```DiscordAPIError[50035]: Invalid Form Body
components[1][UNION_TYPE_CHOICES]: Value of field "type" must be one of (1, 9, 10, 12, 13, 14, 17).```
why wont it accept it? Its literally the selector row, I made sure 20 times
No options
i tried adding options and it results in the same error
this is how i create the row
return new StringSelectMenuBuilder()
.setCustomId("empty_selector")
.setPlaceholder("You dont have any accounts yet!")
.setDisabled(true)
.addOptions(
new StringSelectMenuOptionBuilder().setLabel("None").setValue("null"))
How are you passing this? It needs to be put inside a action row
yeah nvm i fforgot the action row
With the new file upload support for modals incoming, how will the uploads handle e.g. image quality?
Afaik Discord compresses images that you send in channels, lowering the quality. Will the same be true for the upload feature?
You should ask that in ddevs, not here.
Cheers!
Is there a list somewhere of all the components that can be used in a modal?
Should keep in mind that the file input is not supported by the library yet
can you upload files in modal with js?
If you mean can you use the new file upload component with d.js, then no. Not yet
Alright, thx bro
For some unexplainable reason, my periods get put on a new line when I put a linebreak after my option descriptions. And there is no further code, but the final period at the end does get displayed properly
Section responsible for the output:
commands.sortBy((cmd) => cmd.slash.toJSON().name)
.filter((cmd) => cmd.help.category === HelpCategory.Relays)
.forEach((cmd) => {
container.addTextDisplayComponents(
textdisplay => textdisplay.setContent(`### ${cmd.slash.toJSON().name}`),
textdisplay => textdisplay.setContent(`${localeText(cmd.help.description, undefined)}`),
textdisplay => textdisplay.setContent(`>>> ${cmd.slash.toJSON().options!.map((opt) => `${chatInputApplicationCommandMention(getSlashCommmandId(cmd.slash.toJSON().name), cmd.slash.toJSON().name, opt.name)} ${opt.description}\n`)}`),
).addSeparatorComponents(
new SeparatorBuilder().setSpacing(SeparatorSpacingSize.Small).setDivider(false)
)
})
You map your options and then put that array into template literal. So it'll get stringified by adding , between the elements
You'd want to explicitly .join('\n') it instead I guess
Yeah, that worked. thanks.
is there a way to update specific elements of a interactions message? Upon my button being pressed i only want to change a specific button and not regenerate the whole row
yes and no. you still have to pass the full array of components that make up your message but you can reuse the information in the message
const componentBuilders = interaction.message.components.map( c => createComponentBuilder(c.toJSON()))
You still need to find your button in the builders and update it
Hi! I have a quick question. How I can "reset to default" after using the editMe() commands ?
what do you mean reset to default?
like clear the text?
Revert the avatar, bannière, bio, surname…
revert it to what?
Well, the default avatar/bio/etc of the bot ?
The one configured in the panel!
pretty sure you can just set it to null, but i could be wrong
for emojis on bots application do i just put in embed description :loading:
it has id but keeps on going as :loading:
its the same format as every other custom emoji
there's a copy markdown button on the dev portal
How can we use the ephemeral option now?
The ephemeral option when replying to an interaction will be removed in v15
- {..., ephemeral: true}
+ {..., flags: MessageFlags.Ephemeral}
``` Read [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_OR) on how to specify multiple flags
i did that and put it in here ```export const LOADING_EMOJI = ":loading:";
keeeps on switching in markdown to loading when i put id
the emoji format <:name:id>
no
Interesting, why is the MessageFlags not defined?
you have to define it
import it from discord.js
alrighty, ill add it to my types.ts, thank you.
no itd <a:loading:id> that is how i have it this is how i have it in my file
Oh lmao
then the emoji doesnt exist?
documentation suggestion for @silent mirage:
EmojiFormat discord.js@14.23.2
sorry that is the wrong thing
Hi, if a member isn't cached and their roles has been changed and GuildMember partial and intents are enabled does guildMemberUpdate event will start working?
No need to define it, just import MessageFlags from discord.js
documentation suggestion for @silent mirage:
formatEmoji discord.js@14.23.2
Formats an emoji id into a fully qualified emoji identifier.
the old member will be a partial, but the new member should be the full member object. I belive
Yeah thank you. Kinda pisses me off doing any discordjs work cause this isnt like C++ where you need to strictily follow a function signature and if you dont you're cooked
I got it working
Thank you so much
DiscordAPIError[50035]: Invalid Form Body
data.embeds[0][LIST_ITEM_VALUE_REQUIRED]: List item values of ModelType are required
at handleErrors (C:\Users\timpu\OneDrive\Dev Projects\NovaEagle Bot\node_modules@discordjs\rest\dist\index.js:762:13)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
at async BurstHandler.runRequest (C:\Users\timpu\OneDrive\Dev Projects\NovaEagle Bot\node_modules@discordjs\rest\dist\index.js:866:23)
at async _REST.request (C:\Users\timpu\OneDrive\Dev Projects\NovaEagle Bot\node_modules@discordjs\rest\dist\index.js:1307:22)
at async ChatInputCommandInteraction.reply (C:\Users\timpu\OneDrive\Dev Projects\NovaEagle Bot\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:193:22)
at async Object.execute (C:\Users\timpu\OneDrive\Dev Projects\NovaEagle Bot\commands\flight management\create-flight.js:55:9)
at async Object.execute (C:\Users\timpu\OneDrive\Dev Projects\NovaEagle Bot\events\interactionCreate.js:16:4) {
requestBody: { files: [], json: { type: 4, data: [Object] } },
rawError: {
message: 'Invalid Form Body',
code: 50035,
errors: { data: [Object] }
},
code: 50035,
status: 400,
method: 'POST',
url: 'https://discord.com/api/v10/interactions/1429172931447099604/aW50ZXJhY3Rpb246MTQyOTE3MjkzMTQ0NzA5OTYwNDpVRXFQSHVLMkxXZURWU0t6enU0RHAza2c5QU1Hd1JzdXRkYWlpa1k4cENCbjJwUXZOZzV4REo2NWZCaVIxckl1NHJoM1hNc3J1b2VmVENIZ1lodUpucFV2T2ZtOUdDZnE0OGdEWjhmVTVYZVlVS3VuZVZIb0UyOVVjT2taaVdCVw/callback?with_response=false'
}
why im receiving the error when i tried to run /create-flight
Could you show the modal builder you are trying to send to the user?
i'm using embeds
I am sorry I misread model as modal lol.
All the same if you could share your code
On line 42, you assign the new embed builder to {embed} this seems like it's where your error is. Try removing the { }
Otherwise I at a cursor glance. It looks good otherwise
ok
Is it possible to create public buttons ie, so that every user can see and press them and only see results for themselves?
Im assuming we'd have to listen for interactions on some message, and then call interaction reply with ephemeral on?
That’s correct
buttons emit an interactionCreate event...you handle them just as any other interaction (aka, slash commands)
But wont different users see the buttons being pressed by others on that message? Or is that pressing animation rendered clientside?
It’s client sided
will the bot be able to reply to the interactions message with ephemeral status even if it doesnt have permissions to post to the channel the message is on?
i think so but you should test it
Yes, as long as user have permissions to use application commands in that channel, it should work
im getting this error on modal, but no console errors im really confused, i have never had a errorless error on modal so I'm not sure where im erroring
This error happens when discord doesn't receive a response to the ModalSubmitInteraction
But we can't tell you anything about why from that alone
hmm, im responding to it pretty sure, this is the code:
https://pastebin.com/ksMMjXwP
on line 38 you use editReply as the first response it should be update or reply also bc you call a db you should use defer before the db call
ok ive tweaked a bit and stuck in a endless thinking loop waiting for it to timeout if it will time out
how did you tweek it?
Hey I'm trying to debug a missing permissions error but not too sure why im getting it...
I'm sending a message with:
- an embed
- a reply
- pinging a role
json: {
content: '',
tts: false,
nonce: '',
enforce_nonce: true,
embeds: [
{
description: '...',
color: 16448000
},
[length]: 1
],
components: undefined,
username: undefined,
avatar_url: undefined,
allowed_mentions: { parse: [ 'roles', [length]: 1 ] },
flags: undefined,
message_reference: { message_id: '...', fail_if_not_exists: false },
attachments: undefined,
sticker_ids: undefined,
thread_name: undefined,
applied_tags: undefined,
poll: undefined
}
Doing client.channels.cache.get("...").permissionsFor(client.user).serialize() I get:
{
CreateInstantInvite: true,
KickMembers: false,
BanMembers: false,
Administrator: false,
ManageChannels: false,
ManageGuild: false,
AddReactions: true,
ViewAuditLog: false,
PrioritySpeaker: false,
Stream: true,
ViewChannel: true,
SendMessages: true,
SendTTSMessages: false,
ManageMessages: false,
EmbedLinks: false,
AttachFiles: true,
ReadMessageHistory: true,
MentionEveryone: false,
UseExternalEmojis: true,
ViewGuildInsights: false,
Connect: true,
Speak: true,
MuteMembers: false,
DeafenMembers: false,
MoveMembers: false,
UseVAD: true,
ChangeNickname: true,
ManageNicknames: false,
ManageRoles: false,
ManageWebhooks: false,
ManageEmojisAndStickers: false,
ManageGuildExpressions: false,
UseApplicationCommands: false,
RequestToSpeak: true,
ManageEvents: false,
ManageThreads: false,
CreatePublicThreads: false,
CreatePrivateThreads: false,
UseExternalStickers: true,
SendMessagesInThreads: true,
UseEmbeddedActivities: true,
ModerateMembers: false,
ViewCreatorMonetizationAnalytics: false,
UseSoundboard: false,
CreateGuildExpressions: false,
CreateEvents: false,
UseExternalSounds: true,
SendVoiceMessages: false,
SendPolls: true,
UseExternalApps: true,
PinMessages: false
}
I can't see anything im missing...
reply to an interaction or reply to a message?
A message
[
'KickMembers',
'BanMembers',
'Administrator',
'ManageChannels',
'ManageGuild',
'ViewAuditLog',
'PrioritySpeaker',
'SendTTSMessages',
'ManageMessages',
'EmbedLinks',
'MentionEveryone',
'ViewGuildInsights',
'MuteMembers',
'DeafenMembers',
'MoveMembers',
'ManageNicknames',
'ManageRoles',
'ManageWebhooks',
'ManageEmojisAndStickers',
'ManageGuildExpressions',
'UseApplicationCommands',
'ManageEvents',
'ManageThreads',
'CreatePublicThreads',
'CreatePrivateThreads',
'ModerateMembers',
'ViewCreatorMonetizationAnalytics',
'UseSoundboard',
'CreateGuildExpressions',
'CreateEvents',
'SendVoiceMessages',
'PinMessages'
]
These are the ones im missing
and in the reply you mention a role?
content: '', wait no i dont even do that, the content is empty, thought i was
so what is the issue then?
https://sourceb.in/mTj6x1dVgo this is the full error. But as i said i get this, but not too sure why. I also check for permissions before i send
Unless it's possible the people using my bot changed permissions and that was a one off, but i check for these permissions before sending:
return channel.permissionsFor(me)
.has([
PermissionFlagsBits.SendMessages,
PermissionFlagsBits.ViewChannel,
PermissionFlagsBits.ReadMessageHistory
])
for i need anymore?
only SendMessages should be need to send the reply
and use embeds for the embed
And read message history since its a reply, embeds?
presumably you got the message in the first place. your not fetching the message?
yh but to reply to a message you need the read message history permission no? Idk wym
Yh i recieve a message then reply to it in layman's terms
if the bot saw the message create event it has ViewChannel and it is in the history it can see. I will run some tests to validate
At the very top of my function i do
const me = await message.guild.members.fetchMe();
if (!checkPermissions(message.channel,
return;
}
Which runs:
export function checkPermissions(channel, me, type = "drop") {
switch (type) {
case "star": {
...
}
default: {
return channel.permissionsFor(me)
.has([
PermissionFlagsBits.SendMessages,
PermissionFlagsBits.ViewChannel,
PermissionFlagsBits.ReadMessageHistory
]);
}
}
}
Unless ive done something wrong i can't see why i would get missing permissions since i check for all of the ones i believe are required
I think you need to check for EmbedLink as well
What does that permission do? Is this for like putting a thumbnail or literally putting a link in the description for example
for sending a link, having that permission will make discord grab and embed potential data from it
Links sent by users with this permission will be auto-embedded
yh just grabbed it
for sending an embed directly, well.. should be self-explanatory
So I don't need it?
for what?
just sending embeds, im not sending links so i dont need that one
you do
.
you don't have content that could potentially embed based on the permission
you're sending an embed directly
Maybe im just not understanding the docs wording,
Links sent by users with this permission will be auto-embedded
To me talks about links like https://...
and i'm not talking about links
i'm talkign about embeds
a link might happen to embed
for a message to have an embed it needs to have permission to
embed can come from a link, or can be sent directly
both require the permission
you're sending one directly, so dont' look at links
Ok... I think i get what you mean. Let me add that to my check as well, thanks I appreciate it
might also try to bridge the gap with a different thing
you know how embed has types? the deprecated one, like rich or video or image or whatever else it had
this embed there from that link is of rich type
in v11 the embeds were called RichEmbeds
I think my issue is from the wording from the docs, I'm seeing Links and thinking of those. I get you now, but from that it didn't make it super clear i need that one to send straight embeds. But I know now
yeah that's a bit hidden from direct view
As to me at least, a link is a link an embed is an embed, needing EmbedLinks to send an embed is weird, you would think you need that if you want discord to embed a link for you... but now i know i need that for embed sending so it's all good
Thanks however, I appreciate it
i suppose calling it "embedding content" could have been more about both, but then that leaves a big "what is the content" for everyone who isn't a bot dev
Or just changing the description in the docs would be cool
you can still send messages with content and a embeds without EmbedLinks but the embed is blocked.
So by sending a embed only message with out EmbedLinks you are sending a message without anything in it witch is blocked by discord
Ahhhhh that makes sense. When you say the embed is blocked, will the embed just not display?
correct
from my testing. same message only differance is perms at time of send
is the second one doing both content and embeds but without the embedlinks permission?
yes,
messages.reply({
content:"test",
embeds: [new EmbedBuilder().setTitle("test").setDescription("test")],
})
when sending just the embed without the embed permission I got the 50013 error from discord 'Missing Permissions'
ahhh i see, thanks a lot
@red coral as a side note you should try componentsV2. I dont believe it has this problem and your embed could be esaly converted to a text display in a container
Hmm... that's very true actually. Do you need that permission for v2?
no only sendMessage
and im guessing thats because it's not an embed they are components?
correct, here is the link to the guide
https://www.discordjs.guide/legacy/popular-topics/display-components#container
oh yh i can make them just fine, ive used them elsewhere. Icl, Imma move to them since it'll be a bit easier to just not require that permission. Don't want people complaining stuff doesnt work, dont wanna tell ~400 people to reinvite my bot lol. Thanks
for sure
is there an event for expire/removal of a server boost? i believe there is one for an addition of a boost but i am unsure
Update member is the best you're going to be able to get. There's no better event
does update member include any information on boost status and is it triggered on addition/removal of boosts?
Only that the roll was removed. Which you'd have to check for the roles being different
Hi has modal file upload been added to yet?
No
👌
Hello
Has anyone heard about the new file upload feature in Model?
Can I get a example code about it?
discord.js does not support it yet at this time
Ok ty
are there any example codes about the dropdowns/labels? if that's supported
yes SelectMenus and Labels are supported, but the guide has not been updated yet for the new Modal components
alr thanks, ill figure it out
You can check the docs for the new ModalBuilder methods and you can retrieve the info with ModalSubmitFields which comes from interaction.fields
pog thank you
this could help
https://modal.builders/
:O appreciate you both!
oh ya that exists too for building the modal itself
Is there any way for me to upload emojis to the bot using Discord.js, without going through Discord Developers?
documentation suggestion for @steep siren:
ApplicationEmojiCreateOptions discord.js@14.23.2
Options used for creating an emoji of the application
yes you can upload emojis through bot, think thats the doc for it
Alright, thanks bro
How can i make a event that reads all messages in all theards in a forum channel and if sombody send a message it will be forwarded to the dms
that sounds like a weird thing to want
It should be a Modmail
So when a staff sends a Message in the theard the bot finds the caseid for this theard so he can send the message to the user
With messagecreate should it work
yes, you would just do that in your "messageCreate" event
Alright
you should NOT be fetching the content of a channel, rather reacting to the creation of new messages
Hi some one could give me a small example for making a box in modal?
i mean in new modal
thanks :)
wdym box?
nothing bakewithme gave me thats what i want
.
Error:
Error in readCases event: TypeError: Cannot read properties of undefined (reading 'bot')
at Object.execute (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\events\AUTO\readCases.js:23:32)
at Client.<anonymous> (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\utils\Loaders\EventLoader.js:41:76)
at Client.emit (node:events:530:35)
at MessageCreateAction.handle (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\discord.js\src\client\actions\MessageCreate.js:32:14)
at module.exports [as MESSAGE_CREATE] (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\discord.js\src\client\websocket\WebSocketManager.js:352:31)
at WebSocketManager.<anonymous> (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\discord.js\src\client\websocket\WebSocketManager.js:236:12)
at WebSocketManager.emit (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@vladfrangu\async_event_emitter\dist\index.cjs:2504:31)
at WebSocketShard.<anonymous> (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\ws\dist\index.js:1190:51)
at WebSocketShard.emit (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@vladfrangu\async_event_emitter\dist\index.cjs:2504:31)
Code:
async execute(client, message) {
try {
if (message.author.bot) return;
.....
check if message isnt partial or system message
can also add safe chaining
if (message.author?.bot) return;
like this if (!message) return;?
no if message.partial return (for message updates/deletes)
alright
message create should never really be a partial
I think message is just not an instance of Message
The order of function parameters must match between definition and function call.
function execute(client, interaction) { ... };
execute(interaction, client);
- mismatch! you pass an interaction where the client is expected
- mismatch! you pass the client where an interaction is expected
^ partials would leave a bunch of nulls around at best, not undefineds
This is my code https://srcb.in/EXCPLoXeEM
Alright
did the safe chaining work?
I will try now
message.author should not be an undefined
so digging for partial doesn't sound like a valid fix
also i just use client.on events so idk about exporting events
yes sorry for that. partial cant be the issue ^ @toxic moat
Can you show your event handler?
Yep
https://srcb.in/6fcXXCbaBi (Its a base Credits: @distant fox)
Should i send you the Loader to?
https://srcb.in/Gcl7dfl1yK i think this is what you mean
Ahm i did it like this
if (message.author.bot) {
return;
}
And it works
Idk what the probelm was
that wouldnt change anything
And i switched the position async execute(message, client) from message now its the first
how can i tell if this has errored for time? .catch() and try/catch dont collect it
const user_answer = await channel.awaitMessages({
filter: (m) => m.author.id === user.id,
max: 1,
time: 1000,
errors: ["time"],
})```
pretty sure that will only show with a message collector, not the promise based one
Guys do you know why the user gets 5 embed and not only one https://srcb.in/NKiJ6hpKCl
you don’t use embeds in that code
In the code you shared you did not use any Embeds? tho
Im usning a container
I'm also confused on the question. Is the message being sent more than once? (5 times in your question)
Because double messages implies that your bot is running on several processes
So should i turn of my pc
our close vscode
Do you have several terminals open in VSCode?
Nop
Well I can't say for certain if it will fix the issue. But it's worth a shot
That or you can just check to see if there's any node processes in Task Manager. But restarting will gaurentee that there aren't
I restarted my pc now lets try
Nope the problem is in the code
Do you have a log for the ready event?
So I have onboarding in my server, and I want it so that my bot welcomes the new members after the user has completed all of the onboarding questions. How can I do this?
documentation suggestion for @drifting zealot:
GuildMember#pending discord.js@14.23.2
Whether this member has yet to pass the guild's membership gate
Thx
Anyone have any suggestions on how to optimize this to work faster and get less rate limits for my bot.
What are you getting rate limited on?
Message sending.
send less messages

idk what else you want
you're the one that grabs a list of ids and then sends a message for each of it
How many messages are we talking about? If you're getting rate limited on messages. That's pretty egregious
however many there are things in an embed they fetch
2-4 messages per vouch and then maybe 100-1000 vouches per list.
How often does that need to be done?
As often as vouches come in, so about 1-2 times a hour for a big list or 3-5 times for smaller lists.
this server got <1300 messages in total during entire past 24 hours, and that's counting channels you can't even see
and you're just looping over that in single command
Well there is the get, the reply, the decision, and then next.
so we're talking between 200 and 4,000 messages!?
that doesn't even add up
I gave a very large range for this, most of the time the lists range from 100-450 very rarely does it go over that.
2000 messages is still more than half an hour of one message every second
you really might want to rethink this
This is why it needs work, when the rate limit happens and people can't use it there becomes backlog and then hole gets even deeper.
yeah, which is where there should ring a bell that maybe this is really not working out
idk, build a website for this
there you can send messages however fast you want
and however many
the only solution for ratelimits is quite literally just not reaching them, you'll have to rethink how you're approaching this entirely
So I need to find a way to do less messages?
yes
or not do it via discord
Thanks for the help.
Out of curiosity, what's your user interaction goal of the lists that you maintain? Cuz I feel like the answer is to just store it all in a database and then use interactions for users to request the most up-to-dated version of the list
The lists are for showing staff what is pending.
I feel like the answer then is to have a command that staff can use that gets them the current list of pending items
I think I have came up with a idea that can fix my problem.
Are there any rate-limits on reactions to messages or embeds?
Yes, but Discord dynamically does rate limits so there's no posted rate limit for any particular endpoint
there are ratelimits on everything
and embeds aren't standalones, they are part of messages
Do you think it could work if when vouches came in the show up as embed and bot reacts with ✅, ❌, and 📩? For the accept, deny, and proof.
That sounds like you should use buttons
Then the staff reacts with one to make the decision.
instead of immediately ratelimiting yourself to hell and back by having to react 3 times to every message, why not just use buttons
ok
When a user does a command or uses a button? The interaction it creates has individual rate limits for each time a user interacts with it
could anyone take a look at this https://discord.com/channels/222078108977594368/1429300370831708334
the initial responding to an interaction has no ratelimit (so only once per interaction)
Yep, and each vouch only needs one decision each.
everything else still has it
Is it possible to make a select menu autocomplete like slash command options
No, it is not possible. You only get 25 options in a string select menu. Select menus are much closer to a string options Choice then autocomplete
can i somehow detect whether an ephemeral interaction.reply() has been closed?
You don't. What type of feedback are you trying to get from the user? And what action do you want to take upon that feedback?
i was wondering how does that affect the listeners mounted on the ephemeral message
since the message cannot return anything anymore i thought it would be useful to detect when its closed and clean up
Yeah, there's no way to tell if the user closes an ephemeral message. It exists entirely on the users client
a timer after the last interaction is usually the best
if you editReply or deleteReply a deleted ephemeral message it'll just fail silently, won't throw on your side
whats the difference between setId and setCustomId for TextInputBuilder()?
one sets the id, other the custom_id
only interactable components have custom_id, all components have an id
what exactly can I do with the ID?
differ components from each other
basically the same purpose as the customId
oh I see
thanks
do I have to do a .setMaxValues() if I have a .setMinValues()? This seems rather strange
are you getting an error?
yeah
data.components[1].component.min_values[NUMBER_TYPE_MAX]: Int value should be less than or equal to 1.
this happens when I do .setMinValues(2) without .setMaxValues(). If I have .setMaxValues(), the error goes away
I think it's because it defaults to 1
Component Reference - String Select
A String Select is an interactive component that allows users to select one or more provided options. String Selects can be configured for both single-select and multi-select behavior. When a user finishes making their choice(s) your app receives an interaction. String Selects are available in messages and modals. They must be placed inside an Action Row in messages and a Label in modals.
read more
max_values? integer Maximum number of items that can be chosen (defaults to 1); max 25
oh I see, tyty
one more question... how do I show a modal if I already deferred the interaction?
you can't
you'll need another interaction, so you could show a button that opens the modal immediately
ah
but you can't open it with that deferred interaction
ty a lot
Hello! This error just appeared suddenly, I don't understand..
default_values: import_shapeshift4.s.object({ id: import_shapeshift4.s.string(), type: import_shapeshift4.s.literal(import_v1010.SelectMenuDefaultValueType.Channel) }).array().lengthLessThanOrEqual(25).optional()
^
TypeError: Cannot read properties of undefined (reading 'Channel')
at Object.<anonymous> (C:\Users\sabu\Documents\bot protect\node_modules\@discordjs\builders\dist\index.js:1455:159)
at Module._compile (node:internal/modules/cjs/loader:1376:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
at Module.load (node:internal/modules/cjs/loader:1207:32)
at Module._load (node:internal/modules/cjs/loader:1023:12)
at Module.require (node:internal/modules/cjs/loader:1235:19)
at require (node:internal/modules/helpers:176:18)
at Object.<anonymous> (C:\Users\sabu\Documents\bot protect\node_modules\discord.js\src\structures\Embed.js:3:25)
at Module._compile (node:internal/modules/cjs/loader:1376:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
Node.js v20.11.1```
Nuke node_modules and reinstall
i already did this..
Can you show ur package.json file?
yes ofc
"name": "discordjs-v14-template-ts",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "cls && node build/index.js",
"build": "cls && node build.js"
},
"keywords": [],
"author": "MericcaN41",
"license": "ISC",
"dependencies": {
"@discordjs/rest": "^1.1.0",
"@types/node": "^18.7.14",
"chalk": "^4.1.2",
"discord.js": "14.3.0",
"distube": "^5.0.7",
"dotenv": "^16.0.2",
"mongoose": "^6.5.4"
},
"devDependencies": {
"typescript": "^4.8.2"
},
"overrides": {
"discord-api-types": "0.37.20"
}
}
Can you remove the -types override?
Prob not a good idea to tie it down to an old version
Ig ur d.js version is tied down too
what version can i choose ?
Latest is v14.23.2
Oh, for -types
-types latest stable is at v0.38.30
if i already have no intents selected and the bot is only replying to interactions with hardcoded info, are there other elements i can disable the cache for that might reduce the memory usage even further?
Depends on what data you really need
none really, it's just a wiki bot that gets info from a json file
If ur not using guilds intent, consider a lighter library that handles interactions via webhooks calls
Then definitely do that
D.js is overkill for your use case
forgot to say the bot also sets a presence so it needs the gateway, that's why i used djs for it and i believe webhook interactions don't let you set a presence?
That’s correct
so no intents is the max i can do for djs
it's not an issue tbh i was just curious
Maybe just use @discordjs/ws
is there a guide for this? i haven't used that yet
No
There’s always tests and docs
I think WebsocketShard is pretty straightforward tho
would it change anything vs using the regular djs though? since i assume djs' memory footprint comes from caching stuff but in my context i don't know what there is to cache since there isn't many pass through events
Yea
i thought about using makecache but i wasn't sure what to pass to it
Prob just cache nothing
makeCache: () => new LimitedCollection({ maxSize: 0 })
Actually, need to cache the client user
does it break stuff if it's not cached?
thanks for that snippet tho
Nvm, it’s no longer a getter
The ready event might break bc of the guilds thing
I think it was fixed
Otherwise if try to use any event other than interactionCreate (after adding proper intents), it likely won’t work
shardX events should work fine too
dont those require sharding? or are they fired even without
You do have one shard
i fell asleep, but the changes i altered was how i fetched the option on string select, i also added logger points to ensure channel ID is valid in the database (i was getting channel not found at one stage but after changing how i fetched the option from the menu it found the channel) and yeah thats as far as i got to why it is endlessly thinking
const gameOption = interaction.fields.getStringSelectValues('game_selection_option'); ->
const gameOption = interaction.fields.getStringSelectValues('game_selection_option')[0];
how to convert Date to discord time markdown?
Date issues numbers
async exec(channel: DJS.GuildChannel, time: Date) {
const i18n = useI18n();
const lang = await GuildConfig.findOne({ guildId: channel.guildId });
try {
const msg = `${i18n.twl(lang?.lang ?? "en", "channelpins.updated.msg", {
channel: `${channel.name}`,
chan: `${channel}`,
date: `${time}`
})}`
time discord.js@14.23.2
Formats a date into a short date-time string.
@robust flame
tysm
but i did it with moment
That isn't discord markdown though. So that will not use the user's timezone
i feel like ppl use this channel to steal code lol
Ai has done enough of that already
Does it have an ETA for the file Upload?
no
wdym
i added console.log('\x1b[36m[Info]\x1b[0m', 'Suggestion Message Data:', message); nothing is logged to console so its not building? im now logging to ssee if container is being created
const message = await interaction.client.guilds.cache.get(interaction.guild.id).channels.cache.get(suggestionChannelID).send({
content: null,
embeds: [],
components: [suggestionContainer, miscButtons], //commentButton to add back when fixed
allowedMentions: { parse: [] },
flags: MessageFlags.IsComponentsV2,
});
edit: console.log('\x1b[36m[Info]\x1b[0m', 'Suggestion Container Data:', suggestionContainer); also logged nothing
how to stop this embed from appearing when doing message.reply
can I send an ephemeral reply to an arbitrary message without it being the response to a slash command?
nvm u cant
Wrap the link in <>, or pass SuppressEmbeds flag to flags option
It's to check for multiple instances of your application
this happens after a while of thinking loop, also im still confused on where the data has ended up i can confirm its trying to build as the builder itself is registering
[Debug] Resolved channel ID for Contract Ville: [ { name: 'Channel', value: '1130141013168631968' } ]
[Debug] Resolved channel ID for Sandwich Sim: [ { name: 'Channel', value: '1130141013168631968' } ]
[Debug] Resolved channel ID for Dig Island: [ { name: 'Channel', value: '1130141013168631968' } ]
[Info] Game option selected: Channel ID: 1130141013168631968
[Debug] Resolved ContainerBuilder caller: ContainerBuilder { data: { type: 17 }, components: [] }
First, you don't need to get the guild from cache. If the guild is in cache it will exist on the interaction at interaction#guild.
What's the goal of the command?
its more of a event now? as its nested in
if (!interaction.isModalSubmit()) return;```
on the current / based version of the suggestion building it works perfectly fine and sends correctly but ever since ive started to try and experiment with modal version its gone to shit the best way to word it
heres the updated code frm ther last paste i sent
http://pastebin.com/rLKpu4fX
How so? What's not working when you try to use the modal?
modal -> opens on the trigger point, console starts logging each part im monitoring it gets to the builder part i see its logged its started the build process but when it comes to the const message the logger i have attached to the doesnt fire and it ultimatly turns into the empty box in the replied
So upon the modal submission, you want to send a new message to the channel?
In addition to the reply to the interaction
yes, but ive gotten as far as knowing the container builder is registering the action then it dies and it cant be related to the collector in the main interaction as on send its on a diff runtime? i have it for around 5-6 mins const collector = initialMessage.createMessageComponentCollector({ filter, time: 360_000 }); on orignal spawn point for the modal
You maybe suppressing your errors somewhere. Try explicitly catching and logging errors there and see if it logs anything
i dont think im supressing errors, i do have these but surely they shoudlnt effect?
// Handles uncaught errors
process.on('unhandledRejection', (reason, promise) => {
console.error('⚠️ Unhandled Promise Rejection:', reason);
logCrashToFile('Unhandled Promise Rejection', reason);
restartBot();
});
process.on('uncaughtException', (err) => {
console.error('💥 Uncaught Exception:', err);
logCrashToFile('Uncaught Exception', err);
restartBot();
});
// Handles all exits (clean or not)
process.on('exit', (code) => {
logCrashToFile(`Process Exit [code ${code}]`);
});
process.on('beforeExit', (code) => {
logCrashToFile(`Before Exit Triggered [code ${code}]`);
});
// Handles termination signals
process.on('SIGINT', () => {
console.warn('🛑 SIGINT received (Ctrl+C or shutdown)');
logCrashToFile('SIGINT (Interrupt)');
process.exit(0);
});
process.on('SIGTERM', () => {
console.warn('🛑 SIGTERM received (kill or system shutdown)');
logCrashToFile('SIGTERM (Terminate)');
process.exit(0);
});
// Trigger restart logic
function restartBot() {
console.log('🔄 Restarting bot...');
process.exit(1); // Pterodactyl or PM2 should auto-restart on code 1
}
i do have .catch(console.error); on the reply for the modal interaction but not the const message itself ill see if that triggers anything there
oh yeah not sure if i mentioned
console.log('\x1b[36m[Info]\x1b[0m', 'Suggestion Container Data:', suggestionContainer); No data from this caller is logged either
this one should fire after the first check
try this code
console.log("sending message to suggestionChannelID")
const messages = interaction.guild?.channels.fetch(suggestionChannelID).then(async channel => {
if (!channel?.isSendable()) {
console.log("channel not sendable")
return
}
const message = await channel.send({
content: null,
embeds: [],
components: [suggestionContainer, miscButtons], //commentButton to add back when fixed
allowedMentions: { parse: [] },
flags: MessageFlags.IsComponentsV2,
});
console.log('\x1b[36m[Info]\x1b[0m', 'Suggestion Message Data:', message);//No data is logged
})
i just used this and it fired so its seen and sendable
const channel = interaction.client.guilds.cache.get(interaction.guild.id)
.channels.cache.get(suggestionChannelID);
await channel.send({ content: '🧪 Test message: this should fire before modal collects data.' });
ok good to know so the next thing is checking your components. if you log them right before the message is sent. what do you get
could a missing builder be a cuase of no errors? it was right infornt of me as a reason? its not green like the other parts if this was the issue all along
I am unsure. I uses TS so it would throw any error if I used a class not defined
yes that would of done it, why did it not error for that 
glad we could help
appreciated, still mega confused why it never fired a reference error or wht not to say i forgot to define it
my only thought is that you are catching the error somewhere
the only error catcher i have is these no clue if this is really effecting those errors at all?
HI, I have this bit of code
export const registerCommands = async (
client: Client,
commands: Map<string, Command>
): Promise<void> => {
const commandArray = Array.from(commands.values()).map((cmd) => cmd.data);
try {
await client.application?.commands.set(commandArray);
commandArray.forEach((cmd) => {
console.log(`Registered command: ${cmd.type}, ${cmd.name}`);
});
console.log(`Registered ${commandArray.length} commands globally.`);
} catch (error) {
console.error('Error registering commands:', error);
}
};```
which I'm calling in the `main.ts` like
```ts
const client = new Client(...)
await registerCommands(....)
client.login(token)
when the code is local and with a test clientId (test bot), everything works as expected, but when I push the code to a vps, and use another clientId, only events are working, but there's no slash commands.
@normal flare you shouldn't deploy your commands on every start. there's a reason why we suggest the separate script using REST#put()
I see, does that only apply for commands?
yes, only commands. don't even need to run the deployment script on the VPS. run it locally once, and your commands will show up.
as in, what about the events? where would I register events?
// src/index.ts
const client = new Client(...);
await registerEvents(client, events);
await registerCommands(client, commands);
void client.login(config.discord.token);```
there are two different things you are mixing (by calling both register). one is deploying to discord, that only happens for commands. the other is adding handlers to your code; that's on your client side and not sent over the API. that needs to be done for events and commands on startup
there are two different things you are mixing (by calling both register).
are you referring to theregisterEventsandregisterCommands
should I move the client.application.commands.set(..) call to ready event?
no
sending command metadata to discord does not need to happen every time you start your bot
discord keeps the command metadata for your app forever after you send it
or until you change/remove it
what your code does (handles incoming events, loads code for running commands poeple use) is not really a concern of discord
discord only cares about you responding within 3 seconds of the interaction
so why did it still not show / commands?
well, in that one case you can run it once from your ready event
but afterwards you should move this into its separate script like our guide suggests
I do have a script, though I thought that is not mandatory and doing application.commands.set(...) should be fine
both do exactly the same thing anyway
the difference is that using client.application requires that to be done from within your running bot
while the script can be ran at any given time without your bot even being online
unless the application.commads.set() should be moved to the ready event. because currently I have in here (in registerCommands)
move it there once so that this code actually runs
because right now it doesn't because of the ?. in the client.application?.commands.set()
after you move it to ready, and start your bot, your commands should be registered
after that you can remove that call from the ready event
I see, the alternative of moving it, is simply just calling the script with Rest.put right?
if you mean "alternative of moving it [into the ready event]", then yes
yes
I'm still confused tho. because the script should not be mandatory
and it said within 1 hour commands should be there, but it's been a lot more than 1 hour
did you run the script
No
did you ever move the registerCommands() into ready event
No, because I thought that was a temp fix?
then why are you expecting the commands to appear if you never actually deployed them to discord.
yes, it is
because that call is in wrong place
and so it doesn't do anything
it was explained why it doesn't
I don't have access to the vps, waiting for the person who has to be available and run the script
you fix that call not working by moving it to a place that will make it work
which is the ready event
after you run your code once, that call is no longer needed there
because the commands are already registered
what happens when I add new commands then, do I put the call back in the ready event?
you run the script again
you can run that script from your own PC
so can we just get rid of the appliaction.commands.set() call, and just use the script?
yes
I see.
you can do that now instead of waiting for the VPS owner. all you need is just follow the guide for the script and the bot token
I assume I need the clientId of the production bot right?
yeah, that too
since that's where you'd want to deploy the commands
I don't
I'll have to wait
it's just the user id
okay that I can get, but I also think I need the token which I don't have
well, if you don't have that in any .env or config files, then sure, can't help you much with that
no yeah, I'll have to wait for the person who has access to run the script
thanks for the help @loud quartz @steel trail
Is there support for fetching server tag/server user has on their profile, it is relatively new feature
guild tag*
User#primaryGuild discord.js@14.23.2
The primary guild of the user
Thank you
o7
sorry for the ping but its giving undefined, I am on discord 14.20, are there any specific intent or other things needed?
it was added on .22
And latest ist .23.2, so update
got it
i know every embed has that issue with @ mentions showing only the ids (probably some cache thing, i guess). does iscomponentsv2 have the same problem?
No and yes. Components we need to when using a text display will parse four mentions completely, unlike embeds. However, this will lead to the roll or user receiving a push notification. If you turn off mention parsing then it will have the same issue
This might not be an issue for you as you want the user to get pinged or it's in a channel where users can't see so they won't receive a notification
They say to have fixed this issue but didnt work out well. You can with componentsv2 if you keep mentions on (if you dont want them to get pinged use defer or edit for your interaction reply)
Do components with allowedMentions set to none really not parse the mentions correctly? I thought they do 
They do. But if you dis allow mention the @id "issue" can persist
So they don't
you sure? I recall it doesn't have that since it behaved like message content
I am unsure then
I'm pretty sure even with no allowed mentions they get parsed, I've never had that issue since switching to containers and no allowedMentions
thats just coincidence then. mention issue occurs when there are no allowed mentions
dont know what ever happend #1403147433369800888 message
if you're in mentions field you're mentioned, and not being let there by allowedMentions doesn't insert you there, so there's no data about you attached to the message
that said, unsure if they ever fixed the issue with always inserting mentioned things there, given what the issue actually was
hello there. i am trying to make a command and i want to set a timer so that if the button hasnt been interacted with within a certain amount of time the embed will edit
are you using collectors to listen for the button interaction?
no
so you're listening with an interactionCreate listener?
can you show your code?
for when you create the button
const newEmbed = new EmbedBuilder()
.setTitle(`__${brand} Receipt__`)
.setDescription("Press the button down below to get started.")
.setColor(variables.default)
const button = new ButtonBuilder()
.setCustomId(`start${brand}`)
.setLabel("Start")
.setStyle("Primary")
await selected.update({ embeds: [newEmbed], components: [new ActionRowBuilder().addComponents(button)] });```
and how do you then listen to it?
interactionCreate
i have a switch case for the custom ids
given both are separate it might be hard to do that
it's not something built in djs
oh right
djs doesn't manage components pretty much
the only helpers are collectors
it'd be easier with one, since you'd just listen to the end event, see if it hasn't been handled
or with your current way you'd need some kind of map where you put and clear unhandled buttons
can channel message collectors run indefinetely, untill stopped manually?
yeah but at that point why not have an interactionCreate listener
its not about handling interactions the old way, its for something else
I'm not sure what you mean by old way
it'd be easier to suggest whether that approach seems right if you explain your situation
but generally it doesn't sound like it is
i need to have my bot constantly listen for messages on a specific channel
ah, misread your message, thought you meant interactions
though still, you can use the messageCreate event directly
collectors just wrap around its equivalent event
noted
i have a command that when executing it the user has 10 seconds to complete the modals etc. how can i implement that if they take more than 10 seconds to complete the modals that the embed gets edited from whatever point the user is at
you have no way of knowing how completed the modal is only when it is submitted and when you sent it to the user
I've been trying to use interaction.fields.getStringSelectMenuValues() to get the value after submission using new select menu inside model but its getting failed.
pls ping with answer
@junior wraith there's no error here
"getting failed" is not a valid description of an error
TypeError: interaction.fields.getStringSelectMenuValues is not a function or its return value is not iterable

because it indeed isn't a method that exists
ModalSubmitFields#getStringSelectValues() discord.js@14.23.2
Gets the values of a string select component given a custom id
thanks it worked, @loud quartz sorry for being harsh i just need a sleep.
it's all good, take a nap/sleep, the code won't run away 
IT GOT EXECUTED SUCESSFULLY
i was using getStringSelectMenuValues instead of getStringSelectValues, need to go through all documents
ModalSubmitFields discord.js@14.23.2
Represents the serialized fields from a modal submit interaction
That's pretty much the only place you need to look for receiving the data
yep it worked
So I have a bot and it has a dashboard, so far so good, but when I upload my application and put it on my domain, when I do the login callback, it simply says that the page does not exist and keeps saying “not found.” How do I fix this? I'm hosting the back-end using pm2.
seems something you would ask in the dev server #useful-servers
thanks
pls ping with answer
whats your question
This is probably already known, though I searched and couldn't find it (or find where to post). But FYI, images appear to be broken in the guide migration.
what images?
if you have a question about something related to the discord.js library, please consider looking at #how-to-get-help
The guide says "It should look like this:" and it's a blank line
i’ll forward the issue internally, thank you
Thank you!
is it a must to await interaction.deferReply
Only if you can't gaurentee you'll be able to send a reply within 3 seconds
i ment the await
Oh. Well yes and no because deferReply returns a Promise.
You can technically ignore the promise but then you would be disregarding any possible errors or running into race condition issues
what would be the race conditions here
Once you deferReply, you have to use editReply
You could send your defer, it hangs on Discord's side, then you send an edit reply which then fails because you can't edit if you haven't replied
Is the discord-rpc package deprecated or is there a replacement I can't find. The package's linked repo hasn't been touched since the beginning 2022. Asking because I can't find a definitive answer in previous messages. (Repo in question)
The package is deprecated because that system was deprecated in favor of the Game SDK iirc
It should still work however
ok, that's fine for me
It doesn't actually. This is what previous messages say but I can't get it to work. The lack of docs also doesn't help.
The underlying IPC and WebSocket stuff works, just not in that repo's implementation. I was just hoping I didn't have to reinvent the wheel for my project
@topaz bluff not mad at you fyi, thx for helping
I didn't take it that way. I'm just repeating the answer the maintainers give.
I've never used the package. So I can't say if it does or doesn't work personally
Discord discontinued RPC anyways. I don't think that will get revived
#11026 in discordjs/discord.js by OfficialSirH opened <t:1754155774:R> (changes requested)
feat: rpc
its getting a rewrite anyway
can someane help me with my bot? i get this error:
node:events:497
throw er; // Unhandled 'error' event
^
TypeError: eventFunction is not a function
at Client.<anonymous> (/home/willem/craftcamp bot beta/src/handlers/eventHandler.js:18:23)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
Emitted 'error' event on Client instance at:
at emitUnhandledRejectionOrErr (node:events:402:10)
at process.processTicksAndRejections (node:internal/process/task_queues:92:21)
Node.js v22.20.0
i can give sourcecode