#djs-help-v14

78874 messages · Page 23 of 79

rose tangle

"a database" is a very broad term, you'll have to specify which and where, also #1081585952654360687 since it isn't djs related

tough folio
calm burrow

how do i get the new server tag from user?

is it possible?

loud quartz

possible, might be

not with discord.js though, since it's still undocumented by discord

calm burrow

👍 ty

loud quartz

did what?

that's cool, but how is it related to this channel?

stable sun

Use editReply and specify the message

.editReply({ message: followUpMessage, content: …, … });

grizzled bison

hello Can component v2 be used for python?

sharp ginkgoBOT
clear garnet
grizzled bison
stable sun

I thought it just returns the Message

Yea, fetchReply does nothing on a followUp afaik

sonic wasp

Hi everyone,
I'm encountering an issue where my bot returns the error "Cannot Send Empty Message" on certain servers...

I've double-checked the code, and there are no cases where an empty message is being sent (e.g., message.reply({})).
The command works perfectly fine on most servers, but on a few, it throws this error.

Could this be related to a missing permission? If so, does anyone know which one might be causing it??

stable sun

It’s caused by either providing an empty object or an object with invalid keys

stable sun

embeds is misspelled

Could also be caused if you don’t provide a non-null/undefined content, embeds, stickers, files, or components

This would be much easier to track down with proper error handling

prisma ruin

is there any way to know the type of an interaction without running isButton, isStringSelectMenu, etc

vast nymph

the interaction has a type property

sharp ginkgoBOT
odd moon

Are Discord.js memory sweepers microtasks or macrotasks? For example, if I have a lot of async functioning queueing to microtasks, could it block proper sweeping of memory due to the way the NodeJS event loop works since microtasks happen first?

steel trail

They are macrotasks. But are you sure you need/want sweepers if you have that many async functions queued? Sweeping adds quite a burden on CPU cycyles. Could limiting intents or makeCache be the better option for your issue?

odd moon
steel trail They are macrotasks. But are you sure you need/want sweepers if you have that ma...

Well I already use makeCache and also have limited intents as much as I can. Now that you mention it and with that understanding now, removing sweepers could be an option. The problem with that is I run into the issue of the memory ever-expanding overtime, to my knowledge, because my bot is pretty large (70k servers). Other option I am considering is moving the async microtasks that are getting queued to a worker thread or something like that so theoretically it wouldn't block the main event queue (assuming my understanding of that is correct). What are your thoughts?

crimson gale

if you're that concerned about memory and performance you might even fare better with @discordjs/core

odd moon

Also what advantages would I get with that over regular discord.js 🤔

sonic wasp
steel trail

But embed: is also invalid

sonic wasp
stable sun

Might've not been clear that the example I gave was for an invalid use of reply

sonic wasp
crimson gale
odd moon Also what advantages would I get with that over regular `discord.js` 🤔

the advantages are the disadvantages really. discord.js is as comfy to use as it is because of not despite of the aggressive caching - that's what powers a lot of the convenience functions
no caching, whatsoever. you have to do that all yourself
you get a sophisticated rate limit handler, a wrapper for typesafe api calls, a websocket manager and a much smaller set of convenience functions and that's largely it.

so: you loose a lot of the comfort, but you gain all the agency

odd moon

Thanks for the info :)

heady tapir

hi, is there any way to tap into the websocket in djs?
i want to monitor websocket connection close with status codes if possible

a hacky way would be sufficient, i want to expand the monitoring of my bot

sharp ginkgoBOT
steel trail

<Client>.ws.shards has all those

heady tapir

okay thanks
do those instances ever get replaced on reconnect? or do i have to only have to add the event listener once on startup?

median cloak

for v2 components its there a way to put the thumbnail on the left instead of the right

snow onyx

no

median cloak

ok

heady tapir
trim elm

webhooks dont support containers yet i presume?

steel trail

They do

Just need to add withComponents: true as well as the IsComponentsV2 flag

trim elm

cheers man

snow onyx

they dont

they are useless to bots

verbal vine

i need help

iam using componentv2

crimson gale

and what are you sending?

verbal vine
crimson gale

code

verbal vine

oh i think i missed message flags <_<

crimson gale

yeah, prob

verbal vine

thx for your time, im sorry

crimson gale

iirc 1 is actionrow and that is the only allowed topelvel component components[0] without the flag

heady tapir

can the client "ready" event be fired multiple times throughout the lifetime of a client object?

pliant forge

if i remember there is a guide for cooldown for / commands but i couldn't find the page. Can someone send me :

pliant forge

tysm

steel trail

Listening with .once to it is suggested

analog oak
  const row =
      interaction.message.components[interaction.message.components.length - 1];
    if (row.type == ComponentType.ActionRow) {
      const ActionRow = ActionRowBuilder.from(row);

How to see that the action row have buttons? I'm trying to disable a button in the last row

steel trail

Check the type of the first element in its .components

analog oak
steel trail

Do you want to find out if it contains buttons or do you want to typeguard/cast it so ts allows you to use it as buttonbuilder?

analog oak
steel trail

Then just use the generic on the .from<...>() call

And use ActionRowBuilder, not ActionRow nvm, you shouldn't name your variables in PascalCase, those are classes

novel pendant

editing a component color function changed?

steel trail

Components don't have colors regularly. A Container can have an accentColor and a Button can have a style causing it to look differently

analog oak
steel trail

Yes

analog oak
steel trail Yes

it's not letting me..

const component = interaction.message.components.at(-1);
    if (component && component.type == ComponentType.ActionRow) {
      const actionRow = ActionRowBuilder.from<ButtonBuilder>(component);

Should i just cast components as APIActionRowComponent<APIButtonComponent> ?

steel trail

Yes

verbal vine

Webhooks can send componentv2?

polar karma

Yes

little pebble

You need to pass withComponents: true in the options though

verbal vine
sharp ginkgoBOT
grizzled venture

Can someone send the link to the discord.js v14 guide where I can check: How to reply with an embed to a button.

wary coral
sharp ginkgoBOT

method ButtonInteraction#reply() discord.js@14.19.3
Creates a reply to this interaction. Use the withResponse option to get the interaction callback response.


// Reply to the interaction and fetch the response
interaction.reply({ content: 'Pong!', withResponse: true })
  .then((response) => console.log(`Reply sent with content ${response.resource.message.content}`))
  .catch(console.error);

guide suggestion for @grizzled venture:
guide Message Components: Buttons
read more

modest surge
const guild = await client.guilds.fetch('YOUR_GUILD_ID')
await guild.members.fetch()

  const realMembers = guild.members.cache.filter(member => !member.user.bot)

i dont think theres other way

vital vortex

is there a flag or anything to turn off pings even if the container contains a user or role ping? for components v2

modest surge

@languid summit u can fetch first then just add it on a database on howmany the members are

then use guildMemberAdd listener every userjoin it adds +1

steel trail

If the guild is big the difference between with/without bots doesn't really matter though

sharp ginkgoBOT

tag suggestion for @vital vortex:
You can control which entities receive notifications via the allowedMentions option. You can:

{ ..., allowedMentions: { parse: ["users", "roles"] } }
pliant forge

so sorry for bothering but in .addTextDisplayComponents can i put 2 buttons?

steel trail

No. A textdisplay is not a button

pliant forge
steel trail

Then no. A section has exactly one accessory. You can use an actionRow below or above the section if you want more than one

pliant forge

Oh okay tysm for ur time

placid wedge

hi, why do i get 'MessageActionRow is not a constructor' ?

is there something else instead of it

sharp ginkgoBOT
steel trail

Sounds like outdated v13 code

placid wedge

oh okay i'll downgrade to v13

sharp ginkgoBOT

Version 14 has released! Please update at your earliest convenience.

  • Update: npm rm discord.js npm i discord.js
  • Update guide (use CTRL + F to search for the old method or property)
steel trail
placid wedge
steel trail

v13 is outdated and unsupported

placid wedge

who cares if it still works

wary coral
jade falcon

hi!

here's a portion of logs from my bot's startup progress; it's been on a reconnect loop for shards even though they're ready. I was wondering if this is because of the "unavailableGuilds" thing, never seen this error before. some shards start with unavailableGuilds: 0 and the rest are as you see here. is this a common issue? I've also provided some debug logs that show the errors right before the reconnect loops. if you need any other information from the bot, i'll provide it!

(p.s this bot is on a custom clustering package but i just wanted to know if this was an error seen before due to discord.js reasons)

djs v14.9.3

nova pond

Hi, I'd like to know why the v2 component guide documentation no longer works?

shrewd wraith

what a best way to give a one role to multiple members? (about 200)

azure kettle

can someone share with me the code of container with buttons inside

frozen egret

wasn't there something with the new version release, where you can put a horizontal line break or like create sub-sections inside of an embed? i just want to separate two halves of an embed and want it to look nice and clean

elfin scroll
halcyon bison
halcyon bison
halcyon bison
jade falcon
halcyon bison
jade falcon
covert vine

how do i do prefix commands and does discord.js support them?

halcyon bison

prefix commands are entirely just string parsing
you can access message content from <Message>.content, but beyond that, it's up to you to handle

steel trail

While slashcommands are convenient for both user and developer. So why do you want to do prefix commands?

covert vine
ocean portal

why does every sub command I make it doesn't appear in /?
I restarted my discord, and deployed it

module.exports = {
data: new SlashCommandBuilder()
    .setName('entertainment')
    .setDescription('entertainment purpose command, used to have fun.')
    .addSubcommand(sub =>
      sub
        .setName('facepalm')
        .setDescription('Sends a facepalm Image API')
    ),```
steel trail
halcyon bison
covert vine
ocean portal
steel trail

/command key:... operator:... value:... or if you want the full parse experience for you as dev: /command phrase:... and have them enter whatever you wanted in the prefix command and parse the string the same way

As said: if anything prefix commands are less flexible, as they only allow the latter of those two

halcyon bison
covert vine
steel trail

Great, then you won't need any help from us, good luck

covert vine

it seems completely impossible to seperate the sync commands file from main

main needs the commands too

steel trail

Huh? No, it's explained in the guide how to do it and many have done it. So not impossible

steel trail
ocean portal

I don't understand, no errors

halcyon bison
covert vine
ocean portal

ok

steel trail
covert vine
covert vine

oh wait, i dont have to sync my commands lol

i have create a whole new interaction wrapper :(

wary coral
covert vine
topaz bluff

Yes with prefix commands you don't have to deploy anything.

However, if you ever plan on getting into more than 100 servers, then you're probably going to have to covert to slash commands. Discord won't accept your Privalaged intent application for the reason of using prefix commands

But if you don't, then do whatever you want. It's not against any rules, it's just an unsupported implementation

covert vine

fuck discord lol

wary coral

also with slash command you can do ephemeral responses

steel trail

Keep this channel djs related, thank you

compact swan

can I use djs to setup a kind of "teamspeak whisper" feature where x bots join voice channels and are there to just relay audio from one main channel?

steel trail

Yes

wary coral
steel trail

No

Hence the "x bots"

wary coral

Ah, My bad missed that

brittle lintel

How do I get the first/initial message of a form channel thread/post?

sharp ginkgoBOT

method ThreadChannel#fetchStarterMessage() discord.js@14.19.3
Fetches the message that started this thread, if any. The Promise will reject if the original message in a forum post is deleted or when the original message in the parent channel is deleted. If you just need the id of that message, use id instead.

brittle lintel

thanks

crimson gale

that only works if the thread is started on a message afaik

brittle lintel
crimson gale

correct

oh, not even just that, i mean if a thread is started ON a message

brittle lintel

Im only dealing with fourm channels right now which I think must always have either a message or media

crimson gale

because then the message id is the thread id and we can do the fetch
in forum channels there is no easy way to figure that out, unfortunately

not too sure what you are trying to do with the message, but that would be one way to go about it; waiting for it when the thread is created

(discord not implementing "jump to top" in the UI is crazy, btw)

brittle lintel
crimson gale

could also try after: 0

yup, that seems to work

thread.messages.fetch({limit: 1, after: 0})

brittle lintel

fetchStarterMessage actually seems to be working for me, it's resolving the message both with text or with just media

Because im not doing anything automatically/on threadCreate I don't have to worry about the waiting issue

latent pulsar

What is the best and most effective way to programme the bot in several languages? So that you have a /setup command with which you can specify the language of the bot for the server and then everything is translated (command names, buttons, responses etc.). So far I only know about user localisation and I understand how that works.

Is there an example/guide or ready-made handler for the other or do I have to build a solution myself?

stable sun

You don’t want to use interaction.locale?

sharp ginkgoBOT
latent pulsar
rose tangle

that's outside the scope of djs

there are multiple i18n libraries out there though

covert vine

does djs completely ignore the required argument to interaction.options.get(string, required)?
is it only for typing?

unique shoal

What do you mean by ignore?

covert vine
latent pulsar

I mean, my bot will then only have 2 languages anyway

unique shoal

Im not sure why you think it would be ignored

Here it is throwing an error if you specify required, and its not found

covert vine

oh ok

rose tangle

and getting the language is one part of the system

rose tangle
cedar kindle
rose tangle

if your sidebar says message components instead of interactive components maybe you need to reset your cache, ctrl+f5

frozen egret

question:

Events.GuildMemberAdd does not seem to be "seeing" when new members actually join the server. all other event files trigger when they need to. i thought it would be a problem with the priviledged intents but i do infact have the GUILD_MEMBERS intent on, so it should be able to see when people join.

even weirder, to test this, i created another /command for my bot, which is /emit [eventType] [args] and used it to emit the event of a person joining (that I tagged). and it worked, and set the message correctly.

is there a situation where clicking the priviledged intents is not enough, and i need to do something more on the discord developers page to make it work?

TLDR:
Bot doesn't trigger and say hello when guildmember is added. but when i manually emit the event, it triggers, and the code runs smoothly without error. this means there's something going on in between discord emitting the event and my bot catching discord's emittion.

rose tangle

can you show your intents and listener's code?

frozen egret

👍 one second

sharp ginkgoBOT

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

cedar kindle
cedar kindle

thanks

frozen egret
rose tangle can you show your intents and listener's code?

and i found the bug by looking at my index file. i wasn't calling it correctly, when i'm trying to pass it to the client.on(event.name, (...args) => event.execute(...args)); part. so that fixed it.

honestly, just looking at it again from another angle really helped jog my memory in what needed to be done.

grave pond

Is there a way to get user guild current guild tag rn I have auc

little pebble
grave pond
little pebble
sharp ginkgoBOT
covert vine

how does discord.js implement stuff like interaction.options.getString() with the required argument type safely? i cant seem to do it and im losing my mind over it

bleak owl

discord.js is open source and freely accessible via github

covert vine

because i am completely lost

bleak owl

you’ll need to search for it, which the docs can help with since everything in the docs has a link to the specific part you’re looking for on github

sharp ginkgoBOT
bleak owl

there’s a link there that directs to github

covert vine

ok

bleak owl

coding isn’t meant to be something you make quickly, it takes time and effort

which includes searching the docs for what you’re looking for in that time

doesn’t necessarily have to be a short amount of time, but that comes with learning how to read the docs and navigate them

covert vine
bleak owl

not true at all

you just have to learn how

little pebble

Just to clarify, are you trying to understand its usage or how it works under the hood?

covert vine
bleak owl

i don’t quite understand that

implementation of what

little pebble

Can you show the error? Also what editor do you use?

lunar jacinth

Some people are able to add buttons and similar components to their embed. How do we do that, and which method should we use?

bleak owl

that would be in a container, which is part of the new componentsv2 update

lunar jacinth

Uh, I tried a lot but I couldn't do it. Do you have an example code or something, if there is one in JS of course?

lunar jacinth

thanks

toxic moat

@unique shoal wee dont have a way for show avatar user on ThumbnailBuilder Is it necessary to specify the link?

unique shoal

Why are you pinging me for this

orchid radish

is it at all possible (or might it ever be possible) to dynamically update command options if previous ones are set to certain selections?

unique shoal

no

orchid radish

is that a terrible idea

unique shoal

not a terrible idea, just not how it works

orchid radish

omw to discord suggestions somewhere somehow

loud quartz

won't work

command options are either static or dynamic

static are changed via deploy

dynamic are autocomplete

so what you want already exists

unique shoal

theyre talking about dynamic options, which dont exist

loud quartz

what doesn't exist, is the fact that discord client caches the autocomplete results

unique shoal

All options are static, only the choices for them can be dynamic

loud quartz

bleh

too late for me

unique shoal

at least, that was my interpretation

loud quartz

i read as a "tree" of options

but that can be kinda done via ac

orchid radish

is formatting for the switch from fetchReply -> withResponse the same

unique shoal

ahh right, yeah sort of

loud quartz

assuming user fills the options in correct order, which they have no obligation to

unique shoal
orchid radish
loud quartz

autocomplete results are cached locally for the "duration" of one command usage

so doing a backspace a backspace a backspace will not ddos your bot

you can access other options in the autocomplete interaction, but only the ones already filled will be, well, filled

so if user does options out of order there's nothing to read

orchid radish

can i supply predetermined autocomplete options similar to how i have static ones with normal commands

loud quartz

you can return whatever you want to an autocomplete

only limit is the 100 chars for name and value

and up to 25

orchid radish

does the client receive anything once one of those options is selected

loud quartz

autocomplete interaction is request for options to show to user

only thing after that is command interaction

empty cradle

value

loud quartz

which is when user actually submits the whole command

nothing inbetween

orchid radish

sadness

empty cradle
empty cradle value

ye after user submit the options, the bot will receive its value, don't u think?

loud quartz

no, you don't submit options

you submit entire command with all its options

there is no "autocomplete submit interaction"

empty cradle

yes, I just want to say only abt options

loud quartz

but the question wasn't about submitting full command

empty cradle

yk what nvm

loud quartz

the question was if discord sends anything when user selects a value

which discord does not

empty cradle

i see

loud quartz

it is true for select components that have a max of 1

but not for command options, and for selects with more max, where only after user clicks out of the select there's a single interaction with all options selected

scarlet trail
clear garnet

Wrong type

sharp ginkgoBOT
scarlet trail

What u provided doesnt have vote counts

clear garnet

It does, if you look into the nested properties of it

<Message>.poll.answers.at(0).voteCount

scarlet trail

facepalmz thanks

grave pond

Uhh my bot host site got ratelimited is there an eta for when it removes?
eu-ro-01.wisp.uno:9359 is erroring with The owner of this website (discord.com) has banned you temporarily from accessing this website. and You are being rate limited

scarlet trail

varies - minutes / hours

clear garnet

Check the rate limit headers

grave pond

It showed this only

All bots on that node got ratelimited 💀

clear garnet

client.rest.on("rateLimited", console.log)

grave pond

Added in index.js that line

sharp ginkgoBOT

Please add the following code to your code base outside of any other event listeners and provide the full log output relevant to your issue.

client
    .on("debug", console.log)
    .on("warn", console.log)
  • Note: if you initialize your Client as bot or other identifiers you need to use these instead of client
  • If the output is too long to post consider using a bin instead: gist | paste.gg | sourceb.in | hastebin
crimson gale

if it hangs on login ^

ocean portal

I'm pretty confused on why didn't it update to DND and saying its not on any servers (0)

const { PresenceUpdateStatus } = require('discord.js');

function updatePresence() {
      const count = client.guilds.cache.size;
  client.user.setPresence({
    status: 'dnd',
    activities: [{
      name: `${count} servers | /help`,
      type: ActivityType.Playing
    }]
  });
}
client.on('guildCreate', updatePresence);
client.on('guildDelete', updatePresence);```
-# I just couldn't know how to fix this
bleak owl

are you missing the Guilds intent?

also, you don’t have client defined there Thonk

ocean portal

Maybe it's about "client" isn't defined idk
but I have guilds intent

bleak owl

maybe? i mean it’s your code so you should know what’s defined and what’s not and what errors you have

ocean portal

nvm I have it defined

Thonk

bleak owl

where is it defined? is this not the whole code?

ocean portal

but it's pretty long

sharp ginkgoBOT

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

sharp ginkgoBOT

If you aren't getting any errors, try to place console.log checkpoints throughout your code to find out where execution stops.

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

Someone know how i can use Buttons in an Embed with the new Comp's? Or is the update not out yet

crimson gale

embeds are not available to use along with components if you opt into the new system

if you have seen an "embed" with buttons inside, that's a container with an accent color

dusky fern

oh okay

crimson gale

container with text display(s) and an actionrow with buttons // section with button accessory (single button to the right of text)

dusky fern

Thank you

dusky fern

@crimson gale We cant add a Author, Timestamp / Footer & Stuff like this to an container?

crimson gale

correct

you can use the general timestamp format and emulate a footer with -# subtext prefix

sharp ginkgoBOT

discord API Reference - Message Formatting
read more

dusky fern

hmm

why did we not add those small stuff to the container also

crimson gale

firShrug

dusky fern
bleak owl

-# (souji should send the “we just don’t know sticker”)

crimson gale
wintry laurel

is there really no way to fetch past say 100 messages from a specific user? or is fectching messages just limited to channel

ocean portal

how can I remove some commands from being userinstallable?
-# some commands of mine won't work there so that's why

what's this database btw? Thonk

dusky fern
sharp ginkgoBOT
ocean portal

Ty

topaz bluff

Ofc

ocean portal

I have a serious question,
Why does my bot say client is undefined? maybe for function like client.ws.ping
someone tried it on their djs bot and it worked..
what could be so wrong?

clear garnet

Sounds like a basic JavaScript scoping issue

bleak owl

which isn’t the first time you’ve been told that

ocean portal
bleak owl

what function?

tried what?

what’s your code?

ocean portal

client.ws.ping returns undefined

bleak owl

that’s not your full code

haven’t we been down this road before?

you probably don’t have client defined

please stop showing single lines of code without any context

it helps no one

ocean portal
const { Client, SlashCommandBuilder, EmbedBuilder } = require('discord.js');

module.exports = {
  data: new SlashCommandBuilder()
    .setName("ping")
    .setDescription("Returns ping and roundtrip latency for troubleshooting slow response."),

  async execute(interaction) {
    try {  
      const ping = interaction.client.ws.ping;
 
      const embed = new EmbedBuilder()
        .setColor(0xff0000)
        .setTitle('🏓 Pong!')
        .addFields(
          { name: 'WebSocket Ping', value: `${ping}ms`}
            
        );
        
      await interaction.reply({ content: null, embeds: [embed] });

    } catch (error) {
       console.log(error)
       await interaction.reply({ content: `Error:\n\`\`\`${error.message}\`\`\``}); 
        }
      },
    }```
bleak owl

you have interaction.client

not client

ocean portal

I tried both

bleak owl

you can’t use “both”

one wouldn’t be defined regardless

which you should know

where does it say undefined? log ping

there’s a lot of info missing here

ocean portal
bleak owl

there are 3 different errors here

and the 3rd is basic javascript

log interaction.client.ws.ping please

ocean portal

Kk

bleak owl

if you don’t know how to log something, that is where my support ends

ocean portal
bleak owl

okay, please log interaction

ocean portal
bleak owl

that’s it, just interaction

ocean portal

Kk

ocean portal

Its pretty long

bleak owl

why did you delete it?

it looked fine, but i’m confused as to why <Client>.ws.ping is undefined.

ocean portal
bleak owl

no, not necessarily, but it just means that there’s another problem somewhere else

ocean portal

Should I delete and reinstall djs

for node module

what should I do at that moment? OMEGAlul OMEGAlul OMEGAlul

spice thunder

might be simple but I can't figure out how to escape spoilers in markdown links.
so to escape ||this|| I would to \|\|this\|\|which renders as ||this||. so far so good.

but when I try to do the same in a link, it becomes ||this|| notice how the backslashes are visible.
either the link has visible backslashes or has a spoiler in the link. am I missing something?

hallow mesa

I think backslash just doesn't work as an escape character inside a hyperlink. Not really a library thing though

spice thunder

yeah it's just a general "working with discord bots" question, figured someone here would have experience with this situation

hallow mesa

You can probably but an nbsp or other invisible character between pipelines to stop it from formatting as a spoiler if you just want it to look correct

spice thunder

oooh that's a good idea

thorn gate

can bot see user connections?

clear garnet

No, you can only get that info through an OAuth2 grant

trim elm

any way to resize images in the mediagallery components of a container?

molten storm

How do some bots make choices that are fetched before you run the command?

sharp ginkgoBOT
topaz bluff

and if you want them to be dynamically loaded, you can use an autoComplete interaction

sharp ginkgoBOT
coral hollow

I dont know how events work and i want to make one where each time someone sends a message, it reads and sees if its that message. Its gonna have a prefix “!” and will look for something like “!message”. Can someone help me?

plucky coral

Will <member>.createDM() fail if a user has their DMs closed, or will it fail on .send() ?
Just checking where my try-catch should go.

prisma ruin
plucky coral

Cheers

prisma ruin

i think u dont even get an error, u can pass in true in <member>.createDM() to force the dm to be created and then send the msg

plucky coral

Ah I'm more handling the use-case for when the DMs are closed. Like, if .createDM() is used, will a dmChannel still be created? If so, then it should be able to send a message.

More just double checking when I should use my try-catch block, or if it's just outright better to put them both within the try block, and then just assuming it's closed if either fails.

prisma ruin
clear garnet

All createDM() does is fetch the DM channel between your app and the user. If a user's privacy settings don't allow your app to DM them, then it'd throw an error on send(). Just as a side note if you're sending a DM to someone, you aren't required to call createDM() beforehand as d.js will do that internally if deemed necessary to get the DM channel. Of course, if you're doing something else with the DM channel, then you can disregard that last point I made

The force option in createDM() is also merely whether to bypass d.js' cache or not. It has no bearing on "forcing the DM to be created" or anything similar

plucky coral
clear garnet All `createDM()` does is fetch the DM channel between your app and the user. If ...

Yeah, completely off memory, I needed to use .createDM() for something else on one of my bots and the functions I had afterwards were wonky without it. Just a bit habitual to use it beforehand I think.
Good to know nonethless, I'll just handle the try-catch logic on .send() then, but if errors come up then I'll assume I need to include .createDM(). There are very few scenarios I can imagine where the DMs would be off, since you would need to be able to DM the bot to get to this situation.

Thankyou both for being rubber duckys. :)

ocean portal

he said its fine and he's confused on why wasn't it working

odd moon

For makeCache settings, is MessageManager and GuildMessageManager practically the same thing? Like if I set MessageManager to 0 to cache no messages, do I not need to set GuildMessageManager also to 0 since that's already being handled by MessageManager?

upbeat saffron

what does this do?

await interaction.deferReply({withResponse:true});
ocean portal
steel trail
neon stump
        } else if (interaction.type === InteractionType.ApplicationCommandAutocomplete) {
            const command = this.client.commands.get(interaction.commandName);
            if (!command) return;

            try {
                await command.autocomplete(interaction);
            } catch (error) {
                this.client.logger.error(error);
            }
        }

The property 'autocomplete' does not exist on type 'Command'.ts(2339)
any

hi, I updated my code to the latest version of discord.js v14.20.0 and now this line makes an unexpected error for me

steel trail

Command is your own interface. Not one provided by djs

neon stump

my code has not changed between version v14.19.3 and v14.20.0 and in the note patch, there is no mention of change

steel trail

Still, both that code and that interface are made by you. So djs version is completely irrelevant for that

What does your Command interface look like? And what did you type client.commands to be?

neon stump
import type { APIApplicationCommandOption, PermissionResolvable, AutocompleteInteraction } from 'discord.js';
import type Outra from './Outra';

interface CommandDescription {
    content: string;
    usage: string;
    examples: string[];
}

interface CommandPlayer {
    voice: boolean;
    dj: boolean;
    active: boolean;
    djPerm: string | null;
}

interface CommandPermissions {
    dev: boolean;
    client?: PermissionResolvable | PermissionResolvable[];
    user?: PermissionResolvable | PermissionResolvable[];
}

interface CommandOptions {
    name: string;
    name_localizations?: Record<string, string>;
    description?: Partial<CommandDescription>;
    description_localizations?: Record<string, string>;
    aliases?: string[];
    cooldown?: number;
    args?: boolean;
    vote?: boolean;
    premium?: boolean;
    player?: Partial<CommandPlayer>;
    permissions?: Partial<CommandPermissions>;
    slashCommand?: boolean;
    options?: APIApplicationCommandOption[];
    category?: string;
}
steel trail

That is neither of the things I asked for

neon stump

the client cmds, that’s it

steel trail

No. That is neither typing client.commands nor is it the Command interface

neon stump

this?

steel trail

Did you write that code yourself? You don't seem to know where you typed client.commands nor where to find your interface named Command

Then it's indeed hard for you to fix that

neon stump
deft cairn

Is it possible to delete sent ephemeral responses?

hallow mesa

With .deleteReply() on the interaction

deft cairn
steel trail
neon stump

No need to send the whole file, the single line answering one of my questions would've sufficed. And the other question still is not answered from that code

neon stump

what question?

crimson gale

"did you write that code yourself?"

ocean portal

why does the button pages in guides shows 404 errors?

steel trail

I meant the "Command interface" question

steel trail
ocean portal

alr that was a pain going there, also is there a way to make button handler?? i cant find that in docs

steel trail

You can do it similar to the command handler. You already know the concepts if you did that

ocean portal

like this?

const buttonHandler = require('./handlers/buttonHandler');

for (const file of fs.readdirSync(path.join(__dirname, 'handlers/buttons'))) {
  if (!file.endsWith('.js')) continue;
  const btn = require(`./handlers/buttons/${file}`);
  if (btn.customId && typeof btn.execute === 'function') {
    client.buttons.set(btn.customId, btn);
  }
}```
neon stump
steel trail I meant the "Command interface" question
    constructor(client: Outro) {
        super(client, {
            name: 'help',
            description: {
                content: 'cmd.help.description',
                examples: ['help'],
                usage: 'help <command>',
            },
            category: 'Info',
            aliases: ['h'],
            cooldown: 3,
            args: false,
            vote: false,
            premium: false,
            permissions: {
                dev: false,
                client: ['SendMessages', 'ReadMessageHistory', 'ViewChannel', 'EmbedLinks'],
                user: [],
            },
            slashCommand: true,
            options: [
                {
                    name: 'command',
                    description: 'cmd.help.options.command',
                    type: 3,
                    required: false,
                    autocomplete: true,
                },
            ],
        });
    }
steel trail

Still not what I asked for... you have an interface named Command. Reading your code I even know where. But the fact that you don't seem to know is worrying to me

ocean portal
/home/container/index.js:30
    await btn(interaction);
          ^

TypeError: btn is not a function
    at Client.<anonymous> (/home/container/index.js:30:11)
    at Client.emit (/home/container/node_modules/@vladfrangu/async_event_emitter/dist/index.cjs:287:31)
    at InteractionCreateAction.handle (/home/container/node_modules/discord.js/src/client/actions/InteractionCreate.js:104:12)
    at module.exports [as INTERACTION_CREATE] (/home/container/node_modules/discord.js/src/client/websocket/handlers/INTERACTION_CREATE.js:4:36)
    at Client._handlePacket (/home/container/node_modules/discord.js/src/client/Client.js:384:33)
    at WebSocketManager.emit (/home/container/node_modules/@vladfrangu/async_event_emitter/dist/index.cjs:287:31)
    at WebSocketShard.<anonymous> (/home/container/node_modules/@discordjs/ws/dist/index.js:1273:51)
    at WebSocketShard.emit (/home/container/node_modules/@vladfrangu/async_event_emitter/dist/index.cjs:287:31)
    at WebSocketShard.onMessage (/home/container/node_modules/@discordjs/ws/dist/index.js:1091:14)
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5)

Node.js v23.8.0```

```js
const btn = require('./handlers/buttonHandler.js');

else if (interaction.isButton()) {
    await btn(interaction);
  }```

whys this happening? i cant solve this problem
steel trail

And that you client class is named Outra in one place but Outro in another doesn't make it better.

zenith violet

You have to call that

wild mango

is there a way I can get vscode to provide autocomplete for djs?

zenith violet

Use jsdoc or typescript

wild mango

thanks

ocean portal
zenith violet

you dont know how to call a function?

Thats the core basics of js

zenith violet
ocean portal

-# 😭

zenith violet

confused about calling a function you exported? You check for your function being there

your btn.execute is what you need to call

And pass in the interaction or whatever your function expects

zenith violet

I'd recommend you brush up on your js knowledge, #resources

ocean portal

i just didnt understand what u said kek

zenith violet

btn.execute(interaction)

Thats literally it

ocean portal

i tried that and

/home/container/node_modules/@discordjs/rest/dist/index.js:748
      throw new DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData);
            ^
DiscordAPIError[50035]: Invalid Form Body
user_id[NUMBER_TYPE_COERCE]: Value "null" is not snowflake.
    at handleErrors (/home/container/node_modules/@discordjs/rest/dist/index.js:748:13)
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
    at async SequentialHandler.runRequest (/home/container/node_modules/@discordjs/rest/dist/index.js:1149:23)
    at async SequentialHandler.queueRequest (/home/container/node_modules/@discordjs/rest/dist/index.js:980:14)
    at async _REST.request (/home/container/node_modules/@discordjs/rest/dist/index.js:1293:22)
    at async UserManager.fetch (/home/container/node_modules/discord.js/src/managers/UserManager.js:101:18)
    at async Object.execute (/home/container/handlers/buttonHandler.js:5:23)
    at async Client.<anonymous> (/home/container/index.js:30:5) {
  requestBody: { files: undefined, json: undefined },
  rawError: {
    message: 'Invalid Form Body',
    code: 50035,
    errors: {
      user_id: {
        _errors: [
          {
            code: 'NUMBER_TYPE_COERCE',
            message: 'Value "null" is not snowflake.'
          }
        ]
      }
    }
  },
  code: 50035,
  status: 400,
  method: 'GET',
  url: 'https://discord.com/api/v10/users/null'
}
Node.js v23.8.0```
zenith violet

Thats a totally different error

You're trying to fetch a user somewhere but the id yoy pass in is null

neon stump
ocean portal
zenith violet You're trying to fetch a user somewhere but the id yoy pass in is null

ig its coming from this then js module.exports = { customId: 'hello_button', async execute(interaction) { const [ , slashUserId ] = interaction.customId.split(':'); const slashUser = await interaction.client.users.fetch(slashUserId); const clicker = interaction.user; await interaction.reply({ content: `${clicker.tag} clicked after slash run by ${slashUser.tag}` }); } }

time to cook 🔥

trail patio

How to make like this

Im trying to make image thumbnail before the text and button in same section

Is not working how to do it?

dense jackal
trail patio
dense jackal

those are custom emojis inside a text display component, placed in a 2x2 grid

so for each pokemon image you see, 4 custom emojis are used

dense jackal

follow1follow2 Title text
follow1follow2 Description

:follow1::follow2: **Title text**
:follow1::follow2: Description
trail patio

Oh but

Emoji is in same line with the section

crimson gale

yes? you can put text after an emoji?

i do not see where the confusion is coming from here

4 emoji, 2 per line, 2 lines of text

dense jackal
trail patio
trail patio
dense jackal

trail patio

How tl keep it big

dense jackal

4 small emojis make 1 big emoji

crimson gale

it... isn't?

dense jackal
[1][2]
[3][4]

you have to split your image into 4 pieces

crimson gale

_ _
softW1softW2 Hello
softW3softW4 world

dense jackal

upload them as 4 separate emojis

crimson thistle

that's a cool but tricky tech

dense jackal

only downside is that on mobile clients between the lines there is like 1 pixel space between them

crimson gale

it's a very hacky workaround to make it work'ish
dv8 said so themselves kek

covert vine
little pebble Can you show the error? Also what editor do you use?

i dont know if its worth it anymore but its that null is not compliant with the return type
and im using vscode, i tried replicating it, and it seems like its completely impossible to implement complicated return types
because TypeVar bound parameters cant get narrowed down

trail patio

meguFace yes
meguFace no

Ohhhh 4 emojis wtf

crimson gale
  • they used 4 emojis
  • shows grid
  • what
  • OH 4 EMOJIS WTF
trail patio

Why would someone make such a movement for the sake of a message form?

crimson gale

i think you need to start actually reading what people say

trail patio
dense jackal

because its a nice workaround to have decent sized images on the left of your text

crimson gale

"nice" is debatable - horrible for screen readers and accessibility

dense jackal

imo the custom emojis syntax on discord is horrible for screen readers and accessibility in general shrug
-# (off-topic)

vestal sun

my best guess would be that the thumbnail variable is either undefind or that it needs to be as an attachment but im not sure but the error should be bc of the thumbnail accessory

upbeat saffron

how do i mention in components v2? is this enough?

await channel.send({
      flags: MessageFlags.IsComponentsV2,
      components: [container],
      allowedMentions: {parse: ["roles"]}
});
little pebble
upbeat saffron

is it possible to make another ping of a role after i updated the message? because as far as i understand 1 message 1 ping

wary coral
wary coral
dense jackal
upbeat saffron
dense jackal

no, sending a new message mentioning them again, then immediately delete that message after its sent

upbeat saffron

ah yea makes sense

upbeat saffron
dense jackal

it should as its a new different message

upbeat saffron
vital barn

whereas the first one mentions you as well as possibly a role you may have

upbeat saffron
vital barn
upbeat saffron

thats why i got mentioned in the fiorst message

dense jackal
upbeat saffron
dense jackal

yeah so the issue is then that with a followup it should also parse the mentions, which clearly doesn't right now

upbeat saffron
dense jackal

hm alr lol

upbeat saffron
dense jackal

it is, but somehow not for followup messages

dense jackal
upbeat saffron
dense jackal

yeah, as d.js is just making it easier to send requests to discord's api and by the looks of it discord isn't handling the followup message mention parsing correctly

#djs-help-v14 message see this message from qjuh saying it should always parse all mentions on default

upbeat saffron
grizzled bison

| [replaceComponents ERROR] ValidationError > s.nativeEnum(T)
0|moonveil | Expected the value to be a string or number
0|moonveil |
0|moonveil | Received:
0|moonveil | | undefined

how to fix this error

dense jackal
grizzled bison
dense jackal give the full error would be more helpful, now I can only tell you that *somewhe...

0|moonveil | [replaceComponents ERROR] ValidationError > s.nativeEnum(T)
0|moonveil | Expected the value to be a string or number
0|moonveil |
0|moonveil | Received:
0|moonveil | | undefined
0|moonveil |
0|moonveil | at _NativeEnumValidator.handle (/home/ubuntu/moonveil/node_modules/@sapphire/shapeshift/src/validators/NativeEnumValidator.ts:50:3)
0|moonveil | at _NativeEnumValidator.parse (/home/ubuntu/moonveil/node_modules/@sapphire/shapeshift/src/validators/BaseValidator.ts:126:2)
0|moonveil | at SeparatorBuilder.setSpacing (/home/ubuntu/moonveil/node_modules/@discordjs/builders/src/components/v2/Separator.ts:51:40)
0|moonveil | at Timeout._onTimeout (/home/ubuntu/moonveil/src/utils/replaceComponents.js2614)
0|moonveil | at listOnTimeout (node:internal/timers:581:17)
0|moonveil | at processTimers (node:internal/timers:519:7)
0|moonveil | [replaceComponents] Error editing message: TypeError: Cannot read properties of undefined (reading 'Caption')
0|moonveil | at Timeout._onTimeout (/home/ubuntu/moonveil/src/utils/replaceComponents.js:44:40)
0|moonveil | at listOnTimeout (node:internal/timers:581:17)
0|moonveil | at processTimers (node:internal/timers:519:7)

grizzled bison
sharp ginkgoBOT

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

dense jackal
grizzled bison
dense jackal what is line 26 of replaceComponents.js saying?

module.exports = function replaceComponents(message, {
timeout = 1 * 60 * 1000,
text = 'This menu has expired. Please use the command again.',
color = 0x2f3136
} = {}) {
if (!message || typeof message.edit !== 'function') {
console.log('[replaceComponents] Invalid message or no edit function');
return;
}

console.log([replaceComponents] Will edit message in ${timeout}ms);

setTimeout(async () => {
try {
console.log('[replaceComponents] Running timeout callback');

  const expiredContainer = new ContainerBuilder()
    .setAccentColor(color)
    .addTextDisplayComponents(
      new TextDisplayBuilder().setContent('# ![hr](https://cdn.discordapp.com/emojis/1374775456003526776.webp?size=128 "hr") Commands Expired')
    )
    .addSeparatorComponents(
      new SeparatorBuilder().setSpacing(SeparatorSpacingSize.Small).setDivider(true)
    )
    .addTextDisplayComponents(
      new TextDisplayBuilder().setContent(`*${text}*`)
    )
dense jackal

but I think you forgot to import SeparatorSpacingSize from the d.js package into your file

grizzled bison
dense jackal thats a lot for just 1 line... (and not what I asked)

line 26 empty

this full code

const {
ContainerBuilder,
TextDisplayBuilder,
SeparatorBuilder,
ThumbnailBuilder,
MessageFlags,
SeparatorSpacingSize,
TextDisplayStyle
} = require('discord.js');

module.exports = function replaceComponents(message, {
timeout = 1 * 60 * 1000,
text = 'This menu has expired. Please use the command again.',
color = 0x2f3136
} = {}) {
if (!message || typeof message.edit !== 'function') {
console.log('[replaceComponents] Invalid message or no edit function');
return;
}

console.log([replaceComponents] Will edit message in ${timeout}ms);

setTimeout(async () => {
try {
console.log('[replaceComponents] Running timeout callback');

  const expiredContainer = new ContainerBuilder()
    .setAccentColor(color)
    .addTextDisplayComponents(
      new TextDisplayBuilder().setContent('# ![hr](https://cdn.discordapp.com/emojis/1374775456003526776.webp?size=128 "hr") Commands Expired')
    )
    .addSeparatorComponents(
      new SeparatorBuilder().setSpacing(SeparatorSpacingSize.Small).setDivider(true)
    )
    .addTextDisplayComponents(
      new TextDisplayBuilder().setContent(`*${text}*`)
    )
    .addTextDisplayComponents(
      new TextDisplayBuilder().setContent('‎\n‎') // invisible spacer
    )
    .addTextDisplayComponents(
      new TextDisplayBuilder()
        .setContent('> gaeuly & moonveil')
        .setStyle(TextDisplayStyle.Caption)
    )
    .setThumbnailAccessory(
      new ThumbnailBuilder().setURL('https://cdn.discordapp.com/embed/avatars/0.png')
    );

  console.log('[replaceComponents] Editing message with expired container...');
  await message.edit({
    components: [expiredContainer],
    flags: MessageFlags.IsComponentsV2
  });

  console.log('[replaceComponents] Message edited successfully!');
} catch (error) {
  console.error('[replaceComponents] Error editing message:', error);
}

}, timeout);
};

dense jackal

are you on the latest d.js version?

grizzled bison

alr

grizzled bison
wary coral

@grizzled bison ~~this is at lest one of your issues use a separator

          new TextDisplayBuilder().setContent('‎\n‎') // invisible spacer
        )
```~~ NV this is not an issue
dense jackal

not true

wary coral

I thought discord trimmed white space or is that only for conent

dense jackal

the error is saying two things are wrong:

.setSpacing(SeparatorSpacingSize.Small)

error 1: value of SeparatorSpacingSize.Small is undefined (idk how that is)

.setStyle(TextDisplayStyle.Caption)

error 2: value of TextDisplayStyle is undefined, that is because there is no such thing as TextDisplayStyle, use # in front of it to make the text as heading

@grizzled bison ^

grizzled bison

I'm a little confused about which one is correct crySparkle

wary coral

while considering TextDisplayStyle is not real it is likely that

grizzled bison

wait ill try delete caption and spacing

dense jackal

> # header text with inline quote

steel trail
upbeat saffron
dense jackal

no I said that, but looks like I was wrong then

steel trail
upbeat saffron
steel trail

And does the everyone role have permission to ping that particular role?

steel trail

Because interaction followUps don't use the bot's permissions, that would've been a likely reason

upbeat saffron
steel trail

Yes. So there's the reason for your issue

Wait, no

upbeat saffron

ah okay so when I enable this for the bot it should wokrk?

steel trail

Not that

wary coral
upbeat saffron
steel trail
upbeat saffron

ah makes sense

wary coral
steel trail

Why are you asking me?

A followUp is not sent by the bot user

wary coral

It is Not?! Interesting

steel trail

It's a (interaction) webhook after all

wary coral

The more you know. I kind of just assumed that follow-up used the same permissions as the bot user

steel trail

I'm not 100% sure my statement still is accurate, it definitely was the case in the past. Double checking right now

sharp ginkgoBOT

dtypes v10: AuditLogEvent - MemberBanAdd
read more

leaden shuttle

how do i get all non-closed threads (even inactive ones)?

sharp ginkgoBOT
leaden shuttle

no i want NON closed

sharp ginkgoBOT
steel trail
leaden shuttle

oh whats the difference

steel trail

inactive === archived

there is archived and there is locked. which one you mean by "inactive" is ambigous I guess

but since you talk about non-closed inactive that only makes sense if you mean not locked but archived

leaden shuttle

okay i double checked i want all non locked

steel trail

then use those two methods, and filter all locked threads from the archived

leaden shuttle

oki ty

sand heart

can we set image size in Mediagallerybuilder

solid summit

has discord documented the gradient thing with roles?

proud arrow

No

solid summit
proud arrow

Again, no.
Also not the best place to ask

You can follow the pr on their github

solid summit
proud arrow

You can check on their github (discord-api-docs)

visual cobalt

has anyone else been getting this error?

/mnt/funsize/nodejsProjects/TTSBot/node_modules/@discordjs/voice/dist/index.js:531
    throw new Error(`No compatible encryption modes. Available include: ${options.join(", ")}`);
          ^
Error: No compatible encryption modes. Available include: aead_aes256_gcm_rtpsize, aead_xchacha20_poly1305_rtpsize
    at chooseEncryptionMode (/mnt/funsize/nodejsProjects/TTSBot/node_modules/@discordjs/voice/dist/index.js:531:11)
    at /mnt/funsize/nodejsProjects/TTSBot/node_modules/@discordjs/voice/dist/index.js:720:21
Emitted 'error' event on VoiceConnection instance at:
    at VoiceConnection.onNetworkingError (/mnt/funsize/nodejsProjects/TTSBot/node_modules/@discordjs/voice/dist/index.js:1898:10)
    at Networking.emit (node:events:518:28)
    at /mnt/funsize/nodejsProjects/TTSBot/node_modules/@discordjs/voice/dist/index.js:728:32
Node.js v20.11.1

it seems to only be happening in one vc in my server, I moved to a different one and it stopped

verbal vine

why webhook not working in this code

wary coral
verbal vine

okay wait

wary coral
verbal vine okay wait

If you are sending components as part of a webhook you'll need to use the ?with_components=true query param otherwise they'll be ignored.
per the Discord docs

dim estuary

How can you get the maximum amount of Auto-Mod rule for a server?

grizzled venture

Guys, what do I do if it takes 10 minutes exactly for the bot to rename a channel when a button is pressed?

zenith violet

you wait

The ratelimit is twice every 10 minutes

grizzled venture
grizzled venture

Guys, is it possible to make my bot respond to a command with a server custom emoji or no?

rose tangle

yeah, just use the correct format

coral hollow

If i wanted my command to have a randomized response, can it pull from a website?

grizzled venture
sharp ginkgoBOT

tag suggestion for @grizzled venture:

  • Custom emojis: \:name:<a:name:id>
  • Twemojis: \:name: ➞ unicode representation
  • Emoji picker: WIN + . / CMD + CTRL + SPACE / CTRL + .
  • Right-clicking any emoji will not copy its id!
rose tangle

discord is only concerned about you responding within 3s, whether with a full response or a defer

from where or how you pull your response doesn't concern them

coral hollow

Is there a certain way it has to be set up for a pull?

rose tangle

and you don't know how much time the fetch and parsing it will take

coral hollow

Is there a way i could set like all of the random responses, and have it pick a random one each time?

topaz bluff

I mean? Of course....but not with anything from DiscordJS...just with JavaScript

rose tangle

(and it's not part of the library)

at most there's the AttachmentBuilder which helps by accepting local file paths to send them as attachments

coral hollow

Okay

zealous knot

I was just about to mention the attachment builder. For some reason it seems to break randomly when using Bun, though it's totally fine with Node. Any particular reason as to why?

grizzled venture

@rose tangle The emoji is from the server. What am I doing wrong?
message.reply(If your item sells for \:robux: ${price.toFixed(2)}, you will keep \:robux ${afterTax.toFixed(2)} after a 30% tax.);

rose tangle

":name: ➞ <a:name:id>" means, if you have an emoji named "name", you can get the <a:name:id> format by sending a message in discord using the emoji, prefixed by \

crimson thistle

i've seen an interesting function in the discordjs/core from the GuildsAPI that says getMembers
can i use that or no?

rose tangle

why not?

crimson thistle

good question

grizzled venture
rose tangle

that you are not using the <a:name:id>

you're using :name:

crimson thistle

well because it says "GuildsAPI.getMembers is not a function"
this is the entire error:

TypeError: GuildsAPI.getMembers is not a function
    at Object.execute (D:\JX1DX1 bot\src\commands\testing purposes\get-servers.js:15:39)
    at D:\JX1DX1 bot\src\events\interactionCreate\commandHandler.js:20:30
    at Array.forEach (<anonymous>)
    at Object.execute (D:\JX1DX1 bot\src\events\interactionCreate\commandHandler.js:14:56)
    at Client.<anonymous> (D:\JX1DX1 bot\src\index.js:51:47)
    at Client.emit (node:events:519:35)
    at InteractionCreateAction.handle (D:\JX1DX1 bot\node_modules\discord.js\src\client\actions\InteractionCreate.js:97:12)
    at module.exports [as INTERACTION_CREATE] (D:\JX1DX1 bot\node_modules\discord.js\src\client\websocket\handlers\INTERACTION_CREATE.js:4:36)
    at WebSocketManager.handlePacket (D:\JX1DX1 bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:351:31)
    at WebSocketManager.<anonymous> (D:\JX1DX1 bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:235:12)

Node.js v24.2.0
zealous knot
rose tangle you'll have to ask bun

I have. They've reviewed how the attachment builder works and can't locate anything runtime dependent that would potentially break it. Also, it's not a consistent issue. Sometimes it happens, sometimes it doesn't happen at all

coral hollow

Is there something i can see everything djs can do? Like an index?

grizzled venture
rose tangle
crimson thistle
grizzled venture

@rose tangle Discord keeps editing it wrongly. Tho this how it says:

rose tangle
sharp ginkgoBOT

documentation suggestion for @crimson thistle:
method GuildMemberManager#fetch() discord.js@14.19.3
Fetches member(s) from a guild.


// Fetch all members from a guild
guild.members.fetch()
  .then(console.log)
  .catch(console.error);

rose tangle

do consider it'll take a long while in large guilds

since they come in batches through the gateway

rose tangle

I'd suggest finding an alternative

crimson thistle

i assume that there's not a way of getting all the members from a guild that my bot is not in?

rose tangle

correct

crimson thistle

shucks

grizzled venture
rose tangle

then don't put the a

just <:robux:id>

if you send a message with \:name: it'll give you the correct format

topaz bluff
mellow sierra

how to check user tag?

dire rose
grizzled venture
mellow sierra

👍

grizzled frost

How can I synchronize prefix commands for music bots that use the same prefix as the Jockie Music bot?

rose tangle

how is that djs related?

sand heart

how to set the container color

sharp ginkgoBOT
warm elk

Can my bot track when someone appears in the pending list (join applications)?

zenith violet
warm elk

but is possible?

rose tangle

not with djs, it doesn't have undocumented features

ocean portal

is this verison bugged?? it always say client is undefined when it is not

15.0.0-dev```
rose tangle

I mean, that sounds like a js error, not a djs one

and this channel is for v14, not the in-development v15 version

ocean portal

how so?? everyone i asked was confused

rose tangle

and why are you using the dev version in the first place

rose tangle
ocean portal

nvm ill try
cya

rose tangle

you specifically specified the dev version in order to get the dev version

ocean portal

alright

rose tangle

but if the error is the js one then that won't solve your issue either way duckshrug

grave pond

When will the primary_guild key will be able to sense update in updateevent?
Cuz via api it works but via presencedetect or memberupdate it doesn't work

bleak owl

d.js doesn’t support it yet that’s why

grave pond

When will that thing come 😭

bleak owl

whenever it’s documented and finished

rose tangle

(by discord)

grave pond

I tried to do it via api call and presence update bot got ratelimited for 50 minutes 💀

grave pond
shut sphinx

how i can get the tag with djsv14?

rose tangle
rose tangle
shut sphinx

now I am making a system like this, when the user gets the clan tag of the specified server, it will give him a role.

shut sphinx

oh oky

grave pond
shut sphinx
rose tangle

if you plan to pull data constantly that'll easily get you ratelimited

the real way would be through a gateway event

maybe it currently works or maybe it doesn't, I'd advise just waiting for it to fully release

grave pond
grave pond
shut sphinx

@rose tangleWe can do this system in d.py, but can we make an api with d.py and transfer that api to d.js?

rose tangle

what?

grave pond
shut sphinx
rose tangle

right, I wasn't asking you to copy and paste your message

rose tangle

I was asking you to elaborate in an understandable one

"make an api in d.py and transfer that api to d.js" makes no sense

sharp ginkgoBOT

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

shut sphinx

nvm

sharp ginkgoBOT

guide Slash Commands: Advanced command creation
read more

polar karma
grave pond
client.on('raw', async (packet) => {
  if (packet.t !== 'PRESENCE_UPDATE') return;

  const db = global.mongoClient.db('discordBot');
  const guildTags = db.collection('guildTags');
  const userTags = db.collection('userTags');

  const data = packet.d;
  const user = data.user;
  const userId = user?.id;
  if (!userId) return;

  const newTag = user?.primary_guild?.tag || user?.clan?.tag;
  if (!newTag) return;

  const previous = await userTags.findOne({ userId });
  const oldTag = previous?.lastTag || null;

  if (oldTag === newTag) return;

  await userTags.updateOne(
    { userId },
    { $set: { lastTag: newTag, lastUpdated: new Date() } },
    { upsert: true }
  );

  const logChannel = await client.channels.fetch('1386102430961373194').catch(() => null);
  if (logChannel?.isTextBased()) {
    const embed = {
      title: '🛡️ Guild Tag Changed',
      description: `<@${userId}> updated their primary guild tag.`,
      color: 0x00b0f4,
      fields: [
        {
          name: '👴 Old Tag',
          value: oldTag || 'None',
          inline: true
        },
        {
          name: '🆕 New Tag',
          value: newTag,
          inline: true
        }
      ],
      timestamp: new Date().toISOString()
    };
    await logChannel.send({ embeds: [embed] });
  }

  for (const [guildId, guild] of client.guilds.cache) {
    const tagDoc = await guildTags.findOne({ guildId, name: newTag.toUpperCase() });
    if (!tagDoc) continue;

    const member = await guild.members.fetch(userId).catch(() => null);
    if (!member) continue;

    const role = guild.roles.cache.get(tagDoc.roleId);
    if (!role) continue;

    if (!member.roles.cache.has(role.id)) {
      await member.roles.add(role).catch(() => {});
    }
  }
});

Uhh its spamming same update

crimson gale

yeah, that's not the right one

tags have nothing to do with the presence

grave pond

Why? On presenceupdate also it is spamming

rose tangle

also you're pretty much on your own supporting and maintaining undocumented features duckshrug

grave pond
crimson gale

you are wrong

grave pond
crimson gale

again, the tag has nothing to do with the presence. the tag is part of the inner user payload of a guild member update

steel trail

And presence update emits for every guild your bot shares with the user (to answer the second part of your question)

grave pond

Oh guildMember update

crimson gale

what amgelo said is also a good point - you are now in raw API, even undocumented raw API territory
you are on your own with this

grave pond

But why my normal presence uodate also spamming when user going offline to online

client.on('presenceUpdate', async (oldPresence, newPresence) => {
  const userId = newPresence.userId;
  if (userId !== '807961656306040854') return;

  const channel = await client.channels.fetch('1386102430961373194');
  if (!channel || !channel.isTextBased()) return;

  const oldStatus = oldPresence?.status || 'unknown';
  const newStatus = newPresence?.status || 'unknown';

  if (oldStatus !== newStatus) {
    const embed = {
      title: '📶 Presence Status Changed',
      description: `<@${userId}> updated their status.`,
      color: 0x00b0f4,
      fields: [
        {
          name: '📴 Old Status',
          value: oldStatus,
          inline: true,
        },
        {
          name: '📶 New Status',
          value: newStatus,
          inline: true,
        },
      ],
      timestamp: new Date().toISOString(),
    };

    await channel.send({ embeds: [embed] });
  }
});

What can I do for this issue?

Idk why is it spamming 😭

crimson gale

i would recommend re-reading the responses above

grave pond
crimson gale

tbf, the same is true for guild member updates, if the inner user changes - also gets emitted per shared guild

grave pond

I forgot to read that sorry

Now what can I do for that about spam?

rose tangle

I haven't worked with presenceUpdate but I'd implement a debouncer

maybe there's an easier way, though it should be straightforward

crimson gale

probably limit your logging to one guild / log it on the guild it affects

grave pond

If I use cache mechanism would that resolve this issue?

rose tangle

I think a better question would be, what are you specifically trying to implement

rose tangle
grizzled bison

any1 can help me with my error?

bleak owl
grave pond
rose tangle

so you do want to spy on someone?

or why specifically do you only need to filter one user

and send it to a specific channel

grave pond

Right now that's why I'm testing on myself only rn

rose tangle

Thonk so each user opts in for their presence to be logged in a given channel? why would they opt in to that?

grave pond

See like this

Its not to spy on someone 😭
Just working on logs

grizzled bison
l0|moonveil  | [UNCAUGHT send] CombinedError (2)
0|moonveil  |   Received one or more errors
0|moonveil  |   1 ExpectedValidationError > s.instance(V)
0|moonveil  |   |   Expected
0|moonveil  |   |
0|moonveil  |   |   Expected:
0|moonveil  |   |   | [Function: ButtonBuilder]
0|moonveil  |   |
0|moonveil  |   |   Received:
0|moonveil  |   |   | undefined
0|moonveil  |   2 ExpectedValidationError > s.instance(V)
0|moonveil  |   |   Expected
0|moonveil  |   |
0|moonveil  |   |   Expected:
0|moonveil  |   |   | [Function: ThumbnailBuilder]
0|moonveil  |   |
0|moonveil  |   |   Received:
0|moonveil  |   |   | undefined
0|moonveil  |     at _UnionValidator.handle (/home/ubuntu/moonveil/node_modules/@sapphire/shapeshift/src/validators/UnionValidator.ts:9:57)
0|moonveil  |     at _UnionValidator.parse (/home/ubuntu/moonveil/node_modules/@sapphire/shapeshift/src/validators/BaseValidator.ts:126:2)
0|moonveil  |     at SectionBuilder.toJSON (/home/ubuntu/moonveil/node_modules/@discordjs/builders/src/components/v2/Section.ts:150:34)
0|moonveil  |     at /home/ubuntu/moonveil/node_modules/@discordjs/builders/src/components/v2/Container.ts:236:61
0|moonveil  |     at Array.map (<anonymous>)
0|moonveil  |     at ContainerBuilder.toJSON (/home/ubuntu/moonveil/node_modules/@discordjs/builders/src/components/v2/Container.ts:236:32)
0|moonveil  |     at /home/ubuntu/moonveil/node_modules/discord.js/src/structures/MessagePayload.js:151:46
0|moonveil  |     at Array.map (<anonymous>)
0|moonveil  |     at MessagePayload.resolveBody (/home/ubuntu/moonveil/node_modules/discord.js/src/structures/MessagePayload.js:150:49)
0|moonveil  |     at TextChannel.send (/home/ubuntu/moonveil/node_modules/discord.js/src/structures/interfaces/TextBasedChannel.js:189:32)

how to fix this

grave pond
rose tangle

I'm trying to understand what your feature is, to be able to suggest what would be a good approach

rose tangle
rose tangle

sections need an accessory

if you don't set one, the section is pointless, hence why it's not allowed

just add the text displays directly in the container at that point

grave pond

Ok basically I'm trying to use presenceupdate feature to like track like user activities about like they are doing coding in vs code going offline going online
It will be like fully customizable(not to spy on someone 😭)

I was trying to do it from yesterday but it is logging multiple times and as I got told that it would run for every server bot shares with user so how can I limit it to 1 user?

The user in code is me and the channel in code is for testing

rose tangle

but if each server would have their own logging channel, then it sounds like you do want the event to log for each server

grave pond

I'm just looking for a way to make it run once instead of 50 servers

grave pond
rose tangle

then filter by the guild/server

sharp ginkgoBOT
rose tangle

but later on you'll probably want to not filter, but instead use the guild to fetch their logging channel

grave pond

Is there a link to the docs website?

rose tangle

to what part?

rose tangle
grave pond

discordjs.guide ?

rose tangle

there isn't a guide on how to log user presences

grave pond

I have to use like

client.on('GuildMember')

Right?

rose tangle

you already shared code above though? I'm not sure what you're looking for

grave pond

Nvm I'm tired for now will reread all messages in morning and will take help from friends also to figure out what I'm trying to do

prisma ruin

how do i check if a message was sent by a webhook ?

hallow mesa

Check whether it .webhookId is not null. Note this includes interaction webhooks, so you'd need to filter those out if you don't want them

hallow mesa

When you respond to an interaction you are doing so through a webhook

wary coral
crimson gale

author bot true and discriminator 0000 should work

for now apps are not moved to the unique username system so should always have a non 0000 discriminator

prisma ruin

so
if(msg.author.bot)
{
if(message.author.tag == 0000){
//dwadwdw
}
}

hallow mesa

.discriminator, not .tag, and the 0000 should be in quotes since it's a string

prisma ruin

.discriminator doesnt exist in author

hallow mesa

Message.author is a User, so it does

prisma ruin

not showing up in my IDE, let me restart rq

crimson gale

webhookId combined with not applicationId might be the better approach the more i think about it firT

unless the hook was created by an app, then it might have that firT

maybe hook and not interaction metadata?
this is surprisingly annoying

prisma ruin

lmao, all g, im handling this under MessageCreate, would there be interactions attached to the messages?

oh yeah, just seen interactionMetadata, ill run that

hallow mesa

There could be, if the message came from an interaction (like a user using any non-ephemeral command, for example)

ocean portal

i just created another sub command and the old one disappeared with no errors
why?

burnt wolf

Hi Guys Onde Help

import { Client, GatewayIntentBits, Collection } from "discord.js";
import { config } from "dotenv";
import fs from "node:fs";
import path from "node:path";

config();


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

client.commands = new Collection();

function getAllCommandFiles(dirPath: string, arrayOfFiles: string[] = []) {
  const files = fs.readdirSync(dirPath);
  for (const file of files) {
    const fullPath = path.join(dirPath, file);
    if (fs.statSync(fullPath).isDirectory()) {
      getAllCommandFiles(fullPath, arrayOfFiles);
    } else if (file.endsWith(".ts") || file.endsWith(".js")) {
      arrayOfFiles.push(fullPath);
    }
  }
  return arrayOfFiles;
}

const commandsPath = path.join(__dirname, "commands");
const commandFiles = getAllCommandFiles(commandsPath);

for (const file of commandFiles) {
  const command = require(file);
  if ("data" in command.default && "execute" in command.default) {
    client.commands.set(command.default.data.name, command.default);
  } else {
    console.warn(`[WARN] Comando inválido em: ${file}`);
  }
}

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

for (const file of eventFiles) {
  const event = require(path.join(eventsPath, file));
  if (event.default.once) {
    client.once(event.default.name, (...args) => event.default.execute(...args, client));
  } else {
    client.on(event.default.name, (...args) => event.default.execute(...args, client));
  }
}

client.login(process.env.DISCORD_TOKEN);

in my ts is return this error

Property 'commands' does not exist on type 'Client<boolean>'.
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.

red coral

Does djs have a helper function for mentioning commands?

hallow mesa
sharp ginkgoBOT
red coral

cheers

ocean portal
hallow mesa Probably overwriting it. Show the command builder?

the one that dissapeared after new one:

const { Discord, SlashCommandBuilder, EmbedBuilder } = require("discord.js");

module.exports = {
data: new SlashCommandBuilder()
    .setName('entertainment')
    .setDescription('entertainment purpose command, used to have fun.')
    .addSubcommand(sub =>
      sub
        .setName('facepalm')
        .setDescription('Sends a facepalm Image (API)')
    ...```

the new one: 
```js
const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
    .setName('entertainment')
    .setDescription('entertainment purpose command, used to have fun.')
    .addSubcommand(sub =>
      sub
        .setName('nekos')
        .setDescription('Sends a Nekos (API)')
    )```
hallow mesa

Put both subcommands on the same builder. You're probably setting them both to the same collection, which means the last will replace all previous ones

ocean portal

wow... no way to fix it?

bleak owl

they just gave you a way to fix it... waitWhat

ocean portal

??

glossy field

huh

bleak owl
ocean portal

i want both /entertainment ...
why just 1

bleak owl

so put them in the same builder

as said

ocean portal
hallow mesa

Call .addSubcommand twice. Once for each subcommand. On the same builder

ocean portal

isnt both gonna have the same code or what

hallow mesa

Well then you check which subcommand it is and handle it accordingly

ocean portal

?

hallow mesa

?

bleak owl
.addSubcommand(sub =>
     // code
    )
.addSubcommand(sub =>
    // code
    ),
hallow mesa

Without the first comma

glossy field
bleak owl

what message

ocean portal
bleak owl

what?

do you understand what to do here?

glossy field
bleak owl

And if you're curious how this message was built, check out the source code!

ocean portal
bleak owl

in your code?

lol

hallow mesa

Put the second one under the first one, as they showed

glossy field
bleak owl

the source code is literally in that message

ocean portal
bleak owl in your code?

like this?

module.exports = {
    data: new SlashCommandBuilder()
    .setName('entertainment')
    .setDescription('entertainment purpose command, used to have fun.')
.addSubcommand(sub =>
      sub
        .setName('nekos')
        .setDescription('Sends a Nekos (API)'),
        // code
)

.addSubcommand(sub =>
      sub
        .setName('facepalm')
        .setDescription('Sends a facepalm image (API)'),
        // code
),
};```

         i didnt really under what u were saying
bleak owl

thats what we were saying

remove the //code

it was an example

even the guide has a section on subcommands, which i believe i sent for you and shows how to put multiple subcommands

that also shouldn't really be the whole file. usually your command's functionality go in the same file unless your handler handles commands differently

im just basing it off of what our guide suggests

ocean portal
bleak owl

why not?

unique shoal

lol what

ocean portal

mostly undefined

unique shoal

again what

bleak owl

i find it hard to believe you are following the guide properly

what is undefined here?

burnt wolf
burnt wolf Hi Guys Onde Help ```ts import { Client, GatewayIntentBits, Collection } from "...

Create a custom type

import { Client, Collection, GatewayIntentBits, SlashCommandBuilder, CommandInteraction } from "discord.js";

export interface Command {
  data: SlashCommandBuilder;
  execute: (interaction: CommandInteraction) => Promise<void>;
}

export class CustomClient extends Client {
  public commands: Collection<string, Command>;

  constructor() {

    super({ intents: [GatewayIntentBits.Guilds] });
    this.commands = new Collection();
  }
}
``` ands work
stable sun

Unless you cast it. You might be better off augmenting the module as per the second suggestion.
Imo, you should just manage it in a separate DI solution. It’s too easy to override an existing property on a class and mess up the entire lib

trim elm
glossy field

ah so you need to use files: [] for file builders to work, gotcha

trail fog

do dropdowns not support custom emojis?

rose tangle

they do next to the label

just not inside the label itself

there's a separate emoji field

sharp ginkgoBOT
deft ermine
toxic moat
toxic moat

hi guys, im wrong? when im reacting to one message, nothing in console

    console.log(reaction.emoji.id)
})```
snow onyx
toxic moat
snow onyx

post your client constructor

toxic moat
snow onyx post your client constructor
    intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.MessageContent,
        GatewayIntentBits.GuildMembers,
        GatewayIntentBits.GuildMessageReactions,
    ]
});
snow onyx

You most likely also need the Message and Reaction partial.

sharp ginkgoBOT

guide Popular Topics: Partial Structures
read more

toxic moat

works now, thx

another question, cant do ephemeral right?

                return await reaction.message.channel.send({
                    content: 'Your discord account must be at least 6 months old to register.!',
                    flags: [MessageFlags.Ephemeral]
                });```
loud quartz

Can't send an ephemeral, no

Those exist only as a response to an interaction

dim estuary

Hey yall, quick question:

Can you have a filter and lifetime options for sweepers and it will remove if the lifetime is reached or the filter matches?

golden urchin

Problem: I've just started using djs, but am receiving a network error whenever I try to run index.js (code below). I am using WSL Ubuntu on a windows computer. This is the same computer I use for work as a backend dev and don't experience network issues or performance issues during that.

import { Client, Events, GatewayIntentBits } from 'discord.js';
import { token } from './config.json';
const client = new Client({ intents: [GatewayIntentBits.Guilds] });

client.on(Events.ClientReady, readyClient => {
  console.log(`Logged in as ${readyClient.user.tag}!`);
});

client.on(Events.ShardError, error => {
    console.error('A websocket connection encountered an error:', error);
});

console.log(token)

client.login(token).catch(console.error)

**Error Log: **

tsx index.ts in bash at 20:46:49
{EXPECTED TOKEN IS OUTPUT HERE}
ConnectTimeoutError: Connect Timeout Error (attempted address: discord.com:443, timeout: 10000ms)
    at onConnectTimeout (/home/jack/src/personal/discord-community-playlist/src/node_modules/.pnpm/undici@6.21.3/node_modules/undici/lib/core/connect.js:237:24)
    at Immediate._onImmediate (/home/jack/src/personal/discord-community-playlist/src/node_modules/.pnpm/undici@6.21.3/node_modules/undici/lib/core/connect.js:206:11)
    at process.processImmediate (node:internal/timers:478:21) {
  code: 'UND_ERR_CONNECT_TIMEOUT'
}

Steps I've taken so far:

  • Ran ping discord.com to check the connection. This was the output:
PING discord.com (162.159.138.232) 56(84) bytes of data.
64 bytes from 162.159.138.232: icmp_seq=1 ttl=57 time=4.19 ms
...
64 bytes from 162.159.138.232: icmp_seq=7 ttl=57 time=4.16 ms
^C64 bytes from 162.159.138.232: icmp_seq=8 ttl=57 time=8.90 ms

--- discord.com ping statistics ---
8 packets transmitted, 8 received, 0% packet loss, time 65155ms
rtt min/avg/max/mdev = 3.045/5.456/8.898/1.718 ms
  • ran sudo ufw status it was offline
  • restarted my system

I'm unsure how to proceed

toxic moat

guys, why the bot remove completely the emoji button react? i want to remove only the reaction has triggered the client.on('messageReactionAdd')

            if (!isSixMonthPassed) {
                text.setContent('## Your discord account must be at least 6 months old to register!');
                container.addTextDisplayComponents(text)
                await userDM.send({
                    components: [container],
                    flags: [MessageFlags.Ephemeral, MessageFlags.IsComponentsV2]
                });
                return await reaction.remove()
            };```
snow onyx

then use reaction.users.remove(user)
reaction.remove() removes all reactions to that emoji

toxic moat
pearl hazel

does forword message read as sent message ?

crimson gale

yes

pearl hazel

its not content: '', it's empty how can i get to it's content

snow onyx

I believe it was messageSnapshots?

sharp ginkgoBOT
feral thunder

Is a PrimaryEntryPoint application command supposed to trigger the interactionCreate event? If yes, does it trigger right after the command was executed or does it await the successful launch of the activity first?

Asking this because it is not triggering the event for me 🤔

e.g. this "Play" button, runs /Play after pressing

feral thunder

Oh I see

Thanks

polar flare

Does anyone know why my app shows "The application did not respond" in a guild it's not a member of (user-installed), but works fine in a guild where it is a member? Nothing has changed - everything is the same. This issue suddenly started around 3 hours ago.

verbal mica

Does anyone know of a public API link or endpoint to get Guild Tag data from a user, such as: "Seeing when a user claims or changes their tag"?

crimson gale

tags are not yet documented so you will ahve to use raw api requests/events to read it - change emits guild member update per shared server

rose tangle

editReply but only up to 15m, if the message isn't ephemeral and the bot is in the server, it can edit the message directly with Message#edit()

could be that you have a lower node version in your server?

followUp returns the message, you can then pass that to editReply

sharp ginkgoBOT
burnt wolf

i Create a new command but i hour i go to test the command is not showing.

rose tangle

did you run the deploy script?

burnt wolf

i testing in local.

polar flare

So I have a question about ratelimits, how many bans can I perform in a single guild until it hits ratelimit? Does anyone have a approximate number for me?

sharp ginkgoBOT

Ratelimits are dynamically assigned by the API based on current load and may change at any point.

  • The scale from okay to API-spam is sliding and depends heavily on the action you are taking
  • Rainbow roles, clock and counter channels, and DM'ing advertisements to all members are all examples of things that are not okay
burnt wolf
rose tangle
burnt wolf
rose tangle

do you mean the guide?

if yes, then it is there

sharp ginkgoBOT

guide Creating Your Bot: Registering slash commands
read more

burnt wolf

hmm....

In my index.ts there is a similar code



const client = new CustomClient();

client.commands = new Collection();

function getAllCommandFiles(dirPath: string, arrayOfFiles: string[] = []) {
  const files = fs.readdirSync(dirPath);
  for (const file of files) {
    const fullPath = path.join(dirPath, file);
    if (fs.statSync(fullPath).isDirectory()) {
      getAllCommandFiles(fullPath, arrayOfFiles);
    } else if (file.endsWith(".ts") || file.endsWith(".js")) {
      arrayOfFiles.push(fullPath);
    }
  }
  return arrayOfFiles;
}

const commandsPath = path.join(__dirname, "commands");
const commandFiles = getAllCommandFiles(commandsPath);
let sucessFiles = 0;
const errors: string[] = [];

for (const file of commandFiles) {
  try {
    const imported = require(file);
    const command = imported.default ?? imported;

    if ("data" in command && "execute" in command) {
      client.commands.set(command.data.name, command);
      sucessFiles++;
    } else {
      errors.push(`⚠️ Inválido (falta data/execute): ${file}`);
    }
  } catch (err: any) {
    errors.push(`❌ Erro ao carregar ${file}: ${err.message}`);
  }
}

// Exibe resumo dos comandos carregados
console.log(chalk.magenta.bold("[INFO]") + ` - Comandos carregados : ${sucessFiles}`)
if (errors.length > 0) {
 console.log(chalk.green.bold("[ERROR]") + ` - Erro ao carregar os comandos : ${errors}`);
  for (const e of errors) console.error(e);
}

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

for (const file of eventFiles) {
  const event = require(path.join(eventsPath, file));
  if (event.default.once) {
    client.once(event.default.name, (...args) =>
      event.default.execute(...args, client)
    );
  } else {
    client.on(event.default.name, (...args) =>
      event.default.execute(...args, client)
    );
  }
}
```\
rose tangle

that doesn't do the same thing as the deploy script

it's missing the last half of it

the part that actually deploys the commands

burnt wolf

this part you say

// Construct and prepare an instance of the REST module
const rest = new REST().setToken(token);

// and deploy your commands!
(async () => {
    try {
        console.log(`Started refreshing ${commands.length} application (/) commands.`);

        // The put method is used to fully refresh all commands in the guild with the current set
        const data = await rest.put(
            Routes.applicationGuildCommands(clientId, guildId),
            { body: commands },
        );

        console.log(`Successfully reloaded ${data.length} application (/) commands.`);
    } catch (error) {
        // And of course, make sure you catch and log any errors!
        console.error(error);
    }
})();```

i can just write this part adaptate in main index.ts or best soluction is create a new file and run separete ?

zenith violet
burnt wolf

i go to remove in my index.ts to best organization

rose tangle
burnt wolf

Just create a new file separate with the code

const { REST, Routes } = require('discord.js');
const { clientId, guildId, token } = require('./config.json');
const fs = require('node:fs');
const path = require('node:path');

const commands = [];
// Grab all the command folders from the commands directory you created earlier
const foldersPath = path.join(__dirname, 'commands');
const commandFolders = fs.readdirSync(foldersPath);

for (const folder of commandFolders) {
    // Grab all the command files from the commands directory you created earlier
    const commandsPath = path.join(foldersPath, folder);
    const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
    // Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment
    for (const file of commandFiles) {
        const filePath = path.join(commandsPath, file);
        const command = require(filePath);
        if ('data' in command && 'execute' in command) {
            commands.push(command.data.toJSON());
        } else {
            console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
        }
    }
}

// Construct and prepare an instance of the REST module
const rest = new REST().setToken(token);

// and deploy your commands!
(async () => {
    try {
        console.log(`Started refreshing ${commands.length} application (/) commands.`);

        // The put method is used to fully refresh all commands in the guild with the current set
        const data = await rest.put(
            Routes.applicationGuildCommands(clientId, guildId),
            { body: commands },
        );

        console.log(`Successfully reloaded ${data.length} application (/) commands.`);
    } catch (error) {
        // And of course, make sure you catch and log any errors!
        console.error(error);
    }
})();```

and run ?
rose tangle

well you'll need to adapt it to your own code

given you created your commands in a different way as the guide

lean harbor

Hello
I have question about the new enhanced roles system
is it available in discord js or not yet ?
I mean can I make roles with colors using my bot (let's say I want 150 new gradient colors)

zenith violet

it is not yet documented by discord

lean harbor

Ok
Thank you

burnt wolf

i create a deplou command but not workin.

import { REST, Routes, SlashCommandBuilder } from "discord.js";
import config from "../config.json";
import fs from "node:fs";
import path from "node:path";

// Definindo o tipo do comando
interface Command {
  data: SlashCommandBuilder;
  execute: Function;
}

const commands: Command[] = [];

// Pega todos os arquivos de comandos dentro da pasta de comandos
const commandsPath = path.join(__dirname, "commands");

// Função para ler arquivos de forma recursiva
function readCommands(dir: string) {
  const files = fs.readdirSync(dir);
  for (const file of files) {
    const fullPath = path.join(dir, file);
    const stat = fs.statSync(fullPath);
    if (stat.isDirectory()) {
      readCommands(fullPath); // Chama recursivamente para subpastas
    } else if (file.endsWith(".ts")) {
      const command = require(fullPath);
      if ("data" in command && "execute" in command) {
        commands.push(command.data.toJSON());
      } else {
        console.log(
          `[WARNING] Comando não possui 'data' ou 'execute': ${fullPath}`
        );
      }
    }
  }
}

readCommands(commandsPath);

// Criando instância do REST para fazer chamadas à API do Discord
const rest = new REST().setToken(config.token);

// Função de deploy
(async () => {
  try {
    console.log(`Iniciando o registro de ${commands.length} comandos.`);

    // O método PUT é usado para atualizar todos os comandos de uma vez
    const data = await rest.put(
      Routes.applicationCommands(config.clientId), // Para comandos globais
      { body: commands } // Dados dos comandos
    );

    console.log(`Comandos registrados com sucesso: ${commands.length}`);
  } catch (error) {
    console.error("Erro ao registrar comandos:", error);
  }
})();

and message to erro.

[WARNING] Comando não possui 'data' ou 'execute': C:\dev\AusTV\Ticket-Bot\src\commands\hello\hello.ts
Iniciando o registro de 0 comandos.
Comandos registrados com sucesso: 0
lyric laurel

did i miss a change

import {
    ActionRowBuilder,
    ButtonBuilder,
    ButtonStyle,
    EmbedBuilder,
    type Message,
} from "discord.js";

yeah I'm seeing this for

PermissionFlagsBits
RESTPostAPIChatInputApplicationCommandsJSONBody
Routes
ButtonStyle
hallow mesa
burnt wolf
import { SlashCommandBuilder, CommandInteraction } from 'discord.js';

export default {
  data: new SlashCommandBuilder()
    .setName('hello')
    .setDescription('Saúda o usuário'),
  async execute(interaction: CommandInteraction) {
    await interaction.reply(`👋 Olá, ${interaction.user.username}!`);
  },
};```
polar flare

What could be the cause that my bot randomly went offline but showed no errors at all. Yes no hoster issues or anything

hallow mesa
lyric laurel
burnt wolf
hallow mesa

console.log(command)

burnt wolf
hallow mesa console.log(command)

return this message

{
  default: {
    data: SlashCommandBuilder {
      options: [],
      name: 'hello',
      name_localizations: undefined,
      description: 'Saúda o usuário',
      description_localizations: undefined,
      contexts: undefined,
      default_permission: undefined,
      default_member_permissions: undefined,
      dm_permission: undefined,
      integration_types: undefined,
      nsfw: undefined
    },
    execute: [Function: execute]
  }
}
[WARNING] Comando não possui 'data' ou 'execute': C:\dev\AusTV\Ticket-Bot\src\commands\hello\hello.ts```
hallow mesa

ID works too

hallow mesa