#djs-help-v14

78874 messages · Page 15 of 79

steel trail

Depends entirely on what you want it to look like. Maybe https://discord.builders/ can help you with designing it first (and it has a code export option for djs)

steel yacht
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 ?
sharp ginkgoBOT
steel yacht

The checkAdmin parameter is not explained anywhere in that page :/

steel trail

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

steel yacht

Hmm, is that an important distinction ?

steel trail

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 …

steel yacht

Indeed. Thanks

modest surge

what is the difference between awaiting components and collecotrs

steel trail

awaitMessageComponent is a promisified collector

modest surge

i dont get it

steel trail

It‘ll resolve with the collected thing(s) while a regular collector emits collect and end events you need to listen to

rotund vine

Hey. is there a way to get the users timezone?

steel trail
steel trail
steel trail

That doesn’t get you timezones of anyone

modest surge

oh ithought your timezone

modest surge
steel trail

Determine for how long it‘ll keep collecting if no other end condition happens before then

modest surge

i dont really get it could you explain it on simpliest way

sharp ginkgoBOT
steel trail

Maybe that helps

modest surge

thank you

rotund vine
modest surge
steel trail

Huh?

modest surge
toxic moat

anyone know the cause why this ishappening. i have reset my token and still same issue

steel trail
toxic moat

Your handleCommands function uses rest before that login call

So no token set yet

toxic moat

what do i do then? where do i implement it ?

steel trail

LimeBOT_TOKEN is not the token you log in the other file Thonk

toxic moat

ohhh yea its a paste from my other bot mb

working now gang

rose tangle

also it's not advised to deploy commands on every start

and why api 9? Thonk

modest surge

why my buttons automatically activated when send

bold oyster

hey guys any info on guild tags' lib

rose tangle
sharp ginkgoBOT
rose tangle

if yes, with that ^^

modest surge
rose tangle

ah, no that's not possible

modest surge

but it is automatically clicked

rose tangle

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

modest surge

its clicked cuz the component was edited

rose tangle

no, that's not how interactions work

if you could share your code it'd be useful to narrow down what is exactly happening

rose tangle
modest surge
rose tangle

and they're not documented by discord, so it's not implemented by djs in case you meant that

bold oyster
rose tangle
modest surge
  • 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

modest surge

wdym second point

rose tangle
modest surge

oh

jade portal

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?

modest surge
proud arrow
jade portal
sudden grove

i forgot but what is the Max amount of buttons a message can have?

rose tangle
dense jackal
sudden grove
rose tangle

embeds and components are unrelated

sudden grove

oh

dense jackal

^

rose tangle

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)

modest surge

could you put awaitMessageComponent inside of awaitMessageComponent

rose tangle

why? what do you want to do?

sudden grove
modest surge
snow onyx
sudden grove
sudden grove

like "press the userinfo button then use the select menu that came up regarding that followup"

opal pendant

uhhm fair enough

rose tangle
modest surge
dense jackal

below, not inside

rose tangle

you're not putting it inside though, you're putting it later 🐌

modest surge

how do u put it later when u not putting it in side

rose tangle
modest surge its samething lol

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

modest surge
rose tangle

not true

modest surge

its true i tried it doesnt worky anymore

rose tangle

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?

modest surge

its automatically nested

when the interaction is true

rose tangle

nothing is automatically nested Thonk

modest surge

try catch then just return

rose tangle

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

sudden grove

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
    }```?
rose tangle

can't do

const confirmation = await message.awaitMessageComponent(...) {
  const furtherReply = await otherMessage.awaitMessageComponent(...);
}
rose tangle

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

steel trail
modest surge
steel trail

Just show your code instead of trying to describe it

pliant forge

how can i do it like

for english users: name: ban
description: .......

for italian users: name: ....
description: ....

in slash commands

vestal sun
pliant forge
sharp ginkgoBOT
pliant forge

TYsm

sharp ginkgoBOT

guide Slash Commands: Advanced command creation - Localizations
read more

rose tangle

there's also that guide entry

rose tangle

so it won't do anything

modest surge

so is my code fine

rose tangle

in case you meant you removed what this contains, that's not what I meant

modest surge
rose tangle

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

modest surge

so is my code fine

rose tangle

you just said it worked a while ago?

modest surge

yea it works

rose tangle

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?

modest surge

yes

rose tangle

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

modest surge

im not new or something i just asked about awaitMessageComponent

im not using switch cases its only 2 elseifs

feral sky

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!

rose tangle
rose tangle
feral sky

I did it using the slash command builder, is there a new flag for it?

rose tangle

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

feral sky

I see, so simply specifying with a flag should do in that case right?

My app is installable for guild only

rose tangle

where are you checking that? can you show a picture?

feral sky

🤦‍♂️ I forgot to save the changes, it was set to both guild and user

My bad for the misinformation

rose tangle

huh, but then it should default to both guild and user Thonk

no idea what happened but if setting it to only guild fixes it then I guess it's fine

feral sky

That's still set to 1, perhaps reinstallaion would do now that the user is set to off?

rose tangle

you're deploying again and it still logs that?

rose tangle

you're sure you're looking at the correct bot?

feral sky

I'm positive

rose tangle

and the correct token?

feral sky

Yes sir, I'll just state my integration type from now on I suppose

rose tangle

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

feral sky

It works, thank you very much 🙂

rose tangle

you should use the enum instead of raw values btw

sharp ginkgoBOT
rose tangle

it's just more readable

feral sky

That's 100% true, I'll do that

much better PES_Cool

tyvm! have a lovely day

covert scarab

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 ?

steel trail

Rest won't retry a 404

It will only retry if no response at all

e.g. on connection resets, abort errors,

acoustic night

i made components thanks

steel yacht

Hi,
What's the most up-to-date embed preview webapp ?
Thanks

red coral

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

steel yacht

Yeah I meant for EmbedBuilder

rose tangle

also please keep non djs questions outside of this channel

steel yacht

Well, I want a web UI to generate the data to pass to DJS' EmbedBuilder, so it's on-topic

zenith violet

not really since djs does not have a web ui for that

rose tangle

given EmbedBuilder accepts raw api data it should support pretty much every generator out there

steel trail

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

stable sun

Can’t send an empty embed or the embed object is malformed

toxic moat
----[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?
rose tangle

could you log message.id to make sure it's the correct message?

toxic moat
steel trail

What's monitorTask.js line 214? And what does it have to do with your screenshot?

lilac basin

why is my sound command not responding when I try and execute it

toxic moat
steel trail What's monitorTask.js line 214? And what does it have to do with your screenshot...

            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?

steel trail
steel trail
toxic moat
steel trail

And without seeing how you defined containerNew I'll have to assume you defined it before changing the contents

hazy light

Does he know how to place buttons from top to bottom?

toxic moat
rose tangle
hazy light
rose tangle

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

hazy light
rose tangle

I just said how

with that container

toxic moat
toxic moat
rose tangle

did you get interaction_message from the cache?

as in, channel.messages.cache.get(messageId);

toxic moat
            channel_interaction = await client.channels.cache.get(task.info_command.channel_id);
            interaction_message = await channel_interaction.messages.fetch(task.info_command.message_id);```
rose tangle

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 Thonk

toxic moat
toxic moat
rose tangle

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

steel trail
toxic moat
toxic moat
rose tangle

that's not the event

toxic moat

cant understand what him meaning sorry ahah

rose tangle

when does that code run?

on messageCreate, on interactionCreate, etc

toxic moat
rose tangle

so when does it begin?

no code runs by itself, everything is called by something

is it an interval or something?

toxic moat

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]
            });

    };
steel trail

I'll assume that isn't immediately run when monitorTask(...) called right? What causes that to actually run? Is it an interval or ...?

toxic moat
steel trail

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.

toxic moat

you're right I could do it

but why doesn't it work in this mode, I would like to understand why

steel trail

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

toxic moat

ok thx for help guys

warm edge

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?

rose tangle

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

red coral

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

steel yacht

How to upload an image from a Buffer object in an embed ?

sharp ginkgoBOT

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]
});
rose tangle

AttachmentBuilder also accepts a buffer instead of a file path

sharp ginkgoBOT
steel yacht

Thanks

rose tangle
zenith prawn

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 });
    }
}
stable sun
zenith prawn

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

rose tangle

yeah it meant inside the execute callback

which is where interaction is defined

zenith prawn
stable sun

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.

zenith prawn

Ohh alright thanks

stable sun

Just the part that runs when the event fires

zenith prawn

wait

stable sun

Keep state and const that needs to be saved hoisted

zenith prawn
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 });
            }
        }
    },
};
stable sun
zenith prawn
zenith violet

this is starting to turn into very basic js

you did not define interaction outside of your execute function

zenith prawn

the guide here is showing this

zenith prawn
zenith violet

that needs to be added in the execute callback

stable sun

Context matters

zenith violet

please learn the basics of js before creating a discord bot

rose tangle

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

stable sun

It’s talking about in the event callback

zenith violet
stable sun

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

lavish surge

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?

clear garnet

If you have the GuildMembers intent, yes

lavish surge

perfect, tysm :D

zenith prawn

I made the reload.js file, having no errors, but I am not seeing the command showing up in my srver.

steel trail

Did you run your deployment script afterwards?

zenith prawn
rose tangle

every time you add, remove or edit a command's data

zenith prawn

Oh okay

Alright, thank you

zenith prawn

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?

zenith violet

the latter is the most common

zenith prawn
zenith violet

the second one

zenith prawn

Ah okay thanks

burnt orbit

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

red coral

allowedMentions: { roles: [..], users: [..] }

Then pass the snowflakes

shut musk

Is guildMemberUpdate emitted when a user changes their pfp?

snow onyx

it should, yes

shut musk

ty

wintry laurel

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

unique shoal

We cant add anything if it hasnt been added to Discord API

Github issues is probably the best place

wintry laurel
rose tangle
wintry laurel

just feel like it would make sense to have, although it is possiable in most cases without it

rose tangle

are you suggesting that to discord or djs?

wintry laurel

discord's api

because then djs can add it right

sharp ginkgoBOT
rose tangle

looks like it's possible?

wintry laurel

oh weird

i was told that wanst a feature.

thank you

shut musk

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?

wary coral
shut musk

ty

zenith prawn

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?

unique shoal

You didnt close the option above

So eslint thinks its still chained there

zenith prawn
unique shoal

Your addStringOption method is not closed

ESLint thinks addChannelOption is still inside there, at 4 tabs indentation

zenith prawn

Oh how would I properly format it then?

unique shoal

Close the method with a )?

This isnt a formatting issue, its a code issue

zenith prawn
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.')),
        ),
};
unique shoal

Now you also added a , which is incorrect

zenith prawn

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

unique shoal

Its only finding 3 files

zenith prawn

It's in the same folder as all the other cmds

unique shoal

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

zenith prawn

I followed the guide for the code..

unique shoal

Please, read your own screenshot

zenith prawn

I have the "data" thing in my code in the command file, though, no? Is that not what it means?

unique shoal

Whats the other one it mentions

zenith prawn

OHR

unique shoal

If you do have "data", then it must be "execute" thats missing

rose tangle

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

unique shoal

The reason the deploy commands file checks itself is to avoid errors later, if only data was loaded, the command would fail on execution

wintry laurel

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

sharp ginkgoBOT

method 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);

wintry laurel

lmao ty i saw it the second i wrote that ofc

zenith prawn

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'));
    },
};
unique shoal

yep

zenith prawn

Alr thank you

shut musk

Is there any way to track user avatar changes apart from guildMemberUpdate?
I ask this because this event only emits on guild update

unique shoal

guildMemberUpdate events

shut musk

If a user updates their global profile, I suppose there's nothing to track that

unique shoal
shut musk

Yeah it didn't emit

unique shoal

And userUpdate didnt either?

shut musk

userUpdate is an event?

unique shoal

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

shut musk

So the event works for guild avatar update but not for user avatar update

shut musk
unique shoal

Whats not documented

shut musk

ok im just blind

unique shoal

Totally is though?

Yeah sorry haha

shut musk

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?

unique shoal

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

shut musk

right so guildMemberUpdate dispatches everything but d.js does it differently

unique shoal

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

shut musk

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

unique shoal

Yeah, which is how Discord emits it

shut musk

I suppose this will be a major change if it comes out anyways

shut musk

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?

red coral

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)

shut musk

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

red coral

Ah, possibly then. Since discord only sends the id and changes I suppose

shut musk

No that's fine but why is everyone's old data like empty?

red coral

Partial user

shut musk

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

red coral

You won’t know since their old user isn’t complete?

shut musk

Yeah but newUser has their new data right

but for this to emit, the user has to update their profile right?

red coral

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

shut musk

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)

red coral

According to discord they did 🤷‍♂️ djs won’t just emit an event for the sake of emitting an event

shut musk

Not really because I was told this event is not emitted by discord and is done by djs

red coral

By who?

shut musk

yeah but thats

this userUpdate is not for bots, this triggers on discord user updates

red coral

Oh, Yh that’s true. Sorry mb. I’m not too sure, something must have changed

shut musk

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

red coral

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

shut musk

This one I don't know

They might have changed something like that but really unsure

red coral

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

shut musk

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

red coral

Only since the client didn’t have them cached before

zenith prawn

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?

unique shoal

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

zenith prawn

Oh

unique shoal

Ah I think I understand - yeah, "options" dont actually change any command behaviour on their own. Theyre just types of inputs for users

zenith prawn

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

uneven crater
zenith prawn
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?

clear garnet

Don't specify any default member permissions on the command

zenith prawn

so this line?

.setDefaultMemberPermissions(PermissionFlagsBits.KickMembers)
clear garnet

Yes

Just remove that entirely

zenith prawn

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;
        }

    },
};
rose tangle

your bot is the one missing permissions

sharp ginkgoBOT

guide Popular Topics: Permissions (extended) - Missing permissions
read more

rose tangle

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

clear garnet

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

rose tangle

^^ yep, you're supposed to do it the way around

zenith prawn

ic ic thanks

velvet owl

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

unique shoal

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

halcyon bison

I'm also not totally sure how tos compliant selling a server is

steel trail

It isn't

rigid crest

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>
snow onyx

what djs version are you on?
npm ls discord.js

clear garnet
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
snow onyx

oh yeah, I missed that kekw

rigid crest

oh i didnt notice

snow onyx

cant set ephemeral in editReply anyway

needs to be done in the first reply (defer most likely)

rigid crest

i did add there, ig i just have a bad habbit of adding everywhere

rigid crest

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

raven hearth

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

polar karma

That's the only way

raven hearth
feral thunder

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

steel trail

The API allows it (to be future-prone) but there is no feature that uses it (yet)

mental silo

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

unique shoal
mental silo

What

unique shoal

It's not worse UX though

I'd argue flashing a delete is worse

mental silo

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

unique shoal

Yeah, a timeout is fine

mental silo

Lovely, thank you

cosmic grotto

Is the guide for components v2 published yet?

dense jackal

nope

zenith violet

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

zenith violet

Then why are you using it? Use deferUpdate and editReply then

toxic moat

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

wary coral
steel yacht

Hi,
What's the TypeScript fix for this please ?

I tried adding the following :

But then I get something else.
Thanks

wary coral
steel yacht
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);
};
wary coral
steel yacht

Oh yeah it receives the message object from the messageCreate event

snow onyx
sharp ginkgoBOT
steel yacht

Perfect, thanks

terse bronze

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

unique shoal

Why would that need a proxy

terse bronze
wary coral

just use @discordjs/rest on the web side no reason to go thought the gateway

loud quartz

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

terse bronze
loud quartz

And just use that api from the dashboard

terse bronze
loud quartz

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?

terse bronze
loud quartz

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

sharp swallow

Does Discord.js support components V2? Just wondering since there’s no guide for it that I’ve seen

polar karma

yes, there's a pr to the guide for a page on it, but it's fully documented

sharp ginkgoBOT

class ContainerBuilder discord.js@14.19.3
A builder that creates API-compatible JSON data for a container.

sharp swallow

Cool, thanks

sharp swallow

Thx

kind plume
terse bronze
vivid fractal

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?

rose tangle

you need to import it

any variable needs to be imported or declared before you can use it, that's just how js works

vivid fractal

oh shit i completely forgot

polar karma
terse bronze
kind plume

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

rose tangle

is your bot sharded so you can't make the api directly?

terse bronze

Rate limits need to be shared

kind plume

it depends what API calls

rose tangle

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

kind plume

proxy is easier ig

rose tangle

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

kind plume

and what's bad about that exactly?

rose tangle

security

kind plume

if you don't leak secrets to the client nothing would happen

rose tangle

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

rose tangle
terse bronze
rose tangle

it'd be better if it's literally impossible (because the dashboard doesn't know it)

kind plume

but shouldn't be if someone who does this knows how the web works

terse bronze
kind plume

like permissions checks etc.

terse bronze
proud arrow

You probably have an additional space before -

Yes, unfortunately with numbering, this is the compromise.

rose tangle

could make an emoji and use that instead

steel trail

Is it intended to be a nested list?

brisk dew

Any idea to explain why from a button interaction i don't have the cache from interaction.member.roles.cache ?

rose tangle

do you have the Guilds intent?

steel trail

And a bot user in that guild

brisk dew

yes ?

export const client = new Client({
    intents: [
        GatewayIntentBits.Guilds,
...
steel trail

Or is it user-installed app?

brisk dew

It's only a intellisense warning for now, i've not tested yet

sharp ginkgoBOT
steel trail

You want that typeguard then

brisk dew

Hmmmm okayyyy thanks you ! LinkHappySpin

topaz bluff

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

steel trail

Or have them use a slashcommand with 10 options (depending on the use case)

proud arrow

All those can be achieved by slash command options

rigid crest

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?

sharp ginkgoBOT
proud arrow

Editing a message doesn't send the notification

Which update basically is

steel trail

Ah, true

rigid crest

so sending a followup is the key to push notification alright

rose tangle

followUps use the interaction token though, which only lasts 15m

unless your giveaway only lasts 15m you might want to send a regular message

true blaze

Is there a deprecation date for components v1?

rose tangle

they aren't planned to be deprecated by discord

true blaze

Thanks

rose tangle

and that's also a question you should ask discord, though I said the answer

sharp ginkgoBOT

We are not Discord, just some nerds who develop Discord bots!

true blaze

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

rose tangle

there isn't

-# at most you can use this kind of text with -#

true blaze

Gotcha, thats a shame. I liked using the little pictures

topaz bluff

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

true blaze

Thanks. But, using canvas would have to make the entire thing an image right

steel trail

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

true blaze

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

rose tangle

not before, only after

at most you could add the emoji in the text itself but I don't think it looks the same

topaz bluff

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

rose tangle

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

proud arrow

There's no such property

rose tangle

I'm not sure whether that's present since it's not a regular reply but a followUp

but it's worth a try

proud arrow

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

rose tangle

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)

rose tangle

the only cv2 component limit is 40 components per message

sharp ginkgoBOT
rose tangle

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

steel yacht

Hi,
Does DJS provide a constant containing the list of Discord permission names and descriptions ?
Thanks

sharp ginkgoBOT
rose tangle

not descriptions though

steel yacht

And not names either, but slugs

rose tangle

ah, you want the ui name?

steel yacht

Yes, it's for displaying to the user

rose tangle

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

steel yacht
steel yacht
rose tangle

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

steel yacht

Plus I need the descriptions too.

rose tangle

you're out of luck on djs' side for that unfortunately

it's also not something the library would include/plan to include

steel yacht

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

rose tangle

you're not supossed to read it though, you're only supossed to copy the content

fallen trellis

is it possible to retrieve the added subcommands and subcommand groups from a SlashCommandBuilder?

sharp ginkgoBOT
steel yacht

Is a string select menu limited to 25 options ?

bleak owl

25 options

yes

steel yacht

Object.keys(PermissionFlagsBits).length === 50 😭😭😭😭

bleak owl

you can use autocomplete on a slash command, but still limited to showing 25 options

however

acoustic night

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)

bleak owl

you can have as many options as you want, just only 25 will be shown

steel yacht

Using a select menu is mandatory...

bleak owl

doesn’t have to be

steel yacht

I guess I'll have to use 2

rose tangle

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

sharp ginkgoBOT

method 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);

acoustic night
rose tangle

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

acoustic night

alright i added the handler

pliant forge

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?

rose tangle

show your deploy script

pliant forge
rose tangle

how do you deploy your commands to discord

pliant forge

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
                    });
                });
            });
        });```
zenith violet

that is a horrible way to do so

and will get you ratelimited in an instant

pliant forge
rose tangle

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

zenith violet
  1. the script should be separate. And not run every time your bot starts
  2. You should be using global commands if you want them to be available to every server
  3. you deploy all your commands at once. Not one request per command
sharp ginkgoBOT

guide Creating Your Bot: Registering slash commands
read more

pliant forge
zenith violet

why not use builders?

instead of doing double work

rose tangle

and you should put your command's data in a separate property

pliant forge
zenith violet

no

rose tangle

it's entirely negligible

pliant forge

i was thinking that there is a difference

rose tangle

technically, yes, in practice, no

with all your commands it should be less than 1kb

pliant forge

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

zenith violet

just like youre doing now

just in a separate script

read what i linked

pliant forge

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

zenith violet

confused about?

pliant forge

there is a command = [] thing, should i put every command or can i use for method

zenith violet

the code does that for you

pliant forge

TF mb i didn't ready all of the code really

rose tangle

the rest of the code fills that array with the commands

verbal plinth

There are rate limits predicted by discord.js. Is there a list of routes for which discord.js can send a warning?

pliant forge

TYSM! And is there any method the refresh a spesific command?

rose tangle
sharp ginkgoBOT

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
steel trail
pliant forge
zenith violet

just deploy all your commands

PUT overrides anyways

pliant forge

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?

rose tangle

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)

stable sun

The deploy script is the easier way to do that

pliant forge
stable sun

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

pliant forge
stable sun

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

pliant forge
tardy sable

hey, the bug when mentioning a user in an embed and it appearing as their userid. is this gone in components v2?

zenith violet

yes

tardy sable

nice thanks

steel yacht

When not specified, are roles created through DJS mentionable by default ?

topaz bluff

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

steel yacht

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;
}
sweet quarry

any recommendations to the directory structure?

topaz bluff
steel yacht

Good, thanks

Uh what now ?...

tardy sable

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 });
sweet quarry
steel yacht

For adding ?

topaz bluff
steel yacht

I created it above, I'm trying to give it to a user now

snow onyx
topaz bluff
tardy sable

oh ok thanks

pliant forge

I just upgraded my deploy system and upgraded my / commands but i can not see my / commands now what can be reason

zenith violet

did you run the script

pliant forge

yeah

zenith violet

and refresh your client

pliant forge

no lemme refresh the client

zenith violet

your discord client, that is

pliant forge

yeah tysm i didn't know i need to refresh it. And thank you to suggest that method. Its even looking more refresh

tardy sable
rose tangle

that's a container?

tardy sable
rose tangle

maybe because it isn't mentioning them

tardy sable

Could that be the reason?

rose tangle

yeah, that's what I meant

pliant forge

I know im looking dumb but now it doesn't respond my command 😦

rose tangle

but then it'll mention all those people

zenith violet

the deploy script doesnt run your bot

tardy sable
pliant forge
pliant forge
zenith violet

log to see if your interactionCreate event fires at all

pliant forge

uhm f me, i didn't upgrade my interactionHandler 😦

rose tangle
pliant forge
steel yacht

String select menus aren't searchable ?

zenith violet
steel yacht

There's no "PermissionSelectMenuBuilder", is there ? 😭

zenith violet

No

pliant forge
somber zodiac

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
rose tangle

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

somber zodiac

we're talking 2 renames in the span of 15s gets me ratelimited here ?

rose tangle

I don't recall what the exact numbers are but it was an extremely high one

you can double-check with the ratelimit event

somber zodiac

where would i find that ?

TWICE PER 10MIN ???

what the actual fu-

rose tangle
client.rest.on('rateLimited', console.log);

only once, can be where you create your client

and yeah, that sounds about right

rose tangle
somber zodiac

that's soooo stupid. thanks tho

rose tangle

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

somber zodiac

1000 requests per 24 hours, aka 1 per 80s essentially for role edits
meanwhile text - once per 5min, essentially

velvet bane

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?

rose tangle

there's also a payload size limit

and it can indeed happen with select menus and heavily filled messages

velvet bane

I figured

It's weird there's no error message specific to that

rose tangle

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

pliant forge

can ephemeral messages delete or edit?

rose tangle

yes

only through the webhook though

meaning the interaction object

through the deleteReply and editReply methods

pliant forge
rose tangle

just call them

what specific interaction type?

to bring out the docs

pliant forge
compact swan

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

light sapphire

any breaking change that remove interaction.guild ?
cuz i cant access anymore interaction.guild

hybrid olive

did they remove the ability to make messages on prefix commands ephemeral?

sharp ginkgoBOT
light sapphire

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

little pebble

Oops, wrong ping, @compact swan ^

light sapphire
little pebble
hybrid olive
fast lion

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

fast lion

That would make a lot of sense. Thanks!

compact swan
little pebble
sharp ginkgoBOT
zenith prawn

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.');
        }
    },
};
rose tangle
zenith prawn
rose tangle 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

rose tangle

is your bot actually in that guild?

zenith prawn

Yes

rose tangle

double check the clientId, guildId and token are present and with the values you expect

zenith prawn

Ohr, I reset the token and inputted it and it works now 👍 thanks

buoyant cobalt

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

zenith prawn

I'm getting an "invalid token" error even though I copy-pasted the exact token directly from the bot portal

unique shoal

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?

zenith prawn

and yes, i did save the file, and all

buoyant cobalt
unique shoal

dotenv is no longer required, you can pass an env file using node --env-file=.env index.js

zenith prawn

this is a line in my deploy-commands.js

unique shoal

You do not need the dotenv package dependency anymore, node now supports loading a file of environment variables natively

zenith prawn

so like i can just remove any line of code that requires dotenv or what?

unique shoal

If you also add the command line argument I showed

zenith prawn

Such as this in my main file

const dotenv = require('dotenv');
unique shoal

Is that also in your deploy-commands file?

And you run the config?

zenith prawn
require('dotenv').config();
const { clientId, guildId } = process.env;

these two

zenith prawn
unique shoal

Yeah

Sounds like you werent loading dotenv

zenith prawn
rose tangle

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

unique shoal

You can add the command line args to an npm start script in package.json to make things easier

zenith prawn
rose tangle

yes

unique shoal

That looks correct, yeah

But the error came from login()

zenith prawn

Oh

unique shoal

Not deploy-commands (unless it was both)

rose tangle

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)

rose tangle

there's a scripts section in your package.json

zenith prawn

ik that, but how would I write it

unique shoal

Theres a scripts section that looks something like this:

npm start on the command line will run that script

zenith prawn

ic

unique shoal

A few keywords, like start, work directly, the others require npm run <name>

zenith prawn

did i do this properly-

rose tangle

npm start, not node start

zenith prawn

OH

rose tangle

node takes a js file as argument so it runs it

unique shoal

You dont have a dist folder

zenith prawn

meh?

unique shoal

Looks like its running

zenith prawn

wouldn't it show the usual message thing

unique shoal

Yeah it should

zenith prawn

oh wait it showed up a bit later, nvm

alr thanks

vital vortex

Is there a way to log the access join application answers?

rose tangle

no, that's not available through the api

copper trail

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

topaz bluff
copper trail

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

topaz bluff

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

copper trail
topaz bluff

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

copper trail

im just not sure what to use to get the code activitated other than using slash commands

topaz bluff

Well if you have slash commands, then you've made an event listener before. But that was for interactionCreate events rather than messageCreate events.

copper trail

ty

ill will read these and try to debug it and work on it

topaz bluff

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

reef tiger

Does djs automatically respect role hierarchy in its code?

Also @unique shoal there's a scam esex ad above me

unique shoal

And thanks, banned

"automatically respect" in what context?

reef tiger
sharp ginkgoBOT

method 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}`);

unique shoal

There is a method for doing this

reef tiger

Ty

unique shoal

Or there are some helpers

sharp ginkgoBOT
unique shoal

But yes, you must make the checks somehow

Or catch the error when Discord API says no

reef tiger

👍

buoyant birch

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);```
sharp ginkgoBOT
unique shoal

These two methods set how a command can be installed, and where its usable

The same applies to context menu commands

toxic moat

eh

snow onyx

Did you solve your issue?

normal veldt

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 !

unique shoal

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?

normal veldt
.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 🙂

steel trail
normal veldt
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

mental silo

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

steel trail

They can't and won't

Both are fine

0 is not a bitflag. It's the absence of all bits

mental silo

Ah thats good to hear, I'll be using that then. Thank you!

peak pond

Hello,
No text input for components v2 to be used in containers ?

dense jackal

no

peak pond
young zodiac

Is it possible to make the buttons horizontal?

-# do you think it looks better like this?

Nvm

burnt quartz
young zodiac
burnt quartz

a normal action row

young zodiac

Okay

rough tree

Can and how i send like this via discord.js and can i use buttons on dm?

rough tree
steel trail

Those were answers to both of your questions

rough tree

can i use buttons on dm? like green buttons

steel trail

yes, you can

rough tree

Oh thanks ❤️

vernal willow

hello ! i wanted to know if it was possible to send spoiler images in embeds

vernal willow
next mesa yes

do you know how to do this? I use setimage with images renamed with SPOILER_, but they appear clearly.

next mesa
vernal willow

@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`));
sharp ginkgoBOT

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]
});
steel trail
vernal willow
steel trail
vernal willow

ohhh okay, will this eventually replace embeds?

snow onyx

there is no plan to remove legacy components, no

vernal willow

okay thanks

latent plume

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([...])
polar karma

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

latent plume

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

polar karma

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

latent plume
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'
}