#djs-help-v14

78874 messages · Page 51 of 79

stable sun

Ok? Is it not?

There’s no variables being put into any part of the modal

toxic moat

He send me a temp

toxic moat
stable sun There’s no variables being put into any part of the modal

He means this is the temp:

const { ModalBuilder, TextInputBuilder, TextInputStyle, ActionRowBuilder } = require('discord.js');

module.exports = {
    customId: 'test',
    
    async execute(interaction, args, client) {
        const modal = new ModalBuilder()
            .setCustomId('test_modal')
            .setTitle('test Modal');

        const input = new TextInputBuilder()
            .setCustomId('test_input')
            .setLabel('Enter some text')
            .setStyle(TextInputStyle.Short)
            .setRequired(true);

        modal.addComponents(new ActionRowBuilder().addComponents(input));
        await interaction.showModal(modal);
    }
};
stable sun

That’s pretty standard

The legacy way

You can define the modal where you use it

That’s usually where you start before you try factoring it

toxic moat
stable sun

That’s the easiest way

And suitable for most cases

You’d only factor it out into another file if it’s used in multiple places

toxic moat
stable sun

Yea

toxic moat
stable sun

Whatever you need to do before you show the modal

Or decide not to show modal

torn orchid

i dont know if its extension of the discord rich presence made by crawl but how do you get your status to say "Playing Code" instead of "Playing Visual Studio Code"

torn orchid
torn orchid
topaz bluff

No. That will just make it so you can modify the source code yourself

stable sun

The repo doesn’t hold your hand on the inner workings, but you can prob figure it out by inspection

torn orchid

👍

stable sun

(Even easier w/ AI tbh)

toxic moat

@stable sun is this good

.addOptions(
    (optionBuilder) => setLabel('Warning').setValue('warning').setDescription('Issue a warning to a user'),
                        )
stable sun

You forgot the optionBuilder.

toxic moat

Ohh

Thx

fervent ocean

Hi, I'm getting this error when trying to edit an interaction reply after some amount of time:

757 |     if (status >= 400 && status < 500) {
758 |       if (status === 401 && requestData.auth) {
759 |         manager.setToken(null);
760 |       }
761 |       const data = await parseResponse(res);
762 |       throw new DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData);
                  ^
error: Invalid Webhook Token
 requestBody: {
  files: [],
  json: [Object ...],
},
   rawError: {
  message: "Invalid Webhook Token",
  code: 50027,
},
       code: 50027,
     status: 401,
     method: "PATCH",
        url: "https://discord.com/api/v10/webhooks/****/messages/%40original",

is there a way to get around this?

unique shoal

Get around tokens expiring? no

fervent ocean
unique shoal

Only if it isnt ephemeral, and you have a bot user in the guild

fervent ocean

that's a bit limiting but fine i guess. thanks!

unique shoal

Thats necessary for the permissions model

toxic moat

@stable sun this is my Form now:

const modal = new ModalBuilder().setCustomId('open-case').setTitle('Open Moderation Case')
           .addLabelComponents((labelBuilder) => {
            return label
                .setCustomId('case-category')
                .addStringSelectMenuComponent((menuBuilder) => {
                    return menuBuilder
                        .setCustomId('case-category')
                        .setPlaceholder('Select case category')
                        .addOptions(
                            (optionBuilder) => optionBuilder.setLabel('Inquiry').setValue('inquiry').setDescription('General inquiry'),
                            (optionBuilder) => optionBuilder.setLabel('Discipline').setValue('discipline').setDescription('Disciplinary action'),
                            (optionBuilder) => optionBuilder.setLabel('Urgent').setValue('urgent').setDescription('Urgent case'),
                            (optionBuilder) => optionBuilder.setLabel('Executive').setValue('executive').setDescription('Executive decision'),
                        )
                })
                .setLabel('Select the category for this case:')
                .setDescription('Choose the appropriate category for the moderation case.')
           })
           .addLabelComponents((labelBuilder) => {
            return label
                .setCustomId('select-user')
                .addUserSelectMenuComponent((menuBuilder) => {
                    return menuBuilder
                        .setCustomId('select-user')
                        .setPlaceholder('Select a user')
                        .setMinValues(1)
                        .setMaxValues(1);
                })
                .setLabel('Select the user involved in this case:')
                .setDescription('Choose the user who is the subject of this moderation case.')
           });

        await interaction.showModal(modal);

What do you say good our not good?

stable sun

LGTM

toxic moat
stable sun

That’s mb

Obv no custom id on labels

It doesn’t accept input, the inner menu or text input does

toxic moat

new error

stable sun

Either use label or labelBuilder, not both

Not good: (labelBuilder) => { return label

toxic moat

Alright

A new one

stable sun
toxic moat

Is this here the problem? await interaction.showModal(modal);

unique shoal

This is why you should log errors to console, not to Discord

The error stack will tell you exactly where something happened

toxic moat
[05:20:40] [Command ] [Slash] Command "open-case" executed by mihivx (1427480488511279124) in Mein Test Bot server (1428234467272687641)
Error showing modal: ValidationError > s.object(T)
  Expected the value to be an object, but received function instead

  Received:
  | [Function]

    at _ObjectValidator.handle (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:2070:9)
    at _ObjectValidator.parse (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:972:90)
    at C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\builders\dist\index.js:1176:164
    at Array.map (<anonymous>)
    at StringSelectMenuBuilder.addOptions (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\builders\dist\index.js:1175:28)
    at C:\Users\user\Documents\VSCode\random bot\Synapse-Base\commands\Moderation\open-case.js:18:26
    at resolveBuilder (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\builders\dist\index.js:2461:12)
    at LabelBuilder.setStringSelectMenuComponent (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\builders\dist\index.js:1580:27)
    at C:\Users\user\Documents\VSCode\random bot\Synapse-Base\commands\Moderation\open-case.js:14:18
    at resolveBuilder (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\builders\dist\index.js:2461:12)
[05:20:58] [Database] Backup settings changed: Interval=24h, Retention=7d
unique shoal

Something to do with the select menu options

Not sure what though, havent used these new ones

toxic moat

Idk but i looked at the old its much better and easier but i want learn the new one

toxic moat

(node:37) DeprecationWarning: The ready event has been renamed to clientReady to distinguish it from the gateway READY event and will only emit under that name in v15. Please use clientReady instead.

topaz bluff

yes, do you have a question about that deprecation warning?

toxic moat
topaz bluff

by using clientReady instead of ready

toxic moat

I stopped my bot it doesn't run anymore

toxic moat
topaz bluff

wherever your ready event is

toxic moat
wary coral
toxic moat
wary coral
sharp ginkgoBOT

tag suggestion for @toxic moat:
If you aren't getting any errors, try to place console.log checkpoints throughout your code to find out where execution stops.

  • Once you do, log relevant values and if-conditions
  • More sophisticated debugging methods are breakpoints and runtime inspections: learn more
stable sun

Applies to the other method spliceOptions

stable sun
robust flame
echo anvil

Hey. Is there a way to know in advance if a bot can DM someone ? If not, would the send method throw an error that I should catch and do some fallback strategy there ?

echo anvil

So .send would throw an error, go it

stable sun

Yea

echo anvil

Thank you for you guidance

echo anvil

Is it possible to send an ephemeral message in a GuildText channel when it's not a reply ? If the bot doesn't mention anyone in the message who would see it ? And if I mention 1 person would they see it ? 2 persons ?

clear garnet

No, ephemeral messages can only be created through interactions

echo anvil

That's what I thought yea. Makes sense ngl

heavy grail

Hey can anyone tell me which verison of discord js supports all the new components v2

clear garnet
heavy grail

Lemme see thanks tho 🙂

brave moth

Does sharding only affect the number of guilds in a shard, or is it also influenced by the number of members in individual guilds?

For example, will a server with two million members automatically be assigned its own shard?

crimson gale

number of guilds

red coral

So if ur bot was in 100 2m+ member guilds they could technically all be on the same shard?

crimson gale

unlikely

if you want to do load balancing based on guild size, that's on you to implement in the sharder

heavy grail

Anyone got a bot with new components v2? I wanna test em out but my bot crashes when I add them

crimson gale

if you want to solve that, providing the error may help

heavy grail
crimson gale

then what do you hope as result from posting here, if you don't want to fix it?

heavy grail
crimson gale

so instead of fixing the mistake and learning from it you want someone else's work, got it
this is a help channel, please only use it to get help with your own projects, thanks

steady vale

can anyone tell me the ratelimit to edit the bot's profile on the server (avatar, banner, etc)?

zealous marten
sharp ginkgoBOT
crimson gale

oh, wait, rate limit

rate limits are dynamic and based on API load

if you want to cycle through avatars, just don't, tbh

steady vale
brave moth

Is the rate limit per-guild?

steady vale

Probably yes

brave moth

Then you could just show the user that they hit Discord's rate limit.

You don't have to implement a cooldown for something that's limited by Discord anyway.

heavy grail

Got any recommendation?

zealous marten
red coral
heavy grail
red coral

Yes but you can copy and paste the output into your code to use

heavy grail

Thanks

polar olive

Global error or is it just me?

TypeError: Class extends value [object Object] is not a constructor or null
    at Object.<anonymous> (/home/sistemas/Bots/Palitoo Studios - Pureza/Pureza BOT - Pureza/node_modules/discord.js/src/structures/BaseChannel.js:15:27)
    at Module._compile (node:internal/modules/cjs/loader:1706:14)
    at Object..js (node:internal/modules/cjs/loader:1839:10)
    at Module.load (node:internal/modules/cjs/loader:1441:32)
    at Function._load (node:internal/modules/cjs/loader:1263:12)
    at TracingChannel.traceSync (node:diagnostics_channel:322:14)
    at wrapModuleLoad (node:internal/modules/cjs/loader:237:24)
    at Module.require (node:internal/modules/cjs/loader:1463:12)
    at require (node:internal/modules/helpers:147:16)
    at Object.<anonymous> (/home/sistemas/Bots/Palitoo Studios - Pureza/Pureza BOT - Pureza/node_modules/discord.js/src/structures/GuildChannel.js:5:25)```
loud quartz

What are you trying to do?

polar olive

My bot automatically sends rankings to each staff area + automatic reception.
After a while with the bot running, this error starts to appear and the bot kind of freezes.

wary coral
polar olive
wary coral

any where else?

polar olive

Only in him

wary coral

and Client is coming right from the import/require? nothing is done to it before?

wary coral

is there more to you error?

polar olive

None, just this one

wary coral

could you share your Extended Client.js

The issue is sothing to do with your require and export of the class but I am not sure why

I might be going done the wrong road. From my googling it occurs when a circular dependency exists ex: file A calls file B witch calls file A. so it may be unrelated to "Extended Client.js"

crimson gale

re: deleted
we do not provide support for selfbots

sand minnow
crimson gale

?

sand minnow

Like how to fix this, if I'm not allowed I'll delete it

crimson gale

dude

if you post a question, actually read the answers

before moving on into another place and posting the same thing again

or - before posting it in the first place - read the error message

remove a bot, so you don't have 50 bots on the server anymore, then you can invite one again

sand minnow
dense jackal
sand minnow

Thought the issue was with my bot, thanks for the help tho

sand minnow
strange star

Hey, could it be that “bio” is not set in editMe()?

I tested it several times. Avatar, banner, and name were set immediately. The bio was not.

red coral

Did you try reloading the discord app? Potentially it’s a cache thing with the app?

strange star

Yes, I did. But it didn't work. Now, after about 20 minutes, it's showing the new bio 😄

leaden shuttle
balmy kraken

i can only call interaction.reply() and .editReply() once on an interaction? So if i want to edit more times i need to make a followup and base on the new message?

red coral

You can only call .reply once, but you can call edit reply multiple times

I believe only until 15 mins is up, since that’s how long an interaction token is valid for

past spear

hi, why i can't use TextDisplayBuilder? I have djs v14.23.2, but it's doesn't work

in console i got DiscordAPIError 50035 (Invalid Form Body)

balmy kraken
red coral

You can only call .update once too, then use edit reply after

red coral
red coral
balmy kraken
red coral

Yes, you can only use update once. Same as .reply, deferReply deferUpdate

past spear
red coral

If you do that does it error? Maybe ur djs isn’t at the latest version maybe? I’d say try it and then go from there

past spear
red coral If you do that does it error? Maybe ur djs isn’t at the latest version maybe? I’...
components[0][UNION_TYPE_CHOICES]: Value of field "type" must be one of (1,).
DiscordAPIError[50035]: Invalid Form Body
components[0][UNION_TYPE_CHOICES]: Value of field "type" must be one of (1,).
    at handleErrors (/home/Lexis/node_modules/@discordjs/rest/dist/index.js:762:13)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async SequentialHandler.runRequest (/home/Lexis/node_modules/@discordjs/rest/dist/index.js:1163:23)
    at async SequentialHandler.queueRequest (/home/Lexis/node_modules/@discordjs/rest/dist/index.js:994:14)
    at async _REST.request (/home/Lexis/node_modules/@discordjs/rest/dist/index.js:1307:22)
    at async TextChannel.send (/home/Lexis/node_modules/discord.js/src/structures/interfaces/TextBasedChannel.js:195:15)

As I thought, an error occurred

When I check the library version on the hosting, it says 14.23.2, just like in package.json

red coral

What’s your new code?

past spear

I made some changes to my code and used site u sent me and got a new error:

components[0][MODEL_TYPE_CONVERT]: Expected an object/dictionary.
DiscordAPIError[50035]: Invalid Form Body
components[0][MODEL_TYPE_CONVERT]: Expected an object/dictionary.
    at handleErrors (/home/Lexis/node_modules/@discordjs/rest/dist/index.js:762:13)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async SequentialHandler.runRequest (/home/Lexis/node_modules/@discordjs/rest/dist/index.js:1163:23)
    at async SequentialHandler.queueRequest (/home/Lexis/node_modules/@discordjs/rest/dist/index.js:994:14)
    at async _REST.request (/home/Lexis/node_modules/@discordjs/rest/dist/index.js:1307:22)
    at async TextChannel.send (/home/Lexis/node_modules/discord.js/src/structures/interfaces/TextBasedChannel.js:195:15)
    at async Object.execute (/home/Lexis/slash_commands/text_test.js:79:9)
    at async Client.<anonymous> (/home/Lexis/index.js:99:9)

here my actual code:

const {
    SlashCommandBuilder,
    TextDisplayBuilder,
    ButtonBuilder,
    ButtonStyle,
    ActionRowBuilder,
    StringSelectMenuBuilder,
    StringSelectMenuOptionBuilder,
    ContainerBuilder,
    MessageFlags
} = require('discord.js')

module.exports = {
    data: new SlashCommandBuilder()
        .setName('test')
        .setDescription('test'),
    async execute(interaction) {
        const components = [
            new ContainerBuilder()
                .setAccentColor(4149449)
                .addTextDisplayComponents(
                    new TextDisplayBuilder().setContent("Example components:"),
                )
                .addTextDisplayComponents(
                    new TextDisplayBuilder().setContent("# Test header\nButtons"),
                )
                .addActionRowComponents(
                    new ActionRowBuilder()
                        .addComponents(
                            new ButtonBuilder()
                                .setStyle(ButtonStyle.Primary)
                                .setLabel("test1")
                                .setCustomId("36acfad8d418474084daed1d0d06bef2"),
                            new ButtonBuilder()
                                .setStyle(ButtonStyle.Secondary)
                                .setLabel("test2")
                                .setCustomId("212dc1a845d54912cdff8446cdb3d321"),
                        ),
                )
                .addTextDisplayComponents(
                    new TextDisplayBuilder().setContent("\nSelect menus"),
                )
                .addActionRowComponents(
                    new ActionRowBuilder()
                        .addComponents(
                            new StringSelectMenuBuilder()
                                .setCustomId("99fca274f90a4070beb7086fdf335bfc")
                                .setMaxValues(3)
                                .addOptions(
                                    new StringSelectMenuOptionBuilder()
                                        .setLabel("Test selection")
                                        .setValue("44c530edcff948c5e63764303419e252")
                                        .setDescription("test")
                                        .setDefault(true)
                                        .setEmoji({
                                            name: "😜",
                                        }),
                                    new StringSelectMenuOptionBuilder()
                                        .setLabel("Other selection")
                                        .setValue("c0f60f084fc44e99ec904a89f83ffaf6"),
                                ),
                        ),
                )
                .addActionRowComponents(
                    new ActionRowBuilder()
                        .addComponents(
                            new StringSelectMenuBuilder()
                                .setCustomId("0eee4ad1eb8b480dc4a7b448445e666f")
                                .setPlaceholder("TEST SELECT")
                                .addOptions(
                                    new StringSelectMenuOptionBuilder()
                                        .setLabel("TEST SELECT OPTION")
                                        .setValue("6574da11b26146a58f3995d155c32a80"),
                                ),
                        ),
                ),
        ];

        await interaction.channel.send({
            components: [components],
            flags: MessageFlags.IsComponentsV2
        })
    }
}
balmy kraken

ephemeral status is reserved only for command interactions, so there is no way to make a message sent by the bot ephemeral?

brave moth
rose tangle
wary coral
rose tangle

all enum values are in PascalCase

brave moth

I always use the command node --env-file=.env index.js to start my app. Is there a way to stop me having to add --env-file=.env to the command every time?

polar karma
brave moth

Oh I just learned what scripts are, fancy

red coral
past spear
wary coral
sand minnow

I have an issue where when getting who deleted a message to show it in my bot's mod logs, it's not always right

Let me show you guys the code real quick

client.on("messageDelete", async (message) => {
  try {
    const logData = await logSchema.findOne({ Guild: message.guild.id });
    if (!logData) return;

    const logChannel = message.guild.channels.cache.get(logData.Channel);
    if (!logChannel) return logData.delete();
    setTimeout(async() => {
    const fetchedLogs = await message.guild.fetchAuditLogs({ limit: 1, type: 72 });
    const deletionLog = fetchedLogs.entries.first();
    const executor = deletionLog?.executor || 'Unknown';

    const embed = new MessageEmbed()
      .setTitle("Message Deleted")
      .setColor("RED")
      .addFields([
        { name: "Content", value: `${message.content}` },
        { name: "Author", value: `${message.author.tag}` },
        { name: "Deleted by", value: `${executor}` },
        { name: "Channel", value: `${message.channel}` },
      ])
      .setThumbnail(message.author.displayAvatarURL({ dynamic: true }))
      .setTimestamp();

    logChannel.send({ embeds: [embed] });
  }, 2000)
  } catch (error) {
    console.error("Error logging message delete: ", error);
  }
});
wary coral
sand minnow
wary coral

your issue is here const deletionLog = fetchedLogs.entries.first(); you are not check to see if it is the right log

sand minnow

How do I do that?

sand minnow
wary coral

sorry I missed the line above

sand minnow

Yeah

I am setting a limit so it should get the one I need, and the type too

wary coral

really tho it is a race condition. the log has not been created or another has been added at time of fetch

sand minnow

Even tho it still shows a wrong one, not the one who deleted

Not just once, multiple times which is so weird

wary coral

I am saying it fetched the wrong log. bc the right one had yet to be created or to that affect

sand minnow

So what's my fix then?

A delay definitely won't work at all

wary coral

add a wait to the fetch log then get say 10 logs then fitter for the message id

proud arrow
sand minnow
past spear
proud arrow

But this just narrows it doen

sand minnow

Yeah doesn't help that much

It's the only thing I can do tho

wary coral
sand minnow
proud arrow You could add further checks, like checking if target channel is same as the mes...
client.on("messageDelete", async (message) => {
  try {
    const logData = await logSchema.findOne({ Guild: message.guild.id });
    if (!logData) return;

    const logChannel = message.guild.channels.cache.get(logData.Channel);
    if (!logChannel) return logData.delete();
    setTimeout(async() => {
    const fetchedLogs = await message.guild.fetchAuditLogs({ limit: 1, type: 72 });
    const deletionLog = fetchedLogs.entries.first();
    const executor = deletionLog?.executor || 'Unknown';
if(message.channel.id !== deletionLog..extra.channel.id) return;
if(message.author.id !== deletionLog.target.id) return;
    const embed = new MessageEmbed()
      .setTitle("Message Deleted")
      .setColor("RED")
      .addFields([
        { name: "Content", value: `${message.content}` },
        { name: "Author", value: `${message.author.tag}` },
        { name: "Deleted by", value: `${executor}` },
        { name: "Channel", value: `${message.channel}` },
      ])
      .setThumbnail(message.author.displayAvatarURL({ dynamic: true }))
      .setTimestamp();

    logChannel.send({ embeds: [embed] });
  }, 2000)
  } catch (error) {
    console.error("Error logging message delete: ", error);
  }
});

Anything extra I should add?

past spear
wary coral no additional changes are needed. A Text Display builder can just be added to th...
components[0].components[4].components[0].options[BASE_TYPE_MIN_LENGTH]: Must be 3 or more in length.
DiscordAPIError[50035]: Invalid Form Body
components[0].components[4].components[0].options[BASE_TYPE_MIN_LENGTH]: Must be 3 or more in length.
    at handleErrors (/home/Lexis/node_modules/@discordjs/rest/dist/index.js:762:13)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async SequentialHandler.runRequest (/home/Lexis/node_modules/@discordjs/rest/dist/index.js:1163:23)
    at async SequentialHandler.queueRequest (/home/Lexis/node_modules/@discordjs/rest/dist/index.js:994:14)
    at async _REST.request (/home/Lexis/node_modules/@discordjs/rest/dist/index.js:1307:22)
    at async TextChannel.send (/home/Lexis/node_modules/discord.js/src/structures/interfaces/TextBasedChannel.js:195:15)
    at async Object.execute (/home/Lexis/slash_commands/text_test.js:79:9)
    at async Client.<anonymous> (/home/Lexis/index.js:99:9)
wary coral
proud arrow
sharp ginkgoBOT
sand minnow
past spear
wary coral
proud arrow
past spear
wary coral I ment for `components`
const components = [
  new ContainerBuilder()
      .setAccentColor(4149449)
      .addTextDisplayComponents(
          new TextDisplayBuilder().setContent("Example components:"),
      )
      .addTextDisplayComponents(
          new TextDisplayBuilder().setContent("# Test header\nButtons"),
      )
      .addActionRowComponents(
          new ActionRowBuilder()
              .addComponents(
                  new ButtonBuilder()
                      .setStyle(ButtonStyle.Primary)
                      .setLabel("test1")
                      .setCustomId("36acfad8d418474084daed1d0d06bef2"),
                  new ButtonBuilder()
                      .setStyle(ButtonStyle.Secondary)
                      .setLabel("test2")
                      .setCustomId("212dc1a845d54912cdff8446cdb3d321"),
              ),
      )
      .addTextDisplayComponents(
          new TextDisplayBuilder().setContent("\nSelect menus"),
      )
      .addActionRowComponents(
          new ActionRowBuilder()
              .addComponents(
                  new StringSelectMenuBuilder()
                      .setCustomId("99fca274f90a4070beb7086fdf335bfc")
                      .setMaxValues(3)
                      .addOptions(
                          new StringSelectMenuOptionBuilder()
                              .setLabel("Test selection")
                              .setValue("44c530edcff948c5e63764303419e252")
                              .setDescription("test")
                              .setDefault(true)
                              .setEmoji({
                                  name: "😜",
                              }),
                          new StringSelectMenuOptionBuilder()
                              .setLabel("Other selection")
                              .setValue("c0f60f084fc44e99ec904a89f83ffaf6"),
                      ),
              ),
      )
      .addActionRowComponents(
          new ActionRowBuilder()
              .addComponents(
                  new StringSelectMenuBuilder()
                      .setCustomId("0eee4ad1eb8b480dc4a7b448445e666f")
                      .setPlaceholder("TEST SELECT")
                      .addOptions(
                          new StringSelectMenuOptionBuilder()
                              .setLabel("TEST SELECT OPTION")
                              .setValue("6574da11b26146a58f3995d155c32a80"),
                      ),
              ),
      ),
]
sand minnow

Alright, thanks @proud arrow @wary coral appreciate the help fellas

wary coral
past spear

Yep

Thx for help, I delete the maxValues

wary coral

when using Unicode emojis just add it like this .setEmoji("😜")

wary coral
past spear

String Select in modal working right now in djs?

past spear

It's just that my classes aren't showing up there either. Any idea what might be causing this?

topaz bluff

Have you updated your package?

past spear
topaz bluff

What classes are not showing up?

cosmic copper

Any idea on how my bot adds or removes multiple roles? Its supposed to add one role and remove one role. Other roles ( ids ) werent even saved on db

wary coral
primal ridge
wary coral

you mean in the audit log?

primal ridge

Yeah

wary coral

audit log is unreliable as the event only emits when a log is created not when it is updated

primal ridge

I think it would be better if I send you the source code.

Do you mind if I sent it to you in DMs since we operate a public bot

Hope it's not an inconvenience! 🙏🏻

topaz bluff
tardy sable

is it possible to check if a command has server set permissions on the server integration page?

topaz bluff

Through the bot endpoints? No I don't think so

With OAuth? Yes

primal ridge
drifting tartan

hi, am getting error with _Rest i don't know why that's happen

when trying to change my app's avatar using command

i getting this error:
throw new Error('Expected token to be set for this request, but none was present');
^
Error: Expected token to be set for this request, but none was present
at _REST.resolveRequest (C:\Users&&&\Desktop&&&\node_modules@discordjs\rest\src\lib\REST.ts:313:11)
at _REST.queueRequest (C:\Users&&&\Desktop&&&\node_modules@discordjs\rest\src\lib\REST.ts:255:44)
at _REST.request (C:\Users&&&\Desktop&&&\node_modules@discordjs\rest\src\lib\REST.ts:210:31)
at _REST.put (C:\Users&&&\Desktop&&&\node_modules@discordjs\rest\src\lib\REST.ts:191:15)
at GuildMessageManager.react (C:\Users&&&\Desktop&&&\node_modules\discord.js\src\managers\MessageManager.js:255:28)
at Message.react (C:\Users&&&\Desktop&&&\node_modules\discord.js\src\structures\Message.js:872:33)
at C:\Users&&&\Desktop&&&\avatar.ts:27:13
at Generator.next (<anonymous>)
at fulfilled (C:\Users&&&\Desktop&&&avatar.ts:5:58)
at processTicksAndRejections (node:internal/process/task_queues:105:5)

import { Message, Attachment } from 'discord.js';

export const name = 'avatar';

export const execute = async (message: Message) => {
    const args = message.content.split(' ').slice(1);
    const attachment = message.attachments.first();

    try {
        let avatarUrl: string;

        if (attachment) {
            avatarUrl = attachment.url;
        }
        else if (args[0]) {
            avatarUrl = args[0];
            
            if (!avatarUrl.startsWith('http')) {
                return message.reply('❌ Please provide a valid URL or attach an image file!');
            }
        }
        else {
            return message.reply('❌ Please provide a URL or attach an image file!\nUsage: `!avatar <url>` or attach an image with the command');
        }

     await message.client.user.setAvatar(avatarUrl)
    message.react('✅')
        
        
    } catch (error) {
        console.error('Error changing avatar:', error);
        
    }
};
halcyon bison
drifting tartan

14.16.3v

waiiitt is there a new updates ?

wary coral
drifting tartan

shi am dumas

lemme just update it and see if got an error again

@wary coral , @halcyon bison deserves a cookie 🍪 , really thanks.
-# sorry for mention 🙂

brittle current

can i add textdisplay in label comp?

stable sun
brittle current

so only like this

const modal = new ModalBuilder()
    .setCustomId(`reportUserModal_${reportedUser.id}`)
    .setTitle(`Report ${reportedUser.user.username}`)
    .addTextDisplayComponents(
      new TextDisplayBuilder().setContent("**Zneužití** této akce může vést k **moderátorským** akcím ‼️")
    );
stable sun

Yea

Why would you put it in a Label?

brittle current

to put it under select menu

halcyon bison
brittle current

how

also can there be 2 text displays?

halcyon bison

add the label to the modal first, then add the text display
call addLabelComponents before addTextDisplayComponents

topaz bluff
brittle current

oh

proud arrow

Label components also have description, so if your use is not too fancy, you can use that

brittle current
halcyon bison

on the assumption selectMenu is the select menu in question, that's not a label component
add that to the label with <LabelBuilder>.set*SelectMenuComponent()

brittle current
halcyon bison on the assumption `selectMenu` is the select menu in question, that's not a labe...
    const selectMenu = new LabelBuilder()
      .setLabel("Typ reportu")
      .setStringSelectMenuComponent(
        new StringSelectMenuBuilder()
          .setCustomId("typ")
          .setPlaceholder("Vyber typ reportu")
          .addOptions(
            new StringSelectMenuOptionBuilder()
              .setLabel("N-word")
              .setValue("nword")
              .setDescription("Pokud zprava obsahuje N-WORD")
              .setEmoji("⚫"),
            new StringSelectMenuOptionBuilder()
              .setLabel("Spam")
              .setValue("spam")
              .setDescription("Pokud si myslíš že je zpráva spam")
              .setEmoji("📰"),
            new StringSelectMenuOptionBuilder()
              .setLabel("NSFW")
              .setValue("nsfw")
              .setDescription(
                "Pokud zprava obsahuje sexualní nebo jiny nsfw content"
              )
              .setEmoji("🔞"),
            new StringSelectMenuOptionBuilder()
              .setLabel("Hate speech")
              .setValue("speech")
              .setDescription("Pokud zprava obsahuje nenávistné projevy")
              .setEmoji("💢"),
            new StringSelectMenuOptionBuilder()
              .setLabel("Harrasment")
              .setValue("harrasment")
              .setDescription("Obtěžování")
              .setEmoji("😠"),
            new StringSelectMenuOptionBuilder()
              .setLabel("Jiné")
              .setValue("jine")
              .setDescription("Jiný důvod")
              .setEmoji("❓")
          )
      );
``` i know thx

nice thx

lost mason

imagigation

celest coral

Will Channel Select Menus autoupdate the selectable options if i create new channels?

rose tangle

probably, but it's nothing inside djs' control

discord populates that menu, it's a built-in component

celest coral

Thanks

rose tangle

but I'd say you should just try it and see, would be faster than waiting for a reply

celest coral

I retarted the client with CTRL+R and its still the same after creating a channel beforehand

tardy sable

yh it probably doesnt update in realtime

trim elm

there is an enum for RESTEvents but is there one for ClientEvents? Either im blind or there really isnt one. Cant seem to find anything in docs either

sharp ginkgoBOT
torn orchid

is there any docs for how to support usernames & tags?
like i can do !whois koalanate
!whois @torn orchid or !whois 1203401516069822477
?

bleak owl

can you be more specific?

torn orchid
bleak owl

why not just use a User slash command option?

torn orchid

alr

velvet sorrel

How can I know the server guild tag? Is it exposed?

rose tangle

it's exposed by the api but undocumented, so djs doesn't have it

velvet sorrel
rose tangle

yes

sharp ginkgoBOT
velvet sorrel
toxic moat

I have problems with the modal:
This is my error:

Error showing modal: ValidationError > s.nativeEnum(T)
  Expected the value to be a string or number

  Received:
  | undefined

    at _NativeEnumValidator.handle (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:2788:9)
    at _NativeEnumValidator.parse (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:972:90)
    at TextInputBuilder.setStyle (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\builders\dist\index.js:1365:47)
    at C:\Users\user\Documents\VSCode\random bot\Synapse-Base\commands\Moderation\open-case.js:62:26
    at resolveBuilder (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\builders\dist\index.js:2461:12)
    at LabelBuilder.setTextInputComponent (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\builders\dist\index.js:1625:27)
    at C:\Users\user\Documents\VSCode\random bot\Synapse-Base\commands\Moderation\open-case.js:58:18
    at resolveBuilder (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\builders\dist\index.js:2461:12)
    at C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\builders\dist\index.js:2646:48
    at Array.map (<anonymous>)
[01:58:12] [Database] Backup settings changed: Interval=24h, Retention=7d

Code: https://sourceb.in/ZEunMYRRvq

bleak owl

TextDisplayBuilder doesn't have a Paragraph property. you're probably thinking of TextInputStyle

sharp ginkgoBOT
toxic moat
bleak owl

what's the error?

toxic moat
bleak owl what's the error?
Error showing modal: DiscordAPIError[50035]: Invalid Form Body
data.components[2].component.label[TEXT_INPUT_COMPONENT_LABEL_IN_LABEL_COMPONENT]: Cannot set label on a TextInput in a Label component
    at handleErrors (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\rest\dist\index.js:762:13)
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
    at async BurstHandler.runRequest (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\rest\dist\index.js:866:23)
    at async _REST.request (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\rest\dist\index.js:1307:22)
    at async ChatInputCommandInteraction.showModal (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:399:22)
    at async Object.execute (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\commands\Moderation\open-case.js:72:9)
    at async validateAndExecute (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\utils\Handlers\InteractionHandler.js:377:17)
    at async Client.handleInteraction (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\utils\Handlers\InteractionHandler.js:428:21) {
  requestBody: { files: undefined, json: { type: 9, data: [Object] } },
  rawError: {
    message: 'Invalid Form Body',
    code: 50035,
    errors: { data: [Object] }
  },
  code: 50035,
  status: 400,
  method: 'POST',
  url: 'https://discord.com/api/v10/interactions/1428896635450167449/aW50ZXJhY3Rpb246MTQyODg5NjYzNTQ1MDE2NzQ0OTpYUHU3TzBRMTVlU0JYWVhWaVhPQUd3S1o4cXFlc0hUNGdTcFRlNmdyaDV6OENPMHN5b0JpWlhXeFhBc2dCbEt0QWlRVVVEcG45bHJabU5pMUt5bmJxcTNyWjh0ZnN2NjVCTldHYmJrM21BTVY0Y1UxQjB2UVlQRXJiQ1pSNktwRw/callback?with_response=false'
}
bleak owl

well i guess i havent learned how the new modal components work haha. look at the error

limpid pecan

Does anyone know when discord.js will be updated?

crimson gale

regarding what?

releases happen when we need to fix bugs or cover new features

toxic moat

How can i make post in a forms channel with the bot?

sharp ginkgoBOT

documentation suggestion for @toxic moat:
method GuildForumThreadManager#create() discord.js@14.23.2
Creates a new thread in the channel.


// Create a new forum post
forum.threads
  .create({
    name: 'Food Talk',
    autoArchiveDuration: ThreadAutoArchiveDuration.OneHour,
    message: {
     content: 'Discuss your favorite food!',
    },
    reason: 'Needed a separate thread for food',
  })
  .then(threadChannel => console.log(threadChannel))
  .catch(console.error);

thin pagoda

hi can i ask a doubt could i can make a modal that just shows only text? without any of the box or things?

toxic moat

Code
Error:

[02:47:59] [Error   ] Component execution error: interaction.fields.getUserSelectMenuValues is not a function
[02:47:59] [Error   ] Command Error esfrmmve7zo:
[02:47:59] [Error   ] Error Details: (No Detail available)
clear garnet
toxic moat
clear garnet

No, I'm asking who/what told you that that's the name of the method you'd use

sharp ginkgoBOT
clear garnet

Well, not sure where it got that from, but this is the actual method name

topaz bluff

im guessing they are talking about copilot

toxic moat

Yeah

topaz bluff

do not blindly listen to copilot...it does not have real time access to the djs documentation...actually read the docs before trying to do something

toxic moat

Like this

getSelectedChannels<Type? extends ChannelType = ChannelType>(customId: stringrequired: true = falsechannelTypes?: readonly Type[] = []) : ReadonlyCollection<Snowflake, Extract<NonNullable<CommandInteractionOption<Cached>['channel']>, { type: Type extends ChannelType.AnnouncementThread | ChannelType.PublicThread ? ChannelType.AnnouncementThread | ChannelType.PublicThread : Type; }>>

What means

<Type? extends ChannelType = ChannelType>(customId: stringrequired: true = falsechannelTypes?: readonly Type[] = []) : ReadonlyCollection<Snowflake, Extract<NonNullable<CommandInteractionOption<Cached>['channel']>, { type: Type extends ChannelType.AnnouncementThread | ChannelType.PublicThread ? ChannelType.AnnouncementThread | ChannelType.PublicThread : Type; }>>
loud quartz

look at properties

not raw types

spice wyvern

hey guys, any documentation on how to use the new modal components? Specifically file upload?

wary coral
spice wyvern
topaz bluff
spice wyvern
topaz bluff
spice wyvern

check the date...that was before file upload was announced

spice wyvern

rip thats a shame

ok thanks guys, I'll wait for the good news then

toxic moat
limpid pecan
polar karma

And it will be

loud quartz
toxic moat

Error:

Error saving new case to database: TypeError: Cannot read properties of undefined (reading 'id')
    at Object.execute (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\components\modals\open-case.js:19:26)
    at Client.handleInteraction (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\utils\Handlers\InteractionHandler.js:453:41)
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5)

Code:

const user = interaction.fields.getSelectedUsers('select-user')[0];
        const category = interaction.fields.getStringSelectValues('case-category')[0];
        const reason = interaction.fields.getTextInputValue('case-reason');

Im getting the category and the reason but the user is undefined like you can see in the err

loud quartz

Collection is not an Array

toxic moat
sharp ginkgoBOT
toxic moat
loud quartz

and how are you getting it

topaz bluff

did you update your code?

toxic moat
topaz bluff

so what is it now?

toxic moat
topaz bluff

as a value or a method?

toxic moat

im getting <@1187167862448717967 >

How can i clean it

loud quartz

that doesn't look like what you're getting

but what you're making it to be

how are you using this variable

because that is not an id

toxic moat
loud quartz

that does not return what you says it does

so this is not the line of code that is using it

toxic moat

console.log(`Selected User ID: ${user}`); this line prints this

and here

 const newCase = new Case({
            userId: user,
            category: category,
            reason: reason,
            openedBy: interaction.user.id,
            openedAt: new Date(),
            caseStatus: 'Open'
        });

Ahh i need put .id after user

topaz bluff

yes...because user is an object

toxic moat

Ohh

sharp ginkgoBOT
toxic moat
topaz bluff

we were all there at some point

toxic moat

Error:

[03:57:02] [Error   ] Command Error xpp01ilsw8:
[03:57:02] [Error   ] Error Details:```

Code:
https://srcb.in/qGGke5xko7
sharp ginkgoBOT
  • ReferenceError: "x" is not defined: learn more
  • TypeError: Cannot read properties of undefined/null (reading "x"): learn more
topaz bluff

you have a section with 6 textDisplay's...you are only allowed to have a maximum of 3

you should instead combine these into a single textDisplay

rose tangle

(that's not the cause of the error but it will cause that issue if you fix the current one, read Jo's reply for your actual issue)

toxic moat
rose tangle

yeah

on your line 57 you're using a variable called textDisplay but there's no such variable

looks like you forgot to wrap it on a callback like you did on the others, (textDisplay) => ...

or like Samtino said, just merge all your subsequent text displays into one

toxic moat

Yeah i sow it now thanks for the help guys

toxic moat

How can i get the Link from the thread im creating here

forum.threads
        .create({
            name: `Case - ${user.username} (${newCase.caseId})`,
            message: {
                components: [forumContainer],
                flags: MessageFlags.IsComponentsV2,
            },
            reason: `Moderation Case Opened - Case ID: ${newCase.caseId}`,
            
        })
        .catch(console.error);
topaz bluff

Do you need a link or are you just trying to send a mention like this #djs-help-v14

toxic moat

It should look like this

sharp ginkgoBOT
toxic moat

no theards

Nop it wrong

topaz bluff

A forum post is a thread

clear garnet

create() returns a Promise that resolves to the thread channel that was created

So you need to get that resolved value to access the url property from it

toxic moat
clear garnet `create()` returns a Promise that resolves to the thread channel that was create...

When i do .then(threadChannel => console.log(threadChannel)) afther i created the theard i get this

<ref *2> ThreadChannel {
  type: 11,
  guild: <ref *1> Guild {
    id: '1428234467272687641',
    name: 'Mein Test Bot server',
    icon: '5eb9ccb7dcedc66c152721e5d120ee35',
    features: [],
    commands: GuildApplicationCommandManager {
      permissions: [ApplicationCommandPermissionsManager],
      guild: [Circular *1]
    },
    ```

And more...

clear garnet

Yes, that's the ThreadChannel data for the thread you just created

sharp ginkgoBOT
toxic moat

I have it now

Thx @clear garnet and @topaz bluff.

jagged rock

any way to stop this error message from cropping up

DiscordAPIError[50027]: Invalid Webhook Token

stable sun
fervent osprey

Is there any way to detect new member is pending for enter..?

I read the docs and found Events.GuildMemberAvailable but I think its not working

sharp ginkgoBOT
proud arrow

If this is changed, it'll will fire member update event

chrome chasm

what are the possible reasons to get an Unknown Interaction error on ModalSubmitInteraction.reply?

sharp ginkgoBOT

tag suggestion for @chrome chasm:
Common causes of DiscordAPIError[10062]: Unknown interaction:

  • Initial response took more than 3 seconds ➞ defer the response *.
  • Wrong interaction object inside a collector.
  • Two processes handling the same command (the first consumes the interaction, so it won't be valid for the other instance)
    * Note: you cannot defer modal or autocomplete value responses

Common causes of DiscordAPIError[10062]: Unknown interaction:

  • Initial response took more than 3 seconds ➞ defer the response *.
  • Wrong interaction object inside a collector.
  • Two processes handling the same command (the first consumes the interaction, so it won't be valid for the other instance)
    * Note: you cannot defer modal or autocomplete value responses
topaz bluff

Oops can't delete it...guess you get it twice

proud arrow

Oh wait that's gone

Nvm then

topaz bluff

OMEGAlul

swift jewel

is guide not updated with latest changes to modal things like select menu things and input changes ?

because TextInputBuilder marked deprecated and guide still shows old method

topaz bluff

That's only a generic error message. What's the actual error message in your terminal?

chrome chasm

TypeError: Cannot read properties of undefined (reading 'getSelectedUsers')

and yes I am using modal collectors, and also waited for 5 minutes

sharp ginkgoBOT
  • ReferenceError: "x" is not defined: learn more
  • TypeError: Cannot read properties of undefined/null (reading "x"): learn more
chrome chasm

well I did not mean that, I don't need the error ephemeral come in if the 5 minutes expired
my modal collector is set to expire after 5 minutes
getSelectedUsers is undefined because I did not type in anything in the user bar for 5 minutes

topaz bluff

Ohhhh I see

You don't want the second message sent at all... unfortunately I haven't worked with collectors very much or for a long time. You should share a snippet of your code and someone who knows more than me can help from there

chrome chasm
// previous code
const report = await interaction.awaitModalSubmit({ filter: i => i.user.id === interaction.user.id && i.customId === 'report', time: 300000 }).catch(async(err) => {
            console.error(err)
            return interaction.followUp({ content: 'There was an error while recieving this modal or the modal timer of 5 minutes has expired.', flags: MessageFlags.Ephemeral });
        });
        if (report) {
            const user = report.fields.getSelectedUsers('user').first()
            const reason = report.fields.getTextInputValue('reason')
// ...```
rose tangle

well you don't want to return something in that catch

or at least not something truthy, like an interaction response (the followUp)

your if (report) will always be true

since that awaitModalSubmit can either fail or succeed, if it succeeds it returns the interaction, if it doesn't it returns the followUp message (since you're returning it on your catch)

both possible results are truthy when evaluated in an if()

meager meadow

I want to edit the message, but I want to indicate that this is a v2 component, but TypeScript complains.

message.edit({ content: null, components: [container], flags: MessageFlags.IsComponentsV2 });

(property) MessageEditOptions.flags?: BitFieldResolvable<"SuppressEmbeds", MessageFlags.SuppressEmbeds> | undefined

However, if I // @ts-ignore, everything works fine.

But if I don't set any flags at all, the API returns an error that the body is invalid.

stable sun

You either have mismatching d.js and discord-api-types versions or you have a faulty d.js installation

What’s ur d.js version? npm ls discord.js

meager meadow
steel bronze

Have discord.js added support for components v2? if so how would I use it?

sharp ginkgoBOT

guide Display Components
While you might be familiar with embeds in Discord, there are more ways to style and format your apps messages using display components, a comprehensive set of layout and content elements. To use the display components, you need to pass the IsComponentsV2 message flag (in docs: MessageFlags) when sending a message. You only need to use this flag when sending a message using the display components system, not when deferring interaction responses.
read more

brittle current

What is limit in new modal components

eternal harness

Is there a documentation about the new update for modals? (select menus)

proud arrow
proud arrow
brittle current
umbral mulch

do components v2 use the standard 2000 character message length limit or is it changed?

proud arrow
balmy kraken

this is the selection menu (this.selector_pages[this.selector_page_index]) im trying to pass to the components_row below

  data: {
    type: 3,
    custom_id: 'empty_selector',
    placeholder: 'You dont have any accounts yet!',
    disabled: true
  },
  options: []
}```

`this.components_row = [this.selector_pages[this.selector_page_index]]`

```DiscordAPIError[50035]: Invalid Form Body
components[1][UNION_TYPE_CHOICES]: Value of field "type" must be one of (1, 9, 10, 12, 13, 14, 17).```

why wont it accept it? Its literally the selector row, I made sure 20 times
balmy kraken

i tried adding options and it results in the same error

this is how i create the row

return new StringSelectMenuBuilder()
.setCustomId("empty_selector")
.setPlaceholder("You dont have any accounts yet!")
.setDisabled(true)
.addOptions(
new StringSelectMenuOptionBuilder().setLabel("None").setValue("null"))
proud arrow
balmy kraken

yeah nvm i fforgot the action row

tough prairie

With the new file upload support for modals incoming, how will the uploads handle e.g. image quality?

Afaik Discord compresses images that you send in channels, lowering the quality. Will the same be true for the upload feature?

proud arrow
tough prairie

Cheers!

limpid pecan

Is there a list somewhere of all the components that can be used in a modal?

polar karma

Should keep in mind that the file input is not supported by the library yet

toxic moat

can you upload files in modal with js?

proud arrow

If you mean can you use the new file upload component with d.js, then no. Not yet

toxic moat

Alright, thx bro

proud shoal

For some unexplainable reason, my periods get put on a new line when I put a linebreak after my option descriptions. And there is no further code, but the final period at the end does get displayed properly
Section responsible for the output:

commands.sortBy((cmd) => cmd.slash.toJSON().name)
    .filter((cmd) => cmd.help.category === HelpCategory.Relays)
    .forEach((cmd) => {
      container.addTextDisplayComponents(
        textdisplay => textdisplay.setContent(`### ${cmd.slash.toJSON().name}`),
        textdisplay => textdisplay.setContent(`${localeText(cmd.help.description, undefined)}`),
        textdisplay => textdisplay.setContent(`>>> ${cmd.slash.toJSON().options!.map((opt) => `${chatInputApplicationCommandMention(getSlashCommmandId(cmd.slash.toJSON().name), cmd.slash.toJSON().name, opt.name)} ${opt.description}\n`)}`),
      ).addSeparatorComponents(
        new SeparatorBuilder().setSpacing(SeparatorSpacingSize.Small).setDivider(false)
      )
    })
steel trail

You map your options and then put that array into template literal. So it'll get stringified by adding , between the elements

You'd want to explicitly .join('\n') it instead I guess

proud shoal

Yeah, that worked. thanks.

balmy kraken

is there a way to update specific elements of a interactions message? Upon my button being pressed i only want to change a specific button and not regenerate the whole row

wary coral
unreal stone

Hi! I have a quick question. How I can "reset to default" after using the editMe() commands ?

bleak owl

what do you mean reset to default?

like clear the text?

unreal stone

Revert the avatar, bannière, bio, surname…

bleak owl

revert it to what?

unreal stone

Well, the default avatar/bio/etc of the bot ?

The one configured in the panel!

bleak owl

pretty sure you can just set it to null, but i could be wrong

silent mirage

for emojis on bots application do i just put in embed description :loading:

it has id but keeps on going as :loading:

bleak owl

its the same format as every other custom emoji

there's a copy markdown button on the dev portal

hybrid spear

How can we use the ephemeral option now?

sharp ginkgoBOT

The ephemeral option when replying to an interaction will be removed in v15

- {..., ephemeral: true}
+ {..., flags: MessageFlags.Ephemeral}
``` Read [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_OR) on how to specify multiple flags
silent mirage

i did that and put it in here ```export const LOADING_EMOJI = ":loading:";

keeeps on switching in markdown to loading when i put id

bleak owl

no

hybrid spear
bleak owl

you have to define it

import it from discord.js

hybrid spear
silent mirage

no itd <a:loading:id> that is how i have it this is how i have it in my file

hybrid spear

Oh lmao

tardy sable
sharp ginkgoBOT
wary coral

sorry that is the wrong thing

main axle

Hi, if a member isn't cached and their roles has been changed and GuildMember partial and intents are enabled does guildMemberUpdate event will start working?

little pebble
sharp ginkgoBOT
wary coral
hybrid spear
silent mirage

I got it working

Thank you so much

cosmic burrow

DiscordAPIError[50035]: Invalid Form Body
data.embeds[0][LIST_ITEM_VALUE_REQUIRED]: List item values of ModelType are required
at handleErrors (C:\Users\timpu\OneDrive\Dev Projects\NovaEagle Bot\node_modules@discordjs\rest\dist\index.js:762:13)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
at async BurstHandler.runRequest (C:\Users\timpu\OneDrive\Dev Projects\NovaEagle Bot\node_modules@discordjs\rest\dist\index.js:866:23)
at async _REST.request (C:\Users\timpu\OneDrive\Dev Projects\NovaEagle Bot\node_modules@discordjs\rest\dist\index.js:1307:22)
at async ChatInputCommandInteraction.reply (C:\Users\timpu\OneDrive\Dev Projects\NovaEagle Bot\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:193:22)
at async Object.execute (C:\Users\timpu\OneDrive\Dev Projects\NovaEagle Bot\commands\flight management\create-flight.js:55:9)
at async Object.execute (C:\Users\timpu\OneDrive\Dev Projects\NovaEagle Bot\events\interactionCreate.js:16:4) {
requestBody: { files: [], json: { type: 4, data: [Object] } },
rawError: {
message: 'Invalid Form Body',
code: 50035,
errors: { data: [Object] }
},
code: 50035,
status: 400,
method: 'POST',
url: 'https://discord.com/api/v10/interactions/1429172931447099604/aW50ZXJhY3Rpb246MTQyOTE3MjkzMTQ0NzA5OTYwNDpVRXFQSHVLMkxXZURWU0t6enU0RHAza2c5QU1Hd1JzdXRkYWlpa1k4cENCbjJwUXZOZzV4REo2NWZCaVIxckl1NHJoM1hNc3J1b2VmVENIZ1lodUpucFV2T2ZtOUdDZnE0OGdEWjhmVTVYZVlVS3VuZVZIb0UyOVVjT2taaVdCVw/callback?with_response=false'
}

why im receiving the error when i tried to run /create-flight

wary coral
cosmic burrow

i'm using embeds

wary coral

I am sorry I misread model as modal lol.
All the same if you could share your code

cosmic burrow
wary coral

Otherwise I at a cursor glance. It looks good otherwise

cosmic burrow

ok

balmy kraken

Is it possible to create public buttons ie, so that every user can see and press them and only see results for themselves?

Im assuming we'd have to listen for interactions on some message, and then call interaction reply with ephemeral on?

topaz bluff

buttons emit an interactionCreate event...you handle them just as any other interaction (aka, slash commands)

balmy kraken

But wont different users see the buttons being pressed by others on that message? Or is that pressing animation rendered clientside?

stable sun

It’s client sided

balmy kraken

will the bot be able to reply to the interactions message with ephemeral status even if it doesnt have permissions to post to the channel the message is on?

topaz bluff

i think so but you should test it

proud arrow

Yes, as long as user have permissions to use application commands in that channel, it should work

rigid crest

im getting this error on modal, but no console errors im really confused, i have never had a errorless error on modal so I'm not sure where im erroring

unique shoal

This error happens when discord doesn't receive a response to the ModalSubmitInteraction

But we can't tell you anything about why from that alone

rigid crest
wary coral
rigid crest

ok ive tweaked a bit and stuck in a endless thinking loop waiting for it to timeout if it will time out

wary coral

how did you tweek it?

red coral

Hey I'm trying to debug a missing permissions error but not too sure why im getting it...

I'm sending a message with:

  • an embed
  • a reply
  • pinging a role
    json: {
      content: '',
      tts: false,
      nonce: '',
      enforce_nonce: true,
      embeds: [
        {
          description: '...',
          color: 16448000
        },
        [length]: 1
      ],
      components: undefined,
      username: undefined,
      avatar_url: undefined,
      allowed_mentions: { parse: [ 'roles', [length]: 1 ] },
      flags: undefined,
      message_reference: { message_id: '...', fail_if_not_exists: false },
      attachments: undefined,
      sticker_ids: undefined,
      thread_name: undefined,
      applied_tags: undefined,
      poll: undefined
    }

Doing client.channels.cache.get("...").permissionsFor(client.user).serialize() I get:

{
  CreateInstantInvite: true,
  KickMembers: false,
  BanMembers: false,
  Administrator: false,
  ManageChannels: false,
  ManageGuild: false,
  AddReactions: true,
  ViewAuditLog: false,
  PrioritySpeaker: false,
  Stream: true,
  ViewChannel: true,
  SendMessages: true,
  SendTTSMessages: false,
  ManageMessages: false,
  EmbedLinks: false,
  AttachFiles: true,
  ReadMessageHistory: true,
  MentionEveryone: false,
  UseExternalEmojis: true,
  ViewGuildInsights: false,
  Connect: true,
  Speak: true,
  MuteMembers: false,
  DeafenMembers: false,
  MoveMembers: false,
  UseVAD: true,
  ChangeNickname: true,
  ManageNicknames: false,
  ManageRoles: false,
  ManageWebhooks: false,
  ManageEmojisAndStickers: false,
  ManageGuildExpressions: false,
  UseApplicationCommands: false,
  RequestToSpeak: true,
  ManageEvents: false,
  ManageThreads: false,
  CreatePublicThreads: false,
  CreatePrivateThreads: false,
  UseExternalStickers: true,
  SendMessagesInThreads: true,
  UseEmbeddedActivities: true,
  ModerateMembers: false,
  ViewCreatorMonetizationAnalytics: false,
  UseSoundboard: false,
  CreateGuildExpressions: false,
  CreateEvents: false,
  UseExternalSounds: true,
  SendVoiceMessages: false,
  SendPolls: true,
  UseExternalApps: true,
  PinMessages: false
}

I can't see anything im missing...

wary coral
red coral

A message

[
  'KickMembers',
  'BanMembers',
  'Administrator',
  'ManageChannels',
  'ManageGuild',
  'ViewAuditLog',
  'PrioritySpeaker',
  'SendTTSMessages',
  'ManageMessages',
  'EmbedLinks',
  'MentionEveryone',
  'ViewGuildInsights',
  'MuteMembers',
  'DeafenMembers',
  'MoveMembers',
  'ManageNicknames',
  'ManageRoles',
  'ManageWebhooks',
  'ManageEmojisAndStickers',
  'ManageGuildExpressions',
  'UseApplicationCommands',
  'ManageEvents',
  'ManageThreads',
  'CreatePublicThreads',
  'CreatePrivateThreads',
  'ModerateMembers',
  'ViewCreatorMonetizationAnalytics',
  'UseSoundboard',
  'CreateGuildExpressions',
  'CreateEvents',
  'SendVoiceMessages',
  'PinMessages'
]

These are the ones im missing

wary coral

and in the reply you mention a role?

red coral

content: '', wait no i dont even do that, the content is empty, thought i was

wary coral

so what is the issue then?

red coral

https://sourceb.in/mTj6x1dVgo this is the full error. But as i said i get this, but not too sure why. I also check for permissions before i send

Unless it's possible the people using my bot changed permissions and that was a one off, but i check for these permissions before sending:

return channel.permissionsFor(me)
                .has([
                    PermissionFlagsBits.SendMessages,
                    PermissionFlagsBits.ViewChannel,
                    PermissionFlagsBits.ReadMessageHistory
                ])

for i need anymore?

wary coral

only SendMessages should be need to send the reply
and use embeds for the embed

red coral

And read message history since its a reply, embeds?

wary coral
red coral

yh but to reply to a message you need the read message history permission no? Idk wym

Yh i recieve a message then reply to it in layman's terms

wary coral

if the bot saw the message create event it has ViewChannel and it is in the history it can see. I will run some tests to validate

red coral

At the very top of my function i do

            const me = await message.guild.members.fetchMe();
            if (!checkPermissions(message.channel, 
                return;
            }

Which runs:

export function checkPermissions(channel, me, type = "drop") {
    switch (type) {
        case "star": {
           ...
        }
        default: {
            return channel.permissionsFor(me)
                .has([
                PermissionFlagsBits.SendMessages,
                PermissionFlagsBits.ViewChannel,
                PermissionFlagsBits.ReadMessageHistory
            ]);
        }
    }
}

Unless ive done something wrong i can't see why i would get missing permissions since i check for all of the ones i believe are required

wary coral

I think you need to check for EmbedLink as well

red coral

What does that permission do? Is this for like putting a thumbnail or literally putting a link in the description for example

loud quartz

for sending a link, having that permission will make discord grab and embed potential data from it

red coral

Links sent by users with this permission will be auto-embedded
yh just grabbed it

loud quartz

for sending an embed directly, well.. should be self-explanatory

red coral

So I don't need it?

loud quartz

for what?

red coral

just sending embeds, im not sending links so i dont need that one

loud quartz

you do

loud quartz

you don't have content that could potentially embed based on the permission

you're sending an embed directly

red coral

Maybe im just not understanding the docs wording,

Links sent by users with this permission will be auto-embedded
To me talks about links like https://...

loud quartz

and i'm not talking about links

i'm talkign about embeds

a link might happen to embed

for a message to have an embed it needs to have permission to

embed can come from a link, or can be sent directly

both require the permission

you're sending one directly, so dont' look at links

red coral

Ok... I think i get what you mean. Let me add that to my check as well, thanks I appreciate it

loud quartz

might also try to bridge the gap with a different thing

you know how embed has types? the deprecated one, like rich or video or image or whatever else it had

this embed there from that link is of rich type

in v11 the embeds were called RichEmbeds

red coral

I think my issue is from the wording from the docs, I'm seeing Links and thinking of those. I get you now, but from that it didn't make it super clear i need that one to send straight embeds. But I know now

loud quartz

yeah that's a bit hidden from direct view

red coral

As to me at least, a link is a link an embed is an embed, needing EmbedLinks to send an embed is weird, you would think you need that if you want discord to embed a link for you... but now i know i need that for embed sending so it's all good

Thanks however, I appreciate it

loud quartz

i suppose calling it "embedding content" could have been more about both, but then that leaves a big "what is the content" for everyone who isn't a bot dev

red coral

Or just changing the description in the docs would be cool

wary coral
red coral

Ahhhhh that makes sense. When you say the embed is blocked, will the embed just not display?

wary coral

correct

from my testing. same message only differance is perms at time of send

red coral

is the second one doing both content and embeds but without the embedlinks permission?

wary coral
red coral

ahhh i see, thanks a lot

wary coral

@red coral as a side note you should try componentsV2. I dont believe it has this problem and your embed could be esaly converted to a text display in a container

red coral

Hmm... that's very true actually. Do you need that permission for v2?

wary coral

no only sendMessage

red coral

and im guessing thats because it's not an embed they are components?

wary coral
red coral

oh yh i can make them just fine, ive used them elsewhere. Icl, Imma move to them since it'll be a bit easier to just not require that permission. Don't want people complaining stuff doesnt work, dont wanna tell ~400 people to reinvite my bot lol. Thanks

wary coral

for sure

orchid radish

is there an event for expire/removal of a server boost? i believe there is one for an addition of a boost but i am unsure

wary coral
orchid radish

does update member include any information on boost status and is it triggered on addition/removal of boosts?

wary coral

Only that the roll was removed. Which you'd have to check for the roles being different

plush charm

Hi has modal file upload been added to yet?

plush charm
lofty topaz

Hello

Has anyone heard about the new file upload feature in Model?

Can I get a example code about it?

bleak owl

discord.js does not support it yet at this time

lofty topaz
clever vigil

are there any example codes about the dropdowns/labels? if that's supported

topaz bluff

yes SelectMenus and Labels are supported, but the guide has not been updated yet for the new Modal components

clever vigil

alr thanks, ill figure it out

topaz bluff

You can check the docs for the new ModalBuilder methods and you can retrieve the info with ModalSubmitFields which comes from interaction.fields

clever vigil

pog thank you

plush charm
clever vigil

:O appreciate you both!

topaz bluff

oh ya that exists too for building the modal itself

steep siren

Is there any way for me to upload emojis to the bot using Discord.js, without going through Discord Developers?

sharp ginkgoBOT
tardy sable

yes you can upload emojis through bot, think thats the doc for it

steep siren
toxic moat

How can i make a event that reads all messages in all theards in a forum channel and if sombody send a message it will be forwarded to the dms

loud quartz

that sounds like a weird thing to want

toxic moat

So when a staff sends a Message in the theard the bot finds the caseid for this theard so he can send the message to the user

With messagecreate should it work

topaz bluff

yes, you would just do that in your "messageCreate" event

topaz bluff

you should NOT be fetching the content of a channel, rather reacting to the creation of new messages

thin pagoda

Hi some one could give me a small example for making a box in modal?

i mean in new modal

thin pagoda
thin pagoda
balmy kraken

.

toxic moat

Error:

Error in readCases event: TypeError: Cannot read properties of undefined (reading 'bot')
    at Object.execute (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\events\AUTO\readCases.js:23:32)
    at Client.<anonymous> (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\utils\Loaders\EventLoader.js:41:76)
    at Client.emit (node:events:530:35)
    at MessageCreateAction.handle (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\discord.js\src\client\actions\MessageCreate.js:32:14)
    at module.exports [as MESSAGE_CREATE] (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
    at WebSocketManager.handlePacket (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\discord.js\src\client\websocket\WebSocketManager.js:352:31)
    at WebSocketManager.<anonymous> (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\discord.js\src\client\websocket\WebSocketManager.js:236:12)
    at WebSocketManager.emit (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@vladfrangu\async_event_emitter\dist\index.cjs:2504:31)   
    at WebSocketShard.<anonymous> (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\ws\dist\index.js:1190:51)
    at WebSocketShard.emit (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@vladfrangu\async_event_emitter\dist\index.cjs:2504:31)

Code:

async execute(client, message) {
        try {
            if (message.author.bot) return;
.....
tardy sable

can also add safe chaining
if (message.author?.bot) return;

toxic moat
tardy sable
toxic moat

alright

loud quartz

message create should never really be a partial

little pebble

I think message is just not an instance of Message

sharp ginkgoBOT

The order of function parameters must match between definition and function call.

function execute(client, interaction) { ... };
execute(interaction, client);
  • mismatch! you pass an interaction where the client is expected
  • mismatch! you pass the client where an interaction is expected
loud quartz

^ partials would leave a bunch of nulls around at best, not undefineds

toxic moat
tardy sable

did the safe chaining work?

toxic moat
loud quartz

message.author should not be an undefined

so digging for partial doesn't sound like a valid fix

tardy sable

also i just use client.on events so idk about exporting events

tardy sable
little pebble
toxic moat
toxic moat
toxic moat

Idk what the probelm was

tardy sable

that wouldnt change anything

toxic moat
balmy kraken

how can i tell if this has errored for time? .catch() and try/catch dont collect it

                const user_answer = await channel.awaitMessages({
                    filter: (m) => m.author.id === user.id,
                    max: 1,
                    time: 1000,
                    errors: ["time"],
                })```
bleak owl

pretty sure that will only show with a message collector, not the promise based one

toxic moat
bleak owl

you don’t use embeds in that code

toxic moat

But do you know why

wary coral
toxic moat
topaz bluff

I'm also confused on the question. Is the message being sent more than once? (5 times in your question)

Because double messages implies that your bot is running on several processes

toxic moat

our close vscode

topaz bluff

Do you have several terminals open in VSCode?

topaz bluff
toxic moat So should i turn of my pc

Well I can't say for certain if it will fix the issue. But it's worth a shot

That or you can just check to see if there's any node processes in Task Manager. But restarting will gaurentee that there aren't

toxic moat
toxic moat
stable sun
drifting zealot

So I have onboarding in my server, and I want it so that my bot welcomes the new members after the user has completed all of the onboarding questions. How can I do this?

sharp ginkgoBOT
drifting zealot

Thx

solemn arch
wary coral
solemn arch
loud quartz

send less messages

solemn arch
loud quartz

idk what else you want

you're the one that grabs a list of ids and then sends a message for each of it

wary coral
loud quartz

however many there are things in an embed they fetch

solemn arch
wary coral

How often does that need to be done?

solemn arch
loud quartz

this server got <1300 messages in total during entire past 24 hours, and that's counting channels you can't even see

and you're just looping over that in single command

solemn arch
wary coral
loud quartz

that doesn't even add up

solemn arch
loud quartz

2000 messages is still more than half an hour of one message every second

you really might want to rethink this

solemn arch
loud quartz

yeah, which is where there should ring a bell that maybe this is really not working out

idk, build a website for this

there you can send messages however fast you want

and however many

rose tangle

the only solution for ratelimits is quite literally just not reaching them, you'll have to rethink how you're approaching this entirely

solemn arch
loud quartz

yes

or not do it via discord

solemn arch

Thanks for the help.

wary coral
solemn arch Thanks for the help.

Out of curiosity, what's your user interaction goal of the lists that you maintain? Cuz I feel like the answer is to just store it all in a database and then use interactions for users to request the most up-to-dated version of the list

solemn arch
wary coral

I feel like the answer then is to have a command that staff can use that gets them the current list of pending items

solemn arch

I think I have came up with a idea that can fix my problem.

Are there any rate-limits on reactions to messages or embeds?

wary coral
loud quartz

there are ratelimits on everything

and embeds aren't standalones, they are part of messages

solemn arch
wary coral
solemn arch

Then the staff reacts with one to make the decision.

loud quartz

instead of immediately ratelimiting yourself to hell and back by having to react 3 times to every message, why not just use buttons

solemn arch

ok

wary coral
solemn arch ok

When a user does a command or uses a button? The interaction it creates has individual rate limits for each time a user interacts with it

still fulcrum
loud quartz

the initial responding to an interaction has no ratelimit (so only once per interaction)

solemn arch
loud quartz

everything else still has it

visual flame

Is it possible to make a select menu autocomplete like slash command options

wary coral
balmy kraken

can i somehow detect whether an ephemeral interaction.reply() has been closed?

wary coral
balmy kraken

i was wondering how does that affect the listeners mounted on the ephemeral message

since the message cannot return anything anymore i thought it would be useful to detect when its closed and clean up

wary coral

Yeah, there's no way to tell if the user closes an ephemeral message. It exists entirely on the users client

rose tangle

a timer after the last interaction is usually the best

if you editReply or deleteReply a deleted ephemeral message it'll just fail silently, won't throw on your side

gleaming badger

whats the difference between setId and setCustomId for TextInputBuilder()?

rose tangle

one sets the id, other the custom_id

only interactable components have custom_id, all components have an id

gleaming badger
rose tangle

differ components from each other

basically the same purpose as the customId

gleaming badger

oh I see
thanks

do I have to do a .setMaxValues() if I have a .setMinValues()? This seems rather strange

rose tangle

are you getting an error?

gleaming badger

data.components[1].component.min_values[NUMBER_TYPE_MAX]: Int value should be less than or equal to 1.

this happens when I do .setMinValues(2) without .setMaxValues(). If I have .setMaxValues(), the error goes away

rose tangle

I think it's because it defaults to 1

sharp ginkgoBOT

discord Component Reference - String Select
A String Select is an interactive component that allows users to select one or more provided options. String Selects can be configured for both single-select and multi-select behavior. When a user finishes making their choice(s) your app receives an interaction. String Selects are available in messages and modals. They must be placed inside an Action Row in messages and a Label in modals.
read more

rose tangle

max_values? integer Maximum number of items that can be chosen (defaults to 1); max 25

gleaming badger

oh I see, tyty

one more question... how do I show a modal if I already deferred the interaction?

rose tangle

you can't

you'll need another interaction, so you could show a button that opens the modal immediately

gleaming badger

ah

rose tangle

but you can't open it with that deferred interaction

gleaming badger

ty a lot

viral cave

Hello! This error just appeared suddenly, I don't understand..

  default_values: import_shapeshift4.s.object({ id: import_shapeshift4.s.string(), type: import_shapeshift4.s.literal(import_v1010.SelectMenuDefaultValueType.Channel) }).array().lengthLessThanOrEqual(25).optional()
                                                                                                                                                              ^

TypeError: Cannot read properties of undefined (reading 'Channel')
    at Object.<anonymous> (C:\Users\sabu\Documents\bot protect\node_modules\@discordjs\builders\dist\index.js:1455:159)
    at Module._compile (node:internal/modules/cjs/loader:1376:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
    at Module.load (node:internal/modules/cjs/loader:1207:32)
    at Module._load (node:internal/modules/cjs/loader:1023:12)
    at Module.require (node:internal/modules/cjs/loader:1235:19)
    at require (node:internal/modules/helpers:176:18)
    at Object.<anonymous> (C:\Users\sabu\Documents\bot protect\node_modules\discord.js\src\structures\Embed.js:3:25)     
    at Module._compile (node:internal/modules/cjs/loader:1376:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)

Node.js v20.11.1```
stable sun
viral cave
stable sun

Can you show ur package.json file?

viral cave
    "name": "discordjs-v14-template-ts",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
        "start": "cls && node build/index.js",
        "build": "cls && node build.js"
    },
    "keywords": [],
    "author": "MericcaN41",
    "license": "ISC",
    "dependencies": {
        "@discordjs/rest": "^1.1.0",
        "@types/node": "^18.7.14",
        "chalk": "^4.1.2",
        "discord.js": "14.3.0",
        "distube": "^5.0.7",
        "dotenv": "^16.0.2",
        "mongoose": "^6.5.4"
    },
    "devDependencies": {
        "typescript": "^4.8.2"
    },
    "overrides": {
        "discord-api-types": "0.37.20"
    }
}
stable sun

Can you remove the -types override?

Prob not a good idea to tie it down to an old version

Ig ur d.js version is tied down too

viral cave
stable sun

Latest is v14.23.2

Oh, for -types

-types latest stable is at v0.38.30

novel mauve

if i already have no intents selected and the bot is only replying to interactions with hardcoded info, are there other elements i can disable the cache for that might reduce the memory usage even further?

stable sun
novel mauve

none really, it's just a wiki bot that gets info from a json file

stable sun

If ur not using guilds intent, consider a lighter library that handles interactions via webhooks calls

Then definitely do that

D.js is overkill for your use case

novel mauve

forgot to say the bot also sets a presence so it needs the gateway, that's why i used djs for it and i believe webhook interactions don't let you set a presence?

stable sun

That’s correct

novel mauve

so no intents is the max i can do for djs

it's not an issue tbh i was just curious

stable sun

Maybe just use @discordjs/ws

novel mauve

is there a guide for this? i haven't used that yet

stable sun

No

There’s always tests and docs

I think WebsocketShard is pretty straightforward tho

novel mauve

would it change anything vs using the regular djs though? since i assume djs' memory footprint comes from caching stuff but in my context i don't know what there is to cache since there isn't many pass through events

stable sun

Yea

novel mauve

i thought about using makecache but i wasn't sure what to pass to it

stable sun

Prob just cache nothing

makeCache: () => new LimitedCollection({ maxSize: 0 })

Actually, need to cache the client user

novel mauve

does it break stuff if it's not cached?

thanks for that snippet tho

stable sun

Nvm, it’s no longer a getter

stable sun

I think it was fixed

Otherwise if try to use any event other than interactionCreate (after adding proper intents), it likely won’t work

shardX events should work fine too

novel mauve

dont those require sharding? or are they fired even without

steel trail

You do have one shard

rigid crest
wary coral how did you tweek it?

i fell asleep, but the changes i altered was how i fetched the option on string select, i also added logger points to ensure channel ID is valid in the database (i was getting channel not found at one stage but after changing how i fetched the option from the menu it found the channel) and yeah thats as far as i got to why it is endlessly thinking
const gameOption = interaction.fields.getStringSelectValues('game_selection_option'); ->
const gameOption = interaction.fields.getStringSelectValues('game_selection_option')[0];

robust flame

how to convert Date to discord time markdown?

Date issues numbers

async exec(channel: DJS.GuildChannel, time: Date) {
        const i18n = useI18n();
        const lang = await GuildConfig.findOne({ guildId: channel.guildId });
        try {
            const msg = `${i18n.twl(lang?.lang ?? "en", "channelpins.updated.msg", {
                channel: `${channel.name}`,
                chan: `${channel}`,
                date: `${time}`
            })}`
sharp ginkgoBOT
stable sun

@robust flame

robust flame

tysm

but i did it with moment

steel trail

That isn't discord markdown though. So that will not use the user's timezone

lost mason

i feel like ppl use this channel to steal code lol

lilac belfry
north dagger

Does it have an ETA for the file Upload?

novel mauve

no

toxic moat
rigid crest
rigid crest i fell asleep, but the changes i altered was how i fetched the option on string ...

i added console.log('\x1b[36m[Info]\x1b[0m', 'Suggestion Message Data:', message); nothing is logged to console so its not building? im now logging to ssee if container is being created

const message = await interaction.client.guilds.cache.get(interaction.guild.id).channels.cache.get(suggestionChannelID).send({
      content: null,
      embeds: [],
      components: [suggestionContainer, miscButtons], //commentButton to add back when fixed
      allowedMentions: { parse: [] },
      flags: MessageFlags.IsComponentsV2,
    });

edit: console.log('\x1b[36m[Info]\x1b[0m', 'Suggestion Container Data:', suggestionContainer); also logged nothing

toxic moat

how to stop this embed from appearing when doing message.reply

red trellis

can I send an ephemeral reply to an arbitrary message without it being the response to a slash command?

nvm u cant

proud arrow
wary coral
rigid crest
rigid crest i added `console.log('\x1b[36m[Info]\x1b[0m', 'Suggestion Message Data:', messag...

this happens after a while of thinking loop, also im still confused on where the data has ended up i can confirm its trying to build as the builder itself is registering

[Debug] Resolved channel ID for Contract Ville: [ { name: 'Channel', value: '1130141013168631968' } ]
[Debug] Resolved channel ID for Sandwich Sim: [ { name: 'Channel', value: '1130141013168631968' } ]
[Debug] Resolved channel ID for Dig Island: [ { name: 'Channel', value: '1130141013168631968' } ]
[Info] Game option selected: Channel ID: 1130141013168631968
[Debug] Resolved ContainerBuilder caller: ContainerBuilder { data: { type: 17 }, components: [] }
wary coral
rigid crest
wary coral

How so? What's not working when you try to use the modal?

rigid crest
wary coral

So upon the modal submission, you want to send a new message to the channel?
In addition to the reply to the interaction

rigid crest

yes, but ive gotten as far as knowing the container builder is registering the action then it dies and it cant be related to the collector in the main interaction as on send its on a diff runtime? i have it for around 5-6 mins const collector = initialMessage.createMessageComponentCollector({ filter, time: 360_000 }); on orignal spawn point for the modal

proud arrow

You maybe suppressing your errors somewhere. Try explicitly catching and logging errors there and see if it logs anything

rigid crest

i dont think im supressing errors, i do have these but surely they shoudlnt effect?

// Handles uncaught errors
process.on('unhandledRejection', (reason, promise) => {
  console.error('⚠️ Unhandled Promise Rejection:', reason);
  logCrashToFile('Unhandled Promise Rejection', reason);
  restartBot();
});

process.on('uncaughtException', (err) => {
  console.error('💥 Uncaught Exception:', err);
  logCrashToFile('Uncaught Exception', err);
  restartBot();
});

// Handles all exits (clean or not)
process.on('exit', (code) => {
  logCrashToFile(`Process Exit [code ${code}]`);
});

process.on('beforeExit', (code) => {
  logCrashToFile(`Before Exit Triggered [code ${code}]`);
});

// Handles termination signals
process.on('SIGINT', () => {
  console.warn('🛑 SIGINT received (Ctrl+C or shutdown)');
  logCrashToFile('SIGINT (Interrupt)');
  process.exit(0);
});

process.on('SIGTERM', () => {
  console.warn('🛑 SIGTERM received (kill or system shutdown)');
  logCrashToFile('SIGTERM (Terminate)');
  process.exit(0);
});

// Trigger restart logic
function restartBot() {
  console.log('🔄 Restarting bot...');
  process.exit(1); // Pterodactyl or PM2 should auto-restart on code 1
}

i do have .catch(console.error); on the reply for the modal interaction but not the const message itself ill see if that triggers anything there
oh yeah not sure if i mentioned
console.log('\x1b[36m[Info]\x1b[0m', 'Suggestion Container Data:', suggestionContainer); No data from this caller is logged either
this one should fire after the first check

wary coral
rigid crest yes, but ive gotten as far as knowing the container builder is registering the a...

try this code

console.log("sending message to suggestionChannelID")
const messages = interaction.guild?.channels.fetch(suggestionChannelID).then(async channel => {
  if (!channel?.isSendable()) {
    console.log("channel not sendable")
    return
  }
  const message = await channel.send({
    content: null,
    embeds: [],
    components: [suggestionContainer, miscButtons], //commentButton to add back when fixed
    allowedMentions: { parse: [] },
    flags: MessageFlags.IsComponentsV2,
  });
  console.log('\x1b[36m[Info]\x1b[0m', 'Suggestion Message Data:', message);//No data is logged
})
rigid crest

i just used this and it fired so its seen and sendable

const channel = interaction.client.guilds.cache.get(interaction.guild.id)
      .channels.cache.get(suggestionChannelID);
    await channel.send({ content: '🧪 Test message: this should fire before modal collects data.' });

wary coral

ok good to know so the next thing is checking your components. if you log them right before the message is sent. what do you get

rigid crest

could a missing builder be a cuase of no errors? it was right infornt of me as a reason? its not green like the other parts if this was the issue all along

wary coral

I am unsure. I uses TS so it would throw any error if I used a class not defined

rigid crest

yes that would of done it, why did it not error for that ugh

wary coral

glad we could help

rigid crest

appreciated, still mega confused why it never fired a reference error or wht not to say i forgot to define it

wary coral

my only thought is that you are catching the error somewhere

rigid crest
normal flare

HI, I have this bit of code

export const registerCommands = async (
  client: Client,
  commands: Map<string, Command>
): Promise<void> => {
  const commandArray = Array.from(commands.values()).map((cmd) => cmd.data);

  try {
    await client.application?.commands.set(commandArray);
    commandArray.forEach((cmd) => {
      console.log(`Registered command: ${cmd.type}, ${cmd.name}`);
    });
    console.log(`Registered ${commandArray.length} commands globally.`);
  } catch (error) {
    console.error('Error registering commands:', error);
  }
};```

which I'm calling in the `main.ts` like
```ts
const client = new Client(...)
await registerCommands(....)
client.login(token)

when the code is local and with a test clientId (test bot), everything works as expected, but when I push the code to a vps, and use another clientId, only events are working, but there's no slash commands.

steel trail

@normal flare you shouldn't deploy your commands on every start. there's a reason why we suggest the separate script using REST#put()

normal flare

I see, does that only apply for commands?

steel trail

yes, only commands. don't even need to run the deployment script on the VPS. run it locally once, and your commands will show up.

normal flare

as in, what about the events? where would I register events?

// src/index.ts
const client = new Client(...);

await registerEvents(client, events);
await registerCommands(client, commands);

void client.login(config.discord.token);```
steel trail

there are two different things you are mixing (by calling both register). one is deploying to discord, that only happens for commands. the other is adding handlers to your code; that's on your client side and not sent over the API. that needs to be done for events and commands on startup

normal flare

should I move the client.application.commands.set(..) call to ready event?

loud quartz

no

sending command metadata to discord does not need to happen every time you start your bot

discord keeps the command metadata for your app forever after you send it

or until you change/remove it

what your code does (handles incoming events, loads code for running commands poeple use) is not really a concern of discord

discord only cares about you responding within 3 seconds of the interaction

normal flare

so why did it still not show / commands?

loud quartz

well, in that one case you can run it once from your ready event

but afterwards you should move this into its separate script like our guide suggests

normal flare

I do have a script, though I thought that is not mandatory and doing application.commands.set(...) should be fine

loud quartz

both do exactly the same thing anyway

the difference is that using client.application requires that to be done from within your running bot

while the script can be ran at any given time without your bot even being online

normal flare
loud quartz

move it there once so that this code actually runs

because right now it doesn't because of the ?. in the client.application?.commands.set()

after you move it to ready, and start your bot, your commands should be registered

after that you can remove that call from the ready event

normal flare

I see, the alternative of moving it, is simply just calling the script with Rest.put right?

loud quartz

if you mean "alternative of moving it [into the ready event]", then yes

normal flare

yes

I'm still confused tho. because the script should not be mandatory pepo_cry and it said within 1 hour commands should be there, but it's been a lot more than 1 hour

loud quartz

did you run the script

normal flare

No

loud quartz

did you ever move the registerCommands() into ready event

normal flare

No, because I thought that was a temp fix?

loud quartz

then why are you expecting the commands to appear if you never actually deployed them to discord.

yes, it is

because that call is in wrong place

and so it doesn't do anything

it was explained why it doesn't

normal flare

I don't have access to the vps, waiting for the person who has to be available and run the script

loud quartz

you fix that call not working by moving it to a place that will make it work

which is the ready event

after you run your code once, that call is no longer needed there

because the commands are already registered

normal flare

what happens when I add new commands then, do I put the call back in the ready event?

loud quartz

you run the script again

you can run that script from your own PC

normal flare

so can we just get rid of the appliaction.commands.set() call, and just use the script?

loud quartz

yes

normal flare

I see.

loud quartz
normal flare

I assume I need the clientId of the production bot right?

loud quartz

yeah, that too

since that's where you'd want to deploy the commands

normal flare

I don't feelsbadman I'll have to wait

loud quartz

it's just the user id

normal flare

okay that I can get, but I also think I need the token which I don't have

loud quartz

well, if you don't have that in any .env or config files, then sure, can't help you much with that

normal flare

no yeah, I'll have to wait for the person who has access to run the script

thanks for the help @loud quartz @steel trail

tawny geyser

Is there support for fetching server tag/server user has on their profile, it is relatively new feature

guild tag*

sharp ginkgoBOT
topaz bluff

o7

tawny geyser
topaz bluff o7

sorry for the ping but its giving undefined, I am on discord 14.20, are there any specific intent or other things needed?

rose tangle

it was added on .22

steel trail

And latest ist .23.2, so update

tawny geyser

got it

open musk

i know every embed has that issue with @ mentions showing only the ids (probably some cache thing, i guess). does iscomponentsv2 have the same problem?

wary coral

No and yes. Components we need to when using a text display will parse four mentions completely, unlike embeds. However, this will lead to the roll or user receiving a push notification. If you turn off mention parsing then it will have the same issue

This might not be an issue for you as you want the user to get pinged or it's in a channel where users can't see so they won't receive a notification

tardy sable
steel trail
wary coral
steel trail

So they don't

rose tangle

Thonk you sure? I recall it doesn't have that since it behaved like message content

wary coral

I am unsure then

halcyon zephyr

I'm pretty sure even with no allowed mentions they get parsed, I've never had that issue since switching to containers and no allowedMentions

tardy sable

thats just coincidence then. mention issue occurs when there are no allowed mentions

loud quartz

if you're in mentions field you're mentioned, and not being let there by allowedMentions doesn't insert you there, so there's no data about you attached to the message

that said, unsure if they ever fixed the issue with always inserting mentioned things there, given what the issue actually was

glad stone

hello there. i am trying to make a command and i want to set a timer so that if the button hasnt been interacted with within a certain amount of time the embed will edit

rose tangle

are you using collectors to listen for the button interaction?

glad stone

no

rose tangle

so you're listening with an interactionCreate listener?

can you show your code?

for when you create the button

glad stone
const newEmbed = new EmbedBuilder()
            .setTitle(`__${brand} Receipt__`)
            .setDescription("Press the button down below to get started.")
            .setColor(variables.default)

        const button = new ButtonBuilder()
            .setCustomId(`start${brand}`)
            .setLabel("Start")
            .setStyle("Primary")

        await selected.update({ embeds: [newEmbed], components: [new ActionRowBuilder().addComponents(button)] });```
rose tangle

and how do you then listen to it?

glad stone

interactionCreate

i have a switch case for the custom ids

rose tangle

given both are separate it might be hard to do that

it's not something built in djs

glad stone

oh right

rose tangle

djs doesn't manage components pretty much

the only helpers are collectors

it'd be easier with one, since you'd just listen to the end event, see if it hasn't been handled

or with your current way you'd need some kind of map where you put and clear unhandled buttons

balmy kraken

can channel message collectors run indefinetely, untill stopped manually?

rose tangle

yeah but at that point why not have an interactionCreate listener

balmy kraken

its not about handling interactions the old way, its for something else

rose tangle

I'm not sure what you mean by old way

it'd be easier to suggest whether that approach seems right if you explain your situation

but generally it doesn't sound like it is

balmy kraken

i need to have my bot constantly listen for messages on a specific channel

rose tangle

ah, misread your message, thought you meant interactions

though still, you can use the messageCreate event directly

collectors just wrap around its equivalent event

balmy kraken

noted

glad stone

i have a command that when executing it the user has 10 seconds to complete the modals etc. how can i implement that if they take more than 10 seconds to complete the modals that the embed gets edited from whatever point the user is at

wary coral

you have no way of knowing how completed the modal is only when it is submitted and when you sent it to the user

junior wraith

I've been trying to use interaction.fields.getStringSelectMenuValues() to get the value after submission using new select menu inside model but its getting failed.

pls ping with answer

loud quartz

@junior wraith there's no error here

"getting failed" is not a valid description of an error

junior wraith

crySparkle

loud quartz

because it indeed isn't a method that exists

sharp ginkgoBOT
junior wraith
loud quartz
junior wraith

i was using getStringSelectMenuValues instead of getStringSelectValues, need to go through all documents

sharp ginkgoBOT
topaz bluff

That's pretty much the only place you need to look for receiving the data

orchid merlin

So I have a bot and it has a dashboard, so far so good, but when I upload my application and put it on my domain, when I do the login callback, it simply says that the page does not exist and keeps saying “not found.” How do I fix this? I'm hosting the back-end using pm2.

tardy sable
sturdy yarrow

pls ping with answer

tardy sable
trim garden

This is probably already known, though I searched and couldn't find it (or find where to post). But FYI, images appear to be broken in the guide migration.

bleak owl

what images?

bleak owl
trim garden
bleak owl

i’ll forward the issue internally, thank you

trim garden

blobthumbsup Thank you!

still fulcrum

is it a must to await interaction.deferReply

topaz bluff
topaz bluff

Oh. Well yes and no because deferReply returns a Promise.

You can technically ignore the promise but then you would be disregarding any possible errors or running into race condition issues

still fulcrum
topaz bluff

Once you deferReply, you have to use editReply

You could send your defer, it hangs on Discord's side, then you send an edit reply which then fails because you can't edit if you haven't replied

brittle needle

Is the discord-rpc package deprecated or is there a replacement I can't find. The package's linked repo hasn't been touched since the beginning 2022. Asking because I can't find a definitive answer in previous messages. (Repo in question)

topaz bluff

The package is deprecated because that system was deprecated in favor of the Game SDK iirc

It should still work however

brittle needle
brittle needle

@topaz bluff not mad at you fyi, thx for helping

topaz bluff

I didn't take it that way. I'm just repeating the answer the maintainers give.

I've never used the package. So I can't say if it does or doesn't work personally

versed current

Discord discontinued RPC anyways. I don't think that will get revived

rigid ridgeBOT
snow onyx

its getting a rewrite anyway

barren bramble

can someane help me with my bot? i get this error:
node:events:497
throw er; // Unhandled 'error' event
^

TypeError: eventFunction is not a function
at Client.<anonymous> (/home/willem/craftcamp bot beta/src/handlers/eventHandler.js:18:23)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
Emitted 'error' event on Client instance at:
at emitUnhandledRejectionOrErr (node:events:402:10)
at process.processTicksAndRejections (node:internal/process/task_queues:92:21)

Node.js v22.20.0

i can give sourcecode