#djs-help-v14

78874 messages · Page 10 of 79

deft wedge
quiet hinge

Is it possible to get the original ID of the user that used a command by the interaction of a button in this said message?

Like I do a command /messageWithButton the bot reply to that command with a message and a button, can I get the ID of the user who made the command?

sharp ginkgoBOT
steel trail

It‘s in there, on the <ButtonInteraction>.message

steel trail

One per ActionRow. Total components limit is 40

So absolute max would be 19

But that would not be a nice message to work with

No. 19 ActionRows, 19 menus, 1 container = 39 components

Yes

toxic moat

you have a dot after item.ign instead of a comma

magic flume

Hi, is there a way to not have to define an emoji when using StringSelectMenuOptionBuilder ?

proud arrow

Wdym by not have to define emoji? It's optional, you don't need to provide it

magic flume

ig but I'm getting TypeError: Cannot destructure property 'emoji' of 'selectMenuOption' as it is undefined.

I'm probably doing something wrong then

    const selectMenu = new StringSelectMenuBuilder()
            .setCustomId('selectSquad')
            .setOptions(squads.slice(0, 25).map(squad => {
                new StringSelectMenuOptionBuilder()
                    .setLabel(`${squad.id}`)
                    .setValue(squad.name);
            }));
proud arrow

Can you show the full error please?

red coral

Am I also right by saying since you don’t return anything from the .map it’ll result in an empty array?

proud arrow

Ah, that is true as well

magic flume

it's always when you ask that you find your stupid error

red coral

If you didn’t ask you’d have found it later

vast bloom

im sure this question has been asked millions of times but

// if i have a message thats stored in a variable like this
const sent = await message.reply("hi")

// and then significantly later i try to access it
setTimeout(() => {
    await sent.edit("bye")
}, 60 * 60 * 1000)

// how do i ensure at this point sent hasn't been deleted?
// if someone manually deletes it before now then it throws an api error for `Unknown Message`
zenith violet

Catch the rejection when editing

vast bloom

is there not any other method than catching it

zenith violet

No

red coral

Hi, what can cause an error like this?

TypeError: Cannot read properties of null (reading 'byteLength')
    at Object.pull (C:\...\node_modules\undici\lib\web\fetch\body.js:63:20)
    at ensureIsPromise (node:internal/webstreams/util:185:19)
    at readableByteStreamControllerCallPullIfNeeded (node:internal/webstreams/readablestream:3099:5)
    at readableByteStreamControllerPullSteps (node:internal/webstreams/readablestream:3207:3)
    at [kPull] (node:internal/webstreams/readablestream:1197:5)
    at readableStreamDefaultReaderRead (node:internal/webstreams/readablestream:2243:39)
    at nextSteps (node:internal/webstreams/readablestream:507:7)
    at async writeIterable (C:\...\node_modules\undici\lib\dispatcher\client-h1.js:1437:22)```
rose tangle

sounds like a problem while fetching, probably when trying to send an attachment based on its url?

could try fetching yourself and sending the buffer instead

soft socket

I just updated to D.js 14.19.3, updated my Gatewayintentbits, and now messages don't seem to have a "channel" property (in a server)

They have the channelId, but not the actual channel property, has something changed? I have:
GatewayIntentBits.Guilds
GatewayIntentBits.GuildMessages
GatewayIntentBits.MessageContent

Is there something I'm missing?

rose tangle

don't seem to have, or it's null?

and where are you checking that?

soft socket

It's undefined, I have a ton of things that reference message.channel.send() but they all don't work anymore since channel is undefined

I printed Message to the console as well but it's not there

<ref *1> Message { channelId: '547950347814174720', guildId: '135207762299715584', id: '1370808735542280323', createdTimestamp: 1746896670948, type: 0, system: false, content: '!eval main.syncCalendar()', author: User { id: '151030795753095168', bot: false, system: false, flags: UserFlagsBitField { bitfield: 4195072 }, username: 'kiwiz0', globalName: 'Kiwi', discriminator: '0', avatar: '4f3d4d34be7d494787a0d407bfeb98d1', banner: undefined, accentColor: undefined, avatarDecoration: null, avatarDecorationData: null }, pinned: false, tts: false, nonce: '1370808739124215808', 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 }

steel trail

Just because it doesn’t print here doesn’t mean it’s undefined

It‘s a getter from cache, not an enumerable property

hexed marsh

Is there some special magic I need to use, to add a StringSelectMenuBuilder on a ContainerBuilder?

export class BeginQuestSelector extends StringSelectMenuBuilder {
    public customId: string;
    
    constructor(gameNames: string[]) {
        super();
        const selectorId = `selector:beginQuest:${randomUUID()}`;
        this.customId = selectorId;
        
        if (gameNames.length === 0 || gameNames.some(gameName => gameName.length === 0)) {
            throw new Error('Join Quest is improperly configured. Check the configuration.');
        }
        
        this.setCustomId(selectorId)
            .setPlaceholder('Select a quest to begin...')
            .setMinValues(1)
            .setOptions(gameNames.map(gameName => ({ label: gameName, value: gameName })));
    }
}

I'm attempting to put that into a container, (Works just fine for an embed)

    if (quests.length > 1) {
        const beginQuestSelector = new BeginQuestSelector(quests);

        container.addActionRowComponents(
            new ActionRowBuilder<BeginQuestSelector>()
                .addComponents(beginQuestSelector)
        )
    } else {
        container.addActionRowComponents(
            new ActionRowBuilder<ButtonBuilder>()
                .addComponents(
                    new ButtonBuilder()
                        .setCustomId(decodedId.customId)
                        .setLabel(`Begin Quest: ${quests[0]}`)
                        .setStyle(ButtonStyle.Success)
                )
        )

        await interaction.reply({
            components: [container],
            flags: MessageFlags.IsComponentsV2
        });
    };
wary coral
hexed marsh

Uhhh it is being added... right there after the quest length conditional check xD

steel trail
hexed marsh

I even tried using a plain ole "StringSelectMenuBuilder" without my implementation, and statically defined values, even that didn't work

steel trail
hexed marsh

That's the weird part, just times out, no errors, nothing.

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
hexed marsh

Yep done all that too. Stops here. Everything appears valid.

steel trail

Your debugger causing you to not actually find the bugs

hexed marsh

No that was the first thing I checked lmao

steel trail

Run your code regularly, add the logs the tag mentions, show what logs and what doesn’t. And make sure you don’t have any uncaughtException or catch blocks interfering with you getting the actual errors

soft socket
hexed marsh

I'm stupid asf.. I found the problem

wary coral

what was it?

rose tangle

and where is the message coming from

crimson thistle

how big is the difference of the Large and Small size of the SeparatorSpacingSize? i feel like it's basically none

soft socket
rose tangle

so messageCreate?

soft socket

Yeah

rose tangle

can you npm ls discord.js

and show your full client constructor

soft socket

wg-bot@4.4.0 /mnt/c/Code/Javascript/WG-Bot └── discord.js@14.19.3

export const bot = new Client({
    autoReconnect: true,
    messageEditHistoryMaxSize: 2,
    messageCacheMaxSize: 250,
    fetchAllMembers: true,
    intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildExpressions,
    GatewayIntentBits.GuildWebhooks, GatewayIntentBits.GuildInvites, GatewayIntentBits.GuildVoiceStates, GatewayIntentBits.GuildScheduledEvents, GatewayIntentBits.MessageContent,
    GatewayIntentBits.GuildInvites]
});```
steel trail

Only intents are actual properties that djs client accepts. All the rest doesn’t exist

Unless your Client class there is not imported from discord.js

steel trail
soft socket

I'll remove them, I think they're all leftover from a very old version

steel trail

Is message by any chance the result of an <Interaction>.reply()? nvm, you already said it isn’t

rancid folio

Hey, is there any ETA on when the builders will be updated to support the new expanded component limits, or has that already been done?

rancid folio
steel trail Already done

Weird, I've still got the 10 component limit for some reason. I'll try updating again and see what happens.

steel trail

Need builders 1.11.2

Which 14.19.3 depends on

rancid folio

okay, weird, i was certain i had already updated to 14.19.3 but after double checking it looks like it decided to go back to 14.19.2 (or i just never updated it properly)

oh well, fixed, thank you!

soft socket
steel trail Can you show the code where this error gets thrown? And the full error including...
//Developer_Commands.js
export function evalFunc(message)
{
    console.log(message);
    try 
    {
        let args = message.content.slice(1).trim().split(/ +/g);
        const code = args.slice(1).join(" ");
        let evaled = evalFunc(code);


        if (typeof evaled !== "string")
            evaled = require("util").inspect(evaled);

        //message.channel.send(evaled, {code:"xl"});
    }
    catch (err)
    {
        message.channel.send(`\`ERROR\` \`\`\`xl\n${err}\n\`\`\``);
        console.log(err);
    }
}

// ... 
//Command_Check.js
case 'eval':
            if(permLevel>=6)
            {
                developerCommands.evalFunc(message);
            }
            else
            {
                message.channel.send('Insufficient permLevel');
                                // This works, but after being passed to evalFunc, it no longer has channel
            }
// ...

//bot.js
bot.on('messageCreate', async message => {
// ... message is not overwritten anywhere
checkCmd(messageArray, message, bot, args, command, channel);
// channel is message.channel

I figured it out but I'm really baffled on how it broke it. I did a rename symbol in VSCode to rename my function that was called eval. That made the eval in the try block "evalFunc()" instead of eval()

Undoing that fixed it somehow

rose tangle

evalFunc tries to call itself with the code string instead of message, then it can't access message.content, goes to the catch, there's no message.channel either, error

typescript would've caught that dogeHaHa

soft socket

Damn yeah I usually do use Typescript but this code is like 5 years old at this point, just updating from d.js 12 and node 16 lol

Crazy how a function can call itself from within

rose tangle

it's called recursion, you've discovered it by mistake

soft socket

I have to get better about going to debugging instead of console logging T.T

Thanks for the help pals!

terse valley

hi i have a question maybe this is a common issue i don't know but im using

.setThumbnail(target.displayAvatarURL({ dynamic: true }))

in my embed, the image is appearing on my android phone but not on iphone

does anyone know the issue here? or why it's not appearing on iphone?

zenith violet

sounds like a client issue then

nothing djs can do about

terse valley

do you have an iphone?

zenith violet

no

and this is not djs related if it works on other devices

terse valley

i personally don't care, cause i have an android i just wanna know if this is a common issue that images don't appear on a iphone

so i don't have to try search for solutions to fix it, so if it never works on a iphone please let me know

zenith violet
terse valley

o my bad i thought this server knows, do you know what server i need to go to?

zenith violet

sigh

re-read my message

terse valley

no thanks ill just find the right server, fyi. the ''sigh'' makes u sound whiney

rose tangle

ddevs = discord developers, it's a server

zenith violet

it doesnt take much effort to just click

terse valley

not going to lie i still don't knwo which server it is, there's a list of all kinds

thorn bridge
terse valley

ah thank you

rose tangle
terse valley

sorry i didn't know what ddevs means i was looking for it, but now i see u means = discord developers haha

thorn bridge

Amgelo has told you what ddevs means

terse valley

i know but i was looking for that word specifically, nowhere to be found

rose tangle

forgot to reply, there's some internal discussion on how to address it

imo it'll most likely be "fixed", though that wrapping shouldn't have been a thing in the first place

rose tangle

in the meantime you can use resolvePartialEmoji which is what the ButtonBuilder uses

hexed marsh
crimson thistle

hello,

so i'm making a ticket system where, when a modal is submitted, a channel is created with the name "appeal-membername"
i'm currently trying to make a system where, if a mod decides to decline the appeal, a string menu would appear with different options of why to decline to appeal
thing is, how do i send a dm to the member who submitted the modal?

rose tangle

do you have a db?

if yes, you should be saving the channel id and the member that created it and just query that

crimson thistle

so the best thing i can do is set up a data base?
should i do that with sequelize?

rose tangle

if not, you could use the channel name to search the GuildMember, but if they change their username you're out of luck, you could save it to the description but then again if that description is changed it breaks

the most straightforward and constraint-less way would be with a db, yes

what db and orm you use depends entirely in your preferences and usage

crimson thistle

alright, thanks

ivory sable

Does MediaGalleryBuilder not handle audio/audio links?
Is there something that does, or does discord not support in message audio like that

steel trail

It doesn’t and no, not in components (yet?)

ivory sable

Thats a shame, but thank you. Guess I'll have to look into another way to handle them

steel trail

Well, you can put them as File component. It will show as file/attachment. just probably not as playable in the UI directly

ivory sable

I was gonna try that actually, there's a fileBuilder same way there's a textDisplayBuilder and MediaGalleryBuilder, right?

rose tangle

yes

sharp ginkgoBOT
rose tangle

they do show as files though

and it's intended that way

in the future as Qjuh said maybe they'll add some playable component

ivory sable

I see, thank you so much!

craggy flare

Is there any reason why these loading dots show at the bottom of my sent container component?

They don’t show on desktop, only on mobile.

rose tangle

client bug, ask discord

craggy flare

o ok

rose tangle

maybe try updating, it has been an issue for a while

kinda unexpected it's still around

craggy flare

just updated the app, tried again and it still shows, ill just ignore it lol

vague echo

i wanted to transfer my /apod cmd from embed to component and according to the errors componentsv2 dont support such api requests rn is that true?

steel trail

Huh? What „such api requests“? Show the actual error (and code)

vague echo
steel trail Huh? What „such api requests“? Show the actual error (and code)
    at Object.execute (file:///C:/Users/ANON/Documents/spacecat/apod.js:59:19)
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
    at async Client.<anonymous> (file:///C:/Users/ANON/Documents/spacecat/apod.js:88:16)
    Error Support: You won’t get those components, because they belong to Discord's internal/experimental V2 components API, which is not yet part of stable discord.js and isnt published.```

## apod.js code
```import dotenv from 'dotenv';
dotenv.config();

import pkg from 'discord.js';
import fetch from 'node-fetch';

const {
  Client,
  GatewayIntentBits,
  Collection,
  REST,
  Routes,
  SlashCommandBuilder,
  createComponent,
  Container,
  TextDisplay,
  MediaGallery
} = pkg;

// === SlashCommand definieren ===
const apodCommand = new SlashCommandBuilder()
  .setName('apod')
  .setDescription('Zeigt das Astronomy Picture of the Day der NASA mit UI-Komponenten.');

const commands = [apodCommand.toJSON()];
const rest = new REST({ version: '10' }).setToken(process.env.TOKEN);

// === SlashCommand registrieren ===
try {
  console.log(':satellite: Registriere /apod Command...');
  await rest.put(
    Routes.applicationGuildCommands(process.env.CLIENT_ID, process.env.GUILD_ID),
    { body: commands }
  );
  console.log(':white_check_mark: Slash-Command registriert.');
} catch (error) {
  console.error(':x: Fehler bei Registrierung:', error);
}

// === Bot starten ===
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
client.commands = new Collection();

client.commands.set('apod', {
  data: apodCommand,
  async execute(interaction) {
    await interaction.deferReply();

    const url = `${process.env.NASA_APOD_API}?api_key=${process.env.NASA_APOD_KEY}`;
    try {
      const res = await fetch(url);
      const data = await res.json();

      if (data.media_type !== 'image') {
        return await interaction.editReply('Das heutige APOD ist kein Bild. :milky_way:');
      }

      const component = createComponent(
        Container.from([
          MediaGallery.from([
            {
              url: data.url,
              title: data.title
            }
          ]),
          TextDisplay.from([
            `📅 **${data.date}**\n\n**${data.title}**\n\n${data.explanation.substring(0, 4000)}`
          ])
        ])
      );

      await interaction.editReply({ components: [component] });

    } catch (err) {
      console.error('[APOD Fehler]', err);
      await interaction.editReply('Fehler beim Abrufen des Bildes.');
    }
  }
});

client.once('ready', () => {
  console.log(`🚀 Eingeloggt als ${client.user.tag}`);
});

client.on('interactionCreate', async interaction => {
  if (!interaction.isChatInputCommand()) return;
  const command = client.commands.get(interaction.commandName);
  if (command) await command.execute(interaction);
});

client.login(process.env.TOKEN);
zenith violet

and why are you using .from everywhere?Just use builders.
And you're missing the flag

ivory sable

Does the file builder not handle direct file urls same way mediaGalleryBuilder does?

const file = new FileBuilder({
    spoiler: true,
    file: {
        url: 'file.png',
    },
});```
like this
vague echo
zenith violet
steel trail
steady tundra

Is there any built-in support in Discord (Gateway or REST) or in discord.js to tell which invite code a new guild member used when joining (and therefore who invited them)?

Or must bots still implement manual invite tracking (fetching guild invites before/after a join) to determine which invite was used?

steel trail

Why do bots need to know at all? Mods can see it in mod view. Bots can’t

steel trail

Considering you’re the only one that said something since my last message: yes

cedar kindle

guys is there a guide to use the container component?

zenith violet

not yet

deft nimbus

currently running into an issue when attempting to edit an interaction reply with a buffer image created using napi-rs/canvas

const captcha = await buildCaptcha(correct);

const reply = await interaction.editReply({
    embeds: [{
        color: Colours.Primary,
        description: 'To process your vote, please select the button with the right answer',
        image: {
            url: 'attachment://guilds-captcha.png'
        }
    }],
    files: [new AttachmentBuilder(captcha, { name: 'guilds-captcha.png' })],
    components: [{
        type: ComponentType.ActionRow,
        components: words.map((word, index) => ({
            type: ComponentType.Button,
            style: ButtonStyle.Secondary,
            label: word,
            custom_id: `captcha-${index}`
        }))
    }]
});```

This is the code which creates and sends the image. Commenting out the files property prevents the error, though of course prevents the image from being sent.

```sh
TypeError: Cannot read properties of null (reading 'byteLength')
    at Object.pull (C:\...\node_modules\undici\lib\web\fetch\body.js:63:20)
    at ensureIsPromise (node:internal/webstreams/util:185:19)
    at readableByteStreamControllerCallPullIfNeeded (node:internal/webstreams/readablestream:3099:5)
    at readableByteStreamControllerPullSteps (node:internal/webstreams/readablestream:3207:3)
    at [kPull] (node:internal/webstreams/readablestream:1197:5)
    at readableStreamDefaultReaderRead (node:internal/webstreams/readablestream:2243:39)
    at nextSteps (node:internal/webstreams/readablestream:507:7)
    at async writeIterable (C:\...\node_modules\undici\lib\dispatcher\client-h1.js:1437:22)```

I've logged `captcha` and it's definitely a buffer, and I've also stored it as a file, and it's definitely a working image

d.js version: v14.19.3
steady tundra
cedar kindle
zenith violet not yet

do you know how to edit it? or is it even possible to

  1. add buttons below the message + edit the container?
deft nimbus

it's an image/png

steady tundra
steel trail
deft nimbus
const buffer = canvas.toBuffer('image/png');

const tempDir = './tmp';
const fileName = `captcha-${randomText(5)}.png`;
const filepath = join(tempDir, fileName);

await mkdir(tempDir, { recursive: true });
await writeFile(filepath, buffer);

return buffer;

this is what's returned by the buildCaptcha function

steel trail
steady tundra
deft nimbus
steel trail That doesn’t sound like a regular NodeJS Buffer

well the weird thing is, im running the exact same buildCaptcha function and embed on a different version of the bot which uses tsc and it works perfectly fine. same version djs and napi-rs/canvas, only difference is the one experiencing the error is tsup

this is logging captcha

sharp ginkgoBOT
rose tangle

what does that log

deft nimbus

the image works too, it's being saved onto my folder and looks as it's supposed to

deft nimbus
rose tangle what does that log

i can log byte length too

console.log('Buffer.isBuffer: ', Buffer.isBuffer(captcha), captcha.byteLength);
// Buffer.isBuffer:  true 418165```

moved to https://discord.com/channels/222078108977594368/1370887431846498374
north rose

guys, the container can only be sended by a interaction?

zenith violet

no

vague echo
    Client,
    GatewayIntentBits,
    REST,
    Routes,
    SlashCommandBuilder,
    ContainerBuilder,
    TextDisplayBuilder,
    MediaGalleryBuilder,
    MediaGalleryItemBuilder,
    SeparatorSpacingSize,
    MessageFlags,
  } from 'discord.js';
  import fetch from 'node-fetch';
  import dotenv from 'dotenv';
  
  dotenv.config();
  const { TOKEN, CLIENT_ID, NASA_APOD_KEY, NASA_APOD_API } = process.env;
  
  const client = new Client({
    intents: [GatewayIntentBits.Guilds],
  });
  
  const rest = new REST({ version: '10' }).setToken(TOKEN);
  
  const apodCommand = new SlashCommandBuilder()
    .setName('apod')
    .setDescription("Sends NASA's Astronomy Picture of the Day");
  
  async function registerCommands() {
    await rest.put(
      Routes.applicationCommands(CLIENT_ID),
      { body: [apodCommand.toJSON()] }
    );
    console.log('/apod registered');
  }
  
  client.once('ready', () => {
    console.log(`Logged in as ${client.user.tag}`);
  });
  
  client.on('interactionCreate', async interaction => {
    if (!interaction.isChatInputCommand() || interaction.commandName !== 'apod') return;
  
    await interaction.deferReply({ flags: MessageFlags.Loading });
  
    try {
      const res = await fetch(`${NASA_APOD_API}?api_key=${NASA_APOD_KEY}`);
      const data = await res.json();
  
      if (!data || !data.title || !data.explanation || (!data.url && !data.hdurl)) {
        console.log('Fehlerhafte API-Rückgabe:', data);
        return interaction.editReply({ content: 'Fehler beim Abrufen des APOD.' });
      }
  
      const container = new ContainerBuilder().setAccentColor(0x1d2951);
  
      const titleBlock = new TextDisplayBuilder().setContent(`# 🌌 ${data.title}`);
      container.addTextDisplayComponents(titleBlock);
  
      const descBlock = new TextDisplayBuilder().setContent(data.explanation);
      container.addTextDisplayComponents(descBlock);
  
      if (data.media_type === 'image') {
        const media = new MediaGalleryBuilder().addItems([
          new MediaGalleryItemBuilder().setURL(data.hdurl || data.url),
        ]);
        container.addMediaGalleryComponents(media);
      } else {
        const videoBlock = new TextDisplayBuilder().setContent(`🎬 Video statt Bild: ${data.url}`);
        container.addTextDisplayComponents(videoBlock);
      }
  
      container.addSeparatorComponents(s => s.setSpacing(SeparatorSpacingSize.Small));
      const footer = new TextDisplayBuilder().setContent('© NASA - Astronomy Picture of the Day');
      container.addTextDisplayComponents(footer);
  
      await interaction.editReply({
        components: [container],
        flags: MessageFlags.IsComponentsV2,
      });
  
    } catch (err) {
      console.error('APOD Fetch Error:', err);
      await interaction.editReply({ content: 'Fehler beim Abrufen der APOD-Daten.' });
    }
  });
  
  await registerCommands();
  client.login(TOKEN);

is there something wrong that the image never loads?

ivory sable
const audioAttachment = new AttachmentBuilder(Buffer.from(activeContent.url), {name: 'test.mp3'});
            const fileComponent = new FileBuilder({
                file: {
                    url: `attachment://test.mp3`,
                },
            });
            await interaction.channel.send({
                flags: 32768,
                components: fileComponent,
                file: audioAttachment
            });```
Am I doing something wrong here? 
 
`TypeError: this.options.components?.map is not a function at MessagePayload.resolveBody`
I'm getting this error
ivory sable

oh right

remembered both components and file need to be array, but now I'm getting this error message

components[0].file.url[UNFURLED_MEDIA_ITEM_REFERENCED_ATTACHMENT_NOT_FOUND]: The referenced attachment ("attachment://test.mp3") was not found

activeContent.url is just a direct link to a .mp3 file

halcyon bison

files (plural) needs to be an array
in your code above, you're using file (singular)

ivory sable

changing it to files worked, thank you.
Didn't work as file: notarray

fickle galleon

hello

im new with bots and im having problem making the slash command to work

sharp ginkgoBOT
fickle galleon

hello?

topaz bluff

Dekes was pointing you to the guide which has a step by step tutorial on getting slash commands to work

But to help you point somewhere in particular, what issue are you having with your slash commands?

  • are they not loading to the bot (nothing shows up when you press /)
  • are you getting "interaction has not responded"
  • are you getting some other error?
sudden cedar

ive never had this problem before and im really confused:
Type 'MessageFlags.Ephemeral' is not assignable to type 'MessageFlags | undefined'.

return void api.interactions.reply(interaction.id, interaction.token, {
    flags: MessageFlags.Ephemeral,
    content: 'aa',
});

the code works properly

im able to suppress the error by using Math.trunc(MessageFlags.Ephemeral) but i dont know why it just isnt working normally

zenith leaf
sudden cedar

forgot to mention im using /core so itll be a bitfield

stable sun
sudden cedar

is there a way to get ws ping using /core / /ws? WebSocketManager doesnt have a ping propery afaik and Client.gateway doesnt either

uncut quest

You need to either reply or defer beforhand

fading girder
const permissions = new PermissionsBitField(BigInt('36953089'));
console.log(permissions.has(PermissionsBitField.Flags.ManageGuild));

I am trying to use the permissions number from get guilds in 0auth2. This should be correct right?

/users/@me/guilds this is the get method btw

stable sun

It’s alr been replied/updated/deferred

rose tangle

works fine for me

primal yoke

Im getting interaction already replied error and don't know from where

if (interaction.isModalSubmit() && interaction.customId === 'profileCreate') {
      const userId = interaction.user.id;
      const name = interaction.fields.getTextInputValue('name').trim();
      const specialty = interaction.fields.getTextInputValue('specialty')?.trim() || null;
      const bio = interaction.fields.getTextInputValue('bio')?.trim() || null;

      try {
        await User.create({
          userId,
          detectiveName: name,
          specialty,
          bio,
          coins: 200,
          xp: 0,
          level: 1,
          solved: 0,
          failed: 0,
          activeEffects: []
        });

        const embed = new EmbedBuilder()
          .setTitle(`✅ Profile Created: ${name}`)
          .setDescription(`Welcome, detective. Your career begins now.`)
          .addFields(
            { name: ':dart: Specialty', value: specialty || '_None_', inline: true },
            { name: ':coin: Starter Coins', value: '200', inline: true },
            ...(bio ? [{ name: ':book: Bio', value: bio }] : [])
          )
          .setColor(0x3498db)
          .setFooter({ text: 'Use /case to begin your first mystery.' })
          .setTimestamp();

        await interaction.reply({ embeds: [embed], ephemeral: false });
      } catch (err) {
        console.error(':x: Modal failed:', err);
        await interaction.reply({ content: 'Profile creation failed.', ephemeral: false });
      }

      return;
    }
zenith violet

well something is replying to your interaction somewhere

Perhaps some other listener

Show the full code

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.

primal yoke

Its only the profile command with modal

rose tangle

what is actually happening in discord?

upbeat saffron

after updating to 14.19.3 row.components does not exists anymore how do i access the action rows?

const newRows = targetMessage.components.map(row => {
    return new ActionRowBuilder<ButtonBuilder>().addComponents(
        row.components
            .filter((component) => component.type === ComponentType.Button)
            .map((button: any) => {
                return ButtonBuilder.from(button).setDisabled(true)
            })
     );
});
vestal sun
upbeat saffron
bitter leaf
[CRASH] Something went wrong while connecting to your bot...
[CRASH] Error from Discord API:Error: self-signed certificate

whats the wrrong?

proud parrot

I’m building a moderation bot with Discord.js v14.19.3 and Sapphire Framework, but I'm hitting a problem where I get an "Application didn't respond" error when running commands like /ban, /kick, etc.

I’ve already tried using deferReply() for commands and deferUpdate() for buttons to prevent timeouts, but I’m still having the issue. The bot has all the necessary permissions, and commands are registered correctly.

Anyone have any ideas or suggestions on how to fix this?

zenith violet
plain nymph

how to obtain a clan tag and also change the clan tag using a bot?
and also how to create gradient roles?

dense jackal
trim basin

hi i got this error but why it shows an error but the embed is good?

const embed = new EmbedBuilder()
    .setColor(__CONFG.colors.default)
    .setTitle(`User Info: ${user.tag}`)
    .setThumbnail(user.displayAvatarURL({ dynamic: true, size: 512 }))
    .setDescription(`**Nickname:** ${member.nickname || 'None'}\n**Status:** ${user.presence?.status}\n**Roles:** ${member.roles.cache.map(role => role.toString()).join(', ') || 'None'}`)
    .addFields(
        { name: 'ID', value: user.id, inline: true },
        { name: 'Username', value: user.username, inline: true },
        user.discriminator !== '#0' ? { name: 'Discriminator', value: `#${user.discriminator}`, inline: true } : null,
        { name: 'Bot', value: user.bot ? ':white_check_mark:' : ':x:', inline: true },
        { name: 'Joined Server', value: `<t:${Math.floor(member.joinedTimestamp / 1000)}:R>`, inline: true },
        { name: 'Account Created', value: `<t:${Math.floor(user.createdTimestamp / 1000)}:R>`, inline: true }
    )
    .setFooter({ text: `Requested by ${message.author.tag}`, iconURL: message.author.displayAvatarURL({ dynamic: true }) })
    .setTimestamp();
CombinedPropertyError (1)
  Received one or more errors

  input[1]
  | CombinedPropertyError (1)
  |   Received one or more errors
  |
  |   input.value
  |   | ValidationError > s.string()
  |   |   Expected a string primitive
  |   |
  |   |   Received:
  |   |   | undefined

    at _ArrayValidator.handle (C:\Users\ylian\Documents\ecotune\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:1254:70)
    at _ArrayValidator.parse (C:\Users\ylian\Documents\ecotune\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:972:90)
    at EmbedBuilder.addFields (C:\Users\ylian\Documents\ecotune\node_modules\@discordjs\builders\dist\index.js:235:31)
    at Object.execute (C:\Users\ylian\Documents\ecotune\src\commands\userinfo.js:21:14)
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
    at async Client.<anonymous> (C:\Users\ylian\Documents\ecotune\src\app.js:149:13)
dense jackal
trim basin

uuuhh yea bcs im using this:

const user = (await message.guild.members.fetch(message.author.id)) || (await message.guild.members.fetch(message.mentions.users.first().id));
const member = await message.guild.members.fetch(user.id).catch(() => null);
zenith violet

message.member exists too

polar karma

That's incredibly inefficient. There's also mentions.members

sharp ginkgoBOT
polar karma

The data is sent with the message payload, it's always present

trim basin

oh

polar karma

And indeed, members don't have a username. Both your user and member variables are GuildMembers

trim basin

okay

sharp ginkgoBOT
polar karma

Anything needed from the user class is available there

trim basin

ty

shadow oyster

Is it possible to send a Automod Alert message based on a member which have the Spammer UserFlag?

sacred torrent

is tehre a way to give a bot the server tag?

im assuming no

polar karma

No

sacred torrent

hm

rose tangle
fading girder

is there any djs support for linked roles in apps?

crimson gale

linked roles are an oauth2 feature for the most part
the only thing that the library does in regards to it is allow you to figure out which app a role is linked to via role tags

sharp ginkgoBOT

discord Configuring App Metadata for Linked Roles
read more

candid anchor
zenith violet

limited rollout, gradient roles. Not djs related, #archive-offtopic for these kind of questions

fathom warren

what's the difference between dividier and divider property in separator component?
both return boolean

OH ITS TYPO XD

rose tangle

it was a typo yeah, but it was fixed in that version, and also an allowedMentions bug

so you should really update

fathom warren

ty, didnt notice

upbeat saffron

where can I find the limitation of a new components v2 message i see 40 max components but what about the characters, and how much per message? its same like embeds?

humble frost

Does it auto shard as the bot joins more servers?
( Ex it only deployed 1 shard cause the bot had 2500 servers to manage, now it have to manage Like 7500 servers , does it auto deploy? Or needs manual restarts ? )

humble frost
upbeat saffron
humble frost
upbeat saffron

thx

glass basin

regular embed descriptions are limited to 4000 characters right

humble frost
upbeat saffron and 40 per message?

Its 4000 max per message ( default )
but it's 2000 per content component, so you can send a total of 2 content component with 2000 chars in each component.

Or you can send multiple with respect to limit of both content component and message limit

unkempt shard

is there a way i can fetch the server tag of a server using its invite link

rose tangle

server tags are experimental, any functionality with them is not supported

fickle galleon

sorry, but im stuck in the command handling part

halcyon bison
fickle galleon
halcyon bison

@upbeat saffron @humble frost I'm a bit late to the conversation, but there isn't actually a documented limit on text display component content
2000 is the default limit for normal message content
the 4000 total across all components is correct
you can have a single text display with 4000 characters or two text displays with 3000 and 1000 respectively

halcyon bison
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.

upbeat saffron
keen sapphire

hello i have an issue with my ready.js, after a days my bot status going to online, playing activity going to none and left to voice channel i cant fix this issue

Here's the code

const { ActivityType } = require("discord.js");
const { loadCommands } = require("../../Structures/Handlers/commandHandler");
const { joinVoiceChannel } = require("@discordjs/voice");

module.exports = {
  name: "ready",
  once: true,
  async execute(client) {
    loadCommands(client);

    client.user.presence.set({
      activities: [
        {
          name: "LVBEL ❤",
          type: ActivityType.Streaming,
          url: "https://twitch.tv/discord",
        },
      ],
      status: "online",
    });

    console.log(`Hazır! Giriş yapılan bot ${client.user.tag}`);

    const channel = await client.channels.fetch("1343295471988506654");
    if (channel && channel.isVoiceBased()) {
      joinVoiceChannel({
        channelId: channel.id,
        guildId: channel.guild.id,
        adapterCreator: channel.guild.voiceAdapterCreator,
        selfMute: false, // Mikrofon kapalı
        selfDeaf: true, // Kulaklık kapalı
      });
      console.log(`🔊 Ses kanalına katıldı: ${channel.name}`);
    } else {
      console.log("❌ Ses kanalı bulunamadı veya geçersiz.");
    }
  },
};
fickle galleon
fickle galleon
halcyon bison
keen sapphire Here's the code ```js const { ActivityType } = require("discord.js"); const { lo...

I've never actually made the connection before, and previously I had assumed it was just a feature of discord that they don't want bots alone in voice channels 24/7 wasting resources
thinking on your presence, I believe the presence is cleared if your presence isn't set in the client options and it reconnects (which can happen for various reasons)
I could also see this being the reason for your bot disconnecting from the voice channel, especially if it's at the same time

humble frost
fickle galleon

aww thanks

sharp ginkgoBOT

Codeblocks:
```js
const Discord = require("discord.js");
// further code
```
becomes

const Discord = require("discord.js"); 
// further code

Inline Code:
`console.log('inline!');` becomes console.log('inline!');

humble frost
keen sapphire
humble frost
fickle galleon
// Require the necessary discord.js classes
const { Client, Events, GatewayIntentBits } = require('discord.js');
const { token } = require('./config.json');

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

// When the client is ready, run this code (only once).
// The distinction between `client: Client<boolean>` and `readyClient: Client<true>` is important for TypeScript developers.
// It makes some properties non-nullable.
client.once(Events.ClientReady, readyClient => {
    console.log(`Ready! Logged in as ${readyClient.user.tag}`);
});

// Log in to Discord with your client's token
client.login(token);

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

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

client.commands = new Collection();
sharp ginkgoBOT
keen sapphire
fickle galleon

here's the index.js , it says i had to add an additional part for the command handling but gives me some errors

halcyon bison
fickle galleon here's is <@174371986741395457> https://pastebin.com/yEU6mhCp

this looks as though you copy pasted from the guide without really reading the guide or thinking about what the code does
I'd suggest properly rereading the guide and its explanations of each code block, but here's the cliff notes:

  • you're attempting to create 2 variables named client, both of which are separate Client instances
  • I don't see any code for actually loading commands in to that collection
  • it doesn't appear you've finished reading the rest of the guide for where you deploy commands and handle interactions
keen sapphire

so which option i can use it for dont clear presence

fickle galleon

im reading the deploy part right now

humble frost
humble frost

Wait let me check my code

keen sapphire
const client = (global.client = new Client({
  allowedMentions: { parse: ["users"], repliedUser: true },
intents: Object.values(GatewayIntentBits), 
  partials: Object.values(Partials),
}));```
here's the client @humble frost
humble frost
public client: Client = new Client({
        intents: [
            GatewayIntentBits.Guilds,
            GatewayIntentBits.GuildMembers,
            GatewayIntentBits.MessageContent,
            GatewayIntentBits.GuildMessages,
            GatewayIntentBits.DirectMessages
        ],
        partials: [Partials.Channel, Partials.Message, Partials.Reaction],
        presence: {
            status: "online",
            activities: [{
                name: "bls help",
                type: ActivityType.Playing,
            }],
        },
        sweepers: {
            ...Options.DefaultSweeperSettings,
            users: {
                interval: 3600, // Sweep offline users not seen for 1 hour
                filter: () => user => {
    
                    // Try not to sweep the bot it self
                    if (user.id === this.client.user?.id) return false; 
    
                    // Check if the user is offline in ALL guilds the bot is in
                    const isOfflineInAllGuilds = this.client.guilds.cache.every(guild => {
                        const member = guild.members.cache.get(user.id);
                        return member?.presence?.status === "offline" || !member; // Consider not being in a guild as offline
                    });
    
                    return isOfflineInAllGuilds;
                },
            },
    
            messages: {
                // Sweeps messages older than 30 mins??
                interval: 1800, 
                lifetime: 1800, 
            },
        },
    });
halcyon bison
fickle galleon

it said to add this ``` const fs = require('node:fs');
const path = require('node:path');
const { Client, Collection, Events, GatewayIntentBits } = require('discord.js');
const { token } = require('./config.json');

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

client.commands = new Collection(); ``` to the index.js . sorry it's that im new on javascript

humble frost
halcyon bison
fickle galleon it said to add this ``` ...

I admit the wording "make these additions" isn't absolutely 100% clear that you shouldn't copy paste the entire code block
but you're also not expected to copy paste any of the code blocks
and furthermore if you notice, a few of the lines are highlighted
comparing this code block to the code you had prior to this section, you can notice these highlighted lines are the new ones that you should be adding

humble frost
fickle galleon it said to add this ``` ...
const fs = require('node:fs');
const path = require('node:path');
const { Client, Collection, Events, GatewayIntentBits, ActivityType } = require('discord.js');
const { token } = require('./config.json');

const client = new Client({ 
    intents: [GatewayIntentBits.Guilds],
    presence: {
       status: "online",
       activities: [
       {
         name: "LVBEL ❤",
         type: ActivityType.Streaming,
         url: "https://twitch.tv/discord",
       }
       ]
    } 
});

client.commands = new Collection(); 

halcyon bison
humble frost

@halcyon bison could you explain the concept of sharding in discord js?
I have a question. Let's say when I started or ran the script it deployed 1 shard, as it only had like 2000 servers. But now once it reached 4000 servers, will it redeploy another shard for 1500 servers or does it need manual restarts ?

fickle galleon
halcyon bison
uncut tangle

Is there a 15 minutes limit to editing ephemeral messages?

zenith violet

after that the interaction webhook expires yes

uncut tangle

Is there a way around to this?

zenith violet

after 15 minutes most users will have dismissed that message eitherway

halcyon bison

(but also the answer is no)

uncut tangle
orchid latch

Hello guys ! Do you know if there's a way to retrieve a registered slashCommand's ID ? From the client or another source I cannot find any options to do that on the documentation... I can only get the name

blissful abyss
rose tangle

or how are you getting the name?

uncut tangle
orchid latch

I mean idk, I use a command handler that stores commands in a Collection. But it is using provided values from the command's file

blissful abyss
rose tangle
blissful abyss

im assuming the buttons are on the ephemeral message?

sharp ginkgoBOT

documentation suggestion for @orchid latch:
method ApplicationCommandManager#fetch() discord.js@14.19.3
Obtains one or multiple application commands from Discord, or the cache if it's already available.


// Fetch a single command
client.application.commands.fetch('123456789012345678')
  .then(command => console.log(`Fetched command ${command.name}`))
  .catch(console.error);

halcyon bison
uncut tangle
rose tangle
halcyon bison
uncut tangle

Weird, console shows invalid webhook token,

blissful abyss
uncut tangle
blissful abyss

use the interaction from the message component collector and use interaction.update()

sharp ginkgoBOT

method ButtonInteraction#update() discord.js@14.19.3
Updates the original message of the component on which the interaction was received on.


// Remove the components from the message
interaction.update({
  content: "A component interaction was received",
  components: []
})
  .then(console.log)
  .catch(console.error);

rose tangle

not even sure how that didn't error because you're not replying to the button interaction

uncut tangle
blissful abyss

don't defer update, replace that with update

uncut tangle
blissful abyss

unless you editReply the button interaction afterwards

rose tangle
rose tangle
uncut tangle

Oh

blissful abyss

interaction.update() edits the message the button is on

uncut tangle

Oh, thanks

The update takes the message parameters? Like to edit the message the buttons are on

uncut tangle

Lemme go docs ig that would be better, thanks for yall help

rose tangle

it takes what you want to edit

uncut tangle

Ooh thanks for help yall

zenith leaf

hello i have a question, how i can get a tag of a user ?

uncut tangle

Ok ye this is alot better, thanks

zenith leaf

it

uncut tangle

@blissful abyss can i still use defer update as some stuff between the interaction update might be slow

halcyon bison
blissful abyss

Yes, use deferUpdate and then editReply later with the same parameters

uncut tangle

like
int.deferUpdate
//Code
int.update

rose tangle

assuming int is the button interaction and not the original slash command, yes

uncut tangle

Ohk, thanks

rose tangle

ah no, editReply

blissful abyss

it would be editReply though, not update

rose tangle

@uncut tangle just in case you missed it

uncut tangle
merry quiver

is it possible to get the past messages the bot sent to delete it with cmd without being in the server or smth

zenith violet

no

merry quiver

oh

humble frost
halcyon bison

first could you clarify what you're redeploying every time?

halcyon bison

ok just making sure you didn't mean commands
all I said was that you can devise a system
it doesn't have to be every day, but rather just when you need more shards

humble frost
steel trail

Thing is that guilds get assigned to other shards than before if you increase the amount of shards. You‘d need to have a system in place to accommodate that. Restart is often the easier/better solution

But why do you think you‘d need to restart that often? If you feel like your bot will grow that fast just start more shards than you currently need and you‘ll be good for a longer time

humble frost
steel trail

If you spawn the recommended amount of shards (auto mode) then your bot should be able to at least grow to twice its current size without reaching shards limits. Resource limits are another story, but that’s independent of djs

humble frost

ic

merry quiver

how do i fetch the application emojis? using the actual api outside the module? or is there a function?

sharp ginkgoBOT

method ApplicationEmojiManager#fetch() discord.js@14.19.3
Obtains one or more emojis from Discord, or the emoji cache if they're already available.


// Fetch all emojis from the application
application.emojis.fetch()
  .then(emojis => console.log(`There are ${emojis.size} emojis.`))
  .catch(console.error);

merry quiver

oh wait

emojis just isnt showing up in the auto complete

little pebble

Can you show where?

merry quiver
little pebble

What's your discord.js version?

merry quiver

wait whats the cmd to check

little pebble

npm ls discord.js

merry quiver

14.15.3

alr npm i discord.js latest

little pebble

Yeah, their support was added in 14.16

merry quiver

ok its valid in auto complete now

tall swift

is this still possible in componentsV2? the author thing with logo and server name

merry quiver

o so if i wanna now send it as a message do i have to format it myself or is there smth implemented?

sharp ginkgoBOT

method ApplicationEmoji#toString() discord.js@14.19.3
When concatenated with a string, this automatically returns the text required to form a graphical emoji on Discord instead of the Emoji object.


// Send a custom emoji from a guild:
const emoji = guild.emojis.cache.first();
msg.channel.send(`Hello! ${emoji}`);

steel trail
merry quiver

ohh

ok i was gonna do [...emojis].join(' ') but that adds the id, emoji

ill just map and join it

wait or

torpid elm

Hi, am i doing smth wrong ?
TypeError: (intermediate value).setDivider is not a function

return new ContainerBuilder()
        .setAccentColor(colors.BLUE)
        .addTextDisplayComponents(
            new TextDisplayBuilder()
            .setContent('# Test')
        )
        .addSeparatorComponents(
            new SeparatorBuilder()
            .setDivider(false)
            .setSpacing(SeparatorSpacingSize.Large)
        )
        .addTextDisplayComponents(
            new TextDisplayBuilder()
            .setContent('test')
        )
       )
merry quiver

ok [...emojis.values()].join(' ') that will do

steel trail
merry quiver

ok it works

tbh what kind of fun cmds shall i do im just bored

torpid elm
steel trail Show the full error with stacktrace. Because that code looks fine
TypeError: (intermediate value).setDivider is not a function
    at buildVoiceMenu (workspace\utils\customVoiceChat\messageContainers.js:24:14)
    at Object.execute (workspace\commands\textCommands\messages.js:23:45)
    at Object.execute (workspace\events\messageCreate.js:54:34)
    at Client.<anonymous> (workspace\app.js:132:29)
    at Client.emit (node:events:519:28)
    at MessageCreateAction.handle (workspace\node_modules\discord.js\src\client\actions\MessageCreate.js:32:14)
    at module.exports [as MESSAGE_CREATE] (workspace\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
    at WebSocketManager.handlePacket (workspace\node_modules\discord.js\src\client\websocket\WebSocketManager.js:351:31)
    at WebSocketManager.<anonymous> (workspace\node_modules\discord.js\src\client\websocket\WebSocketManager.js:235:12)
    at WebSocketManager.emit (workspace\node_modules\@vladfrangu\async_event_emitter\dist\index.cjs:287:31)
steel trail
torpid elm
steel trail

SectionBuilder is indeed not a SeparatorBuilder

merry quiver

what even is that , SectionBuilder

steel trail

What is what?

steel trail
sharp ginkgoBOT

documentation suggestion for @merry quiver:
class SectionBuilder discord.js@14.19.3
A builder that creates API-compatible JSON data for a section.

merry quiver

oh like the embed has a thumbnail banner at top and then a section splitter under it and then text as i see on google?

wait even buttons inside the embed!?

steel trail

They aren’t embeds. They might look alike but they are components, made to replace the legacy distinction between content, embed, buttons, attachments… all are components in v2

merry quiver

ohh

videos inside embeds possible yet!?

steel trail

No. But inside components: yes

merry quiver

o

button

i clicked on the most clickbait "how to embed videos" video ever, all he did is upload a video to chat and video ended. omg the comments

torpid elm
merry quiver

oh V2 Components seems sick place stuff anywhere

craggy flare

Is it possible to do this thingy <t:${Math.floor(reminder.remind_at.getTime() / 1000)}:R> in a container?

I keep on getting an error when I add it, it works in embeds and when i remove it but doesn't seem to work in containers.

                    const container = new ContainerBuilder()
                        .setAccentColor(0xffff)
                        .addSectionComponents(
                            new SectionBuilder()
                                .addTextDisplayComponents(new TextDisplayBuilder().setContent([
                                    `# __${user.globalName} GrimKin has your reminder!__`,
                                    `-# The time is now <t:${Math.floor(reminder.remind_at.getTime() / 1000)}:R>, that means its time for your reminder!`
                                    ` You asked GrimKin to remind you: \`${reminder.message}\`!`,
                                ].join('\n')))
                                .setThumbnailAccessory(new ThumbnailBuilder().setURL("https://i.ibb.co/XxDqJp7p/Grim-Kin-SVGAnnouncement-White.png"))
                        )
                        .addTextDisplayComponents(footer);

[ERROR] Reminder execution error: Math.floor(...) is not a function

blissful abyss

you're doing Math.floor(...)(...) somewhere, probably because of a missing semicolon

craggy flare

i was missing a comma 💀

merry quiver

im now gonna test around with Components V2 😭

uh it wont show video

oh file literally means file and not like video media?

im guessing media supports attachment url?

aa

woah this is sick

o even User Select and more wow, i think i missed a few updates..

rancid folio
merry quiver

you can put upto like 4

but idk how many component limit is cuz i just put 40... rn

open saddle

So, i have a memory leak on my discord bot and i'm trying to figure out on how to figure out where the leak is from. Best way to figure out?

rose tangle

there isn't a specific way to know tailored for bots if that's the question

open saddle

It's running on a ptero container that is only containing the bot.... It's literally on 2.31`gb and it's slowly climbing

rose tangle

you diagnose it the same way you'd diagnose any node app is what I'm trying to say

the fact that you're using djs is irrelevant to the leak itself

unless djs itself had a memory leak, but that'd be known

merry quiver

seems like i can put 80 videos but then over that it errors

open saddle

I didn't nor say that it's a DJS issue.

rose tangle

you're on the djs help channel

rose tangle
merry quiver

just insane..

o yh no loop

could of done Array.from({length:},()=>)

safe wigeon

With Components v2, how do you use the MediaGalleryBuilder with a file made with the AttachmentBuilder instead of just a url?
I only know of: ```js
const thumbnailImage = new MediaGalleryBuilder()
.addItems([
new MediaGalleryItemBuilder()
.setURL(preview)
]);
container.addMediaGalleryComponents(thumbnailImage);

rose tangle
merry quiver just insane..

in theory if you don't reach the limit size you should be able to send 40 components*10 videos per gallery=400 videos

in practice I don't think you can have a video that small

oops wrong tag

safe wigeon
sharp ginkgoBOT

tag suggestion for @safe wigeon:
Files in embeds should be attached via the message option object and referenced in the embed:

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

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

there you go

it's the same thing for media galleries

safe wigeon

Oh, didn't mean that. Like how do I add it to a container with addMediaGalleryComponents?

rose tangle

you mean like, sending an image file, and showing that image in the gallery?

instead of an image from an online url

safe wigeon
safe wigeon
rose tangle

like in the tag then

just MediaGalleryItemBuilder#setURL() instead of EmbedBuilder#setImage()

safe wigeon

And setURL() will accept attachment (from AttachmentBuilder)?

rose tangle

no, like the tag says, it accepts a string

you send the attachment as part of the files, and reference it through the attachment:// url

merry quiver

ah great params instead of funcs

safe wigeon
rose tangle

yes, and send the attachment in the files

merry quiver

i did mine ts way lol

safe wigeon
merry quiver

mines more raw ig?

merry quiver
safe wigeon

Also, will withResponse: true do the same as fetchReply: true, just different name?

unique shoal

Not exactly the same, no

It returns a different object, but does contain the message as a nested property

fetchReply was as workaround implemented to do that before withResponse was provided

safe wigeon
sharp ginkgoBOT

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

- {..., fetchReply: true}
+ {..., withResponse: true}

```This returns an [InteractionCallbackResponse](https://discord.js.org/docs/packages/discord.js/14.17.3/InteractionCallbackResponse:Class)
Use `<InteractionCallbackResponse>.resource.message` to get the message
safe wigeon

Looks like it from the link, ty ^^

safe wigeon

Another question... with components v2, is it possible to have more than 5 buttons in the same row / next to each other?

unique shoal

no

safe wigeon

With components v2, is it possible to edit a text display? Like

  1. Send container
  2. In message component collector get the container
  3. Edit specific text displays in the container
  4. Edit the message with the edited container
obsidian dust

Hey, is there any API for guild tags yet?

unique shoal

yep

unique shoal
obsidian dust

👍

unique shoal
unique shoal yep

This was a reply to you @safe wigeon, you can edit any component as usual

safe wigeon
unique shoal yep

How can I achieve it? How do I get a specific text display to edit in the container?

unique shoal

The answer kinda depends, I use raw JSON instead of builders, so I'd just make the change and re-send it'

You can otherwise do new ContainerBuilder(message.components[0]) (assuming thats your container) and use spliceComponents to replace them

sharp ginkgoBOT
humble frost

Can we send a components v2 with emperamal flag?

unique shoal

I think so yes

You can combine flags with the | operator

MessageFlags.IsComponentsV2 | MessageFlags.Ephemeral

humble frost

Or operator?

unique shoal

Bitwise OR, yes

humble frost

And how do we check if the bot has access to a channel's send message permission ( not guild send message permission )

humble frost
sharp ginkgoBOT
unique shoal

You can use this to check a users permissions in a channel

merry quiver

woah i just made that... 😭 didnt know thas possible tbh

i guessed it would just accept attachments and voice flag

hm no waveform thoo

wait it shows up as audio file for mobile uhhh

.

unique shoal

This isnt a playground for your bot

merry quiver

where

unique shoal

Not here

river flint

Did something change?

It dont seem that its letting me send messages to a textChannel

topaz bluff

What is the error? And what type is the gatewayChannel claiming to be?

river flint

const gatewayChannel: DMChannel | PartialDMChannel | PartialGroupDMChannel | NewsChannel | StageChannel | TextChannel | PublicThreadChannel<...> | PrivateThreadChannel | VoiceChannel

Property 'send' does not exist on type 'DMChannel | PartialDMChannel | PartialGroupDMChannel | NewsChannel | StageChannel | TextChannel | PublicThreadChannel<...> | PrivateThreadChannel | VoiceChannel'. Property 'send' does not exist on type 'PartialGroupDMChannel'.ts(2339

manic axle

You can just use the isSendable() typeguard to see if it has a send() method

river flint

Fixed. Thats weird tho no?

manic axle

I think it's more sensible than the old methods since just writing if (!gatewayChannel?.isSendable()) return; is both less verbose and more direct toward your use case - checking if you can send something in a channel

river flint

It is. but I dont see why it still failed

topaz bluff

I definitely feel like I've used isTextBased instead of isSendable and got typings correct...but isSendable is probably better anyways

manic axle

isTextBased() doesnt work on its own anymore since, like TS told you, partial group DM channels are text-based but not sendable

river flint

Fair enough

topaz bluff

Does isSendable check permissions or does it just check channel type?

unique shoal

channel only

topaz bluff

peepoSalute

That's what I thought just making sure

tardy sable

question, will this return an error if the channel does not exist

const channel = await member.guild.channels.cache.get(channelId);

or will it only return an error if i try to send something to the channel?

rose tangle

caches are just maps, gets are sync

so that await is useless

and it won't throw an error, it'll return undefined

sharp ginkgoBOT

mdn Map.prototype.get()
The get() method of Map instances returns a specified element from this map. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the Map object.

merry quiver

oh more than one Section isnt possible?

rose tangle

it is possible

merry quiver
rose tangle

sections need an accessory

merry quiver

oh

rose tangle

third point

merry quiver

just wanted to have the 3 fields like embeds

rose tangle

you could just put all those three text displays in a single one

if you're referring to the inline option, there's no alternative for that

merry quiver

ohh

oh theres also text Display limit of 3 so cant either way

rose tangle

per section, not globally

merry quiver

yeah

rose tangle

your code there works if you add an accessory to those sections

merry quiver

i was going for a profile type Component with banner, pfp with name etc and then 3 fields like followerrs following etc

rose tangle

text displays go on top of each other, not side by side

merry quiver

yeah unless future same with author with its icon too

merry quiver
rose tangle

unfortunately no

discord decided that users should control the vertical positioning of components, not the horizontal one

you can "simulate" fields with blank spaces, but it's not mobile friendly

merry quiver

yh lol

unique shoal

I thought I had said yesterday that it wasn't possible but maybe it was someone else

merry quiver

ig others wanted too

tardy sable

for role.managed, will the booster role return as true?

rose tangle

yes

shadow harness

Using ComponentsV2, with ContainerBuilder as my top-level, and then this schema for the rest of my components. Weirdly, I'm getting an error saying components[0].type must be 1, which is... ActionRow? But I didn't think TextDisplays needed to be contained with anything more than Container

Althought that could be referencing the last section which is an array of Buttons... but that doesn't make sense either since I correctly wrapped them with ActionRow

obtuse laurel
shadow harness
obtuse laurel

I think it would be helpful to see some code

shadow harness
private generate(options: [string, string][], page: number, closing?: true) {
    const total = this.options.length;
    return new ContainerBuilder()
        .addTextDisplayComponents(this.text.heading, this.text.query)
        .addActionRowComponents(
            new ActionRowBuilder<StringSelectMenuBuilder>().setComponents(
                new StringSelectMenuBuilder()
                    .setCustomId("ssel")
                    .addOptions(
                        options.map((o) =>
                            new StringSelectMenuOptionBuilder()
                                .setValue(o[0])
                                .setLabel(o[1])
                        )
                    )
                    .setDisabled(closing ?? false)
            )
        )
        .addTextDisplayComponents(this.text.footer(page, total))
        .addActionRowComponents(
            new ActionRowBuilder<ButtonBuilder>().setComponents(
                this.buttons.cancel.setDisabled(closing ?? false),
                this.buttons.previous.setDisabled(closing ?? page === 1),
                this.buttons.next.setDisabled(
                    closing ?? this.getSlice(page)[1] + count(page) > total
                )
            )
        );
}
rose tangle
obtuse laurel

and you're directly passing the return value of this function as a component, right? did you enable the IsComponentsV2 flag?

rose tangle

so it's assuming you're using v1 components, and indeed every component there is wrapped in an action row

shadow harness

My dumbass added that flag to the wrong message. So indeed yes I was forgetting it

Apologies and appreciations good sirs 😂

rose tangle

no worries, it's an understandable mistake

shadow harness

Where I put it [1] vs where it needed to go [2]

shadow harness

So, I've made pagination using buttons. The pagination works exactly how I want it to, but I get

- This interaction failed
```every time I click one of the buttons. Is there a "proper way" to handle button clicks?
hallow mesa
shadow harness
hallow mesa

Is reaction the button interaction and interaction some older interaction? If so yeah

sharp ginkgoBOT

guide Message Components: Component interactions
read more

shadow harness

Yup, that's indeed what did it! Apreciate it good sir

high oxide

do i need intents for guildMemberAdd event?
if so which one? and in the future where can i see the list of intents and what do they do?

sharp ginkgoBOT
  • Websocket intents limit events and decrease memory usage: learn more
  • See what intents you need here
snow onyx

As for the list, see the tag above.

high oxide

ty

pulsar spindle

https://discord.com/api/v10/channels/${ChannelId}/voice-status is this available in discord js ?

pulsar spindle
viral hinge

how to get the user in what clan?

sharp ginkgoBOT

tag suggestion for @viral hinge:

discord.js does not support features until they are officially documented.
While there might be a way for these features to work, it can change at any time without any notice

high oxide

is there a better way to type this out?
its kinda janky

lets try for loop

mapping works

shadow pier

Is there a method on Client that I can use to get the add app link

sharp ginkgoBOT

method Client#generateInvite() discord.js@14.19.3
Generates a link that can be used to invite the bot to a guild.


const link = client.generateInvite({
  scopes: [OAuth2Scopes.ApplicationsCommands],
});
console.log(`Generated application invite link: ${link}`);

hasty fern
unique shoal

When... no command matching the command name was found

e.g., you still have it deployed, but deleted the code locally

hasty fern

Ok that was what I thought at first, thank you!

limber remnant

😮

woeful kraken

question i am using REST And this is actually not working it throw randomly (Unknown interaction)

(Reply is sent before 3 seconds yeah)

sharp ginkgoBOT

Common causes of DiscordAPIError[10062]: Unknown interaction:

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

that's a custom code i am not using discord.js and message is passed corretly inside the function it reach message.id and message.token

zenith violet

Its not a message. And regardless of whether you use djs or not, same causes. Either trying to reply twice to the same interaction or it took longer than 3s to reply

woeful kraken
sick hare
proud arrow

No, both are seprate action that uses seprate route

blissful abyss
sick hare

either react after the message is sent, or use buttons if it's better for the use case

shadow pier

are buttons possible in modals?

dense jackal
zenith violet

No

strange lion

new here. is there any place to find examples? thanks

strange lion
polar karma

you could try searching on github for open source bots/repos. the docs and guide exist to give you the information and references to start making your own app

strange lion

got it thanks !

iron brook

guys i wanna make every single command called, it would be printed on console

import { Events, Listener } from "@sapphire/framework";
import { ChatInputCommandInteraction, Message } from "discord.js";

export class CommandListener extends Listener {
  constructor(context: Listener.LoaderContext, options: Listener.Options) {
    super(context, {
      ...options,
      event: Events.MessageCommandRun,
    });
  }

  run(interaction: ChatInputCommandInteraction | Message) {
    // Check if it's a chat input command (slash command)
    if (interaction instanceof ChatInputCommandInteraction) {
      console.log(
        `[Slash Command] ${interaction.commandName} used by ${interaction.user.tag}`
      );
    }
    // Check if it's a message command
    else if (interaction instanceof Message) {
      console.log(
        `[Message Command] ${interaction.content} used by ${interaction.author.tag}`
      );
    }
  }
}

but i dont think this is how it gonna work tho

tribal warren

For slash commands, it's Events.InteractionCreate.
MessageCommandRun doesn’t seem to exist in discordjs...?

oh, @sapphire/framework

I don't think you're asking this in the right Discord server, since you're using Sapphire

fading girder

does .fetchInvite() not return the uses if the invite was made by a another user?

polar karma

it should, what are you seeing in use that shows otherwise?

fading girder

I think I found how to use it, I've been using client instead of guild

What permission is actually needed to fetchInvites in a guild?

shadow pier

how do i create a collector on the interaction response?

sharp ginkgoBOT

method Message#createMessageComponentCollector() discord.js@14.19.3
Creates a message component interaction collector.


// Create a message component interaction collector
const filter = (interaction) => interaction.customId === 'button' && interaction.user.id === 'someId';
const collector = message.createMessageComponentCollector({ filter, time: 15_000 });
collector.on('collect', i => console.log(`Collected ${i.customId}`));
collector.on('end', collected => console.log(`Collected ${collected.size} items`));

topaz bluff

You also have to use interaction.reply({ fetchReply: true }) to receive a Message instead of an InteractionCallbackResponse

Read below this for the better way of doing this for compatibility with v15

sharp ginkgoBOT

tag suggestion for @topaz bluff:

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

- {..., fetchReply: true}
+ {..., withResponse: true}

```This returns an [InteractionCallbackResponse](https://discord.js.org/docs/packages/discord.js/14.17.3/InteractionCallbackResponse:Class)
Use `<InteractionCallbackResponse>.resource.message` to get the message
sharp ginkgoBOT

documentation suggestion for @fading girder:
discord Guild Resource - Get Guild Invites
read more

polar karma

it's best to refer to the api docs to see what permissions are required for each endpoint/method

shadow pier

How can i disable a button in the original interaction message after an interaction was sent from the button?

rose tangle

do you want to update on click or at a later time

verbal plinth

Is it possible to edit the embed of a StringSelectMenuInteraction with interaction.update and also send a message to the user?

rose tangle

yes

you can do whatever you want (as long as you have perms) during/after an interaction, just make sure you reply to it (.update() is also a reply)

verbal plinth

Does that mean I can just do interaction.update and interaction.reply? Is both possible?

rose tangle

no, but if you want to update and then send another message you can followUp

sharp ginkgoBOT
rose tangle

which is kinda as if you could .update() and then .reply()

shadow pier
rose tangle

.update() sending the button as disabled

basically the same thing you originally sent, but with the disabled button

sharp ginkgoBOT

method ButtonInteraction#update() discord.js@14.19.3
Updates the original message of the component on which the interaction was received on.


// Remove the components from the message
interaction.update({
  content: "A component interaction was received",
  components: []
})
  .then(console.log)
  .catch(console.error);

shadow pier

its a huge container, is it possible i can do something else?

steel trail

new ContainerBuilder(message.components[0].toJSON()) and you got the builder structure again. then you can access the button in it through .components[x].... (or .find or ...) and call setDisabled on it

verbal plinth
rose tangle
rose tangle
sharp ginkgoBOT

mdn Array.prototype.find()
The find() method of Array instances returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.

shadow pier

Ohh

that. I thought it existed on ContainerBuilder my bad

verbal plinth
rose tangle

yes, but when do you want to edit the followup?

at a provided time without user input, or does that new (followUp) message also have components, and you want to update when those are used

verbal plinth

With the same interaction that an ephemeral message that is sent

rose tangle

so without user input? it'll update by "itself"?

shadow pier

hmm

verbal plinth

When the user clicks Select, I first update the embed of the Select with interaction.update, then I send them a response with interaction.followup, stating that they have to wait a moment. After all the database queries, I want to process this message and say whether everything worked or something went wrong.

shadow pier
Argument of type 'APIContainerComponent | APITextDisplayComponent | APISectionComponent | APISeparatorComponent | APIFileComponent | APIMediaGalleryComponent | APIActionRowComponent<...>' is not assignable to parameter of type 'Partial<APIContainerComponent> | undefined'.
  Type 'APITextDisplayComponent' is not assignable to type 'Partial<APIContainerComponent>' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties.
    Types of property 'type' are incompatible.
      Type 'ComponentType.TextDisplay' is not assignable to type 'ComponentType.Container
rose tangle
sharp ginkgoBOT
rose tangle

send it on the message property

verbal plinth
rose tangle

no, it'll update the message you pass

if you don't pass anything it defaults to that, yes

but as I'm suggesting, you'd pass the message followUp returns

so it'd update the followUp message

sharp ginkgoBOT
rose tangle

because technically that component can be any component, hence the union

verbal plinth
rose tangle

no, you get a message

rigid crest

can bots use stickers in stuff like embeds (and the new component)? (stupid question i know but curious as if so then my idea can go in motion)

verbal plinth
rigid crest

alright

rose tangle

though a bot can send embeds and stickers, that's always been a thing

but not stickers in an embed

you can simulate a sticker with a media gallery component though (for cv2)

upbeat saffron

how do i edit a CV2 Message? Tried ContainerBuilder.from but property does not exists

steel trail
shadow pier

how do i edit the message of an emphemeral response

rose tangle

interaction.editReply()

shadow pier
rose tangle

.update() on the collected interaction then

shadow pier

its in the end event

tried using message.edit

rose tangle
shadow pier

oh

im so dumb, im sorry

rose tangle

no worries, interactions can be tricky to understand at first

hallow mesa

I'm trying to replace my fetchReply options with withResponse but I'm getting an unexpected type when I call CommandInteraction.followUp. Replying works as expected:

const initial = await interaction.reply({
    content: "initial response",
    withResponse: true,
})
console.debug(initial) // InteractionCallbackResponse

But a subsequent followUp returns a Message instead. Is this intended? Docs for InteractionReplyOptions.withResponse read to me like it should be another InteractionCallbackResponse:

const response = await interaction.followUp({
    content: "follow-up response",
    withResponse: true,
})
console.debug(response) // Message

`-- discord.js@14.19.3
Edit: Hit enter too quickly. One sec

zenith violet

followUp does return a Message yes

sharp ginkgoBOT
hallow mesa

Is withResponse not even needed then?

sharp ginkgoBOT
hallow mesa

^ That implied to me that it should have been not a Message

red coral

Reply, options

hallow mesa

It is listed as the param type for followUp though

lapis scaffold

Hi! I'm confused with @discordjs/core^2.0.1.

How is this deprecated? What should I use instead of this?

halcyon bison
halcyon bison
hallow mesa
fallow gust

version: 14.19.3

is update() missing on the type declaration for ModalSubmitInteraction? It's there in the documentation, and during runtime, but typescript can't seem to find it for me:
Property 'update' does not exist on type 'ModalSubmitInteraction<any>'

sharp ginkgoBOT
zenith violet

you need to typeguard

fallow gust
zenith violet you need to typeguard

Tyy! Just wondering, but can deferUpdate() be possible while update() isn't, considering deferUpdate() doesn't have the typeguard?
-# As well as some other properties, like message

upbeat saffron

whats the proper way of checking a message is a CV2?

steel trail

check the flag

upbeat saffron
steel trail

yeah, looks good

upbeat saffron
steel trail

do you want the safe variant or the "I know the type of that message" variant?

former: assign the component to a variable, check .type to be ComponentType.Container, then call toJSON() on it.
latter: cast to APIContainerComponent

plush portal

when the users authorize the App as user install. can i get the data of the users who authorize the bot in their account?

bleak owl

discord.js does not support oauth2

plush portal
grim gate

how do i add this in my bot via djs?

crimson gale

discord does that automatically as soon as it has enough usage data for your commands (and your app needs to be verified)

you cannot influence that in any way

frozen egret

I would like my bot to be able to keep track of members who bump the server, and we’re using Disboard. The final version of my bot will be able to run a weekly leaderboard that will reset every Sunday, but that part is easy and I know how to implement that.

Is there a way to grab the username in the Disboard embed of the person who did the /bump command (in disboard?) I’ve attached a picture of the message, and it’s the bit at the top that says “XXXXXX used 💠Bump”.

sharp ginkgoBOT
hallow mesa
sharp ginkgoBOT
exotic lintel

hello, is there any way for me to fetch all members of a role?

little pebble
hasty fern

Hey guys, are there any d.js docs for Components V2?

rose tangle

yes, every builder is in the docs page

sharp ginkgoBOT

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

rose tangle

for instance

hasty fern

Thanks

shadow pier

If i deferUpdate a button interaction, and then edit the original interaction (the command interaction in which the button was sent) would it still throw an error?

rose tangle

it'd throw if the command interaction was sent 15+ mins ago

shadow pier
rose tangle

but ideally you should editReply on the button

after the deferUpdate

rose tangle
shadow pier

Well Im editing the message on the end event

so I can't edit the button interaction there can i?

Or why don't i just use update with an empty object?

rose tangle

what are you doing with the button interaction then?

shadow pier

stopping the collector

rose tangle

but you must give the user some kind of feedback that their button click did something

a reply or an update

shadow pier

The message updates

rose tangle

and how are you updating it? (method)

shadow pier

originalInteraction.editReply

rose tangle

you should be calling .update on the button interaction

or deferUpdate and then editReply, both on the button interaction, in case you need to defer to do async/io calls

shadow pier
rose tangle
shadow pier

This is what i am doing, would this result in an error?

so far i haven't recieved any error

rose tangle

it shouldn't, but I would move that logic to a function that takes the interaction, then on end you pass the last interaction, on button "help-end-interaction" you pass the button interaction

shadow pier

oh, i see

rose tangle

it should show a visual error to the user after a while because you didn't actually editReply on the button after the defer

but it's unlikely the user will see the message for that long

shadow pier
rose tangle

you can stop with another reason and check the reason before calling it in end

thorn pelican

theres no guide yet for components v2 right?

loud quartz

No guide yet, correct

shadow pier
loud quartz

Correct. A preview of a PR

Which can change and whatnot

shadow pier

ah

loud quartz

Since that's not finalized

shadow pier
dense jackal
shadow pier

oh that makes sense

dense jackal

or when the bot doesn’t have access to that message that error also appears

shadow pier

lets say i deleted that message, and the bot tries to edit it

dense jackal

yh

always good to use a catch for such scenarios

and handle it accordingly

verbal iris

Hey, is it possible to get a user's tag?

sharp ginkgoBOT

documentation suggestion for @verbal iris:
property User#tag discord.js@14.19.3
The tag of this user This user's username, or their legacy tag (e.g. hydrabolt#0001) if they're using the legacy username system

verbal iris

I meant the new tags displayed next to the username

crimson gale

they are not yet documented, so we do not expose them through discord.js

they are sent with the raw user payload by the api, though

somber basin

can you not edit an ephemeral message or something

I'm trying to run interaction.message.edit on an ephemeral message from a button interaction event

but i keep getting unknown message

crimson gale

you can, if you want to update from a button press you should respond with update to the interaction, rather than trying to edit the underlying message though

sharp ginkgoBOT

method ButtonInteraction#update() discord.js@14.19.3
Updates the original message of the component on which the interaction was received on.


// Remove the components from the message
interaction.update({
  content: "A component interaction was received",
  components: []
})
  .then(console.log)
  .catch(console.error);

somber basin

oh right my b, I'm way too used to the old way of doing stuff lol

verbal iris
crimson gale

knock yourself out! don't rely on it working or anyone providing support with undocumented endpoints or payloads
-# anything undocumented may be changed or removed by discord at any point in time without notice

verbal iris

Okay thanks

sharp ginkgoBOT
crimson gale

for direct requests, you can use the rest interface we expose through Client instances

sharp ginkgoBOT

class ComponentBuilder discord.js@14.19.3
The base component builder that contains common symbols for all sorts of components.

pine quarry

How can I use Components V2? Is there any documentation for it? If so, could you please share it? I’d like to use it too

upper relic
pine quarry
upper relic
crystal cargo

if (interaction.targetType != "MESSAGE")
how to write this in v14?
this is for message context menus

pine quarry
crystal cargo
upper relic
potent burrow

Discord API types seems to have an incorrect type
message.components is somehow optional for APIMessageComponentInteraction
which does't make sense
how can a message component interaction exist if the message has no components?

upper relic
unique shoal
pine quarry
potent burrow
unique shoal

In theory it could be types as & { components: WhateverType }

jolly bay
somber basin

when doing channel.permissionOverwrites.set(overwrites)

with a valid user id, I get:

Unhandled promise rejection: TypeError [InvalidType]: Supplied parameter is not a cached User or Role.

why does it matter whether the user is cached on the bots end.... isnt this id just sent to discord as is anyway

pine quarry
jolly bay

Nvm I thought discord made it so it's customisable

pine quarry

This is because I use Discord in Turkish, it may be different for you :]

candid grove

I am looking at a logging bot, and want to include some specific audit log actions as it provides a better logging system than custom crafting it for server changes etc. But I am trying to understand the difference between action and actionType and which to use to filter and select the actions I want to log. Which one do I use and how? Are they both enums?

proud parrot

what happens if you call message.reply() without passing any arguments in Discord.js v14?

steel trail
steel trail
sharp ginkgoBOT
candid grove
steel trail

If you want to filter you should include the action to filter for in the fetch call already

sharp ginkgoBOT

method Guild#fetchAuditLogs() discord.js@14.19.3
Fetches audit logs for this guild.


// Output audit log entries
guild.fetchAuditLogs()
  .then(audit => console.log(audit.entries.first()))
  .catch(console.error);

candid grove

Its just a gateway event for GuildAuditLogEntryCreate

sharp ginkgoBOT
steel trail
candid grove

Thanks. Yeah trying to make logging simple for servers. Select a level and watch as the bot logs stuff for you, simply and in a nice way.

Just didn't want to track EVERY gateway event for all the possible changes that servers would want logged.

drifting dirge

does the GuildMemberRemovegets triggered even with a member being kicked or banned

rather than them leaving on their own

steel trail

Yes

sharp ginkgoBOT
candid grove

I keep getting a punycode deprecation warning for @discordjs/ws package, is this meant to happen? Or am I using the wrong node version?

sacred valve

i forgot how to get the guild icon lol, can someone help me?

sharp ginkgoBOT
sacred valve

thanks

also, is there anyway to register commands for only 2 servers?

snow onyx
sharp ginkgoBOT

guide Creating Your Bot: Registering slash commands - Guild commands
read more

steel trail
near siren

im using <Client>.guilds.cache.get('...')?.toJSON() inside a broadcastEval and I sometimes get this error, is it a DJS issue?

node:internal/process/promises:391
     triggerUncaughtException(err, true /* fromPromise */);
     ^
 
 Error [TypeError]: Cannot read properties of undefined (reading 'replace')
     at get nameAcronym [as nameAcronym] (/root/./node_modules/discord.js/src/structures/BaseGuild.js:67:8)
     at flatten (/root/./node_modules/discord.js/src/util/Util.js:36:24)
     at Guild.toJSON (/root/./node_modules/discord.js/src/structures/Base.js:35:12)
     at Guild.toJSON (/root/./node_modules/discord.js/src/structures/Guild.js:1441:24)
     at eval (eval at _eval (/root/./node_modules/discord.js/src/client/Client.js:533:12), <anonymous>:5:19)
     at eval (eval at _eval (/root/./node_modules/discord.js/src/client/Client.js:533:12), <anonymous>:12:7)
     at Client._eval (/root/./node_modules/discord.js/src/client/Client.js:533:12)
     at ClusterClient._eval (/root/./node_modules/discord-hybrid-sharding/dist/Core/ClusterClient.js:199:38)
     at ClusterClientHandler.handleMessage (/root/./node_modules/discord-hybrid-sharding/dist/Structures/IPCHandler.js:111:48)
     at ClusterClient._handleMessage (/root/./node_modules/discord-hybrid-sharding/dist/Core/ClusterClient.js:180:48)
 
 Node.js v20.17.0```
discord.js@14.19.3
steel trail

can you show the warning and node version?

polar karma

.0

steel trail
candid grove
const changes: Array<{ key: string; new: any; old: any }> = [];

entry.changes.forEach((change) => {
  changes.push({
    key: change.key,
    new: change.new || null,
    old: change.old || null
  });
});
```When i run this code, it makes the changes display as new: [ Object ]. How do I make this always show the changes, no matter the target or event type properly for nice logging in an embed sent to a channel?
steel trail

display where?

candid grove

Console

steel trail

that's how logging works if no depth defined

candid grove

And in JSON.stringify(changes) when I send the embed to the channel

steel trail
near siren
steel trail you seem to JSONify a Guild that has no `name` property set... in a broadcastEva...

im not sure which broadcastEval but they're the same for the mostpart.

manager.evalOnGuild(async (cluster, { guildId, userId }) => {
  const guild = cluster.guilds.cache.get(guildId);
  const user = await cluster.users.fetch(userId).catch(() => null);

  return {
      user: user?.toJSON() as DjsUser | null,
      guild: guild?.toJSON() as DjsGuild | undefined
  }
}, { guildId, context: { guildId, userId } })

evalOnGuild is from here: https://github.com/Tomato6966/Codes/blob/main/hybridUtils/customEvaluates.js (at the bottom)

candid grove

I see... So a different embed based on what happened.

steel trail
near siren

well, i dont do undefined, but to another value

actually, infact i do guild.name = guild.name so it shouldnt matter?

steel trail

or you made the same mistake somewhere else too?

near siren

i did ctrl+shift+f name =, name= and only 2 occasions where i did guild.name = guild.name

bitter pivot

HMM

discord.js 14.19.3, anyone know why it's happening to me?

steel trail

are you sure you're on 14.19.3? does your IDE know yet? try reloading

bitter pivot
bitter pivot

What's the maximum textdisplaycomponents you can have with a button accessory in a single container?

i.e. I want something like a box

With a title [btn]
A description

The same below it

But how many can I stack it?

candid grove
topaz bluff
novel mauve

is there a helper function to turn an icon hash into a server icon url or should i build the link manually

red coral

I think the client.rest.cdn has some stuff

sharp ginkgoBOT
novel mauve

ah that's what i wanted, ty

oak dock

hello! how can i add an "watching" activity to my bot?

sharp ginkgoBOT

method ClientUser#setPresence() discord.js@14.19.3
Sets the full presence of the client user.


// Set the client user's presence
client.user.setPresence({ activities: [{ name: 'with discord.js' }], status: 'idle' });

steel trail

with a type: in the activity (check setActivity for another example)

shadow pier

You cant show a modal in a deffered interaction?

sharp ginkgoBOT
hallow mesa
fading girder

how to know if a command is being used from a user who has the bot added to his "apps"

basically all these, "only you can see this" replies from the bot

sharp ginkgoBOT
fading girder

I have a command with these, .setContexts(InteractionContextType.Guild) .setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild)

I want to make sure only users with manage guild can the command and it can't be used even if the user has the app added to his apps list and try to use the admin commands

sinful gazelle

How can I give the bot a role if someone tags put server

oak dock

can somebody help me? client.user.setActivity('Ghosty.', { type: ActivityType.Watching }); ^ TypeError: Cannot read properties of null (reading 'setActivity') at Object. at Module._compile (node:internal/modules/cjs/loader:1368:14) how can i solve this?

hallow mesa
fading girder kinda confused, what does this mean?

That message was the property you can check to see if the command is added to the server. But you can also just set the command to not be available through user installs and require being added to the guild with .setIntegrationTypes

fading girder
hallow mesa

Yep

nova pond

Hello, I would like to contact you because I have my bot which is in more than 2700 servers I did not have any problem at the level of the shards and since this morning I have my bot which makes that to disconnect I tried to leave it offline during one moment but when I restart I fall on this error and that makes only reload the loading of the project: js Erreur lors de la récupération des informations de shard : Error [ShardingInProcess]: Shards are still being spawned. at ShardingManager._performOnShards (C:\Users\james\OneDrive\Bureau\Bad-Protect\node_modules\discord.js\src\sharding\ShardingManager.js:297:13) at ShardingManager.fetchClientValues (C:\Users\james\OneDrive\Bureau\Bad-Protect\node_modules\discord.js\src\sharding\ShardingManager.js:277:17) at Shard._handleMessage (C:\Users\james\OneDrive\Bureau\Bad-Protect\node_modules\discord.js\src\sharding\Shard.js:398:22) at ChildProcess.emit (node:events:518:28) at emit (node:internal/child_process:951:14) at process.processTicksAndRejections (node:internal/process/task_queues:83:21) Erreur lors de la récupération des informations de shard : Error [ShardingInProcess]: Shards are still being spawned. at ShardingManager._performOnShards (C:\Users\james\OneDrive\Bureau\Bad-Protect\node_modules\discord.js\src\sharding\ShardingManager.js:297:13) at ShardingManager.fetchClientValues (C:\Users\james\OneDrive\Bureau\Bad-Protect\node_modules\discord.js\src\sharding\ShardingManager.js:277:17) at Shard._handleMessage (C:\Users\james\OneDrive\Bureau\Bad-Protect\node_modules\discord.js\src\sharding\Shard.js:398:22) at ChildProcess.emit (node:events:518:28) at emit (node:internal/child_process:951:14) at process.processTicksAndRejections (node:internal/process/task_queues:83:21) Erreur lors de la récupération des informations de shard : Error [ShardingInProcess]: Shards are still being spawned. at ShardingManager._performOnShards (C:\Users\james\OneDrive\Bureau\Bad-Protect\node_modules\discord.js\src\sharding\ShardingManager.js:297:13) at ShardingManager.fetchClientValues (C:\Users\james\OneDrive\Bureau\Bad-Protect\node_modules\discord.js\src\sharding\ShardingManager.js:277:17) at Shard._handleMessage (C:\Users\james\OneDrive\Bureau\Bad-Protect\node_modules\discord.js\src\sharding\Shard.js:398:22) at ChildProcess.emit (node:events:518:28) at emit (node:internal/child_process:951:14) at process.processTicksAndRejections (node:internal/process/task_queues:83:21) Erreur lors de la récupération des informations de shard : Error [ShardingInProcess]: Shards are still being spawned. at ShardingManager._performOnShards (C:\Users\james\OneDrive\Bureau\Bad-Protect\node_modules\discord.js\src\sharding\ShardingManager.js:297:13) at ShardingManager.fetchClientValues (C:\Users\james\OneDrive\Bureau\Bad-Protect\node_modules\discord.js\src\sharding\ShardingManager.js:277:17) at Shard._handleMessage (C:\Users\james\OneDrive\Bureau\Bad-Protect\node_modules\discord.js\src\sharding\Shard.js:398:22) at ChildProcess.emit (node:events:518:28) at emit (node:internal/child_process:951:14) at process.processTicksAndRejections (node:internal/process/task_queues:83:21) Erreur lors de la récupération des informations de shard : Error [ShardingInProcess]: Shards are still being spawned. at ShardingManager._performOnShards (C:\Users\james\OneDrive\Bureau\Bad-Protect\node_modules\discord.js\src\sharding\ShardingManager.js:297:13) at ShardingManager.fetchClientValues (C:\Users\james\OneDrive\Bureau\Bad-Protect\node_modules\discord.js\src\sharding\ShardingManager.js:277:17) at Shard._handleMessage (C:\Users\james\OneDrive\Bureau\Bad-Protect\node_modules\discord.js\src\sharding\Shard.js:398:22) at ChildProcess.emit (node:events:518:28) at emit (node:internal/child_process:951:14) at process.processTicksAndRejections (node:internal/process/task_queues:83:21)

hallow mesa
oak dock
hallow mesa
hallow mesa
hallow mesa

Where in index.js? Inside an event?

hallow mesa
oak dock

Make sure the bot is ready before trying to access <Client>.user, otherwise it will be null
You're trying it before the client is ready. Put it inside an event

oak dock
frozen egret

how do i take a user id and turn it into a username while inside a for loop? I can't use await client.users.fetch because of the aformentioned for loop.

vestal sun
manic axle
frozen egret

true but i'm trying to use it in backend and not in a message

vestal sun

else you could use

await Promise.all(async loop)

like this as an example

const items = normalItems.map(async (item) => {
   let emote: string | ApplicationEmoji
   try {
       emote = await interaction.client.application.emojis.fetch(item.item.emoteName)
   } catch (_e) {
       emote = item.item.emoteName
   }
   return `${emote} **${item.item.name[`${locale === 'de' ? 'de' : 'en'}`]}**: ${item.quantity}`
})
const itemsString = await Promise.all(items)```
vital raven
frozen egret
vestal sun
frozen egret

my bad i meant to type foreach

going through an array of ids

vestal sun

uhm for that idk but should be similar (?)

manic axle

You would need to make the callback async if you do that, plus ^
also note that an async forEach() callback will not wait for all the inner loops to run before exiting the forEach() and going to the proceeding code, so take that into consideration if that matters

Using a for...of loop is the easiest method for similar syntax, as long as you dont care about the index
i see that you do use the index though now, so you can just use a normal for loop

vestal sun
vital raven

<Array>.entries() exists. You can use it with for...of

hexed marsh

Does anyone know the pixel width of a container for media? I want to put in a "Legend" for one of my features, but I need it to be an image from a URL. I need to ensure it's sized properly so I need the width. Any suggestions on that?

hexed marsh

I expect it should resize on their display, but is there a maximum size for it, or just send it?

vital raven
idle hollow

where the list of events for logging

vital raven

Logging what?

idle hollow

like message etc

sharp ginkgoBOT
vital raven

All client events are listed in the client

shadow harness

What's wrong with my code here? I am 100% certain the channel exists, and that channel?.isSendable() returns true (I recently removed console.logs that always fired) but the console.log(response) never fires..

steel trail

probably because you don't receive any message. missing GuildMessages intent?

or DirectMessages if in DMChannel

shadow harness

Indeed I was missing DirectMessages on my intents

sharp ginkgoBOT

To receive direct message events on "messageCreate" with your bot, you will need:

shadow harness

@steel trail Do I need to do partials if I just run interaction.user.createDM() every time?

steel trail

if you never expect to receive DMs before you did that: probably not

shadow harness
vagrant mortar

quick question:
if the ephemeral flag isn't set while using deferReply, can I set it later on followUp messages attached to that interaction?

so can I do something like this:

await interaction.deferReply();
await interaction.followUp({content: "hi", flags: MessageFlags.Ephemeral });

because the message is sent but not ephemeral, and I'm wondering if it's just not how it works or it's me who's doing something wrong

steel trail

you can't even set it on deferUpdate. since the message already exists and you can't change ephemeral state

vagrant mortar

oh sorry deferReply() **

steel trail

only when a new message gets made

vagrant mortar

i meant deferReply, muscle memory xd

steel trail

in that case you'd need to include it in the deferReply already

vagrant mortar
steel trail

deleteReply, but yes. it won't show as response to the interaction then though but as response to the deleted message

vagrant mortar

or just gotta use send()?

shadow harness

However, you really don't need to defer unless your DB is incredibly slow. You have 3s to respond to the interaction; if your DB can query in a reasonable amount of time, you can then check if it's valid and use reply with a normal message, otherwise reply with an ephemeral message

jade olive

I'm gonna ask a probably stupid question.

Im trying to detect if reply mention was enable/disabled on a message that replied to a webhook message, message.mentions doesn't pick it up so im assuming its not possible, but i thought to ask cause maybe someone knows something I dont. Is this possible?

vagrant mortar
shadow harness
polar karma

once a reply (defer or reply) is sent, its ephemeral state cannot be changed. running the async code without deferring can work, but if it takes longer than 3s, you're SOL

shadow harness
halcyon bison
frozen egret

if my bot is listening to messageCreate events, how much can it take before it becomes overwhelming? it's doing what it's coded to do, reading every dang message. but like, i don't want to overstress it.

it's really only a bot for our own personal community server, so it won't be too many messages, but if i ever went public with it, i would have to remove/change it, right?

urban nimbus

Question, is there a way to update an existing embed message that has an ActionRowBuilder<StringSelectMenuBuilder> to components v2? When I try to pass the new compoments v2 using await interaction.update({ components: [data], flags: MessageFlags.IsComponentsV2 }); it still throws data.embeds[MESSAGE_CANNOT_USE_LEGACY_FIELDS_WITH_COMPONENTS_V2]: The 'embeds' field cannot be used when using MessageFlags.IS_COMPONENTS_V2 even though the code is fully updated for v2 and works off a new command

steel trail
halcyon bison
steel trail
halcyon bison
urban nimbus
frozen egret
halcyon bison
frozen egret

All it's doing is picking up on the messageCreate events emitted from the one single server

and then checking if the user id is Disboard's ID. if not, it ends. If yes, do stuff.

If all it's doing is seeing a message and then ending the function as it wasnt relevent, does this take up a lot of power?

halcyon bison

Can't imagine so

modern beacon

question plz
will we ever get unlimited timeout and temporary bans?

clear garnet

That'd be a question you'd want to ask Discord

idle hollow
BotStatus: {
    type: 'dnd', // Status types: 'online', 'idle', 'dnd', 'invisible'
    activity: {
        type: 4, // Activity types: 0 = PLAYING, 1 = STREAMING, 2 = LISTENING, 3 = WATCHING, 4 = CUSTOM, 5 = COMPETING
        name: 'Over SNH Discord',
        url: null // Optional: URL for streaming status
    },
    rotationInterval: 300000
}

bot.user.setPresence({
    status: bot.config.BotStatus.type,
    activities: [{
        type: bot.config.BotStatus.activity.type,
        name: bot.config.BotStatus.activity.name,
        url: bot.config.BotStatus.activity.url
    }]
});

any reason why my type wont change

dim finch

How can I make my bot to check if a certain user has our server tag activated?

subtle falcon
        const channel: GuildBasedChannel | null = await guild.channels.fetch(channelId);

        if (!channel?.permissionsFor(client.user as User)?.has(PermissionFlagsBits.Connect)) {
            const Embed: EmbedBuilder = new EmbedBuilder()
                .setColor(parseInt(config.embeds.color, 16))
                .setDescription("`❌` | Je n'ai pas la permission de me connecter à votre salon vocal.");

            return void Interaction.editReply({ embeds: [Embed], components: [] });
        }```
It always says that the bot doesn't have the permission but it does ?
dim finch
polar karma
subtle falcon
polar karma

define "valid". how did you verify it has the Connect permission? did you log ...permissionsFor(...).serialize() or similar to check?

subtle falcon
polar karma

log what i asked for in the last message and show the output

polar karma

then something is returning falsey earlier in the chain, since permissionsFor() cannot return undefined

what does channel log

subtle falcon
polar karma what does `channel` log
<ref *2> VoiceChannel {
  type: 2,
  guild: <ref *1> Guild {
    id: '716334462761435157',
    name: 'DEV BOTS',
    icon: 'cc1f182b999195c9d3336c806bb897f2',
    features: [ 'NEWS', 'COMMUNITY' ],
    commands: GuildApplicationCommandManager {
      permissions: [ApplicationCommandPermissionsManager],
      guild: [Circular *1]
    },
    members: GuildMemberManager { guild: [Circular *1] },
    channels: GuildChannelManager { guild: [Circular *1] },
    bans: GuildBanManager { guild: [Circular *1] },
    roles: RoleManager { guild: [Circular *1] },
    presences: PresenceManager {},
    voiceStates: VoiceStateManager { guild: [Circular *1] },
    stageInstances: StageInstanceManager { guild: [Circular *1] },
    invites: GuildInviteManager { guild: [Circular *1] },
    scheduledEvents: GuildScheduledEventManager { guild: [Circular *1] },
    autoModerationRules: AutoModerationRuleManager { guild: [Circular *1] },
    soundboardSounds: GuildSoundboardSoundManager { guild: [Circular *1] },
    available: true,
    shardId: 0,
    splash: null,
    banner: null,
    description: null,
    verificationLevel: 1,
    vanityURLCode: null,
    nsfwLevel: 0,
    premiumSubscriptionCount: 0,
    discoverySplash: null,
    memberCount: 16,
    large: false,
    premiumProgressBarEnabled: false,
    applicationId: null,
    afkTimeout: 300,
    afkChannelId: null,
    systemChannelId: null,
    premiumTier: 0,
    widgetEnabled: null,
    widgetChannelId: null,
    explicitContentFilter: 2,
    mfaLevel: 0,
    joinedTimestamp: 1747163078343,
    defaultMessageNotifications: 1,
    systemChannelFlags: SystemChannelFlagsBitField { bitfield: 7 },
    maximumMembers: 250000,
    maximumPresences: null,
    maxVideoChannelUsers: 25,
    maxStageVideoChannelUsers: 50,
    approximateMemberCount: null,
    approximatePresenceCount: null,
    vanityURLUses: null,
    rulesChannelId: '1269065559950233781',
    publicUpdatesChannelId: '1269065559950233784',
    preferredLocale: 'en-US',
    safetyAlertsChannelId: null,
    ownerId: '1274808781477380112',
    emojis: GuildEmojiManager { guild: [Circular *1] },
    stickers: GuildStickerManager { guild: [Circular *1] },
    incidentsData: null
  },
  guildId: '716334462761435157',
  permissionOverwrites: PermissionOverwriteManager { channel: [Circular *2] },
  messages: GuildMessageManager { channel: [Circular *2] },
  nsfw: false,
  flags: ChannelFlagsBitField { bitfield: 0 },
  id: '1307142143009226774',
  name: 'b',
  rawPosition: 2,
  parentId: '1157847937171337266',
  rtcRegion: null,
  bitrate: 64000,
  userLimit: 0,
  videoQualityMode: null,
  lastMessageId: null,
  rateLimitPerUser: 0
}```
eternal nebula

uhm

polar karma
eternal nebula

alr

polar karma
subtle falcon
polar karma show the exact code that produced `undefined` when i asked for `...permissionsFo...
        const member: GuildMember = Interaction.member as GuildMember;
        const channelId: string | null = member.voice.channelId;

        if (!channelId) {
            const Embed: EmbedBuilder = new EmbedBuilder()
                .setColor(parseInt(config.embeds.color, 16))
                .setDescription("`❌` | Vous devez être dans un salon vocal pour utiliser cette commande.");

            return void Interaction.editReply({ embeds: [Embed], components: [] });
        }

        const guild: Guild = Interaction.guild as Guild;
        const guildId: string = guild.id;
        const channel: GuildBasedChannel | undefined = await guild.channels.cache.get(channelId);
        console.log(channel?.permissionsFor(client.user as User)?.serialize())

(I changed it back to channels.cache)

polar karma

ditch the ? chaining and see what it outputs. ts-ignore or whatever is needed