#djs-help-v14

78874 messages · Page 18 of 79

verbal vine

no error, but i want to make like this

dense jackal

yeah so different format, not a non-functioning button

unique shoal

Yeah, so

Dont put the button in a separate row

That button is an accesory to a section, as bessel said

sharp ginkgoBOT
chrome cloak

can the image in embedBuilder be a data-uri?

unique shoal

No

keen widget

is cache per shard or global in djs?

for example client.guilds.cache

loud quartz

can be any of them

depends how you're sharding

sharding manager spawns separate processes, so the cache is separate for each

internal sharding runs multiple connections in the same process, so there's only one cache

keen widget
keen jungle

A doubt, are these new overview components, aren't they actually implemented in V14? , and is only possible via API/REST?

keen widget

seperate processes means I use all my cores unlike internal?

keen jungle
rose tangle

um, where would you use them if not in the api?

I'm confused

keen widget
loud quartz
keen widget
loud quartz

If you know why you'd want workers over process

keen widget
loud quartz
keen widget

so worker is internal?

loud quartz

No

keen widget

okay

loud quartz

Internal sharding is something completely else than ShardingManager

keen widget
loud quartz

What

keen widget

how to do internal sharding

loud quartz

How many servers is your bot in

keen widget

2

loud quartz

2 servers?

keen widget
loud quartz

Then you're 1998 away from having to care about any if this at all

keen widget

but I expect easily over 10k this week

loud quartz

Respectfully, OMEGALUL

half rover

naah not respecfully lmao

keen widget
loud quartz

Then if you're expecting to have 50k servers by the end of the month

loud quartz

There's 0 reason to evem bother with internal sharding

It's not made for this amount

keen widget

but I wanna know thinkLul

loud quartz

10k is about the most it can do

keen widget

and whats the difference between ShardingManager modes?

loud quartz
loud quartz
keen widget
loud quartz

Not like it changes much for you though

keen widget
loud quartz

broadcastEval will still be a need

keen widget
rose tangle
loud quartz

I'd say to come back here when you cross a thousand servers

keen widget
loud quartz

Why sharding? because discord requires it

So that a single connection doesn't handle more than 2500 servers

rose tangle
keen widget

but why use worker over process...

loud quartz

You have no idea why

So unsure why are you pushing so much for it

keen widget

yeah thats why I am researching

loud quartz

But why

What's wrong with the default

rose tangle

why sharding in the first place

keen widget

because I dont freaking know the difference

loud quartz
half rover

thanks

loud quartz

Above 2500/shard discord will not identify you

keen widget
loud quartz

1000/shard is the amount they recommend and return for shard count requests

keen widget
loud quartz

Because planning to hit 10k servers in a week is really high plan

I don't know what you'd have to do as a bot to even anticipate that

keen widget
loud quartz

I'll believe it when it happens

keen widget

I can't promise anything

open peak

Hi, do you know if it is possible to put fields in V2 components?

keen widget

but it is a possibility, it's better to stay safe

loud quartz
open peak

oh 😢

keen widget

I am not ur average bot developer SIGMA_SMOKE

loud quartz

Then you wouldn't be here asking about this

Anyway, this is getting off topic

keen widget
loud quartz

Launch your bot first

If you really gonna hit above 2000, just turn on internal sharding

Should give you enough time to add one file and change few things for ShardingManager

snow onyx

then what is this conversation even about

keen widget
loud quartz

Then you were answered half an hour ago

keen widget
loud quartz

So are you clueless or are you using it

keen widget
keen jungle
keen widget
keen jungle
keen widget they are implemented in discordjs

What is the difference between traditional JSON (Actionrow/Button) and the new (Type: 17, 9, 12, Accessory)?
I can use all advanced features (accessories, multiple images, buttons next to the text) with disagreement.js v14, or need to assemble JSON manually

keen widget
snow onyx

disagreement.js 😭
djs supports the new components, yes

sharp ginkgoBOT

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

keen jungle
snow onyx disagreement.js 😭 djs supports the new components, yes

@keen widget Thanks! Now it was clear

The new flexible component system (Message Components V2) is already officially supported by Discord.JS V14.19.3+
It is no longer necessary to assemble JSON manually or use only REST API - Discord.JS itself already abstracts and generates the correct JSON for the API.

keen jungle

Is there any limitation of Rollout/Feature Flag, or is it now available to all bots/servers?

rose tangle
loud quartz
keen widget

dumb question about the sharding, it sure doesn't 💀

loud quartz

Anyway, i have to go

keen widget
keen jungle

Thank you so much for your help

narrow orchid

What's the default max for the VoiceStateManager cache per guild?

red coral

I don’t believe there’s a max

narrow orchid

Oh I see. VoiceStates are only cached if they're like 'active' tho right? Like if its someone speaking/in a vc, itll be active and cached. But then when they stop/leave, itll be inactive and removed from the cache?

steel trail
red coral

I’m guessing the only time it’s cleared by djs is if the member leaves the server?

steel trail

Or if the bot does, yes

ebon belfry

Is it possible for a bot/user bot to change your profile picture?

steel trail

No

atomic cairn

Hi, quick question, is there a way to make "custom" emojis shorter? !TpSq I use a lot of emojis with limiting inside an embed to animate, but the ID counts towards the limit, not sure how to go about this, if its possible to parse the emoji before putting it into the embed. (doesnt sound doable, but the non readable message limit sounds a bit silly). I am "rendering" a frame animation using 19x9 emojis, withoutusing any other text as part of the embed

snow onyx

not possible

atomic cairn

Aww, thanks cry

steel trail
upper mica

hi, what documentation about the latest embed that can have the buttons inside of the embeds?

clear garnet

Those aren't embeds, that's components v2

upper mica
atomic cairn
crimson gale

how is having a whole animation with emojis (!) to the point where it goes past the max allowed characters (!) less of an issue?

pliant forge

How they can do it? The right slides are all buttons and they are working

rose tangle

components v2, it's a container with sections with button accessories

pliant forge

can u send me the docs link?

sharp ginkgoBOT

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

pliant forge

tysm!

pliant forge
steel trail

Example of what?

rose tangle
steel trail
rose tangle

there's a link to the preview there

pliant forge

tysm gonna check them

safe wigeon

If I have sent a reply using components v2 and use the IsComponentsV2 flag, if I then in a messageComponentCollector use update to just change an ActionRow in the container, do I still need to pass in the flag like before?
Code example: ```js
// reply to the interaction, using the flag
const msg = await editReply({ components: [container], flags: MessageFlags.IsComponentsV2 });

// inside collector:
// update an ActionRow in the container...

// update in the collector, not using the flag
await i.update({ components: [container] }); // do I need the flag here?

bleak owl

the flag needs to be passed every time you use components v2

safe wigeon
bleak owl

from what i know you do, but if it works even without it then im not too sure. i would still continue to pass the flag

safe wigeon
modest surge
const commands = new Collection()

commands.execute()

Command execute is not defined

should i make a type interface or is there anohter way

rose tangle

collections indeed have no execute method

I'll insist you learn js basics, at least classes and instances

modest surge

this on typescript

rose tangle

well that entirely depends on how you typed the collection

but then again, not a djs issue

unique shoal

Emphasis on that middle line there

Where you get one command from the collection, and execute that

Instead of trying to execute the whole Collection

modest surge
interface Command {
    data: SlashCommandBuilder
    execute: (interaction: ChatInputCommandInteraction, client: Client) => Promise<void>
}

const commands = new Collection<string, Command>()
unique shoal

Cool

and?

modest surge

is it correct or i am missing something

unique shoal

Wrong reply sorry

weak sluice

is there a way to ignore a mandatory response so the command's output isn't necessarily a reply

like i know you can defer reply but that still throws an error if you never actually reply iirc
so i wanna just get rid of the buffer message and just like
run the command, it silently accepts it and then sends the output message

bleak owl

what you do there is what i was going to suggest. there's no way around it with interaction responses

unique shoal

Is it that important to hide the command params?

loud quartz

Well, having someone do /rps rock and the bot asking to pick rock/paper/scissors won't really be very playable if you can just see that the triggering user picked rock

This looks pretty much like this to me

unique shoal

I mean this says the fish will choose randomly

weak sluice

its rock paper scissors yeah

weak sluice
unique shoal

undocumented new feature

torn orchid

i have a embed that i want to have a button on which is when someone clicks on the button and it gives them a sessions role and if they click again it removes the sessions role

rose tangle

yeah, you can only provide one number per number option

minValue and maxValue control what number you can put

yeah

loud quartz

Yes, that's what you set

10 is indeed higher than 5

rose tangle

minValue: minimum required, maxValue: max required

your input only accepts numbers from 1 to 5

raven hearth

yes??

loud quartz

So what's the question

Or issue

torn orchid

is there a doc on how to do it?

rose tangle

there's multiple parts of that question, from constructing the embed to giving the role

raven hearth
loud quartz

Number option is not a string option

rose tangle

it's always been by value, hence why min/max Value

loud quartz

And therefore max number value is not max string length

raven hearth
loud quartz

Strings are not numbers

rose tangle

I think you were using a string option

raven hearth

maybe, anyways thank you

rose tangle

I said your feature is split in multiple parts, all entirely unrelated from each other

in general

  1. build such an embed, though it sounds like you want a container since you say "it has a button on it", embeds don't have buttons inside, containers do
  2. listen to interactionCreate to listen for button clicks, and deferReply
  3. get the member's roles, check if they have the role you want, if they don't, give it, if they do, remove it
  4. editReply with the success/error message

if you want something more specific than that you'll need to be more specific on your question

which part you tried, where you're having the issue, what issue exactly, etc

torn orchid

okay

torn orchid
rose tangle

do you have a bot already or are you starting from scratch?

torn orchid

i have a bot already

rose tangle
torn orchid

yes

rose tangle

then you can add the code to your interactionCreate.js file

or you can rewrite the event handler in the guide so it accepts a folder instead of a single file

similar to how commands work

and then you can have a interactionCreate file for your commands and another one for your role buttons and so on

torn orchid

k

novel mauve

if i make my bot leave a server, is the cached stuff related to that server instantly deleted?

snow onyx

it should be, yes

novel mauve

okay thank you

pearl roost

what's wrong with it?

uneven crater
pearl roost
snow onyx

refer to my perfect illustration

pearl roost

oh... yeah its work now, thanks blobguns

bitter nova
bitter nova

why can parent_id of type RESTAPIGuildCreatePartialChannel be a number

crimson gale

the endpoint allowing bots to create guilds takes numbers as placeholder so you can define the channel hierarchy
that's going to be deprecated and blocked rather soon with very few exceptions (you cannot apply for it, i tried)
-# ty DD for the reminder, knew i read that somewhere before; src: #discord-dev-news message

bitter pivot

Is there any character limit on .setCustomID() or can I reliably pass something like .setCustomID('update_channel__222197033908436994') in, and just in my own logic manipulate the custom ID?

steel trail

100 chars

bitter pivot

salute ty

lost sparrow

AYAYAwave
Around 2 hours ago, my bot started failing to pull Guild Members:

reason: Error [GuildMembersTimeout]: Members didn't arrive in time.
    at Timeout._onTimeout (/app/node_modules/discord.js/src/managers/GuildMemberManager.js:268:16)
    at listOnTimeout (node:internal/timers:569:17)
    at process.processTimers (node:internal/timers:512:7) {
  code: 'GuildMembersTimeout'
}

I know they can take a little for huge servers and arrive in chunks, but in this case it doesn't make much sense to me. Tried a 60s wait time, but still didn't arrive in time.

  • Bot is only in 1 server, this server has 28 members and the member count hasn't changed in months
  • It worked up until around 2 hours ago
  • Discord API status doesn't indicate issues/downtime
  • Server has 1GB UP&DOWN link and 20TB of bandwidth free

Anyone has any idea what this could be?

zenith violet
lost sparrow
worldly jewel

hello . i need some help listening to the event 'MessagePollVoteAdd' . i tried a simple console.log('test') but i get nothing. i've looked it up here and someone posted the same thing , but no solution has been provided

steel trail

If you don't have the channel, message and poll cached nor have the respective partials the event won't emit

novel mauve

Hi, I'm using this snippet to connect to the gateway, and extract all small servers. But the bot is owned by an org I'm part of but it's not maintained anymore. I'm trying to remove it from a bunch of servers that don't use it to hopefully reduce the amount of cached stuff. I'm temporarily using its token to run this script, but the bot is huge with 64 shards and it seems to never successfully connect (ready never fires, and shards seem to close with a zombie connection). Am I missing something here?

const { Client, GatewayIntentBits } = require("discord.js")
require("dotenv").config()
const fs = require('fs')

const client = new Client({
    intents: [GatewayIntentBits.Guilds],
    shards: 'auto',
    waitGuildTimeout: 60000
})
client.login(process.env.token)

client
    .on("debug", console.log)
    .on("warn", console.log)

client.on('ready', async () => {
    console.log(`Logged in as ${client.user.username}!`);

    const results = await client.shard.broadcastEval(() => {
        return [...this.guilds.cache.values()]
            .filter(g => g.memberCount < 3)
            .map(g => `[SMALL] ${g.id}`)
    })

    const flat = results.flat()
    flat.push('Checked all guilds.')

    fs.writeFile('guilds.txt', flat.join('\n'))
})
proud arrow

I don't think auto sharding can handle 64 shards. You should try with ShardingManager. Probably the reason why it fails to identify

novel mauve

ah ok, i've never had to shard before and this is a unusual thing for me. i'll look into that, thanks

sharp ginkgoBOT

guide Sharding: Getting started - How does sharding work?
read more

proud arrow

We have a guide that can help you with

novel mauve

seems like sharding manager has the same results

the debugger logs this for every shard

[WS => Shard 51] Destroying shard
        Reason: Zombie connection
        Code: 4200
        Recover: Resume
worldly jewel
snow onyx
worldly jewel

i did. i've also noticed that non cached pools do not trigger the event. isn't there a specific partial for it?

feral sky

Hey there, quick question. What could inflict on the duration of the bot's login. sometimes it says it has handshake timeout.
I'm using d.js v14.19.3 on node v20.16.0 with these particals and intents:

  /**
   * Defines the required intents for the bot.
   *
   * @returns An array of required intents.
   */
  private getIntents(): GatewayIntentBits[] {
    const { Guilds, GuildMembers, GuildMessages, MessageContent, GuildVoiceStates } = GatewayIntentBits;
    return [Guilds, GuildMembers, GuildMessages, MessageContent, GuildVoiceStates];
  }

  /**
   * Defines the required partials for the bot.
   *
   * @returns An array of required partials.
   */
  private getPartials(): Partials[] {
    const { User, Message, GuildMember } = Partials;
    return [User, Message, GuildMember];
  }
steel trail
analog oak

Is there a better practice then doing two operations like this? i can't use .set though because it will delete the permissions of other users ..

await interaction.channel.permissionOverwrites.edit(userId, {
        ViewChannel: true,
        SendMessages: true,
        ReadMessageHistory: true,
})
await interaction.channel.permissionOverwrites.edit(guildData.staffRole, {
        ViewChannel: true,
        SendMessages: false,
})
zenith violet
analog oak
heady grail

Hello
i was following discord.js webside tutoriaj, yet my interactionCreate refuses to work
Bot is onlice, commands are registered, file is loading
On discord it says "The application did not respond"
index.js:

const fs = require('node:fs');
const path = require('node:path');
const { Client, Collection, GatewayIntentBits } = require('discord.js');
const { token } = require('./config.json');

const client = new Client({ intents: [GatewayIntentBits.Guilds] });

client.commands = new Collection();
const foldersPath = path.join(__dirname, 'commands');
const commandFolders = fs.readdirSync(foldersPath);

for (const folder of commandFolders) {
    const commandsPath = path.join(foldersPath, folder);
    const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
    for (const file of commandFiles) {
        const filePath = path.join(commandsPath, file);
        const command = require(filePath);
        if ('data' in command && 'execute' in command) {
            client.commands.set(command.data.name, command);
            console.log(`Loaded command: ${command.data.name}`);
            console.log(JSON.stringify(command.data.toJSON(), null, 2));
        } else {
            console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
        }
    }
}

const eventsPath = path.join(__dirname, 'events');
const eventFiles = fs.readdirSync(eventsPath).filter(file => file.endsWith('.js'));

for (const file of eventFiles) {
    const filePath = path.join(eventsPath, file);
    const event = require(filePath);
    if (event.once) {
        client.once(event.name, (...args) => event.execute(...args));
        console.log(`Loaded event: ${event.name} (once)`);
    } else {
        client.on(event.name, (...args) => event.execute(...args));
        console.log(`Loaded event: ${event.name}`);
        
    }
}

client.login(token);

createInteraction.js:

const { Events, MessageFlags } = require('discord.js');

module.exports = {
    name: Events.InteractionCreate,
    async execute(interaction) {
        console.log('Interaction received:', interaction.commandName);
        if (!interaction.isChatInputCommand()) {
            console.log(`Interaction is not a chat input command: ${interaction.commandName}`);
            return;
        };

        const command = interaction.client.commands.get(interaction.commandName);

        if (!command) {
            console.error(`No command matching ${interaction.commandName} was found.`);
            return;
        }

        try {
            console.log(`Executing command: ${interaction.commandName}`);
            await command.execute(interaction);
        } catch (error) {
            console.error(error);
            if (interaction.replied || interaction.deferred) {
                await interaction.followUp({ content: 'There was an error while executing this command!', flags: MessageFlags.Ephemeral });
            } else {
                await interaction.reply({ content: 'There was an error while executing this command!', flags: MessageFlags.Ephemeral });
            }
        }
    },
};

cmd:

zenith violet
sharp ginkgoBOT

documentation suggestion for @analog oak:
mdn Spread syntax (...)
The spread (...) syntax allows an iterable, such as an array or string, to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected. In an object literal, the spread syntax enumerates the properties of an object and adds the key-value pairs to the object being created.

zenith violet

use that to pass the previous overwrites in

analog oak
rigid hinge

hi guys, is there any way to check if specific action row is a button row or menu row?

rose tangle

check the components

the first one

trim basin

hi i got an error here:

    const components = [
        new ContainerBuilder()
          .addSectionComponents(
            new SectionBuilder()
              .addTextDisplayComponents(
                new TextDisplayBuilder().setContent(`:playing_song: **\`${song.name}\` by \`${song.uploader?.name}\`**`),
                new TextDisplayBuilder().setContent(`00:00 ${songdurationbar_pointer}${incompletedurationbar} ${song.formattedDuration}`)
              )
          ),
        new SeparatorBuilder().setSpacing(SeparatorSpacingSize.Small).setDivider(true),
        new ContainerBuilder()
          .addTextDisplayComponents(
            new TextDisplayBuilder().setContent(`:volumeicon: \`???\`%`)
          )
          .addActionRowComponents(
            new ActionRowBuilder().addComponents(stop, playpause, skip, shuffle, repeat),    -- HERE
            new ActionRowBuilder().addComponents(upvol, downvol)                             -- HERE
          )
    ]
bleak owl

what’s the error?

steel trail

Either thumbnail or button. If you don't want either just remove the section and put the textdisplay directly into the container

trim basin
rigid crest

Why does this still show after a v2 message is sent? It doesn’t go away

bleak owl

it’s a bug, nothing you can do about it

steel trail

Apart from waiting for discord to fix it. They are aware

rigid hinge
rose tangle the first one

why when i click on a menu it shows new message (response) and then i delete the menu from the original message by clicking a button on the original message and then from the new message it sent earlier when i click a a button it displays all of the 3 components of the original message when only the button is there now

i do (await interaction.message.fetchReference()).components when you click on button of new message

rose tangle

I got completely lost

can you show a video about it

or a photo

mental silo

I don't really understand the difference between GuildMember
avatarURL(options?: ImageURLOptions = {}) : string | null
A link to the member's guild avatar.

And

displayAvatarURL(options?: ImageURLOptions = {}) : string
A link to the member's guild avatar if they have one. Otherwise, a link to their displayAvatarURL will be returned

Or well what a display avatar is supposed to be in the first place
We have a global avatar (user.avatar) and a guild avatar (guildmember.avatar)

polar karma

avatarURL will be null if they don't have one set (whether a guildmember for a server-specific one if you're checking <GuildMember>.avatarURL() or a user global one with <User>.avatarURL(), displayAvatarURL() will return the avatar if present (for guild member with a guild-specific avatar set), the user's global avatar if no guild one is set, or the default discord avatar otherwise. the latter method is more robust since it has fallbacks

mental silo
mental silo
polar karma

yup

mental silo

Perfect, thank you

Unfortunately there doesn't seem to be the same functionality for the avatar hash only, which I kinda require as I store the hash in a database and then download the avatar

bleak owl
toxic moat

is there any way to create a message collector in a forum channel

clear garnet

No, because forum channels don't have messages. The threads inside them do

sharp ginkgoBOT

method ThreadChannel#createMessageCollector() discord.js@14.19.3
Creates a Message Collector.


// Create a message collector
const filter = message => message.content.includes('discord');
const collector = channel.createMessageCollector({ filter, time: 15_000 });
collector.on('collect', message => console.log(`Collected ${message.content}`));
collector.on('end', collected => console.log(`Collected ${collected.size} items`));

manic burrow
[COMMAND_EXECUTION_ERROR]: RangeError: Non-premium buttons must have a label and/or an emoji

await interaction.editReply({
      flags: MessageFlags.IsComponentsV2,
      components: [
        section, container, textDisplay
      ],
    });

//Line dropping the error 
//i alr tried this one:

 await interaction.editReply({
          components: [container.toJSON()],
          flags: MessageFlags.IsComponentsV2
        });
      };

//Getting the same error, too. 

What i am expecting is, getting a simple embed with 2 buttons on it.

bleak owl
manic burrow
bleak owl

according to your error, they don't

topaz bluff

I've seen that error when someone tried to send a Section without a Thumbnail or Button...idk why that error shows up when that happens but whatevs

halcyon bison
lime trout

is discordjs ever going to update undici which is on a vulnarable version rn?

halcyon bison

I'm sure it will eventually, but the vulnerability also doesn't apply to how djs uses it

pearl venture

im doing

    const channel = await interaction.guild.channels.create({
        name: `${category.ticketPrefix}-${nextId}`,
        reason: `Ticket created by ${interaction.user.username} (${interaction.user.id})`,
        topic: `Ticket created by ${interaction.user.username} (${interaction.user.id})`,
        parent: categoryChannel,
        permissionOverwrites: overwrites
    });

and i get the following error with the overwrites (after error)

180 |       };
181 |     }
182 |
183 |     const userOrRole = guild.roles.resolve(overwrite.id) ?? guild.client.users.resolve(overwrite.id);
184 |     if (!userOrRole) {
185 |       throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'parameter', 'cached User or Role');
                  ^
error: Supplied parameter is not a cached User or Role.
[
  {
    allow: 3072n,
    deny: 17n,
    type: "user",
    target: "1309852092139180124",
  }, {
    allow: 3072n,
    deny: 17n,
    type: "user",
    target: "1149821808070103131",
  }, {
    allow: 3072n,
    deny: 17n,
    type: "user",
    target: "724833136894279690",
  }
]

Im using discord.js 14.19.3 and I have even tried to cache the objects specifically (by fething them with cache set to true) and I still get this error, I have also tried to just pass the fetched object into target instead of just the id but that gave the same error

any ideas
thanks in advance

sharp ginkgoBOT
pearl venture

istg idk how i didnt notice that 😭

ty ❤️

woeful gulch

is it safe to assume the user invoking an interaction is freshly cached (i.e. getting the GuildMember from cache out of that APIInteractionGuildMember's id)

rose tangle

not really, if it was then you'd always get the full member

it depends on the situation

mostly intents and how your bot is used (eg user installs)

woeful gulch

im trying to figure out the most sane way to get the former out of the latter without cache missing and exploding but fetching everything sounds like you'd run up against ratelimit real quick

stable sun

The only reason it can be a raw object is if the guild is uncached

woeful gulch
stable sun

You can check this on the interaction beforehand using the interaction.inCachedGuild() type guard

You will have to handle other cases like Amgelo mentioned

rose tangle

if your bot is only guild installable, you have the Guilds intent, and the bot is in the guild as a member, you can safely assume it's a GuildMember, but the inCachedGuild type guard is an actual runtime check, which is inherently safer than assuming

woeful gulch

is a guild ever partially cached? just overthinking a little if i'd ever somehow cache miss after that check

rose tangle

no, caches always hold full structures

woeful gulch

ok cool

rose tangle

getting partial structures is actually an actual issue sometimes you want to solve, to not omit certain events, which is why Partials exist

trail fog

do embeds and section components fit together? or is that a no no

rose tangle

no, if you use components v2 you can only use components

not content, embeds, stickers, polls, etc

in case you meant a container, then yes, it can have a section

trail fog

So im trying to put my select menu within the container. Im assuming container and embed are 2 different things meaning i have to redsign the embed to be a container right

rose tangle

yes

they're visually similar but they're different objects and support different stuff

trail fog
rose tangle yes

slight issue

const textDisplay = new Discord.TextDisplayBuilder().setContent('heh');
        const containerThing = new Discord.ContainerBuilder()
        .addTextDisplayCompontents(textDisplay, textDisplay)
        .addActionRowComponents(row, row2)
        
        const sentMessage = await message.reply({
            flags: Discord.MessageFlags.IsComponentsV2,
            components: [containerThing]
        });

Im trying to do this, and the error:

TypeError: (intermediate value).addTextDisplayCompontents is not a function
at Object.execute (/home/container/commands/Utility/help.js:101:10)
at Client.<anonymous> (/home/container/index.js:159:19)
at processTicksAndRejections (node:internal/process/task_queues:95:5)

comes up

rose tangle

misspelled components

trail fog

oh 💀

silly me

rose tangle

nw blobReach

trail fog

time to read up on how to make the row work 😭 🙏

trail fog
rose tangle
sharp ginkgoBOT
trail fog
rose tangle

it behaves exactly as in v1 components

just the positioning changes

trail fog
trail fog
rose tangle just the positioning changes
        const title = new Discord.TextDisplayBuilder().setContent('# 📜 Help Menu');
        const textDisplay = new Discord.TextDisplayBuilder().setContent('Select a category from the dropdown below to view its commands.\nUse `;help [command]` to learn about a specific command.\nUse `;manual` to learn about MGS!');
        const separatorComponent = new Discord.SeparatorBuilder();
        const containerThing = new Discord.ContainerBuilder()
        .addTextDisplayComponents(title, separatorComponent, textDisplay)
        .addActionRowComponents(row, row2)
        
        const sentMessage = await message.reply({
            flags: Discord.MessageFlags.IsComponentsV2,
            components: [containerThing]
        });

ValidationError > s.string()
Expected a string primitive
Received:
| undefined
at _StringValidator.handle (/home/container/node_modules/@sapphire/shapeshift/src/validators/StringValidator.ts:108:53)
at _StringValidator.parse (/home/container/node_modules/@sapphire/shapeshift/src/validators/BaseValidator.ts:126:2)
at TextDisplayBuilder.toJSON (/home/container/node_modules/@discordjs/builders/src/components/v2/TextDisplay.ts:48:31)
at /home/container/node_modules/@discordjs/builders/src/components/v2/Container.ts:236:61
at Array.map (<anonymous>)
at ContainerBuilder.toJSON (/home/container/node_modules/@discordjs/builders/src/components/v2/Container.ts:236:32)
at /home/container/node_modules/discord.js/src/structures/MessagePayload.js:151:46
at Array.map (<anonymous>)
at MessagePayload.resolveBody (/home/container/node_modules/discord.js/src/structures/MessagePayload.js:150:49)
at TextChannel.send (/home/container/node_modules/discord.js/src/structures/interfaces/TextBasedChannel.js:189:32)
🥀 is it the seperator

it is

topaz bluff

youre adding a separator as a text component. you have to add the text, add a separator, then add text again

sharp ginkgoBOT
modest surge
rose tangle

there's no special font?

and it's not an embed, it's a container

modest surge

its not bolded

rose tangle

I mean you could replicate that using the embed's description, not the title

modest surge

oh

topaz bluff

cuz its not an embed. youre talking about an embed title field. containers dont have title fields, just text markdown

rose tangle

but then again, it's not an embed

trail fog
const containerThing = new Discord.ContainerBuilder()
        .addTextDisplayComponents(title)
        .addSeparatorComponents(separatorComponent)
        .addTextDisplayComponents(textDisplay)
        .addSeparatorComponents(separatorComponent)
        .addActionRowComponents(row, row2)

is there a more efficient way to do this or i gotta do it like this

stable sun
trail fog
stable sun

Personally, I would use callbacks instead of manually instantiate the components

Unless you are reusing them I guess

rose tangle

it's a correct way (as in, it won't error), whether you use that or other way, depends on your style

topaz bluff
const containerThing = new ContainerBuilder()
    .addTextDisplayComponents((textDisplay) => textDisplay.setContent('Title'))
    .addSeparatorComponents()
    .addTextDisplayComponents((textDisplay) => textDisplay.setContent('Content'))
    .addSeparatorComponents()
    .addActionRowComponents((actionRow) => {
        // Do stuff
    });
topaz bluff

discordjs uses a "vulnerable" version of undici however the vulnerability does not effect the library

rose tangle

are you stating something or was the question deleted?

topaz bluff
thorn gate

what is edit and editreply

knotty wind

Hello, sorry for the quick question.
Was the error came from discord side If:

  • Tested and works without issue on my small test server.
  • Tested on the big server and get DOMException [AbortError]: This operation was aborted errors after some seconds passed (most probably a timeout).
  • Bot permission for both server are sufficient.

Footnote:

  • the bot was attempting to fetch threads for a particular channel.
snow onyx
sharp ginkgoBOT

AbortError: The user aborted a request.
A request took longer than the specified timeout (15 seconds default), and was aborted to not lock up the request handler.

  • This can be caused by an internal server error on Discord's side, or just a slow connection.
  • In case of a slow connection, the timeout option in RESTOptions can be increased to prevent future AbortErrors.
stable sun
thorn gate what is edit and editreply

editReply is exclusive to most interactions in which the reply or deferX is edited.
edit is a common method found amongst many structures which generally applies changes to that particular object

knotty wind
snow onyx

try to up the timeout option and see if it makes a difference

knotty wind
rigid crest

I saw a blue arrow on a bots message, is this exclusive to HTTP version? There was no status icon on the bot profile

snow onyx

what do you mean with blue arrow

rigid crest
zenith violet

thats just a masked link

rigid crest

Ah ig just weird seeing it with emoji as the name part

toxic moat

why is createReactionCollector not working when I'm using emojis from application?

When I'm using emojis like 👋 it works

  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
    GatewayIntentBits.GuildMessageReactions,
    GatewayIntentBits.GuildIntegrations
  ],

these r my intents

polar karma

What'd the collector code and how have you verified it doesn't work with app emojis?

toxic moat

Yea this is not sapphire support but still kinda djs related

obtuse laurel

Would it double the RAM usage if I hosted two bots on the same client instance? Guessing it's not recommended or something?

spice wyvern

Do any slash commands pop up for people in friends DMs? Trying to get the context scope in DMs and it doesn’t work, but then again no bot besides wordle appears

polar karma
polar karma
formal wigeon
obtuse laurel
polar karma Each app should have its own process

I'm trying to make something like whitelabelled bots where each person gets assigned a bot (owned by us). Having one process for one bot isn't very effective. I'd go for http interactions but I need the WS events

steel trail
formal wigeon

if it was possbile (idk if it is) to run them on the same instance, it would have much less performance as multiple "bots" are running the same resources, instead of their own one

obtuse laurel
formal wigeon

thats just.. false

steel trail

Would it? What makes you say so?

harsh kernel

is it possible to get all the badges from an user with djs?

obtuse laurel

hm? it isn't?

steel trail

Some of them correlate with badges, but not all

harsh kernel

okay thanks

steel trail
formal wigeon

yeah im interested too

steel trail

As soon as you have a CPU with more than 1 core the opposite would be true actually

formal wigeon

wanted to say that actually LUL

sharing a single core + same ram with more bots will be bad

obtuse laurel
steel trail

Okay? And how is that an issue?

formal wigeon

Yeah... thats like what others do, like any whitelabel bot hosters.

mee6 does that aswell, shit bot but good example here.

steel trail

If you're concerned about overhead of a node process do node in terminal to start a REPL running nothing and look at that process' resource consumption

formal wigeon

js is also known to use a bit more resources as it is an interpreted language (or idk how u say it)

hidden surge

quick question what do we use in discordjs to move channel permission overwrites from explicity allowed to inherting from roles. I don't want to delete the overwrite.

so for example moving just the view permission of the role from allowed to neutral

like we have for allow / deny.. what for the neutral... i might be dumb 🤔 with this question please bear with me

snow onyx

either edit it and set the specific permission to null, or set it without the permission

hidden surge

🙏 thank u! never knew null would be the solution

sharp ginkgoBOT

method PermissionOverwrites#edit() discord.js@14.19.3
Edits this Permission Overwrite.


// Update permission overwrites
permissionOverwrites.edit({
  SendMessages: false
})
  .then(channel => console.log(channel.permissionOverwrites.get(message.author.id)))
  .catch(console.error);

spice wyvern
formal wigeon are you registering them globally?

heyy!!!! so I added this on the slash command:
.setContexts(InteractionContextType.Guild, InteractionContextType.PrivateChannel, InteractionContextType.BotDM)
I added it as a global command, and I made it so under installation I added user install and installed it on my account

formal wigeon

i dont really do that so someone else has to help you

steel trail
spice wyvern
versed ivy

why message.member return null for me ?

manic leaf
versed ivy

no

manic leaf
versed ivy

yea

polar karma

Webhook?

versed ivy

in a server also i have all intents enabled

formal wigeon

w-why

manic leaf

that's diabolical

formal wigeon

even ai would say not do that

manic leaf
polar karma

You're missing a lot of context and information about your case. What's the event, what's the full message structure show

manic leaf
sharp ginkgoBOT
polar karma
steel trail
manic leaf
formal wigeon
polar karma
manic leaf <@167988857046827010> ?

It's not likely we need the full event listener right now. If message.member were undefined sure, but null points to it being a webhook or something

steel trail
spice wyvern
polar karma

They extended the d.js client

manic leaf
steel trail
spice wyvern

the slash command doesnt show in friends DM

steel trail

Fetch and log all your commands

To find out whether they are deployed correctly and narrow the issue

versed ivy
manic leaf you could also send the code of the event handler
Message {
  channelId: '1246839258078253146',
  guildId: '738862529081507870',
  id: '1380165909947355268',
  createdTimestamp: 1749127595174,
  type: 0,
  system: false,
  content: 'hi',
  author: User {
    id: '527826654660132890',
    bot: false,
    system: false,
    flags: UserFlagsBitField { bitfield: 4194560 },
    username: '7xr.',
    globalName: '7xr',
    discriminator: '0',
    avatar: 'fab7f87a77451112b49a3abd441c82b0',
    banner: undefined,
    accentColor: undefined,
    avatarDecoration: null,
    avatarDecorationData: {
      asset: 'a_8b7ad8479ad8cc9996b508b75410e2f9',
      skuId: '1179493515118514186'
    }
  },
  pinned: false,
  tts: false,
  nonce: '1380165331611287552',
  embeds: [],
  components: [],
  attachments: Collection(0) [Map] {},
  stickers: Collection(0) [Map] {},
  position: null,
  roleSubscriptionData: null,
  resolved: null,
  editedTimestamp: null,
  reactions: ReactionManager { message: [Circular *1] },
  mentions: MessageMentions {
    everyone: false,
    users: Collection(0) [Map] {},
    roles: Collection(0) [Map] {},
    _members: null,
    _channels: null,
    _parsedUsers: null,
    crosspostedChannels: Collection(0) [Map] {},
    repliedUser: null
  },
  webhookId: null,
  groupActivityApplication: null,
  applicationId: null,
  activity: null,
  flags: MessageFlagsBitField { bitfield: 0 },
  reference: null,
  interactionMetadata: null,
  interaction: null,
  poll: null,
  messageSnapshots: Collection(0) [Map] {},
  call: null
}
// event
import { ChannelType, Message } from "discord.js";

export default {
    name: "messageCreate",
    description: "Client on receive message event",
    once: false,
    function: async function (message: Message) {
        if(!message.guild || message.author.bot || message.channel.type !== ChannelType.GuildText) return;
        console.log(message)
        

        
    },
};
steel trail

It does, Show your source code for that

versed ivy
polar karma

That'll do it

steel trail

I suspect the dedent

Or rather that you need to indent one level deeper

  • List nest perfectly
    • if done right
    • like this
  • see?

Did you try without dedent?

Because indentation does matter here

solid summit

How does this works?

cute tag btw ❤️

steel trail

This was a first step to find out whether it works without dedent. If it does you know where the issue lies. If it doesn't you know where it doesn't lie

spice wyvern
solid summit

any docs on it? what has really changed?

steel trail
solid summit
sharp ginkgoBOT

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

solid summit

thanks cutie

steel trail
solid summit

also does the containerbuilder allows the comp v2 too?
like buttons in embed

snow onyx

containerbuilder is comp v2

solid summit

yes
i saw that somewhere

pearl venture

yeah in a section builder you can have a thumbnail accessory or a button accessory

frosty epoch

when sharding, the token is in the shardingManager.js file

const manager = new ShardingManager('./bot.js', {
    token: token,
   ...
});

but im also calling client.login(token); in the bot.js file, should I erase this line?

pearl venture

no you can only have one or another

sharp ginkgoBOT

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

pearl venture

I'm not sure but I don't think so
I think discord just uses the same width and height for all thumbnails no matter the image size

steel yacht

Hi,
Is Idle or Ready the nominal value for WebSocketShardStatus ?
Thanks

steel trail
frosty epoch
steel trail
steel yacht
steel trail

Their value? And their meaning

I get the feeling "nominal" was not what you meant but something else lost in translation maybe?

steel yacht

I meant nominal as everything working perfectly

steel trail

In that case: Ready

Idle is before login

steel yacht

Oh okay, then how to fix the Idle state ?

steel trail

Login

The idle state can only happen before <Client>.login() has been called. There's no way to get back to Idle afterwards

white plank

[SLASH] - There was an error while executing an application command: DiscordAPIError[50035]: Invalid Form Body
embeds[MESSAGE_CANNOT_USE_LEGACY_FIELDS_WITH_COMPONENTS_V2]: The 'embeds' field cannot be used when using MessageFlags.IS_COMPONENTS_V2
at handleErrors (E:\Github\Watcher-V14\node_modules@discordjs\rest\dist\index.js:748:13)

const {
  SlashCommandBuilder,
  ButtonBuilder,
  ButtonStyle,
  ContainerBuilder,
  TextDisplayBuilder,
  MessageFlags,
  EmbedBuilder,
} = require("discord.js");

module.exports = {
  data: new SlashCommandBuilder()
    .setName("help")
    .setDescription("Displays the help menu."),

  async execute(interaction) {
    await interaction.deferReply({ ephemeral: false });

    const thumbnailURL = "https://media.discordapp.net/attachments/889348842179407926/931457370859655168/43fd7dbe-c8f4-4337-b066-934b78270391b.jpg";

    const embed = new EmbedBuilder()
      .setTitle("Help Menu")
      .setDescription("Thank you for using **Watcher**!")
      .setColor(0xe4a726)
      .setThumbnail(thumbnailURL)
      .addFields([
        {
          name: "Commands",
          value: [
            "</add:1359478268289355836> — Track a bot",
            "`/remove` — Untrack a bot",
            "`/list` — Show tracked bots",
            "`/channel` — Set the log channel",
            "`/role` — Set ping role for outages",
            "`/shard` — Display shard information",
            "`/help` — Show this help menu",
          ].join("\n"),
        },
      ]);
      
    const container = new ContainerBuilder();

    container.addTextDisplayComponents(
      new TextDisplayBuilder().setContent("### Useful Links")
    );

    const links = [
      new ButtonBuilder()
        .setLabel("Support Server")
        .setStyle(ButtonStyle.Link)
        .setURL("https....kp"),
      new ButtonBuilder()
        .setLabel("Dashboard")
        .setStyle(ButtonStyle.Link)
        .setURL("https://...s"),
      new ButtonBuilder()
        .setLabel("Invite")
        .setStyle(ButtonStyle.Link)
        .setURL(
          "https://discord.com/oauth2/au....nds"
        ),
    ];

    container.addActionRowComponents((row) => row.addComponents(...links));

    await interaction.editReply({
      embeds: [embed],
      components: [container],
      flags: MessageFlags.IsComponentsV2,
    });
  },
};
crimson gale

either components v2 or embeds

white plank

is their a way to display an image or thumbnail in the new ContainerBuilder?

steel yacht
steel trail

No

steel yacht

Then something strange is happening, because we're seeing discordClient.ws.status === WebSocketShardStatus.Idle after client.on('shardReady')

steel trail

Then not all shards are ready yet

pearl venture
sharp ginkgoBOT
steel trail

v14 is in a weird state of "needs to have client.ws.status to exist the same as it did ever in v14" and "using new /ws that works differently internally"

steel yacht

Code :

client.on("shardReady", (shardID) => {
    client.functions.sendStatusWebhook(`${Constants.Emojis.DND} | Shard #${shardID} is ready! Websocket status: ${client.ws.status}`);
    setInterval(() => client.functions.sendStatusWebhook(`Websocket status: ${client.ws.status}`), 5000);
});
```Webhook channel messages :

:dnd: | Shard #0 is ready! Websocket status: 3
Websocket status: 0
Websocket status: 0
Websocket status: 0

hybrid olive

what even is sharding?

sharp ginkgoBOT

guide suggestion for @hybrid olive:
guide Sharding: Getting started - How does sharding work?
read more

hybrid olive

thanks :3

pearl hazel

if i created a channel with too much permission overwrite it will create 7 channels untail the reqest is set the permissions

steel trail
pearl venture

so i mean as long as the websocket is still connecting eventually i dont think it matters too much as long as shardReady is still called when the shard is ready (even if status is still set to idle)

steel yacht

I just now measured it :

  • 1029ms after script starts, client.ws.status transitions from undefined to 3 ;
  • 640ms after that, the shardReady event is fired ;
  • 62ms after that, client.ws.status transitions from 3 to 0.
pearl venture

yeah i think this is unintended behaviour, client.ws.status should be set to 0 before calling shardReady but it doesnt seem like it could cause an error it just seems minor

steel trail
steel trail

client.ws.status indicates that all shards are ready. shardReady event emits as soon as a shard becomes ready. If you want to listen for when all shards are ready that's what the ready event is for

pearl venture

ohhh i misunderstood the events yeah that makes sense then

steel yacht
pearl venture

yeah but the same code needs to work for multiple shards
so it calls the shardReady event then it realises that all the shards are ready then it sets client.ws.status
(at least im assuming)

steel yacht

Well, client.ws.status is never set to 3 ever again

pearl venture
steel yacht

3 is Ready, not Idle

pearl venture
steel yacht

So it's not WebSocketShardStatus ?

declare enum WebSocketShardStatus {
    Idle = 0,
    Connecting = 1,
    Resuming = 2,
    Ready = 3
}
pearl venture

on the docs it says the type of WebsocketManager#status is Status

sharp ginkgoBOT
steel yacht

Oh

Then what's WebSocketShardStatus for ?

red coral

status of each shard?

pearl venture

just guessing here but that might be for the status of an individual shard not all the shards

steel yacht

Well, that's what I want

red coral
rotund vine

Hey, i want to update an Ephermal message in an another File, how can i do it?

red coral

interaction.editReply is the way you edit ephemeral messages, you can pass the message in there as well of the ephemeral message. But you can also use .update for component interactions. Would need a bit more info to be able to help specifically

rotund vine

how do i pass it?

rotund vine

ya

steel trail

WebSocketShardStatus is only used in private properties in mainlib v14. It's part of @discordjs/ws

pearl venture
rotund vine how do i pass it?

if you just wanna edit an ephemeral message from another file then youll have to pass the interaction object that the message belongs to through to the other file then just call interaction.editReply like normal

if you wanna edit an ephemeral followUp then you need to store the followup message object in a variable then pass that into the editReply with the message argument

steel yacht
steel yacht

Oh sorry 😅

trail fog

How do you set footers with the new containers

steel trail

-# markdown

trail fog
pearl venture

i dont think you can use traditional footers
you have to just add a TextDisplayComponent and use -# before your message

steel trail

Containers are not embeds. They are containers

They are what bots should've had from the beginning so they would've never had to resort to abusing embeds like they do

cunning gazelle

What is deferReply for?

I'd assume it's to give your app more time to reply but idk

loud quartz

If you need more than 3 seconds to produce content for the reply

Since discord only gives you 3 seconds to respond

cunning gazelle

Ah right ty for confirming.

nova pond

Hello, I have a question about how to add a Thumbnailin a ContainerBuilder please ?

bleak owl
steel trail
sacred torrent

Hello where can I find the correct timeout thingy to find out when a person gets timedout in the auditlog

I'm trying to set up a moderationchannel so that I can see what happens in the server and log it in a channel but I can't seem to find the correct one for timingout

im using AuditLogEvent.(the thingy)

but I think im fucking it up

pearl venture

do you want to find timeout events in discords audit log or do you want an event called when someone is timed out?

topaz bluff

You can check the GuildMemerUpdate event to see if their communicationDisabledUntil != null

sacred torrent
pearl venture
sacred torrent

would that also work for serverdeafen?

stable sun

No

That’s under voiceStateUpdate

steel trail

Is it?

topaz bluff

Just a small nitpick. A GuildMember, not a User. There is a difference

pearl venture
stable sun

voiceStateUpdate is only move, leave, join vc

smoky glen

How to use attachment:// in MediaGalleryBuilder?

sharp ginkgoBOT

Files in embeds should be attached via the message option object and referenced in the embed:

const attachment = new AttachmentBuilder('./image.png', { name: 'image1.png' });
const embed = new EmbedBuilder()
  .setTitle('Attachments')
  .setImage(`attachment://${attachment.name}`);

channel.send({
  embeds: [embed],
  files: [attachment]
});
stable sun

Unless d.js changes this

steel trail

Same way as in embeds

smoky glen

Ty

steel trail
sacred torrent
red coral

Hi, iirc the messageUpdate event, the oldMessage can no longer be partial? (or can it)

sharp ginkgoBOT
red coral

I only ask because my types still say it can be a partial message, when was it added?

discord.js@14.19.3 is my version

export const event = new Event({
    event: "messageUpdate",
    async execute(client, oldMessage, newMessage) {

    }
})
// event type
import { type ClientEvents } from "discord.js";
import KFarm from "../client.js";

export class Event<event extends keyof ClientEvents> {
    public readonly event: event;

    public readonly once?: boolean;

    public readonly execute: (client: KFarm, ...args: ClientEvents[event]) => Promise<any>;

    public constructor(eventData: Event<event>) {
        this.event = eventData.event;
        this.once = eventData.once;
        this.execute = eventData.execute;
    }
}
steel trail

oldMessage can still be partial

red coral

but the docs have message ,message

steel trail

Because that's the JSDoc you look at

sharp ginkgoBOT
red coral

I mean I look at the docs

steel trail

From js point of partial messages are still instances of Message

red coral

Isn't that why the PartialMessage exists though?

steel trail

Events don't exist in TSDoc like they do in JSDoc

red coral

Is that not an error in the docs though, bit misleading to have message when it's not, or could not be

steel trail

But it is Message. It's not an error

The docs are documentation for JavaScript. Enhanced by types where types exist for the exact same thing. Which is not the case for events

cobalt tree

Hello! I am working on logging feature on my bot. Currently my member and moderation logs is not working. Can i know what docs should i look for?

red coral

Sorry, I'm a bit confused on what you're saying. It's a Partial Message or a message, but it is a message?

steel trail

Join the typescript community if you want to delve into the big mess that typings of EventEmitter is

sharp ginkgoBOT
red coral

I mean the jsdoc could have Message | PartialMessage type thing no?

steel trail

No, because PartialMessage is a pure ts construct. In js land there is no such thing at all

red coral

Ah right I think I understand what you mean. So it's the fact that you can't put ts constructs inside of jsdoc then. Would this be resolved when djs gets a full rewrite into ts? (or is that already a thing...)

steel trail

Ofc it would. Because then all types would actually exist in code. Currently there's quite a few "helper types" to make ts know about stuff based on information where the instance comes from. Which js can't know/do

red coral

Ok that's makes a lot of sense, thanks for taking the time to explain that

I swear I remember a while back they made a change to the messageUpdate, is this as they always send the full message on update? It was one of these events. I think I'm not remembering it correctly

steel trail

Yes, but that means the newMessage will never be partial

red coral

Ah, it was the newMessage

steel trail

They don't ever send the previous state

red coral

Yh gotcha, thanks again I appreciate it

solar pendant

is there any way to "refresh" a message? for example, if my message contains a variable inside the content, and the variable is updated, is there any way to also change the message without using message.edit and rewriting all the text again?

hallow mesa

I mean that's what functions are for. Just use one to generate the message and call it again when updating the message. You do have to edit the message though unless it's a very special case like formatted timestamps

solar pendant

it’s a big component that’s the problem

but i guess i can return a component with the data inside it

hallow mesa

Yeah. Pass whatever you need to the function and return the formatted component

steel trail

You can also make a new builder out of the message's component data and then edit the component in that builder

keen widget
pastel brook

Is there any way to distinguish if a mentionable option (or mentionable ID) is a user/member or role besides just trying to fetch it and see whether it errors?

zenith violet
pastel brook
rose tangle

I'd store the type in a separate field unless you only want to mention

otherwise you'd have to do mentionableId.includes("&") or something like that

and you'd also have to strip the <@> if you wanted to fetch the member/role

not the most performant approach

keen widget
rose tangle

please keep this channel only for djs help

pearl venture

setButtonAccessory is a function on a SectionBuilder not a ContainerBuilder

sharp ginkgoBOT
pearl venture

so you need to make a section with the text and button, and set that on the container

trail fog
pearl venture so you need to make a section with the text and button, and set that on the cont...

RangeError: Non-premium buttons must have a label and/or an emoji.
at validateRequiredButtonParameters (/home/container/node_modules/@discordjs/builders/src/components/Assertions.ts:123:10)
at ButtonBuilder.toJSON (/home/container/node_modules/@discordjs/builders/src/components/button/Button.ts:138:3)
at SectionBuilder.toJSON (/home/container/node_modules/@discordjs/builders/src/components/v2/Section.ts:150:56)
at /home/container/node_modules/@discordjs/builders/src/components/v2/Container.ts:236:61
at Array.map (<anonymous>)
at ContainerBuilder.toJSON (/home/container/node_modules/@discordjs/builders/src/components/v2/Container.ts:236:32)
at /home/container/node_modules/discord.js/src/structures/MessagePayload.js:151:46
at Array.map (<anonymous>)
at MessagePayload.resolveBody (/home/container/node_modules/discord.js/src/structures/MessagePayload.js:150:49)
at TextChannel.send (/home/container/node_modules/discord.js/src/structures/interfaces/TextBasedChannel.js:189:32)

How does this happen even though my button has labels AND an emoji

pearl venture
sharp ginkgoBOT

tag suggestion for @trail fog:
To share long code snippets, use a service like gist, sourcebin, pastebin, or similar instead of posting them as large code blocks or files.

trail fog

oh myf

pearl venture

I think this might be the issue

setButtonAccessory(
        new Discord.ActionRowBuilder().addComponents(item.button)
      );

setButtonAccessory accepts a button builder directly not an action row

trail fog

ohhh

rose tangle

you should look at the docs given you're having issues knowing what stuff each method takes

which is exactly what the docs document

trail fog

bro love yall

plush portal

how can i fix this ?
am using TS.

sharp ginkgoBOT

We highly recommend you extend the Client structure properly instead of just attaching custom properties like .commands to the regular discord.js Client instance.

shadow harness

Still a little mystified about interaction lifetime. Do all interaction objects become useless after 15m? Do I have to handle timeouts for every command?

clear garnet

Interaction webhook tokens expire after 15 minutes. After that, you cannot take any more actions on the webhook such as editing a reply or following up with another message

shadow harness
clear garnet

There is no way to refresh it. 15 minutes is 15 minutes. Listening for reactions is separate to interactions and they aren't really linked. If you have the Message object for the message you expect to b reacted on, you can listen for reactions. Using the withResponse option in your interaction replies allows you to get the Message instance so you can listen for reactions on it

shadow harness

So, using withResponseCall.resource.message.awaitReactions will last for longer than 15m, but I'd have to... send a new message to the channel on reaction?

topaz bluff

<Message>#edit() still works regardless of an interaction

shadow harness

Unless it's Ephemeral... alright, that's noice

clear garnet

(Or if it's a user-app)

topaz bluff

Correct. But what ephemeral message is still available after >15 minutes?

shadow harness
shadow harness

Alrighty, so basically if it's ephemeral, cope and just manage timeouts

New question... I just added my bot to a test server where I am not the owner nor an admin, and I can't run commands with it. However, there is another bot in the server that I can run commands with. Is this a simple mistake on my part somwhere?

clear garnet

By "can't run commands", do you mean they don't show up in the command picker?

shadow harness

Correct. I've refreshed Discord since I've encountered that before, but that didn't fix it

clear garnet

Could be a perms issue with the commands, or you didn't register your commands to that guild (if you aren't globally registering)

shadow harness

I've been globally registering, and just did it again with another refresh. I'll check with the owner later. Is there anything I can set within permission flags or required permissions with Discord?

topaz bluff

If there were DefaultMemberPermissions set up when the commands were first added to the server, then you would need a server admin to fix the command permissions on the Integrations tab. Or reinvite the bot without the default permissions

shadow harness
hushed mirage

can discord bot send voice message?

topaz bluff

No I don't believe so. But they can send .mp3 files which should have a play button

unique shoal

voice message is undocumented

rose tangle

it's possible but you're on your own for figuring it out ^^

you'll also need a raw rest request

topaz bluff

i assume you found your typo good sir...i was just about to say it

white plank

yeh

unique shoal

no

mellow tinsel

Does anyone know the character limit on the 'name' field for slash command choices?

frosty epoch

when it comes to custom branding (token sharing) what is the common practice architecture wise? Each token must be running its own separate instance, which means you cannot have a sharding manager handling different tokens?

proud arrow

You don't, it's against discords tos to share your token, as such you can't ask users for theirs

frosty epoch

More of a gray area since all major bots offer this feature tho

snow onyx

No, its not a gray area, its against the discord developer tos in section 2-D if I read it right

fallow finch

Isn't it that if you're a provider you can ask for bot tokens

snow onyx

"d. Developer Credentials
You will use any developer credentials (such as your Application ID, passwords, keys, tokens, and client secrets) we assign to you solely with your Application and the applicable APIs (and will not permit or enable any other Application to use them) and will treat them as Discord confidential information (as described below)."

fallow finch

I'm pretty sure there's another section that also states that you can share these informations to providers let me see if I can find it

Section 2D
You will use any developer credentials (such as your Application ID, passwords, keys, tokens, and client secrets) we assign to you solely with your Application and the applicable APIs (and will not permit or enable any other Application to use them) and will treat them as Discord confidential information (as described below). Without limiting the foregoing, you will keep API keys and tokens encrypted in any files or other materials accessible by third parties (other than your Service Providers, subject to Section 12(a)). For the avoidance of doubt, developer credentials may not be embedded in open source projects.

So if you're a service provider (in this case branding falls under as a provider) it is fine

frosty epoch

And that's why major bots have been doing it for the longest time

rose tangle

I'm pretty sure you don't count as a service provider since you're not just providing a host to the user, you're also providing the code

and the terms are set so if the token is misused, responsibility falls into the user to fix it

but if you share your token to do that, there's no way to do it

but better ask discord about it

until then we won't really support stuff with "gray areas"

mellow marsh

doesn't ephemeral flag work with is_component_v2?

snow onyx

only interaction replies can be ephemeral

normal messages cant

scenic berry

how can i show the icons inside the buttons?

sharp ginkgoBOT
mellow marsh
pearl roost

i can't use both? what's wrong with it?

polar karma

withResponse in the options does not make reply() return a message object

sharp ginkgoBOT
upbeat saffron

is it possible to display an emoji withing a codeBlock? I'm trying but its not working 😦

obtuse laurel
upbeat saffron
obtuse laurel

No

steel yacht

Hi,
Do link buttons automatically open external links in the user's browser on click ?
Thanks

steel trail

Depends on user settings. They work like regular links

steel yacht

Okay thanks

slow veldt

Then send the message.

zenith violet

codeblocks dont resolve them

scenic berry

is it alright if i dont load the components like buttons? i will still get the custom id of the buttons?

slow veldt
tidal wolf

how can i achieve something similar to autocomplete on a string select menu?

I have more than 25 options

pearl venture

id love discord to add something like this but at the moment the only options that i can think of are to add a button to search which filters the options or to add next/prev page buttons that shows the next 25 options

tidal wolf

Roger

pearl venture

if you need channels, users or roles discord has an autocomplete type thing on those select menus just not on string select menus

thorn gate

how to disable reply mention

like when bot replies it pings

lavish wasp

Hi guys! I have a question. I have created a command using Components v2. but I want to change the message from components v2 to embed in case the operation is canceled. Is it possible to convert the message from components v2 to embed?

Oh btw, i want to change from components v2 to embed while editing message.

pearl venture
lavish wasp
sharp ginkgoBOT
rigid crest

so jumping to this; i found where i have a collector.stop in all the files from a deep search just one collector has a stop but it doesnt help the error in console doesnt say what command, but im certain its this one in my fun command as its the only command file that is present with on, but i think i used collector stop elsewhere also

collector.on('end', (collected, reason) => {
                if (reason === 'time') {
                    const str = interaction.commandName;
                    const result = str.charAt(0).toUpperCase() +
                        str.slice(1).toLowerCase();
                    interaction.editReply({
                        content: `${result} Expired,\nRemoved Components`,
                        embeds: [],
                        components: [],
                        files: [],
                        flags: MessageFlags.IsComponentsV2,
                        allowedMentions: { parse: [] }
                    });
                    collector.stop()
                }
            });
pearl venture
lavish wasp
pearl venture i dont think this is possible

i tried flags: 0 but i got this error;

Setup interaction error: DiscordAPIError[50035]: Invalid Form Body
flags[MESSAGE_CANNOT_REMOVE_COMPONENTS_V2_FLAG]: The MessageFlags.IS_COMPONENTS_V2 flag cannot be removed from a message once it has been set.

so yeah prob. not possible

Thank you for your answer anyway.

ocean portal

what is shard/Cluster?

sharp ginkgoBOT

guide suggestion for @ocean portal:
guide Sharding: Getting started - How does sharding work?
read more

ocean portal

I see, will need this when my bot becomes a large/famous.

zenith violet

That error also has nothing to do with collector.stop being called

all collectors will eventually end. Whether manually or when the time expires

Though that error usually pops up on promisified collectors

ocean portal

A question; how does integration code grant works? I'm really confused

rocky anvil

Hello there can someone share the links to the docs of new components v2 I can't seem to find them for some reasons

sharp ginkgoBOT

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

ocean portal

I just sent this on DDevs.

zenith violet

no, editReply does

radiant epoch

Does discord.js has AutoModRule_Builder()_ or something works as that? I like to go with all builders or classes rather than objects

sharp ginkgoBOT
wary coral

I believe the create function is the closest

bleak owl

you already have a post open. please do not cross post.

bleak owl

have patience until someone can help inside your thread

which is waiting more than 2 minutes

rose tangle

and use a bin instead of filling the entire chat

sharp ginkgoBOT

To share long code snippets, use a service like gist, sourcebin, pastebin, or similar instead of posting them as large code blocks or files.

zenith violet

and what part do you have issues with?

also

sharp ginkgoBOT

To share long code snippets, use a service like gist, sourcebin, pastebin, or similar instead of posting them as large code blocks or files.

torn orchid

alr

torn orchid
zenith violet and what part do you have issues with?

I don't have any issues. I would like to know how to create a feature where, when someone clicks on the "Sessions Role" button, it assigns the Sessions role and, if clicked again, removes it. However, I also want to include a custom message that adds a role to someone and removes it.

sharp ginkgoBOT

guide Popular Topics: Frequently asked Questions - How do I add a role to a guild member?
read more

worthy drift
torn orchid I don't have any issues. I would like to know how to create a feature where, whe...

you most likely need to add an button handler like you did for your command right here.
you can do that by creating an interactionCreate event listener and check if the interaction is a button:
if (!interaction.isButton()) return
then you check for the button id:
if (interaction.customId = 'your button id') {/*your code goes here*/}
i just saw in your code you dont even have set a custom id for the button yet, dont forget to do that

zenith violet

(you'd preferably use the interactionCreate event you already have

and make a handler based on component type

vapid copper
zenith violet

that is your handling for your interactionCreate

but i dont see your actual interactionCreate event there

sharp ginkgoBOT

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
worthy drift
steel trail
vapid copper

events.js

const { readdirSync } = require("fs");
module.exports = (Bot) => {
    const events = readdirSync("./events").filter(file => file.endsWith(".js"));
    let k = 0;
    for (let file of events) {
        try {
            let event = require(`../events/${file}`);
            if (event.event && typeof event.event !== "string") { console.log(file, `Should be string`); continue; }
            event.event = event.event || file.replace(".js","");
            Bot.on(event.event, event.run.bind(null, Bot));
            k++;
        } catch(err){
            console.error("Events not Loaded!");
            return console.log(err); 
        }
    }
    return console.log(`${k} Events Loaded.`);
}

and then in main.js

// Load all handlers (e.g., events and slash commands)
for (const handler of ["events", "slash_cmds"]) {
    require(`./handlers/${handler}`)(Bot);
}

I load it

steel trail

And what happens when you type in that stringoption in your command?

cunning gazelle

I use roles.cache.has in replit and works fine, but when I host it on railway it just doesn't work

zenith violet
steel trail
torn orchid
sharp ginkgoBOT
cunning gazelle
zenith violet define doesnt work

The requirement is for the user to have a specific role. For replit it verifies it and continues with the script. With railway, it stops there and doesn't go further indicating that the requirement isn't satisfied, even though it is.

zenith violet

follow the guide

zenith violet
steel trail
cunning gazelle
zenith violet

ids are strings

worthy drift
zenith violet

not numbers

steel trail
vapid copper
cunning gazelle
zenith violet

also fyi both replit and railway are a bad choice for ''hosting''

cunning gazelle

Works now

cunning gazelle
zenith violet

any free host will eventually lead to ratelimits, ip bans or network errors

inner nexus

Hello, can someone enlighten me and help me with my problem please ? ```js
Error: Not enough sessions remaining to spawn 1 shards; only 0 remaining; resets at 2025-06-07T04:30:01.111Z
Stack: Error: Not enough sessions remaining to spawn 1 shards; only 0 remaining; resets at 2025-06-07T04:30:01.111Z
at WebSocketManager.connect (/home/container/node_modules/@discordjs/ws/dist/index.js:1458:13)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async WebSocketManager.connect (/home/container/node_modules/discord.js/src/client/websocket/WebSocketManager.js:200:5)
at async Client.login (/home/container/node_modules/discord.js/src/client/Client.js:228:7)

loud quartz

your bot has logged in 1000 times in a span of 24 hours

inner nexus

or reset the token

zenith violet

use that time to do so

inner nexus
zenith violet

you have to figure out why

something caused your bot to get into a crash loop

up to you to figure out why and make it not happen anymore

inner nexus
loud quartz

still, please figure out why your bot has restarted a thousand times

vital vortex

anyone got an example of adding a regular select menu to a container? idk why but i cannot get it to work

        const featureSelectComponent = new StringSelectMenuBuilder({
            custom_id: 'a cool select menu',
            placeholder: 'select an option',
            options: [
                { label: 'option 1', value: '1' },
                { label: 'option 2', value: '2' },
                { label: 'option 3', value: '3' },
            ],
        });
        const containerComponent = new ContainerBuilder()
            .addSectionComponents(sectionOne)
            .addSeparatorComponents(separatorComponent)
            .addSectionComponents(sectionTwo)
            .addSectionComponents(sectionThree)
            // .add(featureSelectComponent)
            .setAccentColor(0xffff69)
``` breaks everything
sharp ginkgoBOT
rose tangle

notice how every method is named addXComponents()

not just add()

vital vortex

oh sick, got it. thank you!!

frank pasture
const cron = require('node-cron');
const fs = require('fs');
const path = require('path');
const config = require('../config/config.json')

async function reboot() {
    console.warn('[REBOOT] Attention, Catherine redémarre (checker les logs). Instruction reboot.js')
    process.exit(0)
}

function scheduleReboot() {
  // Puis tous les jours à 8h
  cron.schedule('0 5 * * *', () => reboot(), {
    timezone: "Europe/Paris"
  });
}

module.exports = { scheduleReboot };
Waiting for the debugger to disconnect...
node:events:497
      throw er; // Unhandled 'error' event
      ^

RangeError: Invalid time value
    at DateTimeFormat.formatToParts (<anonymous>)
    at buidDateParts (E:\OneDrive\MyDocs\Developpment\Discord\CATHERINE-BOT\node_modules\node-cron\dist\cjs\time\localized-time.js:52:30)
    at LocalizedTime.set (E:\OneDrive\MyDocs\Developpment\Discord\CATHERINE-BOT\node_modules\node-cron\dist\cjs\time\localized-time.js:32:22)
    at findNextDateIgnoringWeekday (E:\OneDrive\MyDocs\Developpment\Discord\CATHERINE-BOT\node_modules\node-cron\dist\cjs\time\matcher-walker.js:41:18)
    at MatcherWalker.matchNext (E:\OneDrive\MyDocs\Developpment\Discord\CATHERINE-BOT\node_modules\node-cron\dist\cjs\time\matcher-walker.js:73:22)
    at TimeMatcher.getNextMatch (E:\OneDrive\MyDocs\Developpment\Discord\CATHERINE-BOT\node_modules\node-cron\dist\cjs\time\time-matcher.js:36:29)
    at getDelay (E:\OneDrive\MyDocs\Developpment\Discord\CATHERINE-BOT\node_modules\node-cron\dist\cjs\scheduler\runner.js:163:33)
    at Runner.start (E:\OneDrive\MyDocs\Developpment\Discord\CATHERINE-BOT\node_modules\node-cron\dist\cjs\scheduler\runner.js:110:12)
    at InlineScheduledTask.start (E:\OneDrive\MyDocs\Developpment\Discord\CATHERINE-BOT\node_modules\node-cron\dist\cjs\tasks\inline-scheduled-task.js:84:25)
    at Object.schedule (E:\OneDrive\MyDocs\Developpment\Discord\CATHERINE-BOT\node_modules\node-cron\dist\cjs\node-cron.js:24:10)
Emitted 'error' event on Client instance at:
    at emitUnhandledRejectionOrErr (node:events:402:10)
    at process.processTicksAndRejections (node:internal/process/task_queues:84:21)

i really don't understand, it worked yesterday

Debug ER
Uncaught RangeError RangeError: Invalid time value
at buidDateParts (e:\OneDrive\MyDocs\Developpment\Discord\CATHERINE-BOT\node_modules\node-cron\dist\cjs\time\localized-time.js:52:30)
at set (e:\OneDrive\MyDocs\Developpment\Discord\CATHERINE-BOT\node_modules\node-cron\dist\cjs\time\localized-time.js:32:22)
at findNextDateIgnoringWeekday (e:\OneDrive\MyDocs\Developpment\Discord\CATHERINE-BOT\node_modules\node-cron\dist\cjs\time\matcher-walker.js:41:18)
at matchNext (e:\OneDrive\MyDocs\Developpment\Discord\CATHERINE-BOT\node_modules\node-cron\dist\cjs\time\matcher-walker.js:73:22)
at getNextMatch (e:\OneDrive\MyDocs\Developpment\Discord\CATHERINE-BOT\node_modules\node-cron\dist\cjs\time\time-matcher.js:36:29)
at getDelay (e:\OneDrive\MyDocs\Developpment\Discord\CATHERINE-BOT\node_modules\node-cron\dist\cjs\scheduler\runner.js:163:33)
at start (e:\OneDrive\MyDocs\Developpment\Discord\CATHERINE-BOT\node_modules\node-cron\dist\cjs\scheduler\runner.js:110:12)
at start (e:\OneDrive\MyDocs\Developpment\Discord\CATHERINE-BOT\node_modules\node-cron\dist\cjs\tasks\inline-scheduled-task.js:84:25)
at schedule (e:\OneDrive\MyDocs\Developpment\Discord\CATHERINE-BOT\node_modules\node-cron\dist\cjs\node-cron.js:24:10)
at scheduleReboot (e:\OneDrive\MyDocs\Developpment\Discord\CATHERINE-BOT\utils\reboot.js:13:8)
at execute (e:\OneDrive\MyDocs\Developpment\Discord\CATHERINE-BOT\events\ready.js:143:9)
at processTicksAndRejections (<node_internals>/internal/process/task_queues:95:5)

        scheduleReboot()
ready at 143:9
loud quartz

cron and its input isn't really discord.js related

frank pasture

yes i know but i don't know where to get help sorry ^^'

loud quartz
frank pasture

thanks

harsh kernel

where does this is use UserPremiumType?

unique shoal

Bots are not given that information

harsh kernel

bruh

not event the boost badge or nitro badge?

versed ivy
harsh kernel

ok ok thanks

subtle girder
client.on(Events.MessageDelete, async (message) => {

Doesn’t the message object have an author attribute now?

clear garnet

Not if the message isn't cached

Discord doesn't provide the full data of the message when it's deleted - only the message ID, channel ID, and guild ID (if sent in a guild), so d.js has to rely on its cache for any extra data related to the message

subtle girder

oh ,ty

subtle girder
clear garnet Discord doesn't provide the full data of the message when it's deleted - only th...

this is my code

client.on(Events.MessageDelete, async (message) => {
    if (!message.guild) return;
    try {
        const { backend_channel_ID, backup_database_channel_ID } = require("../config.json");
        const backendchannel = await client.channels.fetch(backend_channel_ID);
        if (!backendchannel) return;

        const messageId = message.id
        const channel = message.channel;
        message = channel.messages.cache.get(messageId);

        const user = message.author;
        // ...
    } catch (err) {
        // ...
    }
});

But the message is still undefined

TypeError: Cannot read properties of undefined (reading 'author')
    at Client.<anonymous> (I:\VSCodefile\Discord\hugocommandbot_cog_JS_BETA\thebotfunction\anythinglog.js:82:38)
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
clear garnet

I mean, yea. Like I said, if the message isn't cached, nothing but the message & channel IDs are guaranteed. You doing that if (!message.guild) return; isn't really gonna help prevent that error

Don't subscribe to partials if you consistently want message data for events that heavily rely on the cache like the messageDelete event does

subtle girder

oh, so I added the ClientOption before.

partials: [
    Partials.Message,
    Partials.Channel,
    Partials.GuildMember,
    Partials.User,
    Partials.GuildScheduledEvent,
    Partials.Reaction,
],

Then it cause this problem

topaz bluff

Partials means that sometimes you might recieve incomplete objects in Events

clear garnet

message = channel.messages.cache.get(messageId);
Doing this is pointless. d.js already tries to resolve the message from cache internally before deciding whether to emit the event or not

topaz bluff

AKA, you might get a messageDelete event without the user who created the message...if you want to ensure you always have the full Message object, remove the partial

subtle girder

oh, tysm

clear garnet
topaz bluff

You can also handle the case where the data is incomplete by casting the undefined value to something else

const user = message.author ? message.author : 'Unknown User';
calm maple

me when ??

topaz bluff

what?

karmic hedge
topaz bluff what?

he’s referring to the nullish coalescence operator although these statements are not equivalent

fading girder

hey guys, need help on this. I am trying to have a command that opens a modal and I do,

        const modalInteraction = await interaction.awaitModalSubmit({
            filter: (i) => i.customId === allowedCustomId && i.user.id === interaction.user.id,
            time: COLLECTOR_TIMEOUT,
        });
if(!modalInteraction) return;
await modalInteraction.deferReply();

When I don't submit and I do the command and submit, I get the unknown interaction error... what do I do to fix this

proud arrow

Probably because your previous collector is still active and both try to collect that modal interaction. Make each custom id unique, you can append the original interaction id to it, and check for that id in filter

fading girder

If there’s no other way then I’ll go with that.

proud arrow

Appending a unique id to existing id shouldn't be that hard

And no, this is the only way. modal collectors are just plain interactionCreate listener without any specific target to filter expect a custom_id (or channel, guild), unlike components, which can be created on message

fading girder

got it

agile nest

does section require text display?

steel trail

Yes

steel trail

Everything that changes a property of a Guild. Name, icon, owner, discovery settings, features, system channel, vanity code, banner, etc.

No. That's what guildMemberAdd and Remove are for

Yes

Then you won't have access to that information

depends on what "frequently enough" is. And you'd need to force fetch the guild probably

The optional chaining there causes undefined, yes

But without GuildMembers intent that number won't ever update

What's the use case for getting that number in real time if I may ask?

Use server widget or invite for showing those then

wet goblet

when i use channel.threads.fetch()
i got error DOMException [AbortError]: This operation was aborted

why ?

steel trail

Then that's exactly why that's a privileged intent. So you don't do things like that

steel trail

You can fetch the approximate member count. But honestly, if it's for a website it'd be better to use widget data as that fetches/caches the information for when someone actually views the website

wet goblet
steel trail
loud quartz

You receive the number alongside the guild during login

From there on out, d.js updates it with relevant member events

urban schooner

I am wondering if I want to add a new permission like Administrator to my bot, while there is already over 13,000 servers added the bot, is there a way to enable that permission in servers who added the bot already ?

loud quartz

Of course not

Privilege escalation like that is not something that can happen because you want to

There's no need for your bot to need administrator permission.

urban schooner
loud quartz

Still no

urban schooner

They have to re-add the bot ?

loud quartz

You can't just.. will the permission into existence

No, they can just edit the roles

urban schooner
loud quartz
urban schooner

It will be really hard to explain that to everyone

loud quartz

Link them a guide

urban schooner
loud quartz

That's fine

Return an error when they try to use it

And your bot doesn't have the permission

There you can tell exactly what's missing and how to enable it

Or why

steel trail

Then those who don't manage to (or don't want to) add those permissions to your bot by reinvite or editing the role won't be able to use that feature. Simple as that. You need to account for missing permissions anyway

urban schooner

is there like a button that an admin or owner in that server can click and it will show them the new perms that they can change ?

loud quartz

No

There is no deep linking into the app or its parts

urban schooner

I want everyone to be able to get access, so I was trying to find new methods to give them that

loud quartz

There is none

It all involves your bot getting that permission

One way or another

Re inviting the bot can have some other consequences that people might have no idea about

urban schooner

thank you

cunning gazelle

Is there a way to make the bot record everything in the vc when requested?

polar karma

Sure, but it's largely outside the scope of d.js. you get the incoming stream from the user and then save it

cunning gazelle
sharp ginkgoBOT
steel trail
zenith violet

Markdown no, you'll have to use a regex

polar karma

You can use /voice to get the stream, but what you do after that is outside of d.js

cunning gazelle
steel trail

No, you can subscribe to all users, just need to combine the streams if you want it as one file in the end

cunning gazelle

Alright.

sharp ginkgoBOT

function escapeMarkdown discord.js@14.19.3
Escapes any Discord-flavored markdown in a string.

zenith violet

that escapes markdown

It doesnt tell you something contains markdown

It escapes markdown characters

you could hack it like that yeah.

keen patio

Could someone help me?

unique shoal

Just post your problem and someone will

keen patio

the bot does not give the icon that supports slash commands but i made one, how is it possible?

pearl venture
keen patio
keen patio
pearl venture

was the bot added with the application.commands scope

keen patio

Yes

pearl venture

how long ago did you register the command and have you restarted your discord since?

zenith violet
keen patio
zenith violet

and if you dont see the commands at all, did you deploy them

if so, how

pearl venture

how did you register your commands to discord?

keen patio
zenith violet

did you confirm you are actually sending any data to discord

keen patio

I think so

zenith violet

and what are you sending to discord

keen patio
zenith violet

so no, you did not confirm

Log and see what you are actually sending

keen patio

Do you want me to send the deploy-commands.js file?

zenith violet

sure

sharp ginkgoBOT

To share long code snippets, use a service like gist, sourcebin, pastebin, or similar instead of posting them as large code blocks or files.

keen patio

Ok

zenith violet

first confirm you are actually sending any data and loading your commands properly

keen patio
zenith violet

So what does it log

keen patio
zenith violet

They cant

zenith violet

So how

We shouldn't have to teach you how to debug

Log the body you are sending to discord

keen patio

It is registered

do I debug?

zenith violet
keen patio
pearl venture

how do you know it's registered then

keen patio

Now yes

How is it lonely now?

zenith violet

what?

is it registered or not

keen patio

Now yes

zenith violet

ok, so whats your issue now then

keen patio

I mean why only now?

zenith violet

you probably didnt run the register script properly

keen patio

Ok, thank you

night kindle

Hi Im a beginner at discordjs and Ive been following the official guide for it, I made a ban slash command here is its code:

module.exports = {
    category: 'mod',
    data: new SlashCommandBuilder()
        .setName('ban')
        .setDescription('Bans a member')
        .addUserOption(option => 
            option.setName('member')
            .setDescription('The member to ban')
            .setRequired(true))
        .addNumberOption(option =>
            option.setName('purge')
            .setDescription('How many messages to purge that the member has sent in the last 7 days(optional)')
            .setMinValue(1)
            .setMaxValue(7)
            )
        .addStringOption(option =>
            option.setName('reason')
            .setDescription('Reason for the ban'))
        .setDefaultMemberPermissions(PermissionFlagsBits.BanMembers)
        .setContexts(InteractionContextType.Guild),
    async execute(interaction){
        const member = interaction.options.getMember('member');
        const purgedDays = interaction.options.getNumber('purge') * 86400 ?? 0;
        const reason = interaction.options.getString('reason') ?? 'No reason specified';
        try {
            await member.ban({deleteMessageSeconds: purgedDays, reason: reason});
            await interaction.reply(`${member.username} Has been banned! Reason: ${reason}`);
        } catch(error) {
            console.error(error);
            await interaction.reply({content:`[ERROR] There was an error while executing the ban command,\n \`${error}\``, flags: MessageFlags.Ephemeral})
        }
    }
};

The problem I want to solve is that the ${member.username} returns undefined so it looks like 'undefined was banned' ik this probably happens because as soon as the user gets banned his 'member' object gets deleted or sth so I can't even get the username property of them, can someone provide a way to sort of cache them before banning or sth like that? sorry for the newbie questions

sharp ginkgoBOT

Despite sounding similar there is a distinct difference between users and members in Discord:

  • User: global Discord user data (global avatar, username, tag, id)
  • GuildMember: user data associated to a guild (guild, nickname, roles, voice, guild avatar, etc.)
  • Conversion: User ➞ GuildMember | GuildMember ➞ User
    * Note: Events received in cached guilds will often have both the member and user available, eg. interaction.user and interaction.member
woven portal

do slashcommandbuilder allow user installations yet?

steel trail

The member variable there is still populated with the GuildMember, you're just accessing the wrong property

steel trail
rose tangle

guild members don't have usernames, users do

toxic moat
woven portal
night kindle
rose tangle
woven portal
rose tangle

not raw numbers

even if you're using raw data

sharp ginkgoBOT
keen jungle

A doubt, do you have a doc link of these flexible messages? How to use them etc? You can send me please

night kindle