#djs-help-v14

78874 messages · Page 70 of 79

stable sun

LabelBuilder do not belong inside of ActionRowBuilders

LabelBuilder replace ActionRowBuilder (in modals)

neat nimbus

so confused
so remove all the ActionRowBuilder

which i done?

module.exports.run = async function (b, c, cfg, i, a, d) {
  var arg = a.split('-'), id = i.message.embeds[0]?.footer?.text || '0', row = null;

  switch (arg[0]) {
    case 'Add':
      return i.showModal(
        new b.djs.ModalBuilder()
          .setCustomId('-Add')
          .setTitle('Add Permission Configuration')
          .addLabelComponents(
            new b.djs.LabelBuilder().setLabel("Select the permission type").setStringSelectMenuComponent(
              new b.djs.StringSelectMenuBuilder()
                .setCustomId('Type')
                .setPlaceholder('Select the permission type...')
                .addOptions([
                  { label: 'Permissions', value: 'Perms' },
                  { label: 'Settings', value: 'Settings' },
                  { label: 'Logging', value: 'Logging' }
                ])
            ),
            new b.djs.LabelBuilder().setLabel('Select a role for the permission').setRoleSelectMenuComponent(
              new b.djs.RoleSelectMenuBuilder()
                .setCustomId('Role')
                .setPlaceholder('Select a role')
            )
          )
      )
  }
};

so this

how would i get the data ? i.fields.?

wary coral

What is up with your function def

neat nimbus

nothing? if its b, c, cfg, i, a, d? its fix on prod one

wary coral

Are you passing the packages as function argument

neat nimbus

yes

wary coral

Why

neat nimbus

tidyer

wary coral

That just raises more questions. Why are you adding the packages as properties of your client?

neat nimbus

cause not wanting in every file just stupid

wary coral

You can import from a package in multiple files

neat nimbus

?

wary coral

I think you should read the guide and a js tutorial for multi-file projects.

To answer your question, you previously asked about the modal and receiving data from it. I would refer you to the modal guide

sharp ginkgoBOT
wary coral
neat nimbus ?

Sorry to clarify and provide more help than just saying go learn js. In javascript.

You can import/require a library in multiple files

neat nimbus

yes by doing example

var { Client, Collection } = require("discord.js"), express = require("express"), a = express();
var mysql = require("mysql2"), cfg = require("../config");```
in each file yes ik that
wary coral

Then why make them properties of your client?

neat nimbus

everything goes off mymain init file

where con bot express etc is

here exmaple

var { Client, GatewayIntentBits, Collection } = require("discord.js"), express = require("express"), a = express();
var mysql = require("mysql2"), cfg = require("../config");

Logger = function (m, o = {}) {
  var out = [];
  if (o.bold) out.push(`\x1b[1m`);
  if (o.color) out.push(`\x1b[${o.color}m`);
  if (o.title) out.push(`[${o.title}]: \x1b[0m`);
  console.log(`${out.join("")}${m}\x1b[0m`);
}

c = mysql.createPool({
  host: cfg.SQLInformation.Host,
  user: cfg.SQLInformation.Username,
  password: cfg.SQLInformation.Password || null,
  database: cfg.SQLInformation.Database,
  charset: cfg.SQLInformation.Charset || "utf8mb4",
  port: cfg.SQLInformation.Port || 3306
});

b = new class extends Client {
  constructor() {
    super({
      intents: [GatewayIntentBits.Guilds]
    });
    this.cfg = cfg;
    this.pkg = require('../package.json');
    this.djs = require("discord.js");
    this.ms = require("ms");
    this.fs = require("fs");
    this.path = require("path");
    this.figlet = require("figlet");
    this.Commands = new Collection();
    this.Events = new Collection();
    this.Buttons = new Collection();
    this.Modals = new Collection();
    this.Menus = new Collection();
  }
}();

a.listen(cfg.SiteInformation.ProcessPort, function (e) {
  if (e) return Logger(e, { title: "EXPRESS", color: 31 });
  require("./backend")(a, b, c, cfg);
});

process.on("uncaughtException", function (e) {
  Logger(e.stack, { title: "ERROR", color: 31 });
});
process.on("unhandledRejection", function (e) {
  Logger(e.stack, { title: "ERROR", color: 31 });
});

module.exports = { a, b, c, cfg };```

Dont really see the diffrence in if there or in the file them self

wary coral

Alright, so I am going to move past this and try to help with your questions. I don't want to get bogged down on this

neat nimbus

i all ready fixed it

wheat gulch

So I think I dont need to explain what the problem yis, it is obvious. Modlog and modules cmds, they are not getting highlighted

related part: https://sourceb.in/m9qB3Gg6c8

I dont use guildcommands*

torn orchid

is there a way to have your bot respond to a button press on a discord embed not owned by your bot?

wheat gulch

thats not possible as ik due to api arch

topaz bluff
loud quartz

But there's a pretty random use of inline codeblocks there

As if you never end them

neat nimbus

is there a way to set defult info from the db into it?

for the select?

            new b.djs.StringSelectMenuBuilder()
              .setCustomId('Language')
              .setPlaceholder('Select a language...')
              .addOptions([
                { label: 'English', value: 'English' },
                { label: 'Spanish', value: 'Spanish' },
                { label: 'French', value: 'French' },
                { label: 'German', value: 'German' }
              ])
              .setDefaultOptions({ label: d.language, value: d.language })
          )```

[Buttons]: TypeError: (intermediate value).setCustomId(...).setPlaceholder(...).addOptions(...).setDefaultOptions is not a function

fallow finch

default exists inside options not a standalone function in StringSelect, you can use StringSelectMenuOptionBuilder for better readability

new StringSelectMenuBuilder().setCustomId("config:misc:language").addOptions(
            new StringSelectMenuOptionBuilder()
              .setLabel(localeFlags["en-GB"])
              .setValue("en-GB")
              .setEmoji("🇬🇧")
              .setDefault(this.guildData.language === "en-GB"),
            new StringSelectMenuOptionBuilder()
              .setLabel(localeFlags["tr-TR"])
              .setValue("tr-TR")
              .setEmoji("🇹🇷")
              .setDefault(this.guildData.language === "tr-TR"),
          ),
``` for example
neat nimbus

how can i do that for mine?

fallow finch

it's basically default: boolean in the object property, so you would have to figure out which one is the default one

neat nimbus

got one how would i do role select

              new b.djs.RoleSelectMenuBuilder()
                .setCustomId('VerRole')
                .setPlaceholder('Select verification role...')
                .setDefault({ id: d.verRole })
            ),```
sharp ginkgoBOT
neat nimbus

see this docs are bit confusing for me in what way that works

fallow finch

You would need an array of role id(s) to put inside and they will show up as defaults

neat nimbus

is there away to select the one in the db on there? and still show the rest?

as there info in db for the channel but still want them to select new one

fallow finch

Putting up a default will show up a default, you can keep selecting or removing regardless

neat nimbus

so this

bleak owl

that won’t work

neat nimbus

why confused on docs dont explain stuff

bleak owl

you can’t specify what roles are shown by default

neat nimbus

so what trying todo wont work then

simple what ever in the db is in there it show on that menu and then they can select new one if they want if not it keep the same

fallow finch

If you wrap it in an array it should show up as the default, and you should be able to just submit it which would return that default one

neat nimbus

? yeah no clue

new b.djs.LabelBuilder()
  .setLabel("Verify Role")
  .setRoleSelectMenuComponent(
    new b.djs.RoleSelectMenuBuilder()
      .setCustomId('VerRole')
      .setPlaceholder('Select verification role...')
      .addDefaultRoles(d.verRole ? [d.verRole] : []) // Ensure it's wrapped in an array
  );
```so that
fallow finch

Yeah

neat nimbus

didnt work

fallow finch

If you log the value of verRole does it return a string

neat nimbus

thats why null i thought i set one ffs

tiny condor
elder bear

Hi I'm having a fun issue with my code, got multiple errors being thrown...

const accountSelectionModal = new ModalBuilder().setTitle(
      "Account Selection",
    ).setCustomId("withdraw_acc");
    const accountSelectionMenu = new StringSelectMenuBuilder().setCustomId(
      "acc_select",
    ).setPlaceholder("Select Account").setRequired(true);
    const accountSelectionList: StringSelectMenuOptionBuilder[] = [];
    accountSelectionList.push(
      new StringSelectMenuOptionBuilder().setLabel("locutus").setDescription(
        "locutus",
      ).setValue("loco_withdraw"),
    );
    for (const account of Accounts) {
      const strOpt = new StringSelectMenuOptionBuilder().setLabel(
        `${account.AccountName}`, 
      ).setDescription(`${account.AccountId.toString()}`).setValue(//Looks like 1fe51e6fb9c81aeb
        `w_${account.AccountId.toString().toLowerCase()}`,  //Looks like w_1fe51e6fb9c81aeb
      );
      accountSelectionList.push(strOpt);
    }

    accountSelectionMenu.addOptions(accountSelectionList);

    const accSelectionLabel = new LabelBuilder().setLabel(
      'Select your Account or select "locutus" to build text block',
    )
      .setStringSelectMenuComponent(accountSelectionMenu);
    accountSelectionModal.addLabelComponents(accSelectionLabel);
    await interaction.showModal(accountSelectionModal);

anybody got any ideas?

for your information, whoever helps: the selection menu is dynamic, we have different accounts for users to choose from

neat nimbus

anyone made a npm packge for a embed builder

elder bear
sharp ginkgoBOT
neat nimbus

yeah seen my this file from my old dev

bleak owl

there’s no reason to use a package when EmbedBuilder exists in discord.js directly

neat nimbus
neat nimbus

there none trying to compact as make code better from previoes bot from 13 best i have did atm

elder bear
elder bear Hi I'm having a fun issue with my code, got multiple errors being thrown... ```t...

here's my full stacktrace + printout of some data

{"type":3,"custom_id":"acc_select","placeholder":"Select Account","required":true,"options":[{"label":"locutus","description":"locutus","value":"loco_withdraw"},{"label":"hell","description":"1fe51e6fb9c81aeb","value":"w_1fe51e6fb9c81aeb"},{"label":"world","description":"2021a606bade7dc4","value":"w_2021a606bade7dc4"}]}
error: Uncaught Error: Received one or more errors
      return errors.length === 0 ? Result.ok(finalObject) : Result.err(new CombinedPropertyError(errors, this.validatorOptions));
                                                                       ^
    at _ObjectValidator.handleIgnoreStrategy (file:///home/monarchalia/WebstormProjects/Shadow/node_modules/.deno/@sapphire+shapeshift@4.0.0/node_modules/@sapphire/shapeshift/dist/cjs/index.cjs:2119:72)
    at _ObjectValidator.handleStrategy (file:///home/monarchalia/WebstormProjects/Shadow/node_modules/.deno/@sapphire+shapeshift@4.0.0/node_modules/@sapphire/shapeshift/dist/cjs/index.cjs:1983:47)
    at _ObjectValidator.handle (file:///home/monarchalia/WebstormProjects/Shadow/node_modules/.deno/@sapphire+shapeshift@4.0.0/node_modules/@sapphire/shapeshift/dist/cjs/index.cjs:2089:17)
    at _ObjectValidator.parse (file:///home/monarchalia/WebstormProjects/Shadow/node_modules/.deno/@sapphire+shapeshift@4.0.0/node_modules/@sapphire/shapeshift/dist/cjs/index.cjs:972:90)
    at LabelBuilder.toJSON (file:///home/monarchalia/WebstormProjects/Shadow/node_modules/.deno/@discordjs+builders@1.13.1/node_modules/@discordjs/builders/dist/index.js:1769:20)
    at file:///home/monarchalia/WebstormProjects/Shadow/node_modules/.deno/@discordjs+builders@1.13.1/node_modules/@discordjs/builders/dist/index.js:2868:64
    at Array.map (<anonymous>)
    at ModalBuilder.toJSON (file:///home/monarchalia/WebstormProjects/Shadow/node_modules/.deno/@discordjs+builders@1.13.1/node_modules/@discordjs/builders/dist/index.js:2868:35)
    at ButtonInteraction.showModal (file:///home/monarchalia/WebstormProjects/Shadow/node_modules/.deno/discord.js@14.25.1/node_modules/discord.js/src/structures/interfaces/InteractionResponses.js:402:46)
    at Object.execute (file:///home/monarchalia/WebstormProjects/Shadow/events/ButtonEvents/BuildWithdraw.ts:70:23)
Watcher Process failed. Restarting on file change...

OH GOD THATS A TEXT WALL SORRY

oh shit am i using builder again.

(no, just checked)

neat nimbus

?

elder bear
neat nimbus ?

I'm running into a very very fun issue, multiple issues with the formatting of my modal's data, but I have no idea where the issues are

neat nimbus

code?

neat nimbus

like so many line for one one embed

elder bear

yeah ngl you're not gonna be able to cut that down easily unless you shove it all to a one-liner

which is not good for readability and definitely not if you ever need to refactor

neat nimbus

unless i put into a db which might do

elder bear

wait can you put numbers in a modal value puppythinks

neat nimbus

? wym

try this

  "Account Selection",
).setCustomId("withdraw_acc");
const accountSelectionMenu = new StringSelectMenuBuilder().setCustomId(
  "acc_select",
).setPlaceholder("Select Account").setRequired(true);
const accountSelectionList: StringSelectMenuOptionBuilder[] = [];
accountSelectionList.push(
  new StringSelectMenuOptionBuilder().setLabel("locutus").setDescription(
    "locutus",
  ).setValue("loco_withdraw"),
);
for (const account of Accounts) {
  const strOpt = new StringSelectMenuOptionBuilder().setLabel(
    `${account.AccountName}`,
  ).setDescription(`${account.AccountId.toString()}`).setValue(
    `w_${account.AccountId.toString().toLowerCase()}`,
  );
  accountSelectionList.push(strOpt);
}
accountSelectionMenu.addOptions(accountSelectionList);
const accSelectionLabel = new LabelBuilder().setLabel(
  'Select your Account or select "locutus" to build text block',
)
  .setStringSelectMenuComponent(accountSelectionMenu); // Fixed: lowercase a
accountSelectionModal.addLabelComponents(accSelectionLabel);
await interaction.showModal(accountSelectionModal);
elder bear

oh well that wasn't the problem as an fyi

that was me making it easier to digest for others, I uppercase the start of every variable in my code

neat nimbus

The key fix was changing AccountSelectionMenu to accountSelectionMenu on line 26 to match the variable name defined on line 4.🤣

elder bear

that's... not the error

neat nimbus

works for me

elder bear

here's what it actually looks like internally.
I would never get an error like that if it had to do with a typo

wary coral
elder bear
elder bear
wary coral

Which file do you need looked at

wary coral

Also what is the problem we are trying to solve

elder bear

provided is a lot of the data in the modal, i don't know if i gave the topmost level of that data, tho, and then the huge asf error

wary coral

I am on mobile so it may take me a sec

elder bear

my thought is maybe values can't have numbers in them?

but, the discord API docs say specifically characters, of which numbers are...

basically I'm just at a loss, my last issue last time was i was importing from builders, made sure that wasn't the case this time

wary coral
sharp ginkgoBOT
elder bear

that seems important yeah? ^

wary coral

No? Id is an optional field

elder bear

oh i misread oops

neat nimbus

what exactly you trying todo?

wary coral
neat nimbus

like trying todo a modal with select modal with the accounts on it?

wary coral

It is a string select menu

neat nimbus

just one

wary coral
elder bear

wait does discord.js filter curse words? (lmao) this ain't api lmao im stupid

stable sun

It’s not any different than typing it yourself and sending in the app

elder bear
wary coral

Does your code work on Node

elder bear

I ain't tested it for that

neat nimbus

is this what your trying todo

elder bear

nor is it built for that, I'm using the same exact format to build this modal as i did my last one

the difference is, this one is a stringselectmenu

elder bear
neat nimbus

what else ?

elder bear

that's the thing, that's what I'm doing

neat nimbus

so this what you want

elder bear

here send it to me and let's see if it works
I'll load it into a sample command

neat nimbus
  let Accounts = [
    { label: 'Account 1', value: 'account1' },
    { label: 'Account 2', value: 'account2' }
  ]
  interaction.showModal(
    new ModalBuilder()
      .setCustomId('Logs-Add')
      .setTitle('Add Log Configuration')
      .addLabelComponents(
        new LabelBuilder().setLabel("Select the account").setStringSelectMenuComponent(
          new StringSelectMenuBuilder()
            .setCustomId('Type')
            .setPlaceholder('Select the account...')
            .addOptions(Accounts)
        )
      )
  )```
elder bear

that works... let me try that way you have the options setup...

neat nimbus
  let List = []
  for (var a of Accounts) {
    List.push(
      new StringSelectMenuOptionBuilder()
        .setLabel(`${a.AccountName}`)
        .setDescription(`${a.AccountId.toString()}`)
        .setValue(`w_${a.AccountId.toString().toLowerCase()}`)
    );
  }
  i.showModal(
    new ModalBuilder()
      .setCustomId('Logs-Add')
      .setTitle('Add Log Configuration')
      .addLabelComponents(
        new LabelBuilder().setLabel("Select the account").setStringSelectMenuComponent(
          new StringSelectMenuBuilder()
            .setCustomId('Type')
            .setPlaceholder('Select the account...')
            .addOptions(...List)
        )
      )
  )```

if want to pull from a db like you had it before

let me know if that works

elder bear

WHY TF DOES THAT WORK??

neat nimbus

🤣 that from db

elder bear

yuh

neat nimbus

atlest it works

elder bear

about to test the full implementation in a moment
wish me luck

neat nimbus

good luck

turbid osprey

How to make it like this?, button inside

wary coral
sharp ginkgoBOT

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

shell girder

Hi, using the API and documentation, is it possible to obtain the amount of boost a user gives to the server? 🙂

tardy sable
shell girder
tardy sable

theres no system message that says they stopped boosting. with the boost message type you can keep track how many times someone boosted

tiny condor

You can listen to the guild member update event to get the role update

Then you would manually have to store the timing

sharp ginkgoBOT
tiny condor

^ That will give you the amount of times a user boosts though for the first time, if they remove one you wouldn't know

shell girder

I understand, thank you very much for the information. ❤️ 🙂

modern mantle

Does anyone know where I can find the JS template on github?

bleak owl

can you be a bit more specific on what you’re referring to?

modern mantle

There was a link to the Github code at the end of the discordjs guide but unfortunately the guide was revised so that it is no longer there.

That was I mean after the event handlers

bleak owl
stable sun

Are you trying to follow the guide, or do you just want a template for creating bots?

fleet spire

Howdy all, where in the docs can I learn how to do non-slash command interactions? im basically trying to do something when someone @ mentions my bot

wary coral
fleet spire

ah

is there a section in the docs for handling events

wary coral

No I dont believe so. You would have to parse the content. it is much eseer to just use slash command.

fleet spire

I see

wary coral

Why do you want to uses message command over slash command?

fleet spire

I do need to sub to messages being sent so its abit odd the docs dont cover it but its fineig

clear garnet
fleet spire
sharp ginkgoBOT
polar karma

There's not much for the docs to cover, message.content is a string, and parsing that is basic js, not related to d.js

fleet spire

Ill have to read up on JS event subscriptions then

wary coral

to check if the bot is mentioned it is in the message object from the Message create event

sharp ginkgoBOT
ruby bane

why couldnt you just do this with a slash command?
/question content:string

fleet spire
tardy sable
fleet spire

all my searches come up with listening to DOM stuff

tardy sable
fleet spire
clear garnet

You should look into the runtime you're working with, which is likely Node.js - not a web environment which is what DOM is associated with

tardy sable
fleet spire
tardy sable

youd create your file, import your client and listen for the event such as client.on(Events.MessageCreate, async (message) => { // your code })

fleet spire

oh it is client.on

tardy sable

did you do client.once? that only emits once and never again iirc

sharp ginkgoBOT

guide Event Handling
Node.js uses an event-driven architecture, making it possible to execute code when a specific event occurs. The discord.js library takes full advantage of this. You can visit the Client documentation to see the full list of events. This page assumes you've followed the guide up to this point, and created your index.js and individual slash commands according to those pages. At this point, your index.js file has listeners for two events: ClientReady and InteractionCreate.

fleet spire

no I think I just did my logic wrong

thanks guys, appreciate it

wary coral

np, Take a read though the guide take a swing at it then come back and we can help you work thought the issue

fleet spire

last question, not something im implementing/learning tonight, but what features would you guys use to design the following:

user uses command
this creates an interactable object of some kind
users can "vote" on this (yes or no vote)

after 2 mins, logic runs based on the vote

I was thinking of using reactions somehow, but there migh be cleaner way of doing it?

ruby bane

discord has native polls

sharp ginkgoBOT
tardy sable

you can do buttons or reactions but yh discord has the poll feature now

you could force end the poll after 2 min

fleet spire

and you can run logic off it?

tardy sable

yes polls emit events too

fleet spire

so:

bot starts a poll, stores the id or something

2 mins later, force close (need to figure out how to do "2 minutes later" logic, I imagine its a node thing)

sub to poll close event, if ID matches run some logic

ruby bane

see setTimeout

fleet spire
sharp ginkgoBOT

mdn Window: setTimeout() method
The setTimeout() method of the Window interface sets a timer which executes a function or specified piece of code once the timer expires.

tardy sable
fleet spire

sweet thankyou all

excited to start my bot journey

sharp ginkgoBOT
tardy sable

duration only supports min 1h. so im not entirely sure theres a way to force end a poll

fleet spire

oh

tardy sable

if the 2min is important you go with buttons/reactions

ruby bane

theres an end method on a poll object

fleet spire
sharp ginkgoBOT
amber spruce

Hi, running v14.25.1, I was under the impression when ClientReady fires that caches are populated. However, this code shows that only the bot user exists in it. Am I doing something wrong?

discord.on(Events.ClientReady, () => {
  const { members } = aParticularGuild();
  for (const [id] of members.cache) {
    logger.info(`Refreshing ${id}`);
    refreshTimeout(id);
  }
});

I do have the GuildMembers intent:

const discord = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMembers,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
  ],
});
wary coral
amber spruce

Oh
So I guess the option is to use fetch(), then

fleet spire

is this depreciated?

just following docs here

bleak owl

no, why would that be deprecated?

it’s not something that exists on Client, but a property you created

fleet spire

oh

yea I shouldve read the docs closer it clearly says that sorry

sharp ginkgoBOT

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

modern mantle
wary coral
modern mantle

Hmmm Ionly find typescript

wary coral

nv they did not get move over so those are the latest. regardless you can use the npm package create-discord-bot

fleet spire

rawError: { message: 'Missing Access', code: 50001 },
code: 50001,
status: 403,
method: 'PUT',
url: ''

discord is returning missing access when trying to register commands, what reason might this be?

topaz bluff
fleet spire

ah

found the issue, sometimes I need to trust my own debug skills instead of asking for help smh

side question, is it advisable to register commands on every boot up of the bot? It will be an entirely private bot

topaz bluff

no... it's generally recommended to have the registerCommands.js file to only be run manually ( like with npm run register or something simiar ) as, especially during development... you can easily hit the 200/day rate limit on commands

fleet spire

ahhhhh gotcha

ruby bane

hes not using interactions

fleet spire
ruby bane

oh well, then yes what samtino said

topaz bluff

if you hit that limit, you have to wait 24 hours before registering again... and since the actual data on a slash command (name, description, options, etc) rarely change... deploying them every time you reload your bot is pointless... you dont need to register your commands when the actual code run on a command execution changes

fleet spire

thanks :)

shell wagon

Could anyone help me make a user install bot that works in DMs? I have it working fine, but I want it to be able to be used in DMs.

topaz bluff

are you registering your commands globally? are you modifying the context or installation_type of your slash commands?

fleet spire
  data: new SlashCommandBuilder()
    .setName('punish')
    .setDescription('Vote to punish a user')
    .addUserOption(),
  async execute(interaction: CommandInteraction) {
    await interaction.reply(`${interaction.user} is being punished!`);
  },

so how can I actually grab and mention the user from addUserOption

shell wagon
topaz bluff
shell wagon
topaz bluff

InteractionContextType.PrivateChannel

shell wagon

ok ty

topaz bluff

yes typo on my part

clear garnet
topaz bluff
fleet spire
clear garnet

Not really - you can just throw it in a template literal and the JS backend will stringify the User object to a user mention

fleet spire

amazing

fleet spire

how do I actually add a message create option to a reply?

vivid oasis

I have interaction files like so

export default {
    name: Events.InteractionCreate,

    async execute(interaction) {
}}

and I load events with this function

function loadInteractionFiles(dir) {
    const files = fs.readdirSync(dir);

    for (const file of files) {
        const filePath = path.join(dir, file);
        const stat = fs.statSync(filePath);

        if (stat.isDirectory()) {
            loadInteractionFiles(filePath);
            return;
        }

        if (!file.endsWith(".js")) return;

        import(pathToFileURL(filePath)).then(module => {
            const handler = module.default || module;

            // Must have "name" and "execute"
            if (!handler?.name || !handler?.execute) {
                console.log(`[WARN] Interaction file missing name/execute: ${filePath}`);
                return;
            }

            client.on(handler.name, (...args) => handler.execute(...args));
        });
    }
}

is having multiple files of the same event allowed? It seems to work and doesn't spit out an error but I wonder if its equivalent of using one monolithic file for one type of event.

topaz bluff

having several files for the same event... while is allowed, is not recommended as you're creating a WS listener for each event

it's preferred to instead, route the events depending on their status to independent files/functions

topaz bluff
fleet spire

I want to build a poll into my reply

fleet spire

or would I need to build a new message entirely

topaz bluff
topaz bluff

yes... poll is just an optional field of a message payload... just like content, embeds, and files

fleet spire

aaaaah

topaz bluff

i dont remember completely what the restrictions are (if any) on sending a poll message... but if you are restricted. you can do interaction.followUp to send a second message with the interaction if needed

fleet spire

as in to follow discords UX philosophy ?

fleet spire
  async execute(interaction: ChatInputCommandInteraction) {
    const user: User | null = interaction.options.getUser('user');
    if (!user) {
      return;
    }
    await interaction.reply({
      poll: {
        question: { text: `Punish ${user}?` },
        answers: [{ text: 'Yes' }, { text: 'No' }],
        duration: 1,
        allowMultiselect: false,
      },
    });
    await handlePunishmentVote(user);
  },
};

how can I actually pass the poll as an object here?

outer plume
const poll = {
  question: { text: `Punish ${user}?` },
  answers: [{ text: 'Yes' }, { text: 'No' }],
  duration: 1,
  allowMultiselect: false,
}

await interaction.reply({ poll })

is this what you mean by passing as an object?

fleet spire

so the literal object of the poll, if thats obtainable

odd stirrup

how in messageCreate do i check if a guild has my guild subscription entitlement?

fleet spire
fallow finch
sharp ginkgoBOT
fallow finch
fleet spire

You wouldn't happen to know about poll stuff ?

fallow finch

You could use withResponse: boolean inside the reply function, that can give you Message which you can pass it down to the function, I think. You gotta be a little more specific

fleet spire

I'm literally just trying to reference a poll im creating in a reply at a different point in my code

So that I can look at the results and do .end()

steel trail

then what ispik said is what you want

fallow finch

Would the poll object be updated though, sure you can get a Message pointing to the poll but if like pollUserAdd or remove happens does the poll in that Message get updated as well? Ig one way to find out

steel trail

if you got GuildMessagePolls intent: yes

fallow finch

Neat

fleet spire
last eagle

hi i realized that there was an option to "Mute Soundboard" for Discord Bots. I'm wondering whether there is an option to make a bot play Soundboards from the server itself in VC.

lament moss

How to detect someone's 2nd boost or more
Like I can detect a single boost done by a user how can I detect their second boost ?

fallow finch
fallow finch
sharp ginkgoBOT
last eagle

ty

steel trail

@fleet spire no, and please don't ghostping

fleet spire

sorry! I solved my problem, wont do next time

wheat gulch

0|Bot | [14:11:16] ERROR: Interaction Error [cfg_welcome_modal_step1]: Guild validation failed: welcome.embed: Cast to Object failed for value "undefined" (type undefined) at path "welcome.embed"

if (type === "text") {
 const currentWelcome = guildData.welcome || {};
 const currentEmbed = currentWelcome.embed || {};

      //
      guildData.welcome = {
        enabled: true,
        channelID: session.data.channelID,
        type: "text",
        text: { card: session.data.text.card },
        embed: currentEmbed, //obj
      };
      await guildData.save();
await interaction.reply({
        content: "✅ Text Welcome Message Setup Complete!",
        flags: MessageFlags.Ephemeral,
      });
}

why does it return undefined? My welcome schema part;

embed: {
        color: { type: String, default: "#000000" },
        author: { type: String, default: null },
        title: { type: String, default: "Welcome!" },
        description: { type: String, default: "Welcome {user} to {server}!" },
        image: { type: String, default: null },
        footer: { type: String, default: null },
        fields: [
          {
            name: { type: String },
            value: { type: String },
          },
        ],
      },
steel trail
flint pier
function sendInteraction(i, options) {
    return i.reply(options)
}

if (i.user.id !== requestUserId) return sendInteraction(i, { content: 'Nút này không dành cho bạn!', flags: 64 });```
Why is this showing an error : The reply to this interaction has not been sent or deferred.
wary coral
flint pier
wary coral what does the full error say?
  process.nextTick(() => { throw err; });
                           ^
Error [InteractionNotReplied]: The reply to this interaction has not been sent or deferred.
    at ButtonInteraction.editReply (/root/LunariTest/node_modules/discord.js/src/structures/interfaces/InteractionResponses.js:246:48)
    at sendInteraction (/root/LunariTest/src/utils/functions.js:54:14)
    at InteractionCollector.<anonymous> (/root/LunariTest/src/events/buttons/buttons/avatarButton.js:64:50)
    at InteractionCollector.emit (node:events:520:35)
    at InteractionCollector.handleCollect (/root/LunariTest/node_modules/discord.js/src/structures/interfaces/Collector.js:133:14)
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5) {
  code: 'InteractionNotReplied'
}

Node.js v24.11.0```
wary coral

The error happens at a ButtonInteraction.editReply. were the interaction has not been deferred or replied to. This can happen if the defer was not awaited

flint pier

It only gives an error when i.reply is passed through the function.

wary coral

I dont know about your fuction but the error is occuring when your app recivces a Button interaction and your app trys to uses editReply before having replyied or deferred the interaction

flint pier
sharp ginkgoBOT
wary coral

yes, but why do you what to do that? that does not seem like good UX

flint pier

I want it to automatically delete after 5 seconds instead of staying on indefinitely.

wary coral

The user can dismiss it and if the reopen the client it goes away

wheat gulch

what is this "overview build" called which yggdrasil use? not modal, not anything elsy I ever seen thou

wary coral

looks like a modal? with two Text Inputs

wheat gulch

nah it is not a modal

subtle girder

will createAudioResource method in @discordjs/voice lock the file or make the file be busy?

crimson gale

that's just a channel topic

i assume the bot finds the channel(s) that have !welcome! in their topic when someone enters the server and posts the welcome message there

wary coral

oh ya that is just the channel settings

modern mantle

any hind where theissue can be? :/

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
modern mantle

found my mistake ty

odd stirrup
sharp ginkgoBOT
wary coral

I know some one has asked this before an I cant remember if there is a way to get entitlements of a individual guild

wait nv I am dumb it is in the fetchoptions

sharp ginkgoBOT
odd stirrup

ah that sounds right

wary coral
client.application.entitlements.fetch({guild:guild})
viral cave

hi, how we can obtain the custom username of an user in a server ?

sharp ginkgoBOT
viral cave

oh ty

warm charm

when a user invite my bot to a guild, how i can check the permission the user give for bot?

steel trail

check the permissions on the bot's guildMember after it joined

sharp ginkgoBOT
warm charm

Thanks

torpid marsh

Somehow when doing this in my code, it does not errors....

try {
      const newTopic = topic.replace(/Strikes:\s*\[\d+\]/, `Strikes: [${strikeNumber}]`);
      await interaction.channel.setTopic(newTopic);
    } catch {
      await interaction.followUp({
        content:
          '⚠️ Failed to update the channel topic. Please update the strike count manually.',
        flags: MessageFlags.Ephemeral
      });
    }

It should error when it hits the ratelimit...

steel trail

no. it should queue the request and do the change when the ratelimit passes. unless you provided a rejectOnRatelimit in ClientOptions#rest

torpid marsh

How do I do that?

I am missing something here....

rest: { rejectOnRateLimit }
sharp ginkgoBOT

propertysignature RESTOptions#rejectOnRateLimit discord.js@14.25.1
Determines how rate limiting and pre-emptive throttling should be handled. When an array of strings, each element is treated as a prefix for the request route (e.g. /channels to match any route starting with /channels such as /channels/:id/messages) for which to throw RateLimitErrors. All other request routes will be queued normally
Default value: null

rose tangle

you can check the docs of everything to figure out what it should be

torpid marsh

Alright

lament moss

How to detect someone's 2nd boost or more
Like I can detect a single boost done by a user how can I detect their second boost ?

What do you suggest is the best way to implement the system

tardy sable
sharp ginkgoBOT
lament moss

I'm using const wasBooster = !!oldMember.premiumSince;
const isBooster = !!newMember.premiumSince;

tardy sable
lament moss Can u elaborate a Lil?

when you boost a server and you set up a channel for discord system messages it sends a message. that message contains the user and by how many times that message is sent you can keep track how many times someone boosted

tardy sable
lament moss
lament moss
tardy sable
tardy sable

can i have a message and component collector in one?

crimson gale

interaction create and message create are two different events, collectors are just temporary event collectors
if you really wanted to (though i really don't think that's the right approach) you could collect the raw gateway event and filter based on type, i suppose

rose tangle

yeah just use two collectors, there shouldn't be an issue

at most if I really wanted to I'd write a single handler function that accepts both and then just call it on each collector

tardy sable

ty

marble jolt

pengu

mental silo

Are embedded images / image URL always accessible via message.embed[n].thumbnail?

I wrote an image filter which scans attachments, then realized people can just send image URL instead
Figured however, those messages will have embed objects with type image. However I am unsure if discord will always put the image into thumbnail, or also into image

wary coral
mental silo

Yeah I am aware, but I talk about normal messages.
When Discord embeds an image URL it will put an embed object into the message

By that definition it should be a thumbnail yeah, I just got confused, because if you check a message object on your client it will be within message.embed.image for some reason

Discord barely documents this anywhere its kinda annoying

wary coral

maybe this is a question for DDevs

tardy sable
mental silo

Alright will do both of those. Thank you guys!

tardy sable

if i do deferReply i dont have to use withResponse to get the message?

unique shoal

yes you do

Unless theres more context to that question

boreal olive

why this error...

idk why but i kinda dug through djs repo to check.. : [i was high lol]

warm charm
boreal olive why this error...

Property 'voice' does not exist on type 'APIInteractionGuildMember'.

if (!(interaction.member instanceof GuildMember)) {
  return;
}

const memberVoice = interaction.member.voice;
red coral

Need to check inCachedGuild

boreal olive

ok. ty

bitter pivot

How do you access emojis from the developer portal? client.emojis.cache.map(e => e.name) shows only a list of the emojis in the server I'm in

worthy plaza
bitter pivot

ahh thank you!

tardy sable
unique shoal yes you do

mh i have a feeling it doesnt. if i use withResponse and then get the resource message it doesnt exist with deferReplies, i can just directly use the message
example

await interaction.deferReply();
const message = await interaction.followUp({ components: [container], flags: MessageFlags.IsComponentsV2 });
const collector = message.createMessageComponentCollector(options);
torpid marsh

When I am adding a channel, it is not syncing the permissions with the category...

const channel = await interaction.guild.channels.create({
      name: channelName,
      topic: `Alliance Channel for: ${allianceName}`,
      parent: Config.Settings.Channels.AlliancesCategoryID,
      permissionOverwrites: [
        {
          id: allianceRole.id,
          allow: [PermissionFlagsBits.ViewChannel]
        }
      ]
    });

Or am I doing something wrong?

sharp ginkgoBOT
torpid marsh

Isn't it that when you create a channel in a category it will copy the permissions automatically?

sharp ginkgoBOT
tardy sable

think you gotta create channel through this then

torpid marsh

Alright. So that is more like <category>.create()

Or how do I make it work properly? Never used that before.

hallow mesa
torpid marsh

Ah alright

torpid marsh
hallow mesa `<CategoryChannel>.children` is the manager, so it would be .children.create()

It creates the channel... But why it still not synces...

const category = await interaction.guild.channels.fetch(Config.Settings.Channels.AlliancesCategoryID)
    if(category?.type == ChannelType.GuildCategory){
      category.children.create({
      name: channelName,
      topic: `Alliance Channel for: ${allianceName}`,
      type: 0,
      permissionOverwrites: [
        {
          id: allianceRole.id,
          allow: [PermissionFlagsBits.ViewChannel]
        }
      ]
    })
hallow mesa

Setting overwrites disables sync

torpid marsh

Ah.

steel trail
tardy sable

well doesnt deferreply always expects you to respond?

steel trail
  1. deferReply is a response. But it is expected to later edit that response, yes
  2. what does that have to do with your initial question or your use of followUp?
tardy sable

ok nvm just trying to understand withResponse better, why would i need it for interaction.reply but for this i didnt need it?

steel trail

You would need it if you wanted deferReply to return the message.

Because that is doing the initial response. followUp is not sending a response though, it is sending a message with the webhook and always returns that message

ocean portal

I did everything correct, and the commands aren't loading, why? (No Errors seen)

const slashDirs = [
    path.join(__dirname, 'commands/slash'),
    path.join(__dirname, 'commands/slash/misc'),
    path.join(__dirname, 'commands/slash/stats')
];```
topaz bluff

Where's the rest? Where are you using those paths to load the slash command file?

ocean portal
topaz bluff Where's the rest? Where are you using those paths to load the slash command file...

To organize the files, so I can easily find them

client.slashCommands = new Collection();

(async () => {
  const slashDirs = [
    path.join(__dirname, 'commands/slash'),
    path.join(__dirname, 'commands/slash/misc'),
    path.join(__dirname, 'commands/slash/stats')
];
  const body     = [];

  for (const file of fs.readdirSync(slashDir).filter(f => f.endsWith('.js'))) {
    const cmd = require(path.join(slashDir, file));
    if (cmd.data && cmd.execute) {
      client.slashCommands.set(cmd.data.name, cmd);
      body.push(cmd.data.toJSON());
    }
  }

  client.once('ready', async () => {
    console.log(`Logged in ${client.user.tag}`);

    const rest = new REST({ version: '10' }).setToken(process.env.TOKEN);
    try {
      await rest.put(Routes.applicationCommands(client.user.id), { body });
      console.log('slash commands registered.');
    } catch (err) {
      console.error('err);
    }
  });
})();```
topaz bluff

For debugging, you should add a log when a command is added to body

You could also add an else for the if (cmd.data && cmd.execute) to say that there was an error with the cmd data

Also 2 other things

  1. It's better to get your client.on listeners outside of other functions/methods as you want those to happen every single time. Unrelated to your command registration

  2. You should NOT be registering your commands every single time your bot starts. That's a great way to get rate limited for 24 hours

ocean portal
bleak owl

you should only be registering when you add, edit or delete command data

there's no need to be doing that every single time your bot starts

ocean portal

Alright, Thank you :)

tawdry cairn

help

[ERRO] Cliente Discord: TypeError: (intermediate value).addImageDisplayComponents is not a function
at buildPrincipalContainer (file:///F:/map-descompiler/discord-bot/index.js:746:6)
at Client.<anonymous> (file:///F:/map-descompiler/discord-bot/index.js:963:17)
at Client.emit (node:events:519:28)
at InteractionCreateAction.handle (F:\map-descompiler\discord-bot\node_modules\discord.js\src\client\actions\InteractionCreate.js:101:12)
at module.exports [as INTERACTION_CREATE] (F:\map-descompiler\discord-bot\node_modules\discord.js\src\client\websocket\handlers\INTERACTION_CREATE.js:4:36)
at WebSocketManager.handlePacket (F:\map-descompiler\discord-bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:352:31)
at WebSocketManager.<anonymous> (F:\map-descompiler\discord-bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:236:12)
at WebSocketManager.emit (F:\map-descompiler\discord-bot\node_modules@vladfrangu\async_event_emitter\dist\index.cjs:2504:31)
at WebSocketShard.<anonymous> (F:\map-descompiler\discord-bot\node_modules@discordjs\ws\dist\index.js:1190:51)
at WebSocketShard.emit (F:\map-descompiler\discord-bot\node_modules@vladfrangu\async_event_emitter\dist\index.cjs:2504:31)

bleak owl

code?

unique shoal

addImageDisplayComponents is in fact not a function

bleak owl

that function doesnt exist anyway

unique shoal

The error is completely correct

tawdry cairn
bleak owl code?
  const s1 = new SectionBuilder()
    .addTextDisplayComponents(
      t => t.setContent('# test'),
      t => t.setContent('test.')
    )
    .setButtonAccessory(btn =>
      btn
        .setLabel('Creator')
        .setStyle(ButtonStyle.Primary)
        .setCustomId('create_room')
    )
  const c = new ContainerBuilder()
    .setAccentColor(5793266)
    .addSectionComponents(s1)

  return c
}```
bleak owl

thats a very nice block of code

i dont know what you're asking

tawdry cairn

I want to put a banner on it above the messages.

bleak owl

use a media gallery component

tawdry cairn

I am going to try

sharp ginkgoBOT

guide Media Gallery
A Media Gallery is a display component that can display a grid of up to 10 media attachments. Each media item can have an optional alt text (description) and can be marked as spoiler. You can use the MediaGalleryBuilder and MediaGalleryItemBuilder classes to easily create a Media Gallery component and its items:...

tawdry cairn
  const s1 = new SectionBuilder()
    .addTextDisplayComponents(
      t => t.setContent('# test'),
      t => t.setContent('test.')
    )
    .setButtonAccessory(btn =>
      btn
        .setLabel('Creator')
        .setStyle(ButtonStyle.Primary)
        .setCustomId('create_room')
    );

  const mediaGallery = new MediaGalleryBuilder()
    .addItem(
      new MediaGalleryItemBuilder()
        .setUrl(config.bannerImage)
        .setAltText('Imagem 1')
    )

  // Container principal
  const c = new ContainerBuilder()
    .setAccentColor(5793266)
    .addSectionComponents(s1)
    .addDisplayComponents(mediaGallery);

  return c;
}```
@bleak owl  Is that correct now?
loud quartz

you can try it out

does it error or does it send and display correctly

tawdry cairn

[ERRO] Cliente Discord: ReferenceError: MediaGalleryBuilder is not defined
at buildPrincipalContainer (file:///F:/map-descompiler/discord-bot/index.js:756:24)
at Client.<anonymous> (file:///F:/map-descompiler/discord-bot/index.js:969:17)
at Client.emit (node:events:519:28)
at InteractionCreateAction.handle (F:\map-descompiler\discord-bot\node_modules\discord.js\src\client\actions\InteractionCreate.js:101:12)
at module.exports [as INTERACTION_CREATE] (F:\map-descompiler\discord-bot\node_modules\discord.js\src\client\websocket\handlers\INTERACTION_CREATE.js:4:36)
at WebSocketManager.handlePacket (F:\map-descompiler\discord-bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:352:31)
at WebSocketManager.<anonymous> (F:\map-descompiler\discord-bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:236:12)
at WebSocketManager.emit (F:\map-descompiler\discord-bot\node_modules@vladfrangu\async_event_emitter\dist\index.cjs:2504:31)
at WebSocketShard.<anonymous> (F:\map-descompiler\discord-bot\node_modules@discordjs\ws\dist\index.js:1190:51)
at WebSocketShard.emit (F:\map-descompiler\discord-bot\node_modules@vladfrangu\async_event_emitter\dist\index.cjs:2504:31)

unique shoal

You need to import it

tawdry cairn

Sorry, my knowledge of Node.js was outdated.

bleak owl

its really basic javascript

tawdry cairn

Node.js was outdated....

bleak owl

that will not resolve your issue

the issue is that you need to define MediaGalleryBuilder, which is done by importing it from the discord.js library

tawdry cairn

Inside node_modules, MediaGalleryBuilder doesn’t appear. I ran npm install discord.js and have already uninstalled discord.js.

loud quartz

MediaGalleryBuilder is not a package from npm, so it will not be in node_modules/

it's a thing that discord.js exports

similarly to how you can import fs or path without installing anything, as those are provided by node itself

wheat gulch

| [20:21:30] ERROR: UNCAUGHT_EXCEPTION: Opening handshake has timed out

what is that

tawdry cairn

Now I understand, thank you very much.

wheat gulch
loud quartz

nothing we can do about it, it's not related to discord.js

it's either your host, or the network connection between it and discord

wheat gulch

well I thought it is since Ive never seen it before and was curious so thats why im here r

loud quartz

well, unfortunately this is d.js support, not "ive never seen this in my code before"

wheat gulch

ur so tuff

jagged rock

how to check if bot is verified

sharp ginkgoBOT
rose tangle

check if it has that flag

languid mesa

Does anyone know how I can get this in discord.js embeds?

The line things I believe called line 14 in some Json embed version and separator 1 in discohook

novel mauve

it’s a separator component, it’s only available with cv2 not embeds

sharp ginkgoBOT
empty vault

Hi everyone, Bots can record voice channels?

versed current

yes, bots can do that

crimson gale

i would be very careful with persisting voice recordings, in many countries that's quite heavily protected by law

especially if they're not explicitly made aware of it

empty vault

Thanks for help

vague plaza

I keep getting a deprecation warning for the ready event. I've already migrated to the clientReady event but it's still popping up. Anyone know why?

unique shoal

Somewhere is still using ready

Node has a trace wranings flag that might help

vague plaza

Yeah I tried using that, it didn't show where it was originating from.

I only have 1 ready event and it uses the clientReady event

languid mesa

I'm not so good at doing discord.js how can I learn?

crimson gale

getting better at stuff usually involves doing more of said stuff
if you are struggling with one thing in particular, describing that thing in particular is useful for anyone to be able and help

vague plaza
languid mesa

How about if we are like just starting

snow onyx

Then the guide is still the go to resource. And if you want to learn JavaScript, #resources has some helpful resources for that.

rose tangle
near siren

if im using the member partial, am i better off listening to GuildAuditLogEntryCreate for role changes, nickname changes etc instead of GuildMemberUpdate?

topaz bluff

For logging? I personally prefer the audit log event for all of that. Regardless on if you're using the partial or not. It shows more information

wary coral

Note that is a user changes multiple roles guid audit log create may only fire once

sharp ginkgoBOT
jolly radish

Why am I geting:

(Use `node --trace-deprecation ...` to show where the warning was created)```

I am clearly using clientReady and nowhere ready.
steel trail

did you try doing what the last line suggests to find out where the warning originates? and are you using any third party libraries apart from discord.js?

jolly radish

Its in ts so --trace-deprecation did nothing

jolly radish
bleak owl

are you sure you didn’t just have a file named ready that you renamed to clientReady

steel trail
stable sun
jolly radish
stable sun
sharp ginkgoBOT

node 'newListener'
The EventEmitter instance will emit its own 'newListener' event before a listener is added to its internal array of listeners.Listeners registered for the 'newListener' event are passed the event name and a reference to the listener being added.The fact that the event is triggered before adding the listener has a subtle but important side effect: any additional listeners registered to the same name within the 'newListener' callback are inserted before the listener that is in the process of being added.

jolly radish

yeah so its the client of the discord-cross-hosting which causes the ready error.

steel trail

not an error, merely a warning

stable sun

You can ignore it

They will have to fix it in the next major version (v15) when it actually gets removed

jolly radish

great! thank you!

neat nimbus

FOR messageUpdate event whats the log type

tardy sable
neat nimbus

djs.AuditLogEvent

unique shoal

there isnt one

tardy sable

since message update is always by the same author

neat nimbus

ah i leave that part blank

unique shoal

it doesnt have an audit log, yeah

neat nimbus

ok

sand minnow
client.on("clientReady", async () => {
  try {
    try {
      await client.guilds.fetch();
      await client.users.fetch();
      console.log(`✅ Fetched ${client.guilds.cache.size} guilds`);
    } catch (err) {
      console.error("Failed to fetch guilds:", err);
    }
    
    const commandsArray = [...client.commands.values()].map((cmd) => ({
      name: cmd.name,
      description: cmd.description || "No description",
      category: cmd.category,
      aliases: cmd.aliases,
      usage: cmd.usage,
    }));

    const slashCommandsArray = [...client.slashCommands.values()].map(
      (cmd) => ({
        name: cmd.name,
        description: cmd.description || "No description",
        category: cmd.category,
        usage: cmd.usage,
      }),
    );

    const guildsArray = client.guilds.cache.map((g) => ({
      id: g.id,
      name: g.name,
      icon: g.icon,
    }));

    const guildCount = client.guilds.cache.size;
    const userCount = client.users.cache.size;

    console.log(`📊 Bot Stats - Guilds: ${guildCount}, Users: ${userCount}`);
   await bot.findOneAndUpdate(
      { id: client.user.id },
      {
        id: client.user.id,
        username: client.user.username,
        avatar: client.user.displayAvatarURL(),
        guildCount: guildCount,
        commands: commandsArray,
        slashCommands: slashCommandsArray,
        guilds: guildsArray,
        userCount: userCount,
        shardCount: client.shard ? client.shard.count : 1,
      },
      { upsert: true },
    );

    console.log("✅ Bot data saved to the database!");
  } catch (err) {
    console.error("❌ Failed to save bot data:", err);
  }
});
``` the users cache is so low only in the on ready
tardy sable
sand minnow
bleak owl
bleak owl

no

sharp ginkgoBOT

Getting your bot's member count

  • client.users.cache.size is unreliable because it will only return cached users
  • The preferred method is using collection.reduce() on client.guilds.cache
client.guilds.cache.reduce((acc, guild) => acc + guild.memberCount, 0)
sand minnow

let me try

bleak owl

pass a param here named c and use that as your Client instance inside the clientReady event

sand minnow

alr 1s

sand minnow
bleak owl

did you replace client.guilds... with c.guilds... ?

sand minnow

yes

every single client inside the event is replaced with c

bleak owl

lets see your current code

sand minnow
bleak owl lets see your current code
client.on("clientReady", async (c) => {
  try {
    const commandsArray = [...c.commands.values()].map((cmd) => ({
      name: cmd.name,
      description: cmd.description || "No description",
      category: cmd.category,
      aliases: cmd.aliases,
      usage: cmd.usage,
    }));

    const slashCommandsArray = [...c.slashCommands.values()].map(
      (cmd) => ({
        name: cmd.name,
        description: cmd.description || "No description",
        category: cmd.category,
        usage: cmd.usage,
      }),
    );

    const guildsArray = c.guilds.cache.map((g) => ({
      id: g.id,
      name: g.name,
      icon: g.icon,
    }));

    const guildCount = c.guilds.cache.size;
    const userCount = c.guilds.cache.reduce((acc, guild) => acc + guild.memberCount, 0)

    console.log(`📊 Bot Stats - Guilds: ${guildCount}, Users: ${userCount}`);

   await bot.findOneAndUpdate(
      { id: c.user.id },
      {
        id: c.user.id,
        username: c.user.username,
        avatar: c.user.displayAvatarURL(),
        guildCount: guildCount,
        commands: commandsArray,
        slashCommands: slashCommandsArray,
        guilds: guildsArray,
        userCount: userCount,
        shardCount: c.shard ? c.shard.count : 1,
      },
      { upsert: true },
    );

    console.log("✅ Bot data saved to the database!");
  } catch (err) {
    console.error("❌ Failed to save bot data:", err);
  }
});```
bleak owl

did you remove the Guilds intent?

sand minnow

no, and guildCount is correct

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMembers,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
    GatewayIntentBits.GuildMessageReactions,
    GatewayIntentBits.GuildVoiceStates,
    GatewayIntentBits.DirectMessages,
    GatewayIntentBits.DirectMessageReactions,
    GatewayIntentBits.GuildPresences,
    GatewayIntentBits.GuildWebhooks,
    GatewayIntentBits.GuildModeration,
    GatewayIntentBits.GuildExpressions,
    GatewayIntentBits.GuildIntegrations,
    GatewayIntentBits.GuildInvites,
    GatewayIntentBits.GuildMessagePolls,
    GatewayIntentBits.GuildScheduledEvents,
  ],
  allowedMentions: {
    parse: ["users", "roles", "everyone"],
    repliedUser: false,
  },
  partials: [
    Partials.Message,
    Partials.Channel,
    Partials.Reaction,
    Partials.User,
    Partials.GuildMember,
  ],
  shards: "auto",
  restRequestTimeout: 1500000,
});```
bleak owl

what's your d.js version? npm ls discord.js

sand minnow

what if I use Partials to fetch the users?

bleak owl

you cannot fetch users

sand minnow
bleak owl

i honestly don't quite know why you're getting NaN since that line of code works perfectly for me

¯_(ツ)_/¯

sand minnow

yikes

sand minnow
bleak owl

the only Partial i can see being used here is Channel, otherwise i dont know if you really need all those others

steel trail

Probably unavailable guild in cache

sand minnow
steel trail

For that guild.memberCount would be null and thus that reduce becomes NaN

steel trail

filter unavailable guilds from that cache before reduce

sand minnow

even doing that code on clientReady it worked once and I got 12k members, original users count is 25k

sharp ginkgoBOT
steel trail

How did you determine the "original users count" you compare against here?

sand minnow
unique shoal

"all users" are almost never cached unless its a small server

steel trail

No, not all users will be cached. Just all users that interacted with something on a guild causing an event to emit to your bot

sand minnow
steel trail

No

sand minnow
steel trail
steel trail
sand minnow
steel trail

It changes when a user joins or leaves the guild. Which will happen quite often on bigger servers. Considering you said 25k I'd say that is the case here

sand minnow
unique shoal

but why save the count is the question

bleak owl

i personally don't see the point in saving the user count

sand minnow
near siren

if discord takes the nitro booster role off of a member, does this emit a guild audit log entry create event? just wondering because theres an GuildAuditLogsEntry.executor.discord property

tardy sable

and that doesnt emit an audit log

stable sun

You can use guild member update event for that

near siren
tardy sable

yh discord doesnt exist on user, it would be user.system

near siren

the only time i use ".discord" is in strings so i dont know how it's being appended

near siren
stable sun

I guess you still need the old member to know it was removed and not smth else that changed

rose tangle
stable sun

I think they meant literally in a string like "foo.discord"

radiant bolt

Can bots determine who moves the channels?

tardy sable
polar karma

Audit logs (if one is generated)

marble plover

i dont think reorder ever makes an audit log

sadly

loud quartz

it doesn't because one channel move could potentially update all the channels in the category

acoustic night

I'm getting error about module not found something like zlibsync (name is inaccurate as I forget the actual name), imported by index.ts of discord.js

polar karma

Posting the actual error will be needed to help with your issue

acoustic night
acoustic night
acoustic night
tardy sable
unique shoal

discord.js isnt web compatible

acoustic night
acoustic night
unique shoal

no it isnt???

I dont know what you mean by that

acoustic night
unique shoal

by connecting to a node.js backend via APIs

or querying a shared database

acoustic night
acoustic night
unique shoal

yeah because it doesnt exist in web environments, its a node native module requiring node-gyp

unique shoal
acoustic night

so there's no option except using discord api directly?

unique shoal

Thats not what I said at all

But that is an option

acoustic night

then what are you saying?

unique shoal

That discord.js does not work in a web browser environment

acoustic night
acoustic night
unique shoal
  • build your own API layer for a server-side application that runs discord.js
  • have your server-side bot appication write necessary data to a database that can be accessed by the front end
acoustic night
unique shoal

Yeah no, no idea what youve done

acoustic night
unique shoal

Also not what I said

acoustic night
acoustic night
unique shoal

just use @discordjs/rest then

discord.js is a full websocket client library, it makes no sense to use it for what youre doing

acoustic night
unique shoal

not at all

mostly because its you know... incompatible

acoustic night
acoustic night

so what do you recommend,
direct discord api or what ?

ruby bane

i mean it should, you dont need the entire package

just call direct routes with the rest package

acoustic night
fallow finch

I have a dashboard that uses an API to communicate with the bot, don't know if sharing the repo would be fine though, if it is to you could see an horrible example at least

polar karma

You can DM it to them if they want

boreal olive

is there any way to await for a modal submission like Message#awaitMessageComponent?

other than handling it through intereaction create event

tardy sable
sharp ginkgoBOT

documentation suggestion for @boreal olive:
method ButtonInteraction#awaitModalSubmit() discord.js@14.25.1
Collects a single modal submit interaction that passes the filter. The Promise will reject if the time expires.


// Collect a modal submit interaction
const filter = (interaction) => interaction.customId === 'modal';
interaction.awaitModalSubmit({ filter, time: 15_000 })
  .then(interaction => console.log(`${interaction.customId} was submitted!`))
  .catch(console.error);

fallow finch

Almost all interaction types should have it btw not just buttons, refer to docs

rigid ermine

Hello, I need help with something. I'm trying to fetch the members from a pretty large server, and I keep on getting the Error [GuildMembersTimeout]: Members didn't arrive in time. error. I already included the intents in my Client constructor and the Server Member Intent is also enabled in the Developer Portal. Can somebody help me? What am I doing wrong?

const { Events } = require("discord.js");

module.exports = {
    name: Events.ClientReady,
    once: true,
    async execute(client) {
        console.log(`${client.user.tag} is now online.`);

        const guild = client.guilds.cache.get(process.env.GUILD_ID);
        await guild.members.fetch().then(console.log).catch(console.error);
    },
};
astral prismBOT
rigid ermine Hello, I need help with something. I'm trying to fetch the members from a pretty...

Discord introduced a rate limit on requesting all guild members (once per 30s per guild).

  • You will have to update your code accordingly to make sure this doesn't affect your app.
  • Look for instances of guild.members.fetch() with no user ids.
  • Starting in version 14.25.0, discord.js rejects the returned Promise and exposes details in error.data.
    -# If you confirmed this cannot be the reason, you can find other caveats in our guide djsguide.
umbral jetty

Does anyone know why the messageDelete event only sends logs if the user who deleted the file is the same user who sent the message?

steel trail

Because that's how discord implemented it

tardy sable

probably to avoid too many unnecessary audit logs

bitter leaf

Can we add selectmenu to modal

bleak owl

yes

sharp ginkgoBOT

guide Modals
Modals are pop-up forms that allow you to prompt users for additional input. This form-like interaction response blocks the user from interacting with Discord until the modal is submitted or dismissed. In this section, we will cover how to create, show, and receive modals using discord.js! This page is a follow-up to the interactions (slash commands) page. Reading that page first will help you understand the concepts introduced in this page.

spring knoll

I have a v2 container with text components and accessory buttons. Is there any way, even a hacky one, to make the widths of the buttons equal?

as far as I understand the limitations, there's only one button accessory per text component, that's why I split the title and the note/timestamp into two text components

bleak owl

nope, the size depends on the text of the button

spring knoll

There's no way of using some sort of non-breaking space or hacky invisible character to pad the width?

bleak owl

you can try

topaz bluff

i know discord trims the display text to remove padding spaces... but some unicode invisible characters might solve this

spring knoll

Thanks. I was leaning toward that idea but wondered if there was an established workaround more experienced bot devs knew of here.

topaz bluff

unfortunately, no... there's very little visual customization you can perform to any of the rendering of data from your bot... it's generally recommended to add as little "hacky" fixes as possible to avoid mismatched rendering between desktop and mobile

spring knoll

makes sense. I'll want to test it on mobile as well of course. I've noticed even normal discord.js features render differently between the platforms

The best approach would probably be to try and use the same (or close to the same) amount of characters in the labels.
Thanks again for the feedback.

Settling for that approach. I didn't like how the note text could go under the "Add Completion" button originally. This is good enough.

neat nimbus

that correct?

crimson gale

Run your code before asking if it can work. (errors are often very useful in pin-pointing the issue! )

neat nimbus

OMEGAlul

uneven remnant

At least put some thought into the UI instead of straight-up copying others

steel trail
low spear

is it a good idea to have massive command files where you do all logic? or do people split them up as command builders + handle logic elsewhere

when I have many sub commands the file gets pretty long handling each case

loud quartz

it's completely up to you

it doesn't particualrly matter if the function is in the same file or is imported from other file

it's still the same function

you can make a "main" command file that gets called by the command handler, and then taht "main" command file then imports all its subcommands from a directory or something

it doesn't need to be something command handler is explicitly aware of (as in, it only calls the command. what the command imports and requires and where from in order to respond isn't really what that handler is concerned with, allowing each command to do it in any way it wants to)

low spear
loud quartz

"hundred of lines long" is not a valid measure

if your command has this much logic, then it has this much logic, and you can't avoid that

low spear

fair enough

loud quartz

if you have 400 lines of logic for one command in one file, or needlessly split it into 4 100 lines files doesnt' change that it's still 400 lines of logic

except now you have parts of it spread around

if your command has a subcommand that can fit its logic in 3 lines, you dont' really have to split it out either, cause you will spend more lines to export and import it back

but then that's really a question of if you want to be super strict about consistency

low spear

i was more concerned about the maintainability of files that get this long, but you would say splitting it up isnt worth it?

loud quartz

400 lines is not long in the slightest

and if you find it long to scroll during development you can always collapse blocks in your IDE

as for splitting - depends. if it's a single command with no subcommands, i would not split at all.
if a command would have subcommands, and each of those could easily reach 400 lines, then i would probably split out, but only after i remove common parts out of each into some reusable function

at the end it's up to you as the maintainer

low spear

alright yeah I get you
cheers

pliant stratus

Yo

sand minnow

can we not send buttons using webhook?

loud quartz

only if the webhook was made by your bot

unless you want to send link buttons

sand minnow

well I tried both

sand minnow
loud quartz

then no

it needs to be made by an app so that discord knows who to send the interactions to

sand minnow

checking if the channel has one alr and if not make a new one?

loud quartz

that's one way

or just create one, grab its id and token (or the url, since it has both of those) and store that

then just reuse that

sand minnow

but that's what I did..

loud quartz

but you made the webhook

not the app

all webhooks have ids and tokens

sand minnow

oh.. can I make one using the bot's eval command and save it?

loud quartz

it's about who created it

sure

sand minnow

let me try(this 15s cooldown kills me)

sand minnow
crimson gale

no, that's just a local object that allows you to control an already existing hook

you have to create it on the channel

sharp ginkgoBOT

method BaseGuildTextChannel#createWebhook() discord.js@14.25.1
Creates a webhook for the channel.


// Create a webhook for the current channel
channel.createWebhook({
  name: 'Snek',
  avatar: 'https://i.imgur.com/mI8XcpG.jpg',
  reason: 'Needed a cool new Webhook'
})
  .then(console.log)
  .catch(console.error)

sand minnow
crimson gale

no

look at the docs, i just sent them

sand minnow

perfect, thanks!

crimson gale

name is required

sand minnow
sand minnow
crimson gale

I can't seem to copy the url manually and in the eval command I only see the webhook's id, no url option

crimson gale

?

sand minnow

nvm I got it, thanks

stuck badger

is there a middleware pattern for discordjs that I can use? or do I have to implement my own.

I have multiple classes i want to integrate as "modules" for my bot, and if the event listeners on those class calls return true i want it to stop execution from going to the next event listener
or, not calling next in a way

unique shoal

Not really no, event listeners are not sequential

You'll have to build your own.

warm charm

How i can set the custom status here?

crimson gale
warm charm

Thanks mate

fathom python

Any way to set a custom avatar for the bot on x server?

sharp ginkgoBOT
snow onyx

guild.members.editMe()

fathom python

Thanks!

warm charm

i can set max 1 activities right

potent badge
warm charm

oh it rotated my status ty, but can i change it for faster?

potent badge
warm charm
potent badge

you will have the use the setInterval(() => {}, ms) function for it.

warm charm

oh okay ty

potent badge

no worries. 🙂

sand briar

Hello, is there a way to know if the event has already been loaded and if so, to delete it?

tiny condor

Do you want an event to run once?

sand briar
tiny condor Do you want an event to run once?

Actually, I'm using client.once and client.on, and I'd like to know which ones are online. If, for example, messageCreate is online, I want to be able to complete it and stop receiving events.

loud quartz

you can remove events via EventEmitter.off() (alias for .removeListener()), passing in the event name and the function that it runs.
if you're doing anonymous functions in the listeners, or any other way that doesn't let you access the actual function in the listener, you can always get to them via EventEmitter.listeners() passing in the event, then you can pass directly from that to the off()

that will remove the listener, but has no way to actually stop an already running one

sand briar
dreamy basin

is there a way to access a users game collection

polar karma

not via the bot api, maybe with oauth2, but that's outside the scope of the library

dreamy basin

thanks

sand minnow

why does the bot sometimes not get the user's banner? rather is sometimes get it most of the time no

polar karma

you need to force fetch the user to get the banner, as the docs state

sand minnow

is it possible to get a user's theme color profile?

sharp ginkgoBOT
tardy sable

Maybe this is it not sure

sand minnow

that's not it

sand minnow

also why does the User#flags only return one enum?

crimson gale

flags are a bit field

sand minnow
sand minnow
crimson gale

no

sand minnow
crimson gale no

but in the api I see "premium_type": 1, "public_flags": 64 how come they r not in djs?

crimson gale

they are, they're just not sent with the public user data

sand minnow
crimson gale

oauth should have them

sand minnow
crimson gale

discord deliberately doesn't send that info to apps via the regular user payload

rose tangle

pretty sure there's also a column in that table that says the oauth scope you need to get each field, including premium_type and whatnot

sand minnow

except verified and email

sand minnow
polar karma

user privacy is a thing

sand minnow
polar karma

what's public to users is not always the same as what's public to bots because of the possibility of automating the access and collection of that data. same reason user profiles are not accessible to bots

similar reasoning to why the message content and presence intents are privileged, for user privacy and to help prevent abuse

sand minnow

but like what's the difference if they add the nitro badges inside the flags bitfield?

rose tangle

yeah first thing that comes to mind is a bot that automates sending phishing links only to nitro users, since that's more "valuable" than a non nitro account

sand minnow
rose tangle

ye sadly you have to think the worst possible ways someone could abuse the info you give, since that'll probably be an actual thing someone will do

ofc the most secure thing would be to not give any data but that's not useful to anyone, so they probably choose to give what's required and maybe some cosmetic stuff that's not really important

tame dagger

anyways ur choice to choose nonsense over basic sense

uneven remnant
uneven remnant
polar karma

you were already told this is not the correct channel to discuss this, please do not continue

ripe topaz

I have a discord bot that sends messages whenever someone finishes a map, the problem is I'm doing something like

const name = [${name}](${playerUrl});

for the name, but this sometimes breaks with an object such as:

{ "timestamp": 1769704328, "map": "Houll", "name": "[D] 末一", "time": 2522.34008789063, "server": "CHN" }

I'm guessing because the name has md characters in it, and I'm not sure if the lib has something to sanitize strings specifically for this kind of usecase or if I should make a function that escapes any special md chars in strings

This is the end result of my current code :/

polar karma

d.js doesn't sanitize input, so there's no function for it. you'd want to check if there's something built into js natively or another package that does it. #1081585952654360687 if you need more help

ripe topaz
scarlet phoenix

Im having trouble finding what is the most current version of discordJS can someone point me in the right direction?

topaz bluff

Ya that too

heavy sinew

how can i make this its a selectmenu in a poll

@wary coral

topaz bluff

Not a poll. That's a modal

Also don't ping random people. Just ask a question and wait

sharp ginkgoBOT

guide Select menu
Select menus allow you to limit user input to a preselected list of values. Discord also offers select menus linked directly to native Discord entities like users, roles, and channels. Since they behave very similarly to how they do in messages, please refer to the corresponding guide page for more information on configuring select menus. Here again, you wrap the select menu with a label component to add context to the selection and add the label to the modal:...

heavy sinew

oh ye solry

thanks

jagged rock

is the new permissions in djs yet > BypassSlowmode

steel trail

Yes

near siren

why would message.content be null for an uncached message despite having message partial enabled?
(messageDelete event)

snow onyx

you already mentioned why

its uncached

and its a deleted message, so why would there be content

near siren
versed bobcat

could i send 2 interactions in 1 response to a command?

unique shoal

The command is the interaction

You can send two responses to one interaction, if thats what you mean?

versed bobcat

i mean i run a command and it returns some data in an embed and then i want the next message to reply to the embed with the data so i can copy it easier on mobile

sharp ginkgoBOT
versed bobcat

thanks!

meager meadow

Why do I get the error DiscordAPIError[10008] when I try to edit an ephemeral message?

bleak owl

could you show your code please?

meager meadow
        {
            customId: `edit_room_name`,
            guildOnly: true,
            async execute(interaction, args) {
                const msg = await interaction.message.fetch();
            },
        },
bleak owl

ephemeral messages don't technically exist as regular messages, so they don't return any message data. you'll want to use .editReply to edit that ephemeral message

meager meadow

This is supposed to be the answer to the button here, but the error pops up even when I do a fetch.

bleak owl

you can't fetch an ephemeral message because it doesn't actually exist

meager meadow

So, will interaction.editReply work here?

bleak owl

it should, yes

meager meadow

Thanks, I didn't understand this for a long time.

autumn tendon

Hi. I'm trying to deploy my bot and it doesn't get online. I tried to reset token and got the same. I deployed the last week without any issues, but now I can't. I tried to deploy with a version of the last week which works and I doesn't deploy too... I added this code to debug it:
console.log("🚀 Iniciando Bot...");

    this.on('debug', (info) => {
        if (!info.includes('Heartbeat')) console.log(`[DEBUG] ${info}`);
    });

    try {
        await this.login(process.env.DISCORD_TOKEN);
        console.log(`✅ ¡Bot loggeado exitosamente como ${this.user?.tag}!`);

        this.user?.setPresence({ status: 'online' });
    } catch (error) {
        console.error('❌ Error FATAL en login:', error);
    }

And I got this error:
❌ ERROR DE RED: No se puede alcanzar discord.com: SyntaxError: Unexpected token '<', "<!doctype "... is not valid JSON
at JSON.parse (<anonymous>)
at parseJSONFromBytes (node:internal/deps/undici/undici:4259:19)
at successSteps (node:internal/deps/undici/undici:6882:27)
at readAllBytes (node:internal/deps/undici/undici:5807:13)
at process.processTicksAndRejections (node:internal/process/task_queues:103:5).

Does anyone know what can I do?

shell wagon
autumn tendon

That code is from that extended class

topaz bluff
autumn tendon

Is a provider. We're using Render

We already tried to "force" the change of the IP. But the error persists

topaz bluff

doesn't render use shared IPs? youre likely getting cloudflare banned

autumn tendon

Yes. The free plan is shared. But it was working during the whole month and we could deployed without any issue, but we got the error now.

topaz bluff

that's how shared IPs work... someone else on that IP has spammed the discord API so much so that cloudflare has temporarily blocked the entire IP (and possibly other IPs from the provider... depending how they do DDoS prevention)

autumn tendon

We would need to change to another provider then?

topaz bluff

or wait for the ip ban to expire

autumn tendon

Ok. Thanks

fleet spire

hey guys, not a coding question but more related to deployment. I want to host a bot on my local server.

basically the pipeline im looking for is ->

I have a "prod" branch in my github repo

whenever a change is made to the prod branch is pushed, the instance on my server updates to it

fallow finch

If you already know how to use workflows then it's just ssh'ing into your server and updating it

fleet spire

or are you literally refering to just sshing in and pulling down the latest v?

fallow finch

Not really djs so I'll keep it simple and you should go to a more appropriate place for more questions,
You use GitHub actions to run a workflow when changes happen to the prod branch and ssh into your server to do the changes

stable sun

That doesn’t sound safe tbh

I’d prob just use cron to poll gh changes or use gh webhooks to listen for changes and pull it

Unless you are referring to the self-hosted runners, which seems ok according to Google

fleet spire

yea i mean ultimately it might be easiest just to dockerize the app and manually deploy it since I wont be updating that often

upper kelp

hi umm just to be clear ChatInputCommandInteraction extends BaseInteraction right? because instanceof is telling me otherwise

steel trail

It does. Are you importing those two classes from the same place?

upper kelp

oh wait do i fr have 2 versions

yep i think thats the issue, i did pnpm link

normal delta

Why images with URL ending in “empty.png” are not displayed in the setURL of a MediaGalleryBuilder? Is that a bug?

loud quartz

setURL doesn't display anything

could you be more specific?

sharp ginkgoBOT
steel trail

This should indeed cause the item to display something. But is the URL actually an image containing something? Considering the name sounds like it might actually be empty

normal delta
loud quartz

how are you changing the name

steel trail

Did you check that the URL actually is a valid image URL and not containing a typo? Did you log the actual payload being sent to discord to find out? Alternatively log the message after it got sent

normal delta
steel trail

Yes

If it's for support purposes like in your case

normal delta

Well, I just tried the same image on a different domain with the URL ending in “empty.png” and it works. So I guess it must be a problem with the domain where I upload the files.

Not a DJS issue

neat nimbus

is there a inviteJoin.js?

topaz bluff
neat nimbus

user joining a server or using a invite

sharp ginkgoBOT
topaz bluff

No you can't see what invite they used if that's what you're looking for

crystal cargo

hello, i am using shard, and i want to DM a user, how can i make sure that only 1 bot will send the message even if the user exist in many shard

topaz bluff

When you run the user.send it should originate from the shard that started the interaction/event. But received dm events should only go to shard 0

crystal cargo

there's no event, lets say i have ID 1117220717935734814, and i just want to send a msg.

because using broadcastEval might send using more than 1 shard

rose tangle

is it some kind of schedule or interval?

crystal cargo
rose tangle

and each shard has an instance of the same schedule?

crystal cargo

no, i think to run the interval in the shard manager file (index.js)

AI says:
Try DM from the manager process directly via client.users.fetch(userId).then(u => u.send(...)).
This usually works regardless of guilds and avoids shard duplication entirely.

but idk the code looks weird

sand minnow

I need help with choosing what intents I need for my bot, is anyone able to help me?

rose tangle
crystal cargo

ok thanks

rose tangle
sharp ginkgoBOT
  • Websocket intents limit events and decrease memory usage: learn more
  • See what intents you need here
fresh eagle

hi

halcyon bison
sand minnow

Does guildCreate event show added by who?

polar karma

no. generally, "who did this action" is available via audit logs

fiery epoch

Does anyone know how to properly do a modal?

sharp ginkgoBOT

guide Modals
Modals are pop-up forms that allow you to prompt users for additional input. This form-like interaction response blocks the user from interacting with Discord until the modal is submitted or dismissed. In this section, we will cover how to create, show, and receive modals using discord.js! This page is a follow-up to the interactions (slash commands) page. Reading that page first will help you understand the concepts introduced in this page.

topaz bluff

If you mean, just how to get them to work... Then the guide above should help

sand minnow

❌ Failed to register commands: DiscordAPIError[50035]: Invalid Form Body 0[BASE_TYPE_MAX_LENGTH]: Must be 110 or fewer in length.⁩what causes this error?

sand minnow
topaz bluff
topaz bluff

100 slash commands, 5 user context menu, 5 message context menu

sand minnow

alr, thanks!

topaz bluff

You can double it by using both global and guild commands

sand minnow
topaz bluff

But you can also use sub commands to combine several into 1

/example add and /example remove can become 1 Application Command and appear as 2 slash commands

sand minnow

yup, that's what I need. I can also do like disable commands all under one and enable also all under one

@topaz bluff is there a limit to how many sub commands a slash command can have?

bleak owl

25

topaz bluff

25? But I would have to double check

sand minnow

more then enough, thanks jo and samtino

topaz bluff

Ofc

sand minnow
thin crypt

Does ⁨⁨Events.ClientReady⁩⁩ event pass a client to you?

red coral

Yes

sharp ginkgoBOT
thin crypt

thank you 🙂

split hornet

maybe this should go in #1081585952654360687 but it's a very small question

Is there a cleaner way to import fields from a JSON in an ESM module? Here's the code for CommonJS as the guidebook uses:

const { productionGuildId, minimumCooldownTimeMs } = require('../../config.json');

Here's my ESM code that does the same thing, but is less ergonomic:

import config from '../../config.json' with { type: 'json' };

const productionGuildId = config.productionGuildId;
const minimumCooldownTimeMs = config.minimumCooldownTimeMs;
topaz bluff

personally, i like having a config.js file that loads the values from the config and handles required, optional, or default values for specific config entries... then you can export the config from your config.js

unique shoal

If you dont mind me asking whats the value of wrapping the config.json in a config.js if the JS file could have done it all on its own anyway

topaz bluff

i mean i also dont use .json, i use environment variables (which also need their types changed sometimes)

shell wagon

Is it necessary to fix every little problem that TS tells you about?

⁨⁨ts await channel.send({ components: [container], flags: MessageFlags.IsComponentsV2, })⁩⁩

Problem is:

⁨⁨'channel' is possibly 'null'.⁩⁩

split hornet
rose tangle
ruby bane
fleet spire

hey guys.

my app runs fine locally, how ever when deployed to my server via docker compose, it somehow fails to find my commands:

Ready! Logged in as Grok#5724
No command matching banish was found.

I dont really know where to start with de bugging this

⁨```Dockerfile
version: "3.9"

services:
grokbot:
image: grokbot:latest
container_name: grokbot
restart: unless-stopped

# Environment variables
env_file:
  - .env

# Optional: keep logs sane
logging:
  driver: "json-file"
  options:
    max-size: "10m"
    max-file: "3"

⁨```Dockerfile
# ---- Build stage ----
FROM node:20-alpine AS builder

WORKDIR /app

# Copy package files first (better Docker caching)
COPY package*.json ./

# Install deps (including dev deps for TypeScript build)
RUN npm ci

# Copy source code
COPY . .

# Compile TypeScript -> dist/
RUN npm run build
# (expects "build": "tsc" in package.json)


# ---- Runtime stage ----
FROM node:20-alpine

WORKDIR /app

# Copy only what we need from builder
COPY --from=builder /app/package*.json ./
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/dist ./dist

# Discord bots don't need ports exposed

# Start the bot
CMD ["node", "dist/index.js"]

```⁩
fleet spire

alright so I worked it out, if anyone has any similar issues in future here was my fix:

since I was writing in TS and docker cant natrually read that, I had to compile to JS.

then since my deploy commands and main script were searching for command files that ended in .ts, it didnt find any cause they had been turned into js.

stable sun
fleet spire

sorry I dont understand the question

stable sun
fleet spire
stable sun

Just strange that it works locally

It might’ve worked if you used bun or ts-node or similar locally

Idk why else it would only work locally

fleet spire

i wasnt running the compiled code, so everything was still in TS and thus it could scan and find the command files

steel trail

With latest node versions you can also run the .ts directly, so in the future transpiling won't be needed at all

fleet spire

oh dope

sand minnow

[Unhandled Rejection] TypeError: Cannot read properties of undefined (reading 'handle') at module.exports [as INTERACTION_CREATE] (C:\Users\zeinf\Documents\Projects\tryhard\main\tryhard-main\node_modules\discord.js\src\client\websocket\handlers\INTERACTION_CREATE.js:4:36) at WebSocketManager.handlePacket (C:\Users\zeinf\Documents\Projects\tryhard\main\tryhard-main\node_modules\discord.js\src\client\websocket\WebSocketManager.js:352:31) at WebSocketManager.<anonymous> (C:\Users\zeinf\Documents\Projects\tryhard\main\tryhard-main\node_modules\discord.js\src\client\websocket\WebSocketManager.js:236:12) at WebSocketManager.emit (C:\Users\zeinf\Documents\Projects\tryhard\main\tryhard-main\node_modules\@vladfrangu\async_event_emitter\dist\index.cjs:2504:31) at WebSocketShard.<anonymous> (C:\Users\zeinf\Documents\Projects\tryhard\main\tryhard-main\node_modules\@discordjs\ws\dist\index.js:1190:51) at WebSocketShard.emit (C:\Users\zeinf\Documents\Projects\tryhard\main\tryhard-main\node_modules\@vladfrangu\async_event_emitter\dist\index.cjs:2504:31) at WebSocketShard.onMessage (C:\Users\zeinf\Documents\Projects\tryhard\main\tryhard-main\node_modules\@discordjs\ws\dist\index.js:1007:14) at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
I get this error when running any slash commands and it doesn't show where the error is

worthy plaza

Maybe it can't find handle function (just guessing)

versed current

lads, when I do this:
currentChannel.permissionsFor(guild.members.me!).has(PermissionFlagsBits.CreatePrivateThreads)

Does this check for guild-wide permissions as well?

sand minnow
sand minnow
versed current
sand minnow
sand minnow
worthy plaza

(or at least specify that you are guessing)

sand minnow

yh I don't need guessing

polar karma
sand minnow
worthy plaza
polar karma
sand minnow
polar karma

I know plenty of stuff and have given lots of answers, but even the best of us guess at times. I didn't even have an idea on your error except that it seemed to somehow be an internal error unless you had a handle function somewhere

sand minnow

I had to go inside the actual djs files to find that one out
⁨```js
'use strict';

module.exports = (client, packet) => {
client.actions.InteractionCreate.handle(packet.d);
};```⁩

polar karma

Yeah don't overwrite lib internals mmLol this is why it's recommended to extend the client or use functions and pass the client instead

sand minnow
polar karma

Yeah, that's one of the dangers of adding stuff to the library structures and why the recommendation was changed some years ago

sharp ginkgoBOT

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

sand minnow

I just changed it to all capslol

shut musk

Is it possible to get a discord user via username?

polar karma

Only if they're cached. Fetching is id only

shut musk
polar karma

Yes, but you asked about a user, that's not the same as a member

shut musk

Oh yeah aware but the latter does exist right?

sharp ginkgoBOT
polar karma

Ok hmmm that wasn't what I wanted

shut musk

Looks correct no?

sharp ginkgoBOT
shut musk

That's the API route nvm

polar karma

That's the library method. The first one is the rest route

red coral

Can someone help me figure out what permissions I’m missing here? I’m using client.channels.cache.get(id).permissionsFor(client.user).serialize() (will send the embed when I’m off cooldown)

Since I’m using reply I already check for


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

I can’t see what else I need

wary coral
red coral

Which is pretty confusing since I feel like I’m checking all possible permissions I need

wary coral
red coral

Returns true 💀, but I thought it took an array? Sorry it took so long

red coral
red coral

Well it has all the ones I specified I believe

wary coral

I dont know

versed current

lads, when I do this:
currentChannel.permissionsFor(guild.members.me!).has(PermissionFlagsBits.CreatePrivateThreads)

Does this check for guild-wide permissions as well?

wary coral

I think is is only the channel

wary coral
civic jungle

is it possible to get a parent message from the interaction on a reply?

sharp ginkgoBOT
proud arrow

If the parent message is an ephemeral reply, you’ll have to then get it through interaction webhook

sharp ginkgoBOT

method CommandInteraction#fetchReply() discord.js@14.25.1
Fetches a reply to this interaction.


// Fetch the initial reply to this interaction
interaction.fetchReply()
  .then(reply => console.log(`Replied with ${reply.content}`))
  .catch(console.error);

little quiver

Weird question, if I receive an interaction for a slash command that doesnt have any subcommands or groups (ie: /ban), and I run getSubcommand() on the interaction, what string is returned? I assume its just the command's name?

clear garnet

If you don't specify the sub command as being required, it errors. If you specify it as not being required, it returns null

sharp ginkgoBOT
proud arrow
red coral
proud arrow

I was thinking if it was voice channel, then the error would make sense without Connect perm

red coral

This is strange, type 0 is guild text right

proud arrow

Yup

red coral

{
  "type": 0,
  "guild": "905194979650052208",
  "guildId": "905194979650052208",
  "permissionOverwrites": [
    "905194979650052208",
    "1380936713639166082",
    "1390416128983040120",
    "1239582062844055592",
    "1314089193340665937",
    "1424421417394507876",
    "646937666251915264"
  ],
  "messages": [
    "1467232437670121676",
    "1467251805468754004",
    "1467251813899047176",
    "1467251903430660339"
  ],
  "threads": [],
  "nsfw": false,
  "flags": 0,
  "id": "1338629243814416445",
  "name": "",
  "rawPosition": 91,
  "parentId": "1338603952773791836",
  "topic": null,
  "lastMessageId": "1467251903430660339",
  "defaultThreadRateLimitPerUser": null,
  "rateLimitPerUser": 0,
  "createdTimestamp": 1739224482254
}

Using

c!e const chan = client.channels.cache.get('1338629243814416445');
const data = JSON.stringify(chan, null, 2);
await message.channel.send({
files: [
{
attachment: Buffer.from(data),
name: 'data.json'
}
]
});

I have this in my cache? 💀

loud quartz

have what?

red coral

Oh nvm it’s because I use json stringify

loud quartz

util inspect instead

red coral

I did and it’s a text channel, I’m gonna guess you want it?

For reference my djs version is root@grapes:/home/CardCompanion# npm ls discord.js
cardcompanion@1.0.0 /home/CardCompanion
└── discord.js@14.23.2

root@grapes:/home/CardCompanion#

loud quartz

did you restart your bot? curious if getting everything fresh will give same results and same data

red coral

We are planning a restart soon so I can try and check the permissions again but I can’t see how that’ll change anything

loud quartz

i'm just curious if it's mismatched state on your end