#djs-help-v14
78874 messages · Page 15 of 79
thanks
export class PermissionsBitField extends BitField<PermissionsString, bigint> {
public any(permission: PermissionResolvable, checkAdmin?: boolean): boolean;
public has(permission: PermissionResolvable, checkAdmin?: boolean): boolean;
public missing(bits: BitFieldResolvable<PermissionsString, bigint>, checkAdmin?: boolean): PermissionsString[];
public serialize(checkAdmin?: boolean): Record<PermissionsString, boolean>;
```What's `checkAdmin` there ?
PermissionsBitField#any() discord.js@14.19.3
Checks whether the bitfield has a permission, or any of multiple permissions.
The checkAdmin parameter is not explained anywhere in that page :/
Huh, that‘s really missing from docs I guess… it decides whether Administrator permission should cause all checks to be true or if you explicitly want to check for the permission bit being present
Hmm, is that an important distinction ?
Sometimes, yes. If you want to find out if someone would still have the permission to do X without being admin
Or when you want to list users having permissions for a specific thing without including all admins in the list, or …
Indeed. Thanks
what is the difference between awaiting components and collecotrs
awaitMessageComponent is a promisified collector
i dont get it
It‘ll resolve with the collected thing(s) while a regular collector emits collect and end events you need to listen to
Hey. is there a way to get the users timezone?
createMessageComponentCollector returns a collector directly and you can do what you want with it. awaitMessageComponent creates the same collector internally and returns a Promise that’ll resolve when it collected something and reject if the end event happened without collecting anything
Only if they tell you themselves
That doesn’t get you timezones of anyone
oh ithought your timezone
but what does the time in createMessageComponentCollector do
Determine for how long it‘ll keep collecting if no other end condition happens before then
i dont really get it could you explain it on simpliest way
Popular Topics: Collectors
read more
Maybe that helps
thank you
Okey, thank you ❤️
i get it now the interaction wont work anymore unlike the component one
Huh?
u can only use the interaction once
anyone know the cause why this ishappening. i have reset my token and still same issue
Your handleCommands function uses rest before that login call
So no token set yet
what do i do then? where do i implement it ?
LimeBOT_TOKEN is not the token you log in the other file 
ohhh yea its a paste from my other bot mb
working now gang
also it's not advised to deploy commands on every start
and why api 9? 
why my buttons automatically activated when send
hey guys any info on guild tags' lib
that's the default, do you want to send them as disabled?
ButtonBuilder#setDisabled() builders@1.11.2
Sets whether this button is disabled.
if yes, with that ^^
no its automatically clicked
ah, no that's not possible
but it is automatically clicked
well if the interaction (click) comes from you, then it could be some kind of mod you installed in your client
it's not possible for interactions to generate out of nowhere
and it's not possible for bots to force an interaction
a manual interaction is a must
its clicked cuz the component was edited
no, that's not how interactions work
if you could share your code it'd be useful to narrow down what is exactly happening
there's no library for guild tags
and they're not documented by discord, so it's not implemented by djs in case you meant that
okok thank you, will they include them?
@bold oyster
thank you! ^^
- and what's the actual problem? double reply or something?
- you need to reply to the confirmation interaction, otherwise you're ignoring it and it'll show an error to the user
(replying to deleted video) maybe because of the second point
try fixing that just in case
wdym second point
the second point here ("you need to reply to...")
oh
This is a general Ping code:
const { SlashCommandBuilder } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('ping')
.setDescription('Replies with Pong and latency!'),
async execute(interaction, client) {
const latency = Date.now() - interaction.createdTimestamp;
await interaction.reply({
content: `🏓 Pong! | ${latency}ms`,
allowedMentions: { repliedUser: true },
messageReference: interaction.id
});
}
};
But the bot isn't pinging like the ping when we reply to someone. What's seems to be the problem?
i fixed it by replacing interaction.editReply to collector.update
It's not a reply to a message for it to ping, it's a response to an interaction. You'll need to mention the user if you want it to ping the user
So we need to mention the user directly.! Ok thanks!
i forgot but what is the Max amount of buttons a message can have?
@covert scarab #app-commands
regular message, 25 (5 action rows holding 5 buttons each)
components v2 flagged message, 33 (6 action rows holding 5 buttons each plus 1 action row holding 3 buttons)
So if i have 1 embed with already 5 buttons, if i make it send a second embed, i can add another button?
embeds and components are unrelated
oh
^
like b3ssel said, it's per message, not per embed
in case you meant a container then it'll be even less because each container is a component
and also the components it contains
(the component limit in components v2 messages is 40 in total, there's no "per component type" limit)
could you put awaitMessageComponent inside of awaitMessageComponent
why? what do you want to do?
my buttons are like this,i want to add "user info" but it would it be possible to add it or?
when a user select a rows it will edit a message with a button then a handler for that button
in a second row, yes
not in the same row
SICK
what if u use a select menu?
i have been experimenting with that but i want to add that later
like "press the userinfo button then use the select menu that came up regarding that followup"
uhhm fair enough
then awaitMessageComponent again after the user has selected
yea? thats what im asking if it doesnt cause an error putting an awaitMessageComponent inside a awaitMessageComponent
below, not inside
you're not putting it inside though, you're putting it later 🐌
its samething lol
how do u put it later when u not putting it in side
not really, because awaitMessageComponent works with collectors, which can be nested (one inside other one), but it's usually a bad idea
which is why I didn't tell you to use a collector and nest it, but instead asked for your use case
but the previous collectors wont work anymore
not true
its true i tried it doesnt worky anymore
it's actually one of the reasons it's usually a bad idea, it can create multiple unintended ones
you switched to collectors and nested them?
its automatically nested
when the interaction is true
nothing is automatically nested 
try catch then just return
I'm not sure you completely understand what nesting means
if (condition) {
// this is a nested condition, it's inside another construct of its same "type": another if
if (otherCondition) {
}
}
similarly you can create nested collectors, one inside an event callback of another
but you can't nest "await collectors", because it's a single statement, nothing can go "inside" it like an if, a while/for loop, etc
e.g, like:
if (!isOptedIn) {
console.log(`Ban not submitted: Guild ${guild.name} ${guild.id} is not opted in for ban submission.`);
return; // Ensure early return to prevent submission
}```?
can't do
const confirmation = await message.awaitMessageComponent(...) {
const furtherReply = await otherMessage.awaitMessageComponent(...);
}
that's more of a guard clause https://en.wikipedia.org/wiki/Guard_(computer_science)
but it works on me
that's not valid javascript
maybe it looks to you that it's working that way, but it's not really what is going on
Yours might look similar, but there’s definitely no {} like that
i only call await message component when the buttons are succesfully send
Just show your code instead of trying to describe it
how can i do it like
for english users: name: ban
description: .......
for italian users: name: ....
description: ....
in slash commands
.setDescriptionLocalisations and .setNameLocalisations in the slash command builder
Can u send the documation link?
documentation suggestion for @pliant forge:
SlashCommandBuilder#setNameLocalizations() discord.js@14.19.3
Sets the name localizations for this command.
SlashCommandBuilder#setDescriptionLocalizations() discord.js@14.19.3
Sets the description localizations for this command.
TYsm
Slash Commands: Advanced command creation - Localizations
read more
there's also that guide entry
i just removed it contains sensitive
so is my code fine
in case you meant you removed what this contains, that's not what I meant
no i just removed the function thingy cuz im changing something
you're defining this function, you're never calling it, it won't do anything
ah
well that's the code you just shared a while ago then
just with confirmation.update instead of interaction.editReply
so is my code fine
you just said it worked a while ago?
yea it works
then it's fine? I'm not sure what the question is if you know what's the answer
or you meant in terms of good practices?
yes
you could use ;s which often avoid unwanted function calls
and a switch instead of a bunch of else ifs, but that's more of a style, personal approach
im not new or something i just asked about awaitMessageComponent
im not using switch cases its only 2 elseifs
Hi! I'm working on djs v14.19.3, for some reason I can't add commands to my bot's intergration.
I'm getting a good response from the API and nothing seems to be off.
My request:
[
{
options: [],
name: 'apply-muted-preset',
name_localizations: undefined,
description: 'Applies all the channels with the mute preset',
description_localizations: undefined,
contexts: undefined,
default_permission: undefined,
default_member_permissions: undefined,
dm_permission: undefined,
integration_types: undefined,
nsfw: undefined,
type: 1
}
]
Response:
Collection(1) [Map] {
'1376581041216819251' => <ref *1> ApplicationCommand {
id: '1376581041216819251',
applicationId: '1376543468897308765',
guild: null,
guildId: null,
permissions: ApplicationCommandPermissionsManager {
manager: [Circular *1],
guild: null,
guildId: null,
commandId: '1376581041216819251'
},
type: 1,
nsfw: false,
name: 'apply-muted-preset',
nameLocalizations: null,
nameLocalized: null,
description: 'Applies all the channels with the mute preset',
descriptionLocalizations: null,
descriptionLocalized: null,
options: [],
defaultMemberPermissions: null,
dmPermission: true,
integrationTypes: [ 1 ],
contexts: null,
version: '1376582624918769714'
}
}
Events are working perfectly fine.
I've set the commands using the ApplicationCommandManager set method.
Thanks for your help!
then it's fine, in general if it doesn't cause issues or deprecation warnings, it should be fine for djs
dmPermission: true, integrationTypes: [ 1 ], contexts: null,
that says your command will show up when the app is user-installed (integration type 1), and only in the bot's dms, is that where you're testing?
Hey thanks for the quick response!
No, I'm trying to test it in a guild channel
I did it using the slash command builder, is there a new flag for it?
okay, given that you're not passing contexts and integration types, it'd sound as if your app is only set as user-installable in the discord dev panel
integration types defaults to the types set in the panel
I see, so simply specifying with a flag should do in that case right?
My app is installable for guild only
where are you checking that? can you show a picture?
🤦♂️ I forgot to save the changes, it was set to both guild and user
My bad for the misinformation
huh, but then it should default to both guild and user 
no idea what happened but if setting it to only guild fixes it then I guess it's fine
Yeah, I never had any problem with it
That's still set to 1, perhaps reinstallaion would do now that the user is set to off?
you're deploying again and it still logs that?
you're sure you're looking at the correct bot?
I'm positive
and the correct token?
Yes sir, I'll just state my integration type from now on I suppose
I just don't think it'd make sense for it to let you at all make it only user installable, if it's not user installable
yeah try that ig
It works, thank you very much 🙂
you should use the enum instead of raw values btw
v10: ApplicationIntegrationType
read more
it's just more readable
That's 100% true, I'll do that
much better 
tyvm! have a lovely day
hello guys 😄 , my default settings has 3 retry for rest api calls but for 404 error i just want to do 1
is it possible ?
Rest won't retry a 404
It will only retry if no response at all
e.g. on connection resets, abort errors,
i made components thanks
Hi,
What's the most up-to-date embed preview webapp ?
Thanks
The actual discord devs website has an embed preview I think but that maybe just for websites, but other than that discord.builders is for components v2
Yh that one is only for metadata for websites
Yeah I meant for EmbedBuilder
also please keep non djs questions outside of this channel
Well, I want a web UI to generate the data to pass to DJS' EmbedBuilder, so it's on-topic
not really since djs does not have a web ui for that
given EmbedBuilder accepts raw api data it should support pretty much every generator out there
But if you have raw api data anyway you shouldn't use a builder anymore
Since builders are there to generate that api data for you
Just put the JSON you have directly then
Can’t send an empty embed or the embed object is malformed
----[ERRORE]----
ContainerBuilder {
data: { type: 17, spoiler: false, id: 1, accent_color: null },
components: [
MediaGalleryBuilder { data: [Object], items: [Array] },
SeparatorBuilder { data: [Object] },
TextDisplayBuilder { data: [Object] }
]
}
TypeError: Cannot read properties of undefined (reading 'setContent')
at monitorTask (C:\Users\Administrator\Desktop\shippingclub_discord_bot_stripe\helper\monitorTask.js:214:54)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
Unhandled promise rejection: TypeError: Cannot read properties of undefined (reading 'setContent')
at monitorTask (C:\Users\Administrator\Desktop\shippingclub_discord_bot_stripe\helper\monitorTask.js:214:54)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)```
why its not cached guys?
could you log message.id to make sure it's the correct message?
im sure 100% is correct
What's monitorTask.js line 214? And what does it have to do with your screenshot?
why is my sound command not responding when I try and execute it
try {
if (task.paymentId) {
containerNew.components[4].accessory.setDisabled(true)
containerNew.components[4].components[0].setContent('## :tickgreen: Paid by Stripe!');
} else {
line 214 containerNew.components[4].setContent('## :tickgreen: Paid by Balance!');
};
} catch (err) {
console.log('----[ERRORE]----');
console.log(containerNew);
console.log(err);
throw err;
}
sorry forget to upload code
with screnshoot you can see are the correct index
is possible after 2/3 second still not cached this index?
Your container has only 3 components in it, so there is indeed no [4]
in the log are 3, but if u can see the screenshot, are 4
And without seeing how you defined containerNew I'll have to assume you defined it before changing the contents
Does he know how to place buttons from top to bottom?
what im saying i call this code 300 time for day, with the same container, i create it as static method, so are not different, but on this 300 times, 3/4 for time i get this error
does who know?
I ask
that's a container, which has (in that order) an action row with 2 buttons, a separator, a media gallery with 1 image, a separator, and an action row with 3 buttons
I know, but how do you put the buttons from top to bottom in this order + in one message?
I just said how
with that container
you can add component one by one, in the order you prefer
really cant understand how fix that guys, im pretty sure is a cache problem...
did you get interaction_message from the cache?
as in, channel.messages.cache.get(messageId);
channel_interaction = await client.channels.cache.get(task.info_command.channel_id);
interaction_message = await channel_interaction.messages.fetch(task.info_command.message_id);```
and how are you sure it's the correct message being fetched?
also why are none of your variables being declared (const, let, var) but re-assigned 
because need under in my code bro
are declared up
i save it on database, and im sure its working beacuse as said, 300 times works, other 3 not, if was a problem of saving the message, i was getting error on all 300
then it could perfectly be a race condition
which by definition only works some of the time due to unexpected behavior
you should actually check whether it's the correct message just in case
if it's in your db you can inspect manually the table
or json or whatever you use
What's the event causing this code to run?
after i restart monitor task bro, all work correctly, aslo the message has gived me the error
if (task.task_id === undefined)
that's not the event
cant understand what him meaning sorry ahah
when does that code run?
on messageCreate, on interactionCreate, etc
no event releated on discord
so when does it begin?
no code runs by itself, everything is called by something
is it an interval or something?
code create the container
let separator2 = new SeparatorBuilder()
container.addSeparatorComponents(separator2);
if (paymentURL) {
let text2 = new TextDisplayBuilder().setContent('## :loading: Waiting your payament...');
let button = new ButtonBuilder().setLabel('Stripe').setEmoji(':credit_card:').setURL(paymentURL).setStyle(ButtonStyle.Link);
let section1 = new SectionBuilder()
.addTextDisplayComponents(text2)
.setButtonAccessory(button)
container.addSectionComponents(section1)
} else {
let text2 = new TextDisplayBuilder().setContent('## :loading: Removing from balance...');
container.addTextDisplayComponents(text2);
};
await interaction.editReply({
flags: MessageFlags.IsComponentsV2,
components: [container]
});
//monitoring task
monitorTask(obj, interaction.client);```
code handle the container
monitorTask.js
if (task.task_id === undefined) {
let channel_interaction;
let interaction_message;
let containerNew;
if (!task.groupMetadata) {
channel_interaction = await client.channels.cache.get(task.info_command.channel_id);
interaction_message = await channel_interaction.messages.fetch(task.info_command.message_id);
containerNew = new ContainerBuilder(interaction_message.components[0].toJSON())
try {
if (task.paymentId) {
containerNew.components[4].accessory.setDisabled(true)
containerNew.components[4].components[0].setContent('## :tickgreen: Paid by Stripe!');
} else {
containerNew.components[4].setContent('## :tickgreen: Paid by Balance!');
};
} catch (err) {
console.log('----[ERRORE]----');
console.log(containerNew);
console.log(err);
throw err;
}
/*
if (task.paymentId) {
containerNew.components[4].accessory.setDisabled(true)
containerNew.components[4].components[0].setContent('## :tickgreen: Paid by Stripe!');
} else {
containerNew.components[4].setContent('## :tickgreen: Paid by Balance!');
};
*/
let separator = new SeparatorBuilder();
containerNew.addSeparatorComponents(separator);
await interaction_message.edit({
flags: MessageFlags.IsComponentsV2,
components: [containerNew]
});
};
I'll assume that isn't immediately run when monitorTask(...) called right? What causes that to actually run? Is it an interval or ...?
if not stripe (text + button), it will pass instant in this condition
with stripe i never get this problem, beacuse i wait some seconds for the payament
Then why not pass the container directly? Why fetch and parse again?
You have the container builder in the first file, you want it in the second file.
you're right I could do it
but why doesn't it work in this mode, I would like to understand why
Because it's definitely a race condition here. The messageUpdate event caused by your edit call hasn't reached your bot yet, so the cached message still has the state from before the edit
ok thx for help guys
Hello, i want to handle both message and interactions for my commands. How can I do? To reply directly or send messages in the same Chanel?
we don't give support for message content commands ("!command")
it only involves string parsing though, but it's not advised to support them
you're entirely on your own for that
It’s generally not recommended to try and handle both interactions and message commands through the same system. It gets rather complex where you may as well write code for either commands
How to upload an image from a Buffer object in an embed ?
tag suggestion for @steel yacht:
Files in embeds should be attached via the message option object and referenced in the embed:
const attachment = new AttachmentBuilder('./image.png', { name: 'image1.png' });
const embed = new EmbedBuilder()
.setTitle('Attachments')
.setImage(`attachment://${attachment.name}`);
channel.send({
embeds: [embed],
files: [attachment]
});
AttachmentBuilder also accepts a buffer instead of a file path
AttachmentBuilder discord.js@14.19.3
Represents an attachment builder
Thanks
#1081585952654360687 and ask directly, not just whether someone knows https://dontasktoask.com
I pasted the following code into my events/interactionCreate.js file, given what the guide told me, and I'm receiving an error that says: Parsing error: 'return' outside of function eslint
if (timestamps.has(interaction.user.id)) {
const expirationTime = timestamps.get(interaction.user.id) + cooldownAmount;
if (now < expirationTime) {
const expiredTimestamp = Math.round(expirationTime / 1_000);
return interaction.reply({ content: `Please wait, you are on a cooldown for \`${command.data.name}\`. You can use it again <t:${expiredTimestamp}:R>.`, flags: MessageFlags.Ephemeral });
}
}
Pretty sure the guide mentioned smth about module.exports
this is my entire code in events/interactionCreate.js
const { Events, MessageFlags } = require('discord.js');
const { cooldowns } = interaction.client;
if (!cooldowns.has(command.data.name)) {
cooldowns.set(command.data.name, new Collection());
}
const now = Date.now();
const timestamps = cooldowns.get(command.data.name);
const defaultCooldownDuration = 3;
const cooldownAmount = (command.cooldown ?? defaultCooldownDuration) * 1_000;
if (timestamps.has(interaction.user.id)) {
const expirationTime = timestamps.get(interaction.user.id) + cooldownAmount;
if (now < expirationTime) {
const expiredTimestamp = Math.round(expirationTime / 1_000);
return interaction.reply({ content: `Please wait, you are on a cooldown for \`${command.data.name}\`. You can use it again at <t:${expiredTimestamp}:R>.`, flags: MessageFlags.Ephemeral });
}
}
module.exports = {
name: Events.InteractionCreate,
async execute(interaction) {
if (!interaction.isChatInputCommand()) return;
const command = interaction.client.commands.get(interaction.commandName);
if (!command) {
console.error (`No command matching ${interaction.commandName} was found.`);
return;
}
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
if (!interaction.replied || interaction.deferred) {
await interaction.followUp({ content: 'There was an error while executing the command.', flags: MessageFlags.Ephemeral });
} else {
await interaction.reply({ content: 'There was an error while executing the command.', flags: MessageFlags.Ephemeral });
}
}
},
};
I'm p sure the timestamp stuff has to be outside the module.exports, but the guide wouldn't show specifically where- so i got confused
yeah it meant inside the execute callback
which is where interaction is defined
do i put this entire thing in it?
The name property states which event this file is for, and the once property holds a boolean value that specifies if the event should run only once. You don't need to specify this in interactionCreate.js as the default behavior will be to run on every event instance. The execute function holds your event logic, which will be called by the event handler whenever the event emits.
Ohh alright thanks
Just the part that runs when the event fires
wait
Keep state and const that needs to be saved hoisted
const { Events, MessageFlags } = require('discord.js');
const { cooldowns } = interaction.client;
if (!cooldowns.has(command.data.name)) {
cooldowns.set(command.data.name, new Collection());
}
const now = Date.now();
const timestamps = cooldowns.get(command.data.name);
const defaultCooldownDuration = 3;
const cooldownAmount = (command.cooldown ?? defaultCooldownDuration) * 1_000;
module.exports = {
name: Events.InteractionCreate,
async execute(interaction) {
if (!interaction.isChatInputCommand()) return;
const command = interaction.client.commands.get(interaction.commandName);
if (!command) {
console.error (`No command matching ${interaction.commandName} was found.`);
return;
}
if (timestamps.has(interaction.user.id)) {
const expirationTime = timestamps.get(interaction.user.id) + cooldownAmount;
if (now < expirationTime) {
const expiredTimestamp = Math.round(expirationTime / 1_000);
return interaction.reply({ content: `Please wait, you are on a cooldown for \`${command.data.name}\`. You can use it again at <t:${expiredTimestamp}:R>.`, flags: MessageFlags.Ephemeral });
}
}
timestamps.set(interaction.user.id, now);
setTimeout(() => timestamps.delete(interaction.user.id), cooldownAmount);
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
if (!interaction.replied || interaction.deferred) {
await interaction.followUp({ content: 'There was an error while executing the command.', flags: MessageFlags.Ephemeral });
} else {
await interaction.reply({ content: 'There was an error while executing the command.', flags: MessageFlags.Ephemeral });
}
}
},
};
That’s only defined in the execute callback
What?
this is starting to turn into very basic js
you did not define interaction outside of your execute function
the guide here is showing this
im p sure im doing what the guide is saying
that needs to be added in the execute callback
in your InteractionCreate event …
Context matters
^^
the guide is not specific about where each part needs to go because it assumes that you know that, since that code uses the interaction, it's inside the event callback
It’s talking about in the event callback
Guide doesn’t assume you are using the event handler since it’s not necessarily required
It will speak in a way so that it works with either types of codebases
Hello! I'm doing
await <Guild>.members.fetch();
when starting my bot. And whenever I need all members I check
<Guild>.members.cache.
Does this cache update whenever someone joins or leaves?
If you have the GuildMembers intent, yes
perfect, tysm :D
I made the reload.js file, having no errors, but I am not seeing the command showing up in my srver.
Did you run your deployment script afterwards?
oh, do I have to run node deploy-command.js every time?
every time you add, remove or edit a command's data
Oh okay
Alright, thank you
I am trying to follow this page in the guide, and it says to put
const data = new SlashCommandBuilder()
rather than the usual module.exports with the
data: new SlashCommandBuilder();
and the guide doesn't tell where data should be added in the file, but maybe that is just me
Does it really matter which one you use?
the latter is the most common
latter?
the second one
Ah okay thanks
How do I use allowedMentions if I want to only mention specific users and a specific role
Currently it seems to only ping user mentions, even though a role id was provided
allowedMentions: { roles: [..], users: [..] }
Then pass the snowflakes
Is guildMemberUpdate emitted when a user changes their pfp?
it should, yes
ty
is there a place to suggest things to add to either djs or discord's api in general?
should have asked this somehwere else hold on
We cant add anything if it hasnt been added to Discord API
Github issues is probably the best place
yea i figured that, ill open a issue
add what specifically?
just feel like it would make sense to have, although it is possiable in most cases without it
are you suggesting that to discord or djs?
discord's api
because then djs can add it right
documentation suggestion for @wintry laurel:
ThreadChannel#fetchOwner() discord.js@14.19.3
Fetches the owner of this thread. If the thread member object isn't needed, use ownerId instead.
looks like it's possible?
oh weird
i was told that wanst a feature.
thank you
Can I put 2 images in one embed? like on top then bottom?
I suppose I could with components v2 but can you do it with embeds?
No, but you should use components v2. It can do that
ty
I'm trying to add a "channel" input option to my command, and I'm pretty sure I'm supposed to indent it at the same point as the "input" option, as the guide showed, but VSC is giving me indent errors, which ESLint rule is this for?
You didnt close the option above
So eslint thinks its still chained there
hm?
Your addStringOption method is not closed
ESLint thinks addChannelOption is still inside there, at 4 tabs indentation
Oh how would I properly format it then?
Close the method with a )?
This isnt a formatting issue, its a code issue
const { SlashCommandBuilder } = require('discord.js');
module.exports = {
category: 'utility',
data: new SlashCommandBuilder()
.setName('echo')
.setDescription('Replies with your input.')
.addStringOption(option =>
option.setName('input')
.setDescription('The input to echo back.')
.setRequired(true)),
.addChannelOption(option =>
option.setName('channel')
.setDescription('The channel to echo into.')),
),
};
Now you also added a , which is incorrect
oh
Now I get this
oh wait
neverminndd thanks
I'm running my deploy-commands.js file, but only seeing 3 commands, when I have 4
Its only finding 3 files
It's in the same folder as all the other cmds
Its correctly reporting that echo is missing a property
Can you please like... read the error? We include that in our sample code to help you for this exact reason
I followed the guide for the code..
Please, read your own screenshot
I have the "data" thing in my code in the command file, though, no? Is that not what it means?
Whats the other one it mentions
OHR
If you do have "data", then it must be "execute" thats missing
Inside this file, you're going to define and export two items.
- The data property, which will provide the command definition shown above for registering to Discord.
- The execute method, which will contain the functionality to run from our event handler when the command is used.
These are placed inside module.exports so they can be read by other files; namely the command loader and command deployment scripts mentioned earlier.
https://discordjs.guide/creating-your-bot/slash-commands.html#individual-command-files
given you didn't read the error before asking for help I'm not sure you've read the guide or just copied and pasted
The reason the deploy commands file checks itself is to avoid errors later, if only data was loaded, the command would fail on execution
what is the method equivalent to closing a fourm post in djs?
all i see is delete but i want to like archive it or whatever
nevermind
ThreadChannel#setArchived() discord.js@14.19.3
Sets whether the thread is archived.
// Archive the thread
thread.setArchived(true)
.then(newThread => console.log(`Thread is now ${newThread.archived ? 'archived' : 'active'}`))
.catch(console.error);
lmao ty i saw it the second i wrote that ofc
I'm not too sure about this, but would this be the proper way to get the input I want from the "input" option?
const { SlashCommandBuilder } = require('discord.js');
module.exports = {
category: 'utility',
data: new SlashCommandBuilder()
.setName('echo')
.setDescription('Replies with your input.')
.addStringOption(option =>
option.setName('input')
.setDescription('The input to echo back.')
.setRequired(true))
.addChannelOption(option =>
option.setName('channel')
.setDescription('The channel to echo into.'),
),
async execute(interaction) {
await interaction.reply(interaction.options.getString('input'));
},
};
yep
Alr thank you
Is there any way to track user avatar changes apart from guildMemberUpdate?
I ask this because this event only emits on guild update
guildMemberUpdate events
If a user updates their global profile, I suppose there's nothing to track that
^
Yeah it didn't emit
And userUpdate didnt either?
userUpdate is an event?
It is, but it's supposed to be that userUpdate is for the bot user, and guildMemberUpdate is everything else
But we might do some handling redirection
So the event works for guild avatar update but not for user avatar update
not documented or is that something new
userUpdate is not documented in the events page but i found it
Whats not documented
ok im just blind
Totally is though?
Yeah sorry haha
Wait so Triggered by the Discord gateway events UserUpdate, GuildMemberUpdate, and PresenceUpdate.
This event only triggers once right?
If a user updates their avatar, does it also trigger in guild member update? I suppose it shouldn't because it's user data rather than guild member?
I'm not sure, but it should only be once
Im pretty sure it's a bit of handling we do - when we receive a guildMemberUpdate event that is actually a change to the user object, we emit userUpdate instead, even though thats not how Discord handles it
right so guildMemberUpdate dispatches everything but d.js does it differently
I think so? It often gets debated if we should or not, so I'm never sure if its changed
But between the two events, it'll emit somewhere haha
Idk imo it should be one event or a setting to sync it to one
because a user update is a guild member update, changing my user pfp here will update it in a guild if i dont have a guild one
Yeah, which is how Discord emits it
I suppose this will be a major change if it comes out anyways
Does userUpdate need to cache in or something? This event is triggering so hard even though I know some of these people have not changed anything like what is this meant to be
Are these users being cached or something?
Maybe they’re partials? Not every user is cached so you may get an event with a partial user, hence only the id. Do you have the user partial? (I believe there’s one but will check)
Yes
but is this to do with cache? I saw this event trigger for some people even though they did not update anything
This "empty" data gives me the vibe of discord getting that user from the server and is currently caching it or something
Ah, possibly then. Since discord only sends the id and changes I suppose
No that's fine but why is everyone's old data like empty?
Partial user
I see users with having old data which are the current ones but 85% of them are empty
yeah but they did not even update their profile so what's triggering it
You won’t know since their old user isn’t complete?
Yeah but newUser has their new data right
but for this to emit, the user has to update their profile right?
Yes but I’m saying it’s a possibility you can’t know for sure since you don’t have all the old data. And there’s getters which don’t show on the log
I'm very certain this user has not updated anything in their profile
and this event triggers on cache update too where the user is currently being cached rather actually "userUpdate" (user actually updating the data)
According to discord they did 🤷♂️ djs won’t just emit an event for the sake of emitting an event
Not really because I was told this event is not emitted by discord and is done by djs
By who?
^ Him
yeah but thats
this userUpdate is not for bots, this triggers on discord user updates
Oh, Yh that’s true. Sorry mb. I’m not too sure, something must have changed
this is not a discord event and is done by djs so idk what's actually emitting it if someone knows
^ It seems that this data is partially emitted by djs so I can ignore partial data though whatever is emitting it, im curious to know
I was trying to search through the source code but is there a possibility they were changing like a clan tag? So a cached property is different to what’s received
This one I don't know
They might have changed something like that but really unsure
No nvm. Tbh I’m not too sure, something must have changed or at least djs thinks something changed for it to be emitted. Ig you have to be 100% something changed or didn’t change
Like im having around 70 emits on this and 65 is partial data lol
I just added a partial check to ignore it off because it's unnecessary imo to have this much emits though never seen this much partial data being emitted
Only since the client didn’t have them cached before
I'm following the guide, and i did the thing where u can choose the channel for the bot to echo the input into, but it won't echo into the chosen channel but rather the current channel
const { SlashCommandBuilder } = require('discord.js');
module.exports = {
category: 'utility',
data: new SlashCommandBuilder()
.setName('echo')
.setDescription('Replies with your input.')
.addStringOption(option =>
option.setName('input')
.setDescription('The input to echo back.')
.setRequired(true))
.addChannelOption(option =>
option.setName('channel')
.setDescription('The channel to echo into.'),
),
async execute(interaction) {
await interaction.reply(interaction.options.getString('input'));
},
};
I do realize the code isn't there, does anyone know how to make it work?
interaction.reply does that - replies
Nothing in your code tells it to send to a different channel
You would need to get the channel option and send to that
Keep in mind the interaction still needs a response of some sort
Oh
Ah I think I understand - yeah, "options" dont actually change any command behaviour on their own. Theyre just types of inputs for users
I didn't change anything in the rest of my code, I only just created a kick command, and my terminal isn't loading anything. It hasn't for a while. Before the kick command, I created a ban command, and it was working perfectly fine.
then again it might just be my internet
Show your deploy-commands.js file.
const { REST, Routes } = require('discord.js');
require('dotenv').config();
const { clientId, guildId } = process.env;
const fs = require('node:fs');
const path = require('node:path');
const commands = [];
const foldersPath = path.join(__dirname, 'commands');
const commandFolders = fs.readdirSync(foldersPath);
for (const folder of commandFolders) {
const commandsPath = path.join(foldersPath, folder);
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
if ('data' in command && 'execute' in command) {
commands.push(command.data.toJSON());
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" propery.`);
}
}
}
const rest = new REST().setToken(process.env.token);
(async () => {
try {
console.log(`Started refreshing ${commands.length} application (/) commands.`);
const data = await rest.put(
Routes.applicationGuildCommands(clientId, guildId),
{ body: commands },
);
console.log(`Successfully reloaded ${data.length} application (/) commands.`);
} catch (error) {
console.error(error);
}
})();
I haven't touched this for a while-
Is there something wrong with my deploy-commands.js file?
I think it's my internet, the deploy-commands.js one worked, but I'm doing node . and its also taking a while longer than usual 😂
thanks anyways
Oh uhm. I noticed that in the guide, with the kick and ban commands, it makes it so that other users cannot see the slash command at ALL, but I'm trying to make it so they can see it but the bot replies saying they can't use it, how can i do that?
Don't specify any default member permissions on the command
ohh alright
so this line?
.setDefaultMemberPermissions(PermissionFlagsBits.KickMembers)
Yes
Just remove that entirely
alr thanks
I'm trying to make it so if another person without the permissions tries to use the command, an embed will send saying they don't have the permissions, but instead I get a private terminal message saying they didn't have the permissions rather than an embed showing in discord
const { InteractionContextType, SlashCommandBuilder, EmbedBuilder, PermissionFlagsBits } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('kick')
.setDescription('Kicks a selected member from the server.')
.addUserOption(option =>
option
.setName('target')
.setDescription('The member to kick.')
.setRequired(true))
.addStringOption(option =>
option
.setName('reason')
.setDescription('The reason for kicking'))
.setContexts(InteractionContextType.Guild),
async execute(interaction) {
const target = interaction.options.getUser('target');
const reason = interaction.options.getString('reason') ?? 'No reason provided.';
await interaction.reply(`Kicking ${target.username} for the following reason:\n**${reason}**`);
await interaction.guild.members.kick(target);
if (!interaction.member.permissions.has(PermissionFlagsBits.KickMembers)) {
const embed = new EmbedBuilder()
.setTitle('Insufficient Permissions')
.setDescription('You do not have permission to use this command.')
.setColor(0xFF0000);
await interaction.reply({ embeds: [embed], ephemeral: true });
return;
}
},
};
your bot is the one missing permissions
Popular Topics: Permissions (extended) - Missing permissions
read more
it can't kick that member, check that guide part for possible reasons
also it doesn't really make sense to kick and then check permissions
Your code also isn't going to function like you think it is. JavaScript code executes top to bottom, meaning your code is first going to kick the person and then check if the person running the command has the appropriate permissions. That's probably not what you're looking for
^^ yep, you're supposed to do it the way around
can you help me write a bot code that will delete all channels, categories and roles on the server? (there is an unnecessary server with participants that needs to be sold, but the channels should be deleted) djs@14.18 pls
That sounds an awful lot like a nuke bot, so no, we will not
Regardless of if thats why you intend to use it or not
I'm also not totally sure how tos compliant selling a server is
It isn't
huh?? this error is new to me, and i checked to make sure the stuff i did was correct
components[0][UNION_TYPE_CHOICES]: Value of field "type" must be one of (1,).```
<https://pastebin.com/XknAWzpa>
what djs version are you on?
npm ls discord.js
flags: MessageFlags.IsComponentsV2,
allowedMentions: { parse: [] },
flags: MessageFlags.Ephemeral```
You're overwriting your IsComponentsV2 flag with the Ephemeral flag here by specifying the `flags` option twice
oh yeah, I missed that 
oh i didnt notice
cant set ephemeral in editReply anyway
needs to be done in the first reply (defer most likely)
i did add there, ig i just have a bad habbit of adding everywhere
i do have this one issue, when i make a thread on a suggestion component i spawn my buttons inside the component are nullified and my debugger prints
[WARN] ActionRow not found
but if i dont make a thread using the commenting button the buttons inside will register clicks and update,
-# Code
https://pastebin.com/Vk1X4j88
also how do i go for resending the comment button when a upvote/downvote has been pressed when i tried to do it a few days ago it just errored constantly i cannot remeber the error tho
what's a good way to prevent "Unknown Message", when a user deletes the interaction's message and the bot tries to edit it
sure I could just add a catch, but that's not really how I'd like it to be
That's the only way
smh, alright
Looking at Message#messageSnapshots I noticedit returns a collection, so a single message can contain multiple snapshots at once? I haven't seen a message contain more than one snapshot yet
The API allows it (to be future-prone) but there is no feature that uses it (yet)
What would be the best way to reply to a command without replying to the command.
For a tag system for example. The user can specify if the bot should reply to a specific message. Obviously we can't interaction.reply while also replying to the message.
My current solution for a different command is
Emphereal reply "Success!" - imo bad UX because its ugly and you can literally see it suceed when sending the requested tag message
A different idea I got
Not empheral reply and then just interaction.deleteReply()
This'll "flash" the message initially and kinda is a waste of resources but oh well. Sadly it's not possible to delete emphereal replies afaik.
Does anyone know a better ugly workaround to Discords "forcing good UX" but actually making it worse
You can delete ephemeral replies
What
It's not worse UX though
I'd argue flashing a delete is worse
This becomes a pain when having multiple messages in a row
You end up with a screen full of "sent"
But if empheral messages are actually deletable (i think they weren't when slash commands were first released) the best approach is probably to keep that success message for a bit and delete it after 10 seconds or so
Yeah, a timeout is fine
Lovely, thank you
Is the guide for components v2 published yet?
you cannot deferReply and deferUpdate at yhe same time
Nor does deferUpdate take embeds and component
You're looking for editReply
still the same answer
you're looking for editRepky after your deferReply
Not deferUpdate
any pointers
Then why are you using it? Use deferUpdate and editReply then
anyone know if its possible for parsing to exceed a parsing? like for example how it is
option.setName('category')
.setDescription('The gif category')
.setRequired(true)
.addChoices(
{ name: 'Funny', value: 'gif_funny' },
{ name: 'Meme', value: 'gif_meme' },
{ name: 'Movie', value: 'gif_movie' },
)),
For parsing options. Is it possible to add a choice ontop of a choice. im trying to make something where on selection of "Category" and then "Streaming" it gives other choices / options
you are going to want to use autocomplete it will give you the more dynamic choices. but the user can submit input that is not the provided options
Hi,
What's the TypeScript fix for this please ?
I tried adding the following :
But then I get something else.
Thanks
could you share your code
export default async (message: Message) => {
console.log(message.channel.parent); // TS2339: Property `parent` does not exist on type
};
export default async (message: Message) => {
if(!(message.channel instanceof BaseGuildTextChannel)) return; // Redundant 'instanceof' check: 'channel' has type 'BaseGuildTextChannel' or a subtype of 'BaseGuildTextChannel'
console.log(message.channel.parent);
};
is this for an event or just a fuction?
Oh yeah it receives the message object from the messageCreate event
use the .inGuild() typeguard on the message, that should take care of it
Message#inGuild() discord.js@14.19.3
Whether this message is from a guild.
Perfect, thanks
How do i setup discord.js proxy? I want to be able to make API requests to discord from the bot and the wev dashboard
Why would that need a proxy
Rate limit handling ig?
just use @discordjs/rest on the web side no reason to go thought the gateway
Or don't do that and have your dashboard ask your bot for the data it most likely already has
This way you also don't run into the fact that those 2 separate instances have no idea about each other for the purpose of ratelimit handling
Doesn't that make it much more complicated? How would I handle communication between them?
With a simple rest api that runs along your bot
And just use that api from the dashboard
Is using discord.js rest good enough? Discord still responds with remaining requests before the limit so they shouldn't be fully out of sync
They still are out of sync though
One instance has no clue about the fact that the other is waiting out a ratelimit
And it will make a request and get a 429 back
Is the dashboard for your bot?
But isn't the point of discordjs proxy to solve that problem so all requests are sent and received from 1 place and the rate limits are synced?
But why do you need to make requests directly though
Your bot most likely already has the data you need
You just need a way to ask your bot for it
Does Discord.js support components V2? Just wondering since there’s no guide for it that I’ve seen
yes, there's a pr to the guide for a page on it, but it's fully documented
ContainerBuilder discord.js@14.19.3
A builder that creates API-compatible JSON data for a container.
Cool, thanks
Thx
I would recommend using @discordjs/proxy or third party nirn proxy
Yeah seems much easier the writing an API to allow the dashboard to request stuff
Hello, I replaced the deprecated ephemeral: true for my embed but it is giving me an error saying it doesnt recognise MessageFlag. what is the problem?
you need to import it
any variable needs to be imported or declared before you can use it, that's just how js works
oh shit i completely forgot
fwiw we've had multiple issues reported stemming from nirn proxy - timeouts, etc - that don't continue when not using the proxy
So I go with discord.js proxy?
personally I would go with a nirn proxy as long as it doesn’t cause any issues
if the issue occurs like Mark said then you can debug it yourself or change it to djs one
is your bot sharded so you can't make the api directly?
No I need to make API calls with the bots token from my web dashboard
Rate limits need to be shared
it depends what API calls
and why not just make the bot do the api calls
and reply to the dashboard with the response
or whatever is useful for the dashboard
proxy is easier ig
yeah but more prone to network issues and the dashboard would need to know the client's token
or well some kind of discord secret
and what's bad about that exactly?
security
if you don't leak secrets to the client nothing would happen
if there's an approach that doesn't require that and it's not that unreasonable then I'd say it's worth a try
I mean, people have and failed to "not leak secrets to the client" for as long as the internet existed
Il first try without a proxy ig, if it takes too much time il go with the proxy
it'd be better if it's literally impossible (because the dashboard doesn't know it)
yeah that is a good point actually
but shouldn't be if someone who does this knows how the web works
All of the calls would be made server side tho
you still would need to protect the routes that makes these requests
like permissions checks etc.
Yeah ofc
You probably have an additional space before -
Yes, unfortunately with numbering, this is the compromise.
could make an emoji and use that instead
Is it intended to be a nested list?
Any idea to explain why from a button interaction i don't have the cache from interaction.member.roles.cache ?
do you have the Guilds intent?
And a bot user in that guild
yes ?
export const client = new Client({
intents: [
GatewayIntentBits.Guilds,
...
Or is it user-installed app?
It's only a intellisense warning for now, i've not tested yet
BaseInteraction#inCachedGuild() discord.js@14.19.3
Indicates whether this interaction is received from a cached guild.
You want that typeguard then
Hmmmm okayyyy thanks you ! 
5
A Modal interaction cannot trigger another Modal...so if you need 10, at some point the user will have to trigger the second modal to appear
Or you can use DMs and ask each question 1 by 1
Or have them use a slashcommand with 10 options (depending on the use case)
All those can be achieved by slash command options
so, ive been playing with a giveaway command all day, i have noticed when the user wins they dont get pinged but the ping effect still shows when they look in the channel, is there a way with v2 to send a ping ping in the updated message? or do i have to send a followup to ping with the actual notification?
You can control which entities receive notifications via the allowedMentions option. You can:
- Set a default on the client
- Set for a specific message
- Use the
repliedUserkey to disable in-line reply mentions
{ ..., allowedMentions: { parse: ["users", "roles"] } }
Editing a message doesn't send the notification
Which update basically is
Ah, true
so sending a followup is the key to push notification alright
followUps use the interaction token though, which only lasts 15m
unless your giveaway only lasts 15m you might want to send a regular message
Is there a deprecation date for components v1?
they aren't planned to be deprecated by discord
Thanks
and that's also a question you should ask discord, though I said the answer
We are not Discord, just some nerds who develop Discord bots!
- /report appeals and age updates
- /howtoreport reports (harassment/hacking/spam/abuse)
- /support anything Discord related
- /billing payment/nitro
- /feedback feedback/feature requests
Do you know if there is a way to set Author and Footer on components v2? I dont see that on discord.js v2 containers
there isn't
-# at most you can use this kind of text with -#
Gotcha, thats a shame. I liked using the little pictures
You can't do the tiny pictures like Embeds have (unless you build them yourself using a canvas library) but you can use the Section Thumbnail
Thanks. But, using canvas would have to make the entire thing an image right
You can make the avatar into an application emoji. But that's only feasible for few different author icons.
Footer can be completely replaced with markdown though
The footer has the little image too
That is a good idea to use emojis, but woudn't work in my application because anyone in the server could be the author
not before, only after
at most you could add the emoji in the text itself but I don't think it looks the same
You can make each button part of a Section but then the button would be on the right side, not directly after the text
Ya, using emoji inside of the button is likely your best option
you can't
why do you want that though?
you'd need some kind of reference to it, or since it's not ephemeral you could follow the event based approach, make an event emitter for question creates (and other related events): emit when it's added, edit the message when it's received
you could also just make it one straightforward workflow ig, add the question embed below instead of in a new message
yes, next to the first embed
or well, below the first embed
There's no such property
I'm not sure whether that's present since it's not a regular reply but a followUp
but it's worth a try
It wouldn't work, since the message the button would be is a reply to modal interaction not a message, so there'll be no reference
you'll have to ask discord
the question is whether it counts as a reference
but apparently it does if you tested it and it worked
so you can ask discord if it'll always work (it's an intended feature)
the only cv2 component limit is 40 components per message
Component Reference - Container
read more
also check the docs for info on limits
as you can see there, there's no specific limit for action rows
the action row is a component as well
and the container
assuming you don't have 19 other components, yes
if you do, then no
Hi,
Does DJS provide a constant containing the list of Discord permission names and descriptions ?
Thanks
not descriptions though
And not names either, but slugs
ah, you want the ui name?
Yes, it's for displaying to the user
you'll have to code that yourself
or maybe there's an external library, though tbh I'd just code that
maybe unless you want to consider i18n as well
But you can't even select and copy text in Discord settings, would you really just manually read and re-type ?
Thankfully that's not required 😅
pretty sure you can in the web ui
and even if not, you can inspect element as well
just giving alternatives
you could also just format the flags
ManageChannel => Manage Channel
though not all flags are named like in their ui names
but it's something
could only include the exceptions, format based on flag name as fallback
Plus I need the descriptions too.
you're out of luck on djs' side for that unfortunately
it's also not something the library would include/plan to include
So, selection doesn't work in browser either, as for the inspector, the structure is unreadable 😭
How do you even add class without value
What's ":r24:" and "0d850"
And it's super laggy too
I've never seen DevTools lag before
you're not supossed to read it though, you're only supossed to copy the content
this is out of scope for djs though, so #archive-offtopic
is it possible to retrieve the added subcommands and subcommand groups from a SlashCommandBuilder?
documentation suggestion for @fallen trellis:
SlashCommandBuilder#options discord.js@14.19.3
The options of this command.
Is a string select menu limited to 25 options ?
25 options
yes
Object.keys(PermissionFlagsBits).length === 50 😭😭😭😭
you can use autocomplete on a slash command, but still limited to showing 25 options
however
now what is this?
DiscordAPIError[50027]: Invalid Webhook Token
at handleErrors (/home/container/node_modules/@discordjs/rest/dist/index.js:748:13)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
at async SequentialHandler.runRequest (/home/container/node_modules/@discordjs/rest/dist/index.js:1149:23)
at async SequentialHandler.queueRequest (/home/container/node_modules/@discordjs/rest/dist/index.js:980:14)
at async _REST.request (/home/container/node_modules/@discordjs/rest/dist/index.js:1293:22)
at async InteractionWebhook.send (/home/container/node_modules/discord.js/src/structures/Webhook.js:227:15)
at async ChatInputCommandInteraction.followUp (/home/container/node_modules/discord.js/src/structures/interfaces/InteractionResponses.js:277:17)
you can have as many options as you want, just only 25 will be shown
Using a select menu is mandatory...
doesn’t have to be
I guess I'll have to use 2
interaction tokens only last 15 mins (after an initial reply)
you can't editReply or followUp afterwards
if you have the appropiate permissions and it's not an ephemeral message you can reply to the message
Message#reply() discord.js@14.19.3
Send an inline reply to this message.
// Reply to a message
message.reply('This is a reply!')
.then(() => console.log(`Replied to message "${message.content}"`))
.catch(console.error);
alright, also it crashed my code.. + it says webhook token..
interactions replies are done through webhooks
you can actually see that in your stacktrace
at async InteractionWebhook.send (/home/container/node_modules/discord.js/src/structures/Webhook.js:227:15) at async ChatInputCommandInteraction.followUp
and yes, it can crash if you don't handle the error
alright i added the handler
my code is: module.exports = { name: "message-system", description: "Configure the message system settings.", description_localizations: { "en-US": "Configure the message system settings.", "tr": "Mesaj sistemi ayarlarını yaparsınız.", "es-ES": "Configura los ajustes del sistema de mensajes.", "de-DE": "Konfigurieren Sie die Einstellungen des Nachrichtensystems." },
but i guess description_localizations isn't working, how can i use it correctly?
show your deploy script
so sorry but what is the deploy script
how do you deploy your commands to discord
oh my bad sorry, here it is:
fs.readdir("./commands/slash", (err, files) => {
if (err) return console.log(err);
files.forEach(file => {
console.log(file + " isimli slash command yüklendi.");
const command = require("../commands/slash/" + file);
client.slashcommands.set(command.name, command);
client.guilds.cache.forEach(guild => {
guild.commands.create({
name: command.name,
description: command.description,
options: command.options
});
});
});
});```
that is a horrible way to do so
and will get you ratelimited in an instant
What is the best method
also you're not passing description_localizations there, hence why it's not working
if you want commands in every guild just set them globally
- the script should be separate. And not run every time your bot starts
- You should be using global commands if you want them to be available to every server
- you deploy all your commands at once. Not one request per command
Creating Your Bot: Registering slash commands
read more
u're right but i don't know how to add it. Is it like description_localizations: command.description_localizations?
And nvm i will be looking for this method. Tysm for suggestion
why not use builders?
instead of doing double work
and you should put your command's data in a separate property
isn't it too much for the low rams?
no
it's entirely negligible
i was thinking that there is a difference
technically, yes, in practice, no
with all your commands it should be less than 1kb
Then its nothing! I will use the method that u told me and will use builders tysm!
@rose tangle so sorry to ping! Should i add all my command in const commands = []; or there is any way to get them from slash commands folder
just like youre doing now
just in a separate script
read what i linked
i am not fluent in English im trying my best sorry, i am looking at the link that u sent me but im a little bit confused
confused about?
there is a command = [] thing, should i put every command or can i use for method
the code does that for you
TF mb i didn't ready all of the code really
the rest of the code fills that array with the commands
There are rate limits predicted by discord.js. Is there a list of routes for which discord.js can send a warning?
TYSM! And is there any method the refresh a spesific command?
There are rate limits predicted by discord.js.
no
Is there a list of routes for which discord.js can send a warning?
(in case you meant for a list of the ratelimits) no as well, read below
Ratelimits are dynamically assigned by the API based on current load and may change at any point.
- The scale from okay to API-spam is sliding and depends heavily on the action you are taking
- Rainbow roles, clock and counter channels, and DM'ing advertisements to all members are all examples of things that are not okay
the list exists, it's the list of all routes on ddocs
Sorry for bothering
just deploy all your commands
PUT overrides anyways
nono im asking that like i put a command in it and it send all of the guilds. Then i change the description of the command. Is there any need for refreshing?
yes, but the PUT will handle that, and again, you don't need to deploy to every individual guild. deploy globally and you're done ("global" is a kind of deployment, like a "guild" deploy)
The deploy script is the easier way to do that
Yeah tysm! All makes sense rn. Ty for help!
It’s more work to make an automated script or CLI that will update particular commands. This way will also require more api calls if you update multiple commands
Yeah, idk why but now im doing in this way
I think the only reason you’d need to call a route for a particular command is if ur trying to delete an entry point command
Yes and it will make more less api disturb
hey, the bug when mentioning a user in an embed and it appearing as their userid. is this gone in components v2?
yes
nice thanks
When not specified, are roles created through DJS mentionable by default ?
Yes, all mentions should send a notification unless stated otherwise (either per message, or globally on your client declaration)
That is, if whatever is sending it supports mentions. Because Embeds for example, cannot ping users
Sorry I'm not sure we're talking about the same thing, I'm talking about the mentionable parameter of guild.roles.create :
export interface RoleData {
name?: string;
color?: ColorResolvable;
hoist?: boolean;
position?: number;
permissions?: PermissionResolvable;
mentionable?: boolean;
icon?: BufferResolvable | Base64Resolvable | EmojiResolvable | null;
unicodeEmoji?: string | null;
}
any recommendations to the directory structure?
Ohhh I see what you're talking about. Iirc it defaults to false when not specified
Good, thanks
Uh what now ?...
what am i doing wrong: content[MESSAGE_CANNOT_USE_LEGACY_FIELDS_WITH_COMPONENTS_V2]: The 'content' field cannot be used when using MessageFlags.IS_COMPONENTS_V2
const container = new ContainerBuilder();
const mediaGallery = new MediaGalleryBuilder()
.setId(1)
.addItems([
//guild banner
new MediaGalleryItemBuilder().setURL(newMember.guild.bannerURL({ size: 4096 }))
])
container.addTextDisplayComponents(new TextDisplayBuilder().setContent(`text`)).addMediaGalleryComponents(mediaGallery);;
container.addSeparatorComponents(separator => separator.setSpacing(SeparatorSpacingSize.Large));
container.addTextDisplayComponents(new TextDisplayBuilder().setContent(`text`));
container.addSeparatorComponents(separator => separator.setSpacing(SeparatorSpacingSize.Small));
container.addTextDisplayComponents(new TextDisplayBuilder().setContent(`text`));
await message.edit({ components: [container], flags: MessageFlags.IsComponentsV2 });
is it roles.cache?
For adding ?
That's not how you create a role
I created it above, I'm trying to give it to a user now
use the .inCachedGuild() typeguard on commandInteraction
Make sure content: null if you're editing
oh ok thanks
Thanks !
I just upgraded my deploy system and upgraded my / commands but i can not see my / commands now what can be reason
did you run the script
yeah
and refresh your client
no lemme refresh the client
your discord client, that is
yeah tysm i didn't know i need to refresh it. And thank you to suggest that method. Its even looking more refresh
I guess on mobile the bug is still present?
that's a container?
Yes
maybe because it isn't mentioning them
I currently have allowed mentions off
Could that be the reason?
yeah, that's what I meant
I know im looking dumb but now it doesn't respond my command 😦
but then it'll mention all those people
is your bot actually running
the deploy script doesnt run your bot
Alright thanks. The mentioning shouldnt matter cuz its editing a message
yes
it deployed very well also local things works so good
log to see if your interactionCreate event fires at all
uhm f me, i didn't upgrade my interactionHandler 😦
you're probably not filling your client.slashcommands collection like in here
yes i removed it and im creating it again i will tell the result
String select menus aren't searchable ?
Correct
There's no "PermissionSelectMenuBuilder", is there ? 😭
No
I created a new thing and everything is perfect! Tysm amgeloa and wolvinny
i'm bewildered.
made this extremely simple channel renaming tool
async execute(interaction) {
const opt = interaction.options.getString('undo');
console.log(interaction.channel)
if (opt === 'yes') {
await interaction.deferReply();
let name = interaction.channel.name.split('-')
let first = name.shift()
if (first !== '🔴') return interaction.reply({ content: "Channel doesn't seem to be set as live", flags: MessageFlags.Ephemeral });
name = name.join('-')
try {
await interaction.channel.setName(name);
await interaction.reply({ content: 'Channel renamed.', flags: MessageFlags.Ephemeral });
} catch (error) {
console.error("Failed to rename channel:", error);
await interaction.reply({ content: 'An error occurred while renaming the channel.', flags: MessageFlags.Ephemeral });
}
} else {
await interaction.deferReply();
if (!interaction.channel.name.startsWith('🔴-')) {
await interaction.channel.setName(`🔴-${interaction.channel.name}`);
}
const embed = new EmbedBuilder()
.setTitle("🔴 - Live!")
.setDescription(`${interaction.user} will stream this match and will be the one providing the invite code!\nWait for them to give the go before drafting.`)
.setColor('#6441a5');
interaction.reply({ embeds: [embed] });
}
},```
the first rename and undo works just fine, but as soon as one rename and one undo have been done, the code just hangs and never ends, never rename, and never gives any error
i'm beyond confused
channel renames are heavily ratelimited
mostly to avoid counter channels iirc
the setName promise won't resolve until the request actually goes through, which is after the ratelimit ends
we're talking 2 renames in the span of 15s gets me ratelimited here ?
I don't recall what the exact numbers are but it was an extremely high one
you can double-check with the ratelimit event
where would i find that ?
TWICE PER 10MIN ???
what the actual fu-
client.rest.on('rateLimited', console.log);
only once, can be where you create your client
and yeah, that sounds about right
^^
so they see no problem with people spamming, idk, text, color hex changing roles, but nuh huh, 2 renames per dozen minute dangerous !!11!!§1
that's soooo stupid. thanks tho
I mean, rainbow roles are also against the api
just not sure what are the ratelimits on that
but they can get you in trouble if you do it
1000 requests per 24 hours, aka 1 per 80s essentially for role edits
meanwhile text - once per 5min, essentially
I'm getting the error HTTPError: Internal Server Error for a bot message
I have 5 components + an embed on the bot, and each component is heavily filled but respects all the constraints discord has set out < 25 options, IDs/labels/descriptions < 100 chars, < 5 rows..etc
When I comment out just 1 select menu or remove the descriptions for each, I don't get that error anymore
Why am I getting this?
there's also a payload size limit
and it can indeed happen with select menus and heavily filled messages
I figured
It's weird there's no error message specific to that
yeah iirc that's still a pending fix from discord
but it's not that bad so probably buried in backlog
eg there's also a 500 if you send some specific utf16 chars in customId
tiny stuff they probably don't bother too much and just focus on others
can ephemeral messages delete or edit?
yes
only through the webhook though
meaning the interaction object
through the deleteReply and editReply methods
Oh, how can i do it?
just call them
what specific interaction type?
to bring out the docs
Oh! sorry for bother. I figured it out
can i if I have a webhook url from discord use that to send messages to that, and if so how
or do I need to create a webhook with my bot first
any breaking change that remove interaction.guild ?
cuz i cant access anymore interaction.guild
did they remove the ability to make messages on prefix commands ephemeral?
Show your code
documentation suggestion for @light sapphire:
WebhookClient discord.js@14.19.3
The webhook client.
my bad i find the issue, as i switch to a test bot i forgot to reenable bot in the installation thing so i add the bot but he never join
Oops, wrong ping, @compact swan ^
You could never do that, ephemeral is an interactions thing
ah
must've misremembered it
Is it possible to set a custom emote for a bot's custom activity type? I've got the unicode emotes working but not custom
Don't think so
That would make a lot of sense. Thanks!
there is no other way of doing this if I only have the webhook url, right?
I need a webhook client?
You can create a webhook client and pass the url
WebhookClientDataURL discord.js@14.19.3
Represents the credentials used for a webhook in the form of a URL.
Popular Topics: Webhooks
read more
I'm trying to create a command for my bot that takes information from an API, but I'm getting an error as follows:
const { SlashCommandBuilder } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('roster')
.setDescription('Shows the current roster of the chosen team.'),
async execute(interaction) {
const teamInput = interaction.options.getString('team').toLowerCase();
// Map of team names to balldontlie team IDs
const teamMap = {
lakers: 14,
warriors: 10,
celtics: 2,
bulls: 6,
heat: 16,
suns: 24,
knicks: 20,
// Add more as needed...
};
if (!teamMap[teamInput]) {
return interaction.reply(`❌ Team "${teamInput}" not recognized. Try 'lakers', 'celtics', etc.`);
}
const teamId = teamMap[teamInput];
const url = `https://www.balldontlie.io/api/v1/players?team_ids[]=${teamId}&per_page=100`;
try {
const res = await fetch(url, {
headers: {
'Authorization': 'Bearer 97a165ad-5904-4f8f-b7dc-46895cb38d8c'
}
});
const data = await res.json();
if (!data.data.length) {
return interaction.reply(`😢 No roster found for team "${teamInput}".`);
}
const roster = data.data.map(player =>
`${player.first_name} ${player.last_name} – ${player.position || 'N/A'}`
);
const response = `📋 **${teamInput.toUpperCase()} Roster**:\n` + roster.join('\n');
return interaction.reply(response);
} catch (err) {
console.error(err);
return interaction.reply('⚠️ An error occurred while fetching the roster.');
}
},
};
that error comes from your deploy commands script though
const { REST, Routes } = require("discord.js");
require('dotenv').config();
const { clientId, guildId } = process.env;
const fs = require("node:fs");
const path = require("node:path");
const commands = [];
const foldersPath = path.join(__dirname, "commands");
const commandFolders = fs.readdirSync(foldersPath);
for (const folder of commandFolders) {
const commandsPath = path.join(foldersPath, folder);
const commandFiles = fs
.readdirSync(commandsPath)
.filter((file) => file.endsWith(".js"));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
if ("data" in command && "execute" in command) {
commands.push(command.data.toJSON());
} else {
console.log(
`[WARNNING] The command at ${filePath} is missing a required "data" or "execute" property.`
);
}
}
}
const rest = new REST().setToken(process.env.token);
(async () => {
try {
console.log(
`Started refreshing ${commands.length} application (/) commands.`
);
const data = await rest.put(
Routes.applicationGuildCommands(clientId, guildId),
{ body: commands }
);
console.log(
`Successfully reloaded ${data.length} application (/) commands.`
);
} catch (error) {
console.error(error);
}
})();
is there something wrong with this?
I don't think I changed anything in this file
is your bot actually in that guild?
Yes
double check the clientId, guildId and token are present and with the values you expect
Ohr, I reset the token and inputted it and it works now 👍 thanks
Does anyone know if its possible to run a deferReply() within the client 'messageCreate' method in response to a user command (not within a slash command)? I'm looking for a loading response to be completed when a promise completes
I'm getting an "invalid token" error even though I copy-pasted the exact token directly from the bot portal
If Discord says its invalid, its invalid
So - did you save the file?
Is it pasted directly into the login method, or somewhere else, and if somewhere else, are you referencing it correctly?
i use dotenv
no
and yes, i did save the file, and all
sadness....
dotenv is no longer required, you can pass an env file using node --env-file=.env index.js
this is a line in my deploy-commands.js
what do you mean by that?
You do not need the dotenv package dependency anymore, node now supports loading a file of environment variables natively
so like i can just remove any line of code that requires dotenv or what?
If you also add the command line argument I showed
Such as this in my main file
const dotenv = require('dotenv');
Is that also in your deploy-commands file?
And you run the config?
require('dotenv').config();
const { clientId, guildId } = process.env;
these two
I did that, it did work, would I have to use that instead of node . every time?
Yeah
Sounds like you werent loading dotenv
huh?
dotenv doesn't run by itself when you require it
you need to run .config()
then it reads the .env file and patches your process.env object
You can add the command line args to an npm start script in package.json to make things easier
isnt that what i did in the line in my deploy-commands.js thing
require('dotenv').config();
yes
That looks correct, yeah
But the error came from login()
Oh
Not deploy-commands (unless it was both)
and you weren't running your deploy-commands.js
you were running your main file
so the code there is unrelated (unless the main require()d the deploy-commands, but it doesn't and shouldn't)
how would I do that exactly?
there's a scripts section in your package.json
ik that, but how would I write it
Theres a scripts section that looks something like this:
npm start on the command line will run that script
ic
A few keywords, like start, work directly, the others require npm run <name>
did i do this properly-
npm start, not node start
OH
node takes a js file as argument so it runs it
You dont have a dist folder
meh?
Looks like its running
wouldn't it show the usual message thing
Yeah it should
oh wait it showed up a bit later, nvm
alr thanks
Is there a way to log the access join application answers?
no, that's not available through the api
Hi all, im trying to have m bot listen to a channel and send the messages that have been sent from that channel, here is my current code:
const Discord = require("discord.js");
const { SlashCommandBuilder, GuildMessageManager } = require('discord.js');
const { MessageCollector } = require('discord.js')
module.exports = {
data: new SlashCommandBuilder()
.setName('forward')
.setDescription('forwards messages from one channel to another')
.addChannelOption(option =>
option.setName('source')
.setDescription('The channel to forward messages from')
.setRequired(true))
.addChannelOption(option =>
option.setName('destination')
.setDescription('The channel to forward messages to')
.setRequired(true)),
permissions: ['ManageMessages'],
permissions: ['Administrator'],
async execute(interaction) {
await interaction.messagechannel.send('Forwarding messages...');
const sourceChannel = interaction.options.getChannel('source');
const destinationChannel = interaction.options.getChannel('destination');
if (!sourceChannel || !destinationChannel) {
return interaction.reply('Please provide valid source and destination channels.');
}
await interaction.reply( ${} ).
}
};
im not sure what to put in await interaction.reply( ${}).
by not what sure what to put i mean i dont know what to put so that it will send the messages and not just send one if you know wohat i mean
Just to clarify, your question is how to make it so your bot automatically sends messages from 1 channel to another channel automatically?
yes
im just testing it to listen only in my server
basically thats what im trying to get it to
I have searched the discord js and tried using of the code from the guide but i got stuck on choosing which option to use
How to set it up so it's modular, is completely up to you. You can make a post in #1081585952654360687 as most of the process would be pretty unrelated to DiscordJS
But the method to achieve it will always be the same. You have to make a client.on("messageCreate") listener, filter the messages from the "source" channel and do a channel.send to the "destination" channel
would i need to set it up as a slash command or how can i do it otherwise and how would i make sure it would work without slash commands
If you want to hard code it (so it will only ever watch specific channels defined in the code, rather than by users) then no you won't need Slash Commands. Honestly, making it with slash commands is the hardest part
im only confident in using slash commands 😭
im just not sure what to use to get the code activitated other than using slash commands
Well if you have slash commands, then you've made an event listener before. But that was for interactionCreate events rather than messageCreate events.
ty
ill will read these and try to debug it and work on it
Ya, you can't really do that with Slash Commands alone because slash commands are a temporary action. They're only able to perform a single action (or flow of actions) when a user uses said command. If you want something to happen indefinitely, then you can't do it with a Slash Command.
You can integrate a slash command to control your listener, but again, that is a lot more challenging
Does djs automatically respect role hierarchy in its code?
Also @unique shoal there's a scam esex ad above me
discord.js does no role checking. Discord does
And thanks, banned
"automatically respect" in what context?
So I have to code it manually to check if someone's role is higher?
Role#comparePositionTo() discord.js@14.19.3
Compares this role's position to another role's.
// Compare the position of a role to another
const roleCompare = role.comparePositionTo(otherRole);
if (roleCompare >= 1) console.log(`${role.name} is higher than ${otherRole.name}`);
There is a method for doing this
Ty
Or there are some helpers
GuildMember#bannable discord.js@14.19.3
Whether this member is bannable by the client user
But yes, you must make the checks somehow
Or catch the error when Discord API says no
👍
Hello Discord.js
I'm looking to integrate my Discord bot in a specific way: I want users to be able to invite my bot directly to their Discord profile (as USER), without going through a server.
Once added to their profile, they will be able to use a contextual application in their private messages to report a message.
📌 System Objective:
The bot must be added to a user's profile, like a contact or a personal application.
- The bot must only work in private messages, and not be accessible on servers.
- Users must see the "Report" option in the "Applications" menu when interacting with a private message.
- The report must be sent to a specific admin or channel, for secure reporting.
So, I want to configure and deploy my bot via discord.js with global contextual commands (Routes.applicationCommands(CLIENT_ID)). However, my "Report" app only appears on servers and not in PMs.
const TOKEN = 'XXX';
const CLIENT_ID = 'XXX';
const client = new Client({ intents: [GatewayIntentBits.DirectMessages], partials: ['CHANNEL'] });
const commands = [
new ContextMenuCommandBuilder()
.setName('Signaler')
.setType(ApplicationCommandType.Message)
].map(command => command.toJSON());
const rest = new REST({ version: '10' }).setToken(TOKEN);
(async () => {
try {
console.log(':arrows_counterclockwise: Déploiement de l’application contextuelle en MP...');
await rest.put(
Routes.applicationCommands(CLIENT_ID),
{ body: commands }
);
console.log(':white_check_mark: Application contextuelle "Signaler" activée pour les messages privés.');
} catch (error) {
console.error(':x: Erreur lors du déploiement :', error);
}
})();
client.once('ready', () => {
console.log(`🤖 Connecté en tant que ${client.user.tag}`);
});
client.on('interactionCreate', async interaction => {
if (!interaction.isMessageContextMenuCommand()) return;
if (interaction.commandName !== 'Signaler') return;
// Vérifier que l’interaction vient d’un MP
if (interaction.guildId !== null) {
await interaction.reply({ content: ":warning: Cette option est uniquement disponible en message privé.", ephemeral: true });
return;
}
const message = interaction.targetMessage;
const user = interaction.user;
const adminId = "353927301425266708";
const admin = await client.users.fetch(adminId);
await admin.send(`🚨 **Signalement !**\n📌 **Utilisateur**: ${user.tag}\n📝 **Message signalé**: "${message.content}"`);
await interaction.reply({ content: ':white_check_mark: Message signalé avec succès.', ephemeral: true });
});
client.login(TOKEN);```
SlashCommandBuilder#setIntegrationTypes() discord.js@14.19.3
Sets the integration types of this command.
SlashCommandBuilder#setContexts() discord.js@14.19.3
Sets the contexts of this command.
These two methods set how a command can be installed, and where its usable
The same applies to context menu commands
eh
Did you solve your issue?
Heya !
❯ docker logs bot-container
> lebottom@0.0.0 start
> node .build/index.js
user loaded.
(node:18) ExperimentalWarning: Type Stripping is an experimental feature and might change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
server loaded.
node:internal/modules/esm/resolve:274
throw new ERR_MODULE_NOT_FOUND(
^
Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/usr/src/app/src/client.js' imported from /usr/src/app/src/commands/utility/reload.ts
at finalizeResolution (node:internal/modules/esm/resolve:274:11)
at moduleResolve (node:internal/modules/esm/resolve:859:10)
at defaultResolve (node:internal/modules/esm/resolve:983:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:799:12)
at #cachedDefaultResolve (node:internal/modules/esm/loader:723:25)
at ModuleLoader.resolve (node:internal/modules/esm/loader:706:38)
at ModuleLoader.getModuleJobForImport (node:internal/modules/esm/loader:307:38)
at #link (node:internal/modules/esm/module_job:170:49) {
code: 'ERR_MODULE_NOT_FOUND',
url: 'file:///usr/src/app/src/client.js'
}
Node.js v24.1.0```
```ts
import { ChatInputCommandInteraction, SlashCommandBuilder } from "discord.js";
import { ExtendedClient } from "../../client.js";
export default {
data: new SlashCommandBuilder()
.setName('reload')
.setDescription('Reloads a command.')
.addStringOption(option =>
option.setName('command')
.setDescription('The command to reload.')
.setRequired(true)),
...
src/
├── client.ts
├── commands
│ └── utility
│ ├── infos.ts
│ ├── ping.ts
│ ├── reload.ts
│ ├── server.ts
│ └── user.ts
├── commands.d.ts
└── index.ts
I'm encountering this issue while importing a file in my reload command.
I'm using typescript and Node16. Im still a beginner in TS so it might be a very silly error x)
Lemme know if you need more context !
This would be an issue in JS too - likely a circular reference
Where do your compiled output files go? A /dist dir or something? It attmepting to import a js file from /src
I see, .build?
Yup
.build
├── client.js
├── commands
│ └── utility
│ ├── infos.js
│ ├── ping.js
│ ├── reload.js
│ ├── server.js
│ └── user.js
└── index.js
And my tsconfig.json has "outDir": ".build",
Then "start": "node .build/index.js" in my package.json 🙂
What does your reload command actually do? If it imports files dynamically they need the .build/ path in them
import { ChatInputCommandInteraction, SlashCommandBuilder } from "discord.js";
import { ExtendedClient } from "../../client.js";
export default {
data: new SlashCommandBuilder()
.setName('reload')
.setDescription('Reloads a command.')
.addStringOption(option =>
option.setName('command')
.setDescription('The command to reload.')
.setRequired(true)),
async execute(ctx: ChatInputCommandInteraction) {
const client = ctx.client as ExtendedClient;
const commandName = ctx.options.getString('command', true).toLowerCase();
const command = client.commands.get(commandName);
if (!command)
return await ctx.reply(`There is no command with name \`${commandName}\`!`);
}
};
Well I figured out that It might causes some issues so I juste deleted everything for now, just to get that import issue fixed
That's all it does
await interaction.deferReply({ flags: hideReply ? MessageFlags.Ephemeral : 0 });
await interaction.deferReply({ flags: hideReply ? MessageFlags.Ephemeral : undefined });
Whats safer? 0 is a bit cleaner but I can't be sure if Discord some day adds a flag with value 0
They can't and won't
Both are fine
0 is not a bitflag. It's the absence of all bits
Ah thats good to hear, I'll be using that then. Thank you!
Hello,
No text input for components v2 to be used in containers ?
no
Sadge
Is it possible to make the buttons horizontal?
-# do you think it looks better like this?
Nvm
not possible in a section. they would have to be on the left side
What’s the other option of not “section”
a normal action row
Okay
Can and how i send like this via discord.js and can i use buttons on dm?
#announcements message and yes, you can
and for the other question? 😢
Those were answers to both of your questions
can i use buttons on dm? like green buttons
yes, you can
Oh thanks ❤️
hello ! i wanted to know if it was possible to send spoiler images in embeds
yes
do you know how to do this? I use setimage with images renamed with SPOILER_, but they appear clearly.
can you gimme a screenshot or snippet of your code where you do dat?
@next mesa
const evolutionEmbed = new EmbedBuilder()
.setTitle(embed.title)
.setDescription(embed.description(member.id, evolution.name))
.addFields({ name: embed.fields.name, value: embed.fields.value(100) })
.setImage(getImage(`evolutions/SPOILER_${evolution.slug}.png`));
Files in embeds should be attached via the message option object and referenced in the embed:
const attachment = new AttachmentBuilder('./image.png', { name: 'image1.png' });
const embed = new EmbedBuilder()
.setTitle('Attachments')
.setImage(`attachment://${attachment.name}`);
channel.send({
embeds: [embed],
files: [attachment]
});
Not to my knowledge, only in components v2
they dont work on image url
what is this ?
ohhh okay, will this eventually replace embeds?
there is no plan to remove legacy components, no
okay thanks
is there a reason when i call member.roles.add([...]) and then in the same bit of code member.roles.remove([...]) my bot only removes roles (including the one i told it to add)?
my code looks kinda like this:
await member.roles.add([...])
await member.roles.remove([...])
because member is the same data from before adding the roles, so it's setting it to the old roles and removing the ones in remove(...)
it would be better to use roles.set(...) to make all changes at once
ive tried using roles.set but have the issue of my bot often having a lower role. with set it appears that i need to have permission to manage all the members roles?
when i tried filtering to only ones my bot could manage it still failed
shouldn't be unless you're trying to modify roles it can't manage, which is the same for add/remove
show the full error with stack
Failed to update roles: DiscordAPIError[50013]: Missing Permissions
at handleErrors (/Bot/node_modules/@discordjs/rest/dist/index.js:748:13)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
at async SequentialHandler.runRequest (/Bot/node_modules/@discordjs/rest/dist/index.js:1149:23)
at async SequentialHandler.queueRequest (/Bot/node_modules/@discordjs/rest/dist/index.js:980:14)
at async _REST.request (/Bot/node_modules/@discordjs/rest/dist/index.js:1293:22)
at async GuildMemberManager.edit (/Bot/node_modules/discord.js/src/managers/GuildMemberManager.js:382:15)
at async updateMemberRoles (/Bot/.build/src/utils/hooks/events/applications/end/roles.js:41:9)
at async Object.execute (/Bot/.build/src/interactions/buttons/deleteApp.js:35:13)
at async Object.execute (/Bot/.build/src/events/interactionCreate.js:81:21)
at async Client.listener (/Bot/.build/src/handlers/eventHandler.js:79:13) {
requestBody: { files: undefined, json: { roles: [Array] } },
rawError: { message: 'Missing Permissions', code: 50013 },
code: 50013,
status: 403,
method: 'PATCH',
url: 'https://discord.com/api/v10/guilds/1023670040136011846/members/804265795835265034'
}
https://pastebin.com/myy8uRU6
thats the update roles funtion