#djs-help-v14

78874 messages · Page 31 of 79

obtuse gyro

Can someone please sanity check this, for some reason the actionRow gives the error TypeError: Cannot read properties of undefined (reading 'toJSON') and im too tired to see why lol

message.addTextDisplayComponents([
    (textDisplay: Discord.TextDisplayBuilder)=> textDisplay
        .setContent(`## What is the airspeed velocity of an unladen swallow?`)
])
message.addActionRowComponents((actionRow: Discord.ActionRowBuilder) => {
    actionRow.setComponents(
        new Discord.StringSelectMenuBuilder()
            .setCustomId("teams-events-trivia")
            .setPlaceholder("Select an Answer")
            .setOptions([
                new Discord.StringSelectMenuOptionBuilder()
                    .setLabel("An African or European swallow?")
                    .setValue("1"),
                new Discord.StringSelectMenuOptionBuilder()
                    .setLabel("42MPH")
                    .setValue("2"),
                new Discord.StringSelectMenuOptionBuilder()
                    .setLabel("What?")
                    .setValue("3"),
            ])
    )
})
hallow mesa

Remove the curlies around actionRow. With them the function that you're passing to .addActionRowComponents() doesn't return anything.

obtuse gyro

right of course thank you

RamiLaugh 4am peak coding hours does have its drawbacks, cheers

rose tangle

npm ls discord.js

bronze hill
rose tangle

then @discordjs/rest

bronze hill

@discordjs/rest@2.5.1

rose tangle

huh, actually rest should be completely unaffected

can you show the full stacktrace?

bronze hill

Error: Expected token to be set for this request, but none was present
at _REST.resolveRequest (/app/node_modules/@discordjs/rest/dist/index.js:1367:15)
at _REST.queueRequest (/app/node_modules/@discordjs/rest/dist/index.js:1327:46)
at _REST.request (/app/node_modules/@discordjs/rest/dist/index.js:1293:33)
at _REST.post (/app/node_modules/@discordjs/rest/dist/index.js:1267:17)
at Object.execute (/app/commands/edit_submission.js:77:28)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
at async /app/index.js:120:21

at index.js it's just the exec function

rose tangle

are you using setToken anywhere?

bronze hill

just did a ctrl+f on the github, only one place

rose tangle

which is?

bronze hill

top of the file, here

rose tangle

why let and not const?

bronze hill

no particular reason

should I make it const just to be sure or smth

rose tangle

yeah, just in case it's not being overwritten somewhere

I'd also make sure that .env variable is actually present before setting it

bronze hill

well it's def present, since the bot works for like at least a few hours before that happens

rose tangle

maybe it's being overwritten somewhere then

bronze hill

or well, sometimes a few hours, sometimes longer, its kinda random. I'll try the const thing just to be certain

I'll ping you some other time if that doesn't end up working if you're fine with that

rose tangle

sure, though there's usually always someone here, not just me

bronze hill

ah alright then

jade portal

Can we get a user id from its username. (@username doesn't work for tagging an user)

rose tangle

you can't

how did you get their username and not their id though?

jade portal
rose tangle you can't

There's no way?? Suppose a command !kick <username> if I don't have their how will I kick the user??

rose tangle
  • wouldn't happen with slash commands with a user option
  • why would they type their username instead of mentioning them?
  • users != members, you can't search a user from its username, but you can search a member by that
jade portal
rose tangle

what about the rest of the points though

jade portal
rose tangle

then they'd like a slash command

jade portal

Nope!

rose tangle

why?

jade portal

They feel prefixed commands are more easy to use!

rose tangle

I really doubt that, given a slash command would give you full autocomplete

but anyways, it's up to you I guess, it's getting out of topic

sharp ginkgoBOT
rose tangle

you can use that to search members

I'd recommend adding some kind of confirmation step though

jade portal

Ok thanks!

rose tangle

just so the user confirms it's the user they wanted to target

amber mango
jade portal They feel prefixed commands are more easy to use!

You could reply with an user selection menu, when users type !rob for example - that's the most user friendly solution i'd say, especially if you dont want to use SlashCommands or ContextMenuCommands (which would be an option for something like rob aswell)

elfin basin

is channel.messages.fetch() with a before message id sequetial in fetching?

given a limit i mean so if i give a fetch limit of 100 before this message id, will it be ordered by time sent?

snow onyx

it should be, yes

elfin basin

got it thanks

hazy agate

is there a way to fetch members in a guild by username?

dry whale

interaction.guild doesnt exist anymore?

crimson gale
dry whale

its a ApplicationCommandType.ChatInput

it was sent in a guild

and im using "discord.js": "^14.18.0",

zenith violet

do you have the Guilds intent

And is the app added with the bot scope

dry whale
upbeat saffron

how do i access the value of an unselected role in a roleselectmenu?

steel trail

By filtering the selected roles from all existing roles.

upbeat saffron
steel trail

No. You get the values that are selected now. If you need to work based on previous state you need to store that state yourself somehow

What's the use case here?

upbeat saffron
steel trail What's the use case here?

I thought so. I was hoping there would be a way to access the unselected ones as well.
The use case here is that users can assign and remove roles themselves. However, there are roles that should not be filtered out, because if I go through the user's roles, compare which ones were not selected, and then remove them, roles that they did not select would disappear.

So I thought I would also get the information that was deselected.

And if I do it with my own state, I also have to make sure that it survives a bot restart^^

steel trail

You don't need to know what they deselected for that. Only what they now got selected

.roles.set(...)

karmic hedge

If my welcome message is being sent more than once, are there any reasonable explanations besides the bot running multiple instances somewhere or duplicated event listeners?

upbeat saffron
stable sun

Oh right, sharding a single-guild bot

That’s alway quite the edge case

steel trail
steel trail
karmic hedge
stable sun
upbeat saffron

Thank you, qjuh. I think I need to design the command so that the administrator must first select which roles are selectable, then I can apply the filter as you describe.

steel trail

Well, do you want them to be able to select all of them? Or what do you mean by "allow all"?

upbeat saffron
steel trail

Yes, that's the UI part. I'm talking about your code handling the selection. What happens if I select the admin role there?

Or DevBot, or ...

upbeat saffron
steel trail

So you literally allow your code to grant any role. That sounds like a big security issue as soon as a guild admin accidentally give the bot a higher role or moves the role higher in hierarchy

steel trail

So the changes are needed either way, and then your question is answered too 👍

upbeat saffron
steel trail

No

A role select menu will always show all roles. The default roles are which are selected per default

upbeat saffron

so a string select would better fit?

steel trail

If you want the menu to only show and allow a subset of at most 25 roles: yes

upbeat saffron
karmic hedge
steel trail
upbeat saffron
steel trail

In your previous example it wouldn't matter if I selected role b or not, it won't change

ivory spoke

I have GatewayIntentBits.GuildPresences set as an intent both in my program and on the dev portal, but users always show as offline with user.presence.status

subtle spoke

Can someone help me with this:?

    const voiceStates = guild.voiceStates.cache;
    const voiceActive = voiceStates.size;
    const selfMuted = voiceStates.filter(vc => vc.selfMute).size;
    const selfDeafened = voiceStates.filter(vc => vc.selfDeaf).size;
    const serverMuted = voiceStates.filter(vc => vc.serverMute).size;
    const serverDeafened = voiceStates.filter(vc => vc.serverDeaf).size;

It works, but after the update, an error appeared and, for example, channel members are incorrect and are not updated.

zenith violet

what error

And do you have the GuildVoiceStates intent

subtle spoke
karmic hedge
zenith violet
subtle spoke
stable sun

It’s rarely ever (if ever) an issue w/ Discord nor d.js

karmic hedge

Okay thanks 👍

stable sun

In my experience, it’s always one of the 3 possibilities that occurs

Whether it’s the host spawning more processes, or some old node.js processes still running on ur machine

stable sun

Or even initializing ur events twice

You would also easily see if ur event is running twice just by adding a log in the listener

If so, then work ur way up the code

I really don’t know how much debugging you’ve actually done just from the messages you’ve sent here

sharp ginkgoBOT

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

subtle spoke
zenith violet

and where is that function called. Also channels do not need fetching if you have the Guilds intent

subtle spoke
steel trail
ivory spoke
steel trail

Sounds like it wasn't a GuildMember before then

ivory spoke

Oh, maybe. Does interaction.author not return a GuildMember when a command was executed in a guild?

snow onyx
ivory spoke

ah ok, sorry don't have my editor open rn so i just assumed it was .author. I'll switch it out to use .member. Thank you for your help!

full crystal

hii, im having problem with guildMemberRemove event
for some reason it doesnt triggers when a member is kicked/ or leaves
but it is working totally fine when emitted manually via client.emit()

i was using makeCache: Options.cacheWithLimits in my client options to limit member's and user's cache but even after removing that, event does not trigger.

It triggers normally when a member joins and leave, but doesnt triggers when a member leaves and was already present in the guild

polar karma

If the member isn't cached and you don't have partials enabled, you won't get the event from d.js

coarse storm

Can I limit the AttachmentOption of a slash command to only allow certain file types?

polar karma

no

full crystal
jade portal
zenith violet
wary coral
full crystal

ty yall :)

inland sentinel

im getting a lot of HTTPError: Service Unavailable from my code even tho discord isnt down?

amber mango
zenith violet

so nothing we really can do about, can be a temporary outage

jade portal
amber mango
jade portal
rose tangle

you could make the select menu ephemeral if you were using slash commands mmLol

hallow mesa

(Or just use the one built into the user option)

rose tangle

can't filter users from there though

hallow mesa

String option with autocomplete then. Regardless, prefix command into a select menu is clunky

heady lintel

Is there a reason why HTTP errors have no code property and instead have the code in status?

rose tangle

Error#code is a string, HTTPError#status is a number, which follows the naming after http status codes

heady lintel
rose tangle

yeah

heady lintel

so i guess i need to check for both

rose tangle

why?

rose tangle

and since http status codes are numbers it could be kinda confusing

not to mention "status" is probably better naming, since that's how they're called either way

you can open an issue about it though, maybe you can get a response from an actual maintainer, but that's my opinion

heady lintel
rose tangle why?

because I have a method that decides whether an error is worth retrying or not, and it failed because it only checked for code and not status

it's not worth opening an issue for, i just incorrectly assumed http errors would have code too

bronze hill
tidal ravine

what's the fastest way of getting an application emoji from the name? right now i was thinking of doing this but i think there's proabbly a better way

client.application.emojis.fetch().then(emojis => emojis.find(emoji => emoji.name === 'name'))
rose tangle
bronze hill

All the usage is in the commands folder

rose tangle

unless you expect your app emojis to change in runtime

rose tangle
bronze hill

Dms

tidal ravine

ok cool i dunno why i didn't think of that thank you

rose tangle

nw blobreach

past gate

Hi. I have a problem. I have started to use

// to do 
 await interaction.reply({ embeds: [embed], components: [row], ephemeral: true });
}

and I got error:

 requestBody: { files: undefined, json: { type: 5, data: [Object] } },
 rawError: { message: 'Unknown interaction', code: 10062 },
 code: 10062,
 status: 404,
 method: 'POST', ```
pls, help ![dobradDivkaheart](https://cdn.discordapp.com/emojis/1050042267076927558.webp?size=128 "dobradDivkaheart")  What am I doing wrong? Everything works fine locally, but not on the server under heavy load.
wary coral
past gate
wary coral

What I mean what does your Discord client do when you click the button?

wary coral

can you show the full error that you get

past gate
wary coral can you show the full error that you get

The client only sees this

On server error:

  at handleErrors (/root/secret/node_modules/@discordjs/rest/dist/index.js:748:13)
  at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
  at async BurstHandler.runRequest (/root/secret/node_modules/@discordjs/rest/dist/index.js:852:23)
  at async _REST.request (/root/secret/node_modules/@discordjs/rest/dist/index.js:1293:22)
  at async ButtonInteraction.reply (/root/secret/node_modules/discord.js/src/structures/interfaces/InteractionResponses.js:200:22)
 rawError: { message: 'Unknown interaction', code: 10062 },
 code: 10062,
  status: 404,
 method: 'POST',```
wary coral

and what is the full code for your interaction handling

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.

Common causes of DiscordAPIError[10062]: Unknown interaction:

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

likely the first

past gate
wary coral

The issue affecting your code is likely the first point "Initial response took more than 3 seconds ➞ defer the response"

hollow dawn

Good afternoon. Does anyone know how to create this system? Or any documents that can help me? The button system is linked directly to the item description and when you press the button, the item is automatically purchased. This function is new and unknown to me.

sharp ginkgoBOT

guide suggestion for @hollow dawn:
guide Popular Topics: Display Components - Section
read more

bitter leaf

this embed ?

zenith violet

No, thats a container

hallow mesa

See the message above yours

viral cave

Hello! I have a question that's been on my mind: why is it that I removed the bot's permissions (in a channel), but it can still send messages (including the embed from my /ping command)?

zenith violet

because interaction webhooks are not bount to send permissions

bots can be in guilds without actually being a member

viral cave
export const data = new SlashCommandBuilder()
  .setName("ping")
  .setDescription("Replies with the latencies")
  .setContexts(0)
  .setDescriptionLocalizations({
    fr: "Répond avec les latences"
  });

export const botPermissions = ["SendMessages", "EmbedLinks"];```

What permission can I check with the ping command then? Any permission that might prevent the command?
viral cave
near siren
data: new SlashCommandBuilder()
        .setName("cleardata")
        .setDescription("Clear data for a server")
        .setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild)
        .setContexts(InteractionContextType.Guild)
        .addStringOption(option => option.setName('server').setDescription('Select a server').setRequired(true).setAutocomplete(true))```

Type 'SlashCommandOptionsOnlyBuilder' is not assignable to type 'ContextMenuCommandBuilder | SlashCommandBuilder'.
  Type 'SlashCommandOptionsOnlyBuilder' is missing the following properties from type 'SlashCommandBuilder': addSubcommandGroup, addSubcommandts(2322)
typings.d.ts(69, 3): The expected type comes from property 'data' which is declared here on type 'Command'

anyone know how to fix this? addStringOption is the cause
wary coral
wary coral
near siren
wary coral I belive it is a typing issue in your command registration as `ContextMenuComman...

this is my typing

export type Command = {
  category: string;
  disabled: boolean;
  execute(client: Client, interaction: ChatInputCommandInteraction | ContextMenuCommandInteraction): any;
  guildOnly?: boolean;
  id?: string;
  usage?: string;
} & ({
  autocomplete?(client: Client, interaction: AutocompleteInteraction): any;
  data: SlashCommandBuilder;
} | {
  data: ContextMenuCommandBuilder;
})```
wary coral

Like the error says SlashCommandOptionsOnlyBuilder is not ContextMenuCommandBuilder | SlashCommandBuilder

near siren

just fixed it with Omit<SlashCommandBuilder, "addSubcommand" | "addSubcommandGroup"> | SlashCommandSubcommandsOnlyBuilder

wary coral

I used the following type for my code SlashCommandBuilder | SlashCommandSubcommandsOnlyBuilder | SlashCommandOptionsOnlyBuilder | Omit<SlashCommandBuilder, 'addSubcommand' | 'addSubcommandGroup'>;

clear garnet

Just use SlashCommandSubcommandsOnlyBuilder | SlashCommandOptionsOnlyBuilder

The omit that you're doing serves the same purpose as the OptionsOnlyBuilder

wary coral

Got it

shut musk

Just wanted to confirm rq, how many sections can a container have?

hallow mesa

13. There's a total of 40 components in the message, so one for the container and each section would take up 3

shut musk

Where did you find that

rose tangle

there's no section limit, he just calculated based on the 40 component limit

shut musk

so how big can a container be then?

hallow mesa

In what units?

shut musk

Ideally I have an embed with some text a button next to it, how much can I scale it?

rose tangle

the only limit is the 40 component limit and the 4k character limit

per message

shut musk

I suppose my limitation is characters here

40 component limit but what counts as a component sorry?

rose tangle

components

hallow mesa

Container, section, text displays, accessories, etc. Buttons

shut musk

right so under 1 section if I have a text display and accessory then thats 3 already

rose tangle

buttons, containers, sections, anything that has a component in the name and goes in the components array

yes

shut musk

so i could have 13 sections ideally

rose tangle

correct

if you only make each section have one text display

shut musk

yeah ideally i want

TEXT - BUTTON so i just have to use single sections

I assume there's no better way to do it?

rose tangle

imo it's best to think of "only 40 components" rather than "only 13 sections" since the latter isn't accurate

shut musk

i mean yeah because you could have 40 text display components

for my case it just sadly comes to 13, I thought it would've been higher, sadge

rose tangle

13 is high enough, it'd be a big message in desktop and gigantic in mobile

shut musk

It's mainly the buttons for me but i cannot have more than 1 button per section or I'd have to use the old action rows which isnt pretty

rose tangle

then use an action row

shut musk

yeah just mentioned xd

rose tangle

no other choice then

shut musk

Yeah figured

ty guys

crude vapor

Can I get container component from an existing message? Just like for editing a button's style, you can do js const newButton = ButtonBuilder.from(oldButton).setStyle(2).setLabel("Closed");I want to do a similar thing like js const newContainer = ContainerBuilder.from(oldContainer).spliceComponents(1, 1, newComponent);Is this possible?

It would just make it so much easier to edit a specific component from an existing container, rather than rebuilding every components of a container that includes the edited component

clear garnet

new ContainerBuilder(oldContainer.toJSON())

crude vapor

Oh thank you so much!

blazing ivy

Heya,
What would be a good point to start in the following situation:
I listen to both guildMemberRemove and guildBanAdd
Both send a message: Member left, and Member got banned
How to check if the removed member has been banned, so only the guildBanAdd message gets sent?

inland pawn

does an ephemeral deferred reply need to be acknowledged?

clear garnet
sharp ginkgoBOT

guide suggestion for @blazing ivy:
guide Popular Topics: Working with Audit Logs
read more

clear garnet
blazing ivy
inland pawn
clear garnet

No

waxen venture

~~```js
const response2 = await interaction2.reply({
embeds: [editembed],
components: [row1, row2],
});
const collectorFilter = (i) => i.user.id == interaction.user.id;
let collector = response2.createMessageComponentCollector({
filter: collectorFilter,
time: 120000,
});

      collector.on("collect", async (interaction3) => { //...```

When I press a button on the response2 message, any code after the //... should run, but it doesn't reach that. Does anyone know the problem~~

naive rapids

is there any info documented about the max limit of text display in a container?

hallow mesa
naive rapids

tho i was wondering if that's documented on the official api docs too

ripe violet

is there away to check if a orb quest is out using a discord bot?

unique shoal

No, no APIs that I know of and they're unlikely given that is purely user based functionality

glossy sky

how can i get old Guild Vanity Url and New Guild Vanity Url?

summer flower

Do the container need to have thumbnails?

snow onyx
snow onyx

yes?

glossy sky

newGuid
oldGuikd
like this?

snow onyx

oldGuild, newGuild

summer flower

Is there possible way to disable mentions in container?

sharp ginkgoBOT

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

{ ..., allowedMentions: { parse: ["users", "roles"] } }
summer flower

thats works for containers as well?

zenith violet

yes

shut musk

When I try to edit a message by it's reference I get this:

zenith violet

Show your code

shut musk

Wait I think i know it, isn't there a param for like fetchReply in TextChannel.send?

zenith violet

no

send already returns a Message

shut musk

then im unsure ok so

zenith violet

and do you have the Guilds intent

shut musk

Actually i am stupid, I could just edit the message from interaction because i have a button in it. I don't even need that reference 😂

languid summit

does disord bot itself needs crate invite perm to create invite or if the evryone have that perm will that work?

snow onyx

if everyone has that perm, the bot doesn't need it again

fallen fjord

how did they do these lines in the embed?

zenith violet
sharp ginkgoBOT

guide Popular Topics: Display Components - Separator
read more

fallen fjord

thats dope thank you

red trellis

is there a way to react with multiple emojis in 1 api call?

snow onyx

no

hazy agate

whats the best way to filter errors like this, should i check js err.message === 'Used disallowed intents'
or is there a better way?

also, what kind of errors can appear in the client.login besides, invalid intents and invalid token

obtuse laurel
hazy agate

there doesnt seem to be any error code on this particular error, for Invalid tokens it exists

obtuse laurel

I don't think disallowed intents has a code, so yeah you'll have to check message for that one

hasty osprey

how do i reply to someone using an interaction

apparently the type Interaction aint the same as ChatInputCommandInteraction

zenith violet

you can reply to the interaction, but there's no data if that command was ran as a a reply to someone

hasty osprey

its just a slash command

steel trail

So it is a ChatInputCommandInteraction

hasty osprey

i added this in the start and it tells me unable to find .deferReply()
when i run the command

steel trail

Show your exact code and error. Not paraphrase it

hasty osprey

the callback of the slash and the function that runs the callback of the slash

brb gotta get my dog to the bath

sharp ginkgoBOT

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

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

btw does interaction already have the client within it?

zenith violet

yes

Virtually all djs structures do

hasty osprey

oh so i dont need to send it

zenith violet

Not really

unless you have a custom client

hasty osprey

oki

only custom thing i have is the commands added to the client's structure so i think im ok

rose tangle

the client instance is re-used either way so you can still avoid passing it

you'd just need to type assert it as your custom client

rose tangle
hasty osprey

as a suggestion to avoid this in the future, given you're using ts, you should make a type for your command functions, and make those functions inside the files match that

so if you make a mistake like that again, ts will catch it

onyx lagoon

is it possible to fetch an ApplicationEmoji with their name?

halcyon bison
solid summit

can i know any eta for gradient role support?

halcyon bison
hasty osprey

is there any guide for components v2

sharp ginkgoBOT

guide suggestion for @hasty osprey:
guide Popular Topics: Display Components
read more

hasty osprey

ty :3

open fox

hey, im trying to check a member permissions but its returning me a string

steel trail

Need to typeguard as inCachedGuild() first

Else it could be a raw API member object

open fox

sorry and ty

onyx lagoon

when i try using client.ws.ping i get the result of -1 as my latency why is that?

zenith violet

Takes around 41~s

onyx lagoon

oh thanks

kindred moon

if i deferReply, how long do i have to respond to the interaction?

bleak owl

15 minutes after the deferReply is sent

you still need to respond with a deferReply within 3 seconds though for it to be acknowledged

kindred moon

alright thanks

dapper oyster

is there any module that generates usage text from ApplicationCommandJSON data?

bleak owl

usage text?

glossy field

is there any way to make a command see how mush members used my server tag?

dapper oyster
bleak owl

i don’t really understand what you mean

d.js doesn’t output data like that for you. you’ll need to manually get that

deft nimbus

you want to generate example usage of a command using the command data? you'd have to do that yourself

kindred moon

is there a helper function for putting backticks around content such as the bold function?

sharp ginkgoBOT

documentation suggestion for @kindred moon:
function inlineCode discord.js@14.21.0
Wraps the content inside backticks, which formats it as inline code.

kindred moon

thank you

mighty wyvern

how to fetch slash options

bleak owl

interaction.options…

sharp ginkgoBOT
zealous knot

Hey. Which is the recommended event for checking role updates? I assume it's GuildMemberUpdate though I'd still like confirmation.

rose tangle

assuming you mean whether a role was added/removed from a member, yeah it's the only event actually

grizzled bison

Is it still a long time before discord.js updates its version again?

zealous knot
rose tangle

there's no eta, though I personally wouldn't say it'll take much

rose tangle
zealous knot

Discord.ts when tho why_god_why

rose tangle

if they meant v15 then yeah, no eta at all

and no priority in particular either

zealous knot
rose tangle
zealous knot

True. Though it'd be nice to see the main lib join it's "siblings" in the language they use.

grizzled bison
rose tangle

why would you try previous versions?

zealous knot

Wait, Amgelo, the roles in member update can be more than 1 right?

grizzled bison
rose tangle

that's current version Thonk

rose tangle
grizzled bison

lmao

rose tangle

and not necessarily a role change though, update also triggers for other stuff

so you'll also need to check if the roles changed

zealous knot
grizzled bison
bleak owl

what do you mean appear?

those never went away Thonk

grizzled bison

Isn't it true that the current version can't use author and footer? emm how do i say it?

bleak owl

components v2?

grizzled bison
bleak owl

embeds still exist and are not components

rose tangle

it's not for djs to decide what discord supports, and containers do not support author and footer

only embeds

lean sail

this isnt specifically a discord js question but im using zod to check my env and was wondering if the bot tokenn and cllient id always have fixed lengths

rose tangle

bot token I wouldn't rely on it, client id is a snowflake so it has a minimum length at the very least

lean sail

and that would be 17 iirc?

rose tangle

I don't think it's worth validating that though

lean sail

ah alright. do you think i shouldnt validate at all beyond string?

rose tangle

env values are already strings, you should just validate that they're present

lean sail

ok

shut musk

So I saved a reference of a interaction message in a object to use it across another file to edit and while doing so I get TypeError: Cannot read properties of undefined (reading 'channels')

const msg = value.msgReference // valid because i have it logged
const ref = await msg.edit({ content: 'hii' })
zenith violet

Show the code and error

shut musk

thats the log of msg ^ (and more, just doesn't fit in ss)

How would I go about editing this message 🤔
Would have to fetch the guild, channel and then message is the other workaround but I thought saving this reference would help me out

rose tangle

what about the error?

like, the full stacktrace

not just the message

shut musk

yeah sorry I was just getting the stack trace, forgot about that 😭

rose tangle

from where does the message come from?

shut musk
const reference = await dedicatedVoteKickChannel.send({ content: mentions.join(' '), embeds: [voteKickEmbed], components: [row] })
    return client.activeVoteKicks.set(voteKickGuildMember.user.id, { msgReference: reference }, votingTime)
``` Here

client.activeVoteKicks is a node-cache

rose tangle

it sounds like the channel isn't cached

do you have the Guilds intent?

shut musk

Yeah but if its not cached then how was the message sent there

rose tangle

wdym?

shut musk

its something to do with putting the reference inside the object

shut musk
rose tangle

how is dedicatedVoteKickChannel defined?

shut musk
    const dedicatedVoteKickChannel = interaction.guild.channels.cache.get(currentServerConfig.vote_kick_channel);
shut musk

but the second I use msgReference from the object, it doesn't work lol
I guess the object does something to the variable

rose tangle

ah, nvm, it looks like this.client is somehow undefined in the Message

zenith violet

might be node-cache doing something to lose the this binding

shut musk

potentially.

rose tangle

tried reading their code but it's written in .coffee Thonk

you could change the library or save just the channel and message ids, then you can get the channel from cache, and call #edit()

shut musk

to manually get the message, i would need to get the guild, the channel and then the msg right?

sharp ginkgoBOT
rose tangle

you don't need the message

shut musk

huh

rose tangle

and since channel ids are unique you don't need the guild either

sharp ginkgoBOT

property Client#channels discord.js@14.21.0
All of the BaseChannels that the client is currently handling - as long as sharding isn't being used, this will be *every * channel in *every * guild the bot is a member of. Note that DM channels will not be initially cached, and thus not be present in the Manager without their explicit fetching or use.

shut musk

Can I fetch a message direct by ID or need to find the channel first

rose tangle

you need the channel, but unless you need the message's contents, you don't need to fetch it

shut musk

no i dont, i just want to edit that message

mental idol

Can I get the message author via targetMessage?

wintry laurel

what does the error HTTPError: Service Unavailable mean and why am i getting it? never seen it before

temporary discord outage ig?

zenith violet

It is an issue on discord's end yeah

mental idol
sharp ginkgoBOT

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

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

anyone knows the reason of this error?

i dont know where in the code im inputting undefined instead of a string.. at least its what i understood

trim basin

Show us your deploy-cmds file please

stable sun
trim basin

Ah yes didn't see the validateDescription

hasty osprey
zenith violet

Yes

hasty osprey

should i always use interaction.options.getString() //or any other over interaction.options.get()?.value ?

halcyon bison

generally you'll want to use getString and similar methods since they also have type safety and resolve ids to structures when applicable (e.g. getUser returns a User instead of just an id)
but there are cases where you may want to use get directly (e.g. in autocomplete interactions where you want to access a different option's value where the whole structure isn't sent with the interaction)

orchid radish

hi is it possible for a bot to sync a channels permissions to its parent category?

sharp ginkgoBOT
halcyon bison

(yes)

orchid radish

thank mr or ms duck

hasty osprey

how do i turn the user i got in getUser into a guild member?

halcyon bison

you can use getMember instead (or if you really want you could use <Interaction>.guild.members.fetch(), but the member would be sent with the interaction)

hasty osprey

oh oki

addUserOption is for both user and member right?

halcyon bison

yes, there isn't a separate member option type

hasty osprey

oke

turns out i think i need both

hasty osprey
halcyon bison

probably didn't typeguard the interaction with <Interaction>.inCachedGuild() so member is GuildMember | APIInteractionGuildMember

hasty osprey

how do i check if my bot can dm a user
just so i avoid an error

hallow mesa
hasty osprey

is it okay if i trycatch inside a trycatch

hallow mesa

Sure?

wintry laurel

what am i doing wrong here? im trying to get the first user mentioned in a message. const user = message.content.mentions.parsedUsers.first(). looking at the docs parsedUsers is the only thing that was a collection of users based on which appeared first

oh, i included content in there. no wonder.

stable sun
shut musk

To fetch a message, i would need the channel first right?

loud quartz

Yes

Along with permissions to view its contents

merry cedar

What’s the rate limit for bots sending DMs to users?

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

Mass DMing users is not allowed as per developer ToS, considered spam and can get you and your bot banned.

  • Mention @everyone to inform all your users at once instead
  • Discord Developer Terms of Service: learn more
shut musk

How would I get the permissions for a user in a channel

sharp ginkgoBOT
zenith violet

Also, users dont have permissions, members do

plush veldt

Hello! Is there any way to show a slash command to the members that have a specified role?

steel trail

Yes, as guild admin you can set the command permissions in server settings > integrations > your bot

plush veldt
zenith violet

No

You would need an oauth2 token of a guild admin for that

steel trail

That's not your responsibility as bot dev. The server admins are responsible for permissions of roles. You as bot dev are responsible for permissions (like ban members permission, manage guild permission, ...) needed to run your commands, not specific roles (as they vary from guild to guild anyway)

plush veldt

Thank you!

shut musk

Could I check if a channel has any overwrites for a member specifically?

guildMember.voice.channel.permissionsFor(userID).toArray()
```shows me the member's permissions but those are inherited from the everyone role. I want to see if they have anything for that member specifically

Why? Ideally when resetting their perms. I want to see if I should set that permission to null or delete the member permissions entirely 

Why? If they have any other permission i want to make sure to keep that and just reset what I need however if they dont, i want to delete it because then the user stays in the permissions tab of the channel and I believe there is a limit to how many member can have permissions overwrites in a channel (correct me if im wrong)
stable sun
shut musk

Yeah but can I not show specifically from the member?

stable sun

Just get the overwrite from the cache then

shut musk

wdym

stable sun

channel.permisssionOverwrites.cache.get(id);

You might still have to take other overwrites into account if the permission ur checking is inherited/neutral

shut musk

ty for ur help, i was after that specifically

sudden estuary

random question but is it possible for a bot to crash simply due to too many people clicking a button, and the bot handling all those interactions extremely quickly?

shut musk

unlikely, it would just slow down

sudden estuary

tyty

languid summit

Can bot fetch existing invite from a guild?

sharp ginkgoBOT
shut musk

Having a weird one trying to set permissions. Deny works but allow doesn't

    await voiceChannel.permissionOverwrites.set(newPerms);

It's a voice channel though I don't think that matters much does it?

I found the fix. It seems like deny needs to always be first then allow BlobThink

delicate flare

i'm getting this error here:

error: Invalid Form Body
data.components[0].components[0].options[BASE_TYPE_MIN_LENGTH]: Must be 25 or more in length.

the first component i'm sending is of type ActionRowBuilder<StringSelectMenuBuilder> that i dynamically create from a function

const { excludeNFT = true, includeAmount = false, maxOptions = 25 } = options; // NFT = Not For Trading
    const menu = new StringSelectMenuBuilder()
        .setCustomId("card.selector")
        .setPlaceholder("Select cards...")
        .setMinValues(1)
        .setMaxValues(maxOptions);

and for adding options i use StringSelectMenuBuilder#addOptions(...) like this:

for (const {card, amount} of userCards) {
        const option = new StringSelectMenuOptionBuilder()
            .setLabel(`${card.name} (${card.cardID})${includeAmount ? ` ×${amount}` : ''}`)
            .setDescription(`${card.rarity}${card.group}`)
            .setValue(card.cardID);
        
        menu.addOptions(option);
    }

i can't see anything that would need 25+ options, and i don't think i'm even close to 25 cards, any ideas?

zenith violet

you are setting the max amount of options to 25 or higher

Therefore discord expects you to have 25 or more options (which isnt possible)

delicate flare

i see, i expected it to adapt, my bad 😅

bleak owl

all guilds are cached with the Guilds intent, but yes, it checks cache first

cached guilds doesn’t take up nearly as much memory as you think

you can customize the cache if you’d like, but i do not suggest disabling that intent

sharp ginkgoBOT

guide Miscellaneous: Cache customization
Customization of caching behavior is an advanced topic. It is very easy to introduce errors if your custom cache is not working as expected.
read more

zenith violet

You should look into using /core then

The Guilds intent is required for djs to function properly

If memory is an issue, you should use /core

bleak owl

those are your options.

zenith violet

then you'd use /core

djs isnt meant to be a lightweight wrapper

disabling the Guilds intent will cause issues; you're on your own then

lean sail

Type 'string | undefined' is not assignable to type 'APIEmbedAuthor | undefined'.
Type 'string' is not assignable to type 'APIEmbedAuthor'.ts(2322)
channel.d.ts(1187, 5): The expected type comes from property 'author' which is declared here on type 'APIEmbed'

How would I be able to fix this?

little pebble
sharp ginkgoBOT
lean sail

so would i just return the icon url or whatever as is along with the name? in order to meet that?

little pebble

I think you want { name: truncateString(....) } : undefined

lean sail

that did the job. appreciate the help

fathom sand

I'm adding discordjs into a nextjs project, my package manager is pnpm.
I don't have this issue with my other project, but I get a zlib-sync module not found and I was wondering if we need to manually install dependencies^

should I simplyt add it manually or there might be another underlying problem?

zenith violet

djs is not meant to run in a web environment

you should look into using /rest

fathom sand

Does /rest allow to get user that are in voice channel? If so, it solve half of my problem.

The other part is that I want the list of active voice user to be updated when someone connects or disconnect. For this part I think I need a bot that would trigger something on my main backend via rest or something else.

lean sail

is there a better way to do this?

basically the goal is to take in an embed, truncate all the values that contribute to character length, and then also return a custom embed if that is still too long but im not sure if this is the most efficient way to do this

sharp ginkgoBOT

function embedLength discord.js@14.21.0
Calculates the length of the embed.

rose tangle

its definition is actually the exact same thing you currently have (in that red line)

lean sail

so i can essentially just replace the red line with that?

rose tangle

but could help to make it shorter

yeah

lean sail

lol alright thank u

rancid elbow

the channelSelect component was updated with interaction.update()

it keeps the last selected value in there, the correct select menu is "underneath"... i am confusion. I can "x" the old selection, but I feel like that should have happened when the component was replaced with .update()

rose tangle

you must've sent the select menu with that option selected (check for .default = true in its options)

or you didn't send a components array, so the previous state is kept

rancid elbow

let me recheck, ty already

hmm no, I even hardcoded it to the new component, it still keeps the old value after updating

fathom sand

Is there a comprehensive list of Route that can be used with discordjs/rest? I'm searching trought the doc and can't figure

rose tangle

can you try using #setDefaultChannels() and passing an empty array?

rancid elbow

sure.

sharp ginkgoBOT

documentation suggestion for @fathom sand:
dtypes v10: RoutesDeclarations
read more

rancid elbow
rose tangle

I think clicking that "going to another channel and back" is a feature, or well, it has worked like that for a while

kindred moon

is there a way to get the role and channel overrides that a server administrator has set for a command?

rose tangle

but from my understanding it should've cleared with what you had at the beginning, though I have only done that with string selects, maybe it's different with channels?

you can send it on #986520997006032896 so it doesn't get lost, maybe someone else can give more info

rancid elbow
sharp ginkgoBOT

documentation suggestion for @kindred moon:
method ApplicationCommandPermissionsManager#fetch() discord.js@14.21.0
Fetches the permissions for one or multiple commands. Providing the client's id as the "command id" will fetch only * the guild level permissions


// Fetch permissions for one command
guild.commands.permissions.fetch({ command: '123456789012345678' })
  .then(perms => console.log(`Fetched ${perms.length} overwrites`))
  .catch(console.error);

true lynx

how do i properly slice my embeds?

rose tangle

its an array, you can directly call slice on it

sharp ginkgoBOT

mdn Array.prototype.slice()
The slice() method of Array instances returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.

true lynx
unique shoal

Yeah, by slicing the content

viral cave

Hello!

How we can put commands in embed like this?

loud quartz

click on it

clicking still works

orchid radish

would someone mind linking me to the docs on adding right click apps options to my bot?

i cannot seem to find it

sharp ginkgoBOT

guide Other Interactions: Context Menus
read more

ripe quiver

I'm running into an odd ts issue with components

 Property 'type' is missing in type 'ActionRowBuilder<MessageActionRowComponentBuilder>' but required in type 'ActionRowData<MessageActionRowComponentBuilder | MessageActionRowComponentData>'.ts(2322)
index.d.ts(301, 3): 'type' is declared here.

its worked fine with regular js, even with ts-check turned on. the code doesn't seem to be out of the ordinary. I'm on 14.18.0 right now

msg.reply({ components: [
          new Discord.ActionRowBuilder<Discord.ButtonBuilder>().addComponents(
            new Discord.ButtonBuilder().setLabel("Testing").setCustomId("testButton").setStyle(Discord.ButtonStyle.Primary)
          )
        ]})

any clues?

ripe quiver
orchid radish

how long after i deploy a context menu command will it take to be visible within discord? im sure i did it right but i cannot find it on my server

wary coral
orchid radish
wary coral
chilly spruce
novel mauve

100 per request

zenith violet

but 50 if no limit specified

grim reef

how do I use withResponse instead of fetchReply?

sharp ginkgoBOT

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

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

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

I want to increase my bot shard count to 2 but it is not working and there is no guide for that
Only for auto guide is given

const { ShardingManager } = require('discord.js');
const { token } = require('./config.json');

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

manager.on('shardCreate', shard => {
  console.log(`🚀 Launched shard ${shard.id}`);

  shard.on('death', process => {
    console.warn(`💀 Shard ${shard.id} died (code: ${process.exitCode})`);
  });

  shard.on('exit', (code) => {
    console.log(`🚪 Shard ${shard.id} exited (code: ${code})`);
  });
});

manager.spawn();
const client = new Client({ intents, shards: 'auto' });
stable sun
grave pond
viral cave

hello! how we can reset a stringselectmenu option after interaction without a interaction.editReply or interaction.update ?

zenith violet

refresh your discord client

thats the only other way

viral cave
zenith violet

Edit the message with the same components

Which you dont want to do

viral cave
zenith violet

no

you have to edit it with the same components

viral cave
zenith violet

if its not ephemeral, and ran in a channel the bot has access to, yes

icy surge

Hello does this image link keep on expiring due to the empheral-attachment being in the link

harsh elbow

did server tags finally get documented/added to discord js?

snow onyx

the pr for it was merged, but its not yet released

zenith violet
icy surge
novel mauve

that's for attachments uploaded through slash command options

you need to save it somewhere if you need it longer

icy surge
thorn gate

can i edit bot bio?

using cmds

sharp ginkgoBOT
snow onyx

client.application.edit() and then you can pass a new description

lean sail

why would this be happening?

Type '{ type: ComponentType.Container; components: { type: ComponentType.Section; components: ({ type: ComponentType.TextDisplay; content: string; } | { type: ComponentType.Button; style: ButtonStyle.Primary; label: string; customId: string; })[]; }[]; }' is not assignable to type 'APIMessageTopLevelComponent | JSONEncodable<APIMessageTopLevelComponent> | TopLevelComponentData | ActionRowData<...>'.
  Types of property 'components' are incompatible.
    Type '{ type: ComponentType.Section; components: ({ type: ComponentType.TextDisplay; content: string; } | { type: ComponentType.Button; style: ButtonStyle.Primary; label: string; customId: string; })[]; }[]' is not assignable to type 'APIComponentInContainer[] | readonly MessageActionRowComponentData[] | readonly (JSONEncodable<APIComponentInContainer> | ComponentInContainerData)[] | readonly TextDisplayComponentData[] | readonly (MessageActionRowComponentData | MessageActionRowComponentBuilder)[] | undefined'.
      Type '{ type: ComponentType.Section; components: ({ type: ComponentType.TextDisplay; content: string; } | { type: ComponentType.Button; style: ButtonStyle.Primary; label: string; customId: string; })[]; }' is not assignable to type 'APIComponentInContainer'.
        Types of property 'components' are incompatible.
          Type '({ type: ComponentType.TextDisplay; content: string; } | { type: ComponentType.Button; style: ButtonStyle.Primary; label: string; customId: string; })[]' is not assignable to type 'APITextDisplayComponent[]'.
            Type '{ type: ComponentType.TextDisplay; content: string; } | { type: ComponentType.Button; style: ButtonStyle.Primary; label: string; customId: string; }' is not assignable to type 'APITextDisplayComponent'.
              Object literal may only specify known properties, and 'style' does not exist in type 'APITextDisplayComponent.'
wary coral
sharp ginkgoBOT

documentation suggestion for @lean sail:
discord Component Reference - Section
read more

guide Popular Topics: Display Components
read more

kindred moon

is there a format function that both bolds and italicizes the string its passed? similar to the bold function yet 3 *** on either side

chilly spruce

/edit <module> <value>
Considering that value is an autocompleting option, is it possible for the autocomplete interaction to see what module has been choosen? (module is string option)

sharp ginkgoBOT
kindred moon

i know that is a function but i wasnt sure on if there was a function that did both

i guess ill just combine them

red coral

Is there a way to get the command ids from others bots commands?

full crystal
lunar lantern
        if(member.user.bot) return;
        client.users.send(member.id,"Hello")
        console.log("success").catch(error => {
            console.log(error);
        });
    });```
I'm just wondering if anyone knows why this isn't working? It doesn't give me an error but it doesn't send the message to the user either.

It did give me an error earlier but that was because I forgot to prohibit it from sending a message to itself or any other bots

sharp ginkgoBOT

tag suggestion for @lunar lantern:
Mass DMing users is not allowed as per developer ToS, considered spam and can get you and your bot banned.

  • Mention @everyone to inform all your users at once instead
  • Discord Developer Terms of Service: learn more
lunar lantern

Oh ok thanks for the info

rose tangle

or just filled with your own bot

because console.log() returns void, you can't call .catch() on it

if that line ever ran, it'd throw an error

daring coral
daring coral
muted crater

Hello, if i sweep all emojis and stickers from cache, and call guild.fetch, stickerCreate, and emojiCreate events will be fired with existing emojis and stickers, is there a way to prevent any of this?

zenith violet
chilly spruce
acoustic night

can we build this type of buttons and gradient buttons?

zenith violet

No

toxic moat

Can I get user’s about me

rose tangle

nope

lean sail

can i set the specific roles and channels that can be assigned with a command integration by server admins?

like if i have a /modrole command that sets the role to be able to access all the moderation related commands through integrations

rose tangle

only with an admin's oauth token

which is out of scope for djs

lean sail
rose tangle

no, oauth is an entirely different workflow than what a bot does

daring coral
lean sail

its just a question? anyways thanks for the info

rose tangle

then you receive their token and you can use it to make the request

lean sail

ah alright

dapper flower

Guys i was using RoleSelectMenuBuilder to create an Select Menu of Roles but the Select Menu is only showing the Roles that i used to separete my roles (don't mind the text bc i am from brazil)

zenith violet

You can type to search

dapper flower
pliant forge

how can i set localization names for choices or can i

uncut quest
pliant forge how can i set localization names for choices or can i

yes you can

in JSON it would be something like

choices: [
    { name: "...", name_localizations: { fr: "...", ja: "..." }, value: "..." },
    { name: "...", name_localizations: { fr: "...", ja: "..." }, value: "..." }
    ],```

but you can also in the slashCommandBuilder with a addStringOption , you put your choices there and the choice has name localization available in it
pliant forge
.addChoices(
                    {
                        name: 'taş', value: 'taş', setNameLocalizations: {
                            'en-US': 'rock',
                            'tr': 'Taş'
                        }
                    },
                    {
                        name: 'kağıt', value: 'kağıt', setNameLocalizations: {
                            'en-US': 'paper',
                            'tr': 'kağıt'

                        }
                    },
                    {
                        name: 'makas', value: 'makas', setNameLocalizations: {
                            'en-US': 'scissors',
                            'tr': 'makas'
                        }
                    }
                )```

i tried like this but didn't get a chance to try yet
zenith violet

please dont just guess

You were even given an example

You call setNameLocalizations on the builder if using builders, or use the proper name_localizations key

Not both combined

true lynx

is there a way to achieve multi choice string options?

bleak owl

yes

sharp ginkgoBOT

guide Interactive Components: Select menus - Multi-selects
Where slash command options fall behind is in their single-select limitation on User, Role and Channel option types. Select menus can support this use case via BaseSelectMenuBuilder#setMinValues()open in new window and BaseSelectMenuBuilder#setMaxValues()open in new window. When these values are...
read more

zenith violet

not in a slash command though

true lynx
zenith violet

its not possible

You will need to use a select menu

true lynx
zenith violet

or you can try to hack autocomplete to achieve what you want

true lynx
sharp ginkgoBOT

guide Interactive Components: Select menus
read more

lunar lantern
            name: "cool role",
            permissions: [PermissionsBitField.Flags.SendMessages, PermissionsBitField.Flags.KickMembers],
            //parent: cat[0].ID,
        });
        server.members.cache.get(memberid).roles.add(assignedRole.id);```

gives me ``Cannot read properties of undefined (reading 'roles')``
Does anyone understand what's wrong here?
weary swallow
kindred moon

^ and is server defined as just Guild or also null

lunar lantern

Earlier on in the code

weary swallow

It would be useful if you would show how it is defined

lunar lantern

It works fine though since I used it for other functions with no problems


var assignedRole = server.roles.create({
            name: "cool role",
            permissions: [PermissionsBitField.Flags.SendMessages, PermissionsBitField.Flags.KickMembers],
            //parent: cat[0].ID,
        });
        server.members.cache.get(memberid).roles.add(assignedRole.id);```
Like this

There is a lot more code in there but don't wanna clog up the message with too much irrelevant stuff since it all works fine. But they are different functions and this is outside of those blocks of code

kindred moon

its possible that the guild isnt in the cache

you have the guilds intent correct? try fetching the guild instead

zenith violet

Its always cached by the Guilds intent

the id is incorrect

or the bot isnt in the server (or without the bot scope)

Also

That error likely comes from your rokes.add call

Not all members are cached

You need to fetch the member

kindred moon

unless you use GuildMembers as an intent

zenith violet

No

That wont cache all members

lunar lantern

Changed it to c.guilds.fetch(serverid).members.fetch(memberid).roles.add(assignedRole.id);
and got Cannot read properties of undefined (reading 'fetch')

zenith violet

You still need to fetch the member regardless of the intent

No

Get the guild from cache

Like you did before

Then fetch the mem er

That returns a promise

So you'll have to resolve it before adding the role

lunar lantern

Oh right. I tried that earlier and got a similar error but I'll try again

zenith violet

Because you didnt resolve the promise

lean sail

is the first line enough to make sure that the member provided is actually a member? or do i have to also fetch and return that it isnt if its null

zenith violet

how is options defined

lean sail

GuildMember

zenith violet

i doubt that

But using getMember, if you use it inside one of your custom classes, will return null if the member isnt in the server

lean sail

but from what code ive written, it should still get catched right? it just wont say that the provided person isnt in the guild

and if i did want to return specifically that, id need to fetch and check for nullish? or is there a better way

tepid plover

Does the ComponentBuilder/EmbedBuilder supports Components V2 already or we have to still send it using JSON?

zenith violet

djs supports it

tepid plover

Any docs for that?

zenith violet
sharp ginkgoBOT

documentation suggestion for @tepid plover:
class ContainerBuilder discord.js@14.21.0
A builder that creates API-compatible JSON data for a container.

tepid plover

Thanks

lean sail
zenith violet

I have no clue how options.member is defined

So i have 0 clue how you determine that

lean sail

its defined as GuildMember

zenith violet

But users can pass in a non guildmember

As i mentioned, using getMember on the interaction.options will return null if the member isnt in the server

You need to adapt that logic to your custom handler

lean sail

as in GuildMember | null right?

zenith violet

yes

Assuming you use what i mentioned under the hood

lean sail

i do, thanks

lunar lantern
zenith violet Because you didnt resolve the promise

I got past that members bit but now I have anothe error
server.members.fetch(memberid).then(member => member.roles.add(server.roles.cache.get(assignedRole.id)));
TypeError [InvalidType]: Supplied roles is not a Role, Snowflake or Array or Collection of Roles or Snowflakes. at GuildMemberRoleManager.add
Not sure if I did the promise wrong or something else

zenith violet

In the code you showed above, you did not resolve the promise of the create call

and you can add the role directly then

tulip sphinx

why would my bot randomly stop responding after i leave it running for awhile
only a restart fixes it no errors are visible

zenith violet

whats your djs version

tulip sphinx

14.18.0

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 | sourceb.in | hastebin
bleak owl

i also suggest updating

tulip sphinx

K I will add more logging to see if it catches it

lunar lantern
shut terrace

import { createRequire } from "module";
const require = createRequire(import.meta.url);

const { Client, Events, GatewayIntentBits } = require('discord.js');
const { token } = require("./config.json")

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

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

client.login(token);

async function sendToChannel(channelId) {
const channel = await client.channels.fetch(channelId);
if (!channel || !channel.isTextBased()) {
console.error('Channel not found or not text‑based');
return;
}
//const everyone = await guild.roles.fetch("@everyone"); not using
await channel.send(Hello);
}

sendToChannel("1397403533875220584");


This keeps giving me the error: --Channel not found or not text‑based-- even when the channel is text based and ive tripled checked the ID?

zenith violet

first of all, you dont need to fetch channels at all with the Guilds intent, second, log channel

tulip sphinx

How do you fix this line the types changed

const found = interaction.message.components.find((row) => 
    row.components.some((component) => component.customId === "repost")
)
Property 'components' does not exist on type 'TopLevelComponent'.
Property 'components' does not exist on type 'FileComponent'.
shut terrace

Thats why I came here Im lost

zenith violet

did you write that code

shut terrace

With lots of research

zenith violet

i dont see how the platform you use is relevant to what I said

shut terrace

In deno we have different and built in request types. Like we dont need to use fetch. Also im very new to discord.js which is in node

I js want help

zenith violet

that has nothing to do with your code

You can just get the channel from cache

But log it

tulip sphinx

Does your bot have permission to view that channel

zenith violet

that doesnt matter

It will still be cached

shut terrace

has Administrator

shut terrace
zenith violet

cached yes

shut terrace

im lost. chat

zenith violet

Also you should move that code into your ready event and it'll work

You should look into djs docs and guides then

shut terrace

I have been Im lost im telling you

zenith violet

caches are a core part of djs

tulip sphinx

Maybe you are fetching the channel before the bot has logged in (ready event). There is a race condition there

shut terrace

wheres a ready event

zenith violet

...in your code

shut terrace

chat

zenith violet

or well, ClientReady in the enum

shut terrace

i have 7 tabs open of searches and sites to send one message

zenith violet

If you wrote that code yoy should know what events you listen to

bleak owl

it’s really not that difficult

<Client>.channels.cache.get('id').send(…)
shut terrace
clear garnet
shut terrace

it says you create a client then login like page 1

zenith violet

you should know what the code does

And what we mean by ready event, or any event in general

shut terrace
zenith violet

you follow the rest of the guide

blazing ivy

Heya, i'm currently ugprading from djs13, and am stuck on editing an embed here.

In djs13 I do the following:

const embed = msg.embeds[0].setDescription('new desc').setFooter(`new footer`);
msg.edit({ embeds: [embed] });

I know about the new .setFooter() syntax, but none of the set methods exist anymore, what is the new way to edit embeds?

sharp ginkgoBOT

Structures from the API cannot be edited directly. To do so, you can create a new structure (a builder) using the .from() method

const newEmbed = EmbedBuilder.from(embed).setTitle("title")
const newRow = ActionRowBuilder.from(row).addComponents(component)
blazing ivy

Oh, i see... not sure how I missed that
Thank you!

viral cave

Hi! I recently modified a command but it refuses to update on Discord. I even deleted it, but I can still use the interaction. I don't understand, help meee!

this is my command's register

import fs from "fs";
import path from "path";
import {
  Client,
  Collection,
  PermissionResolvable,
} from "discord.js";

import log from 'silly-logger';
import { CommandModule } from '../../@types/discord.js';

export default async function registerCommands(client: Client) {
  client.commands = new Collection<string, CommandModule>();
   if (client.application) {
    await client.application.commands.set([]);
    log.info("[CMD] Toutes les commandes ont été supprimées");
  }

  client.commands = new Collection<string, CommandModule>();

  const commandsRoot = path.join(__dirname, "..", "..", "commands");
  const groups = fs
    .readdirSync(commandsRoot, { withFileTypes: true })
    .filter((dir) => dir.isDirectory())
    .map((dir) => dir.name)
    .sort((a, b) => a.localeCompare(b));

  let total = 0;
  for (const group of groups) {
    const groupPath = path.join(commandsRoot, group);
    const files = fs
      .readdirSync(groupPath)
      .filter((f) => f.endsWith(".ts") || f.endsWith(".js"))
      .sort((a, b) => a.localeCompare(b));

    for (const file of files) {
      const filePath = path.join(groupPath, file);
      const mod = require(filePath) as Partial<CommandModule & { 
        botPermissions?: PermissionResolvable[]; 
        userPermissions?: PermissionResolvable[]; 
      }>;

      if (!mod.data || typeof mod.execute !== "function") {
        console.warn(
          `[registerCommands] skipping ${group}/${file}: missing data or execute`
        );
        continue;
      }

      const commandObject: CommandModule = {
        data: mod.data,
        execute: mod.execute,
        botPermissions: mod.botPermissions,
        userPermissions: mod.userPermissions
      };

      client.commands.set(mod.data.name, commandObject);
      total++;
      log.startup(`[CMD] Commande "${mod.data.name}" chargée`);
    }
  }

  log.startup(`[CMD] ${total} commandes en cache.`);

  if (!client.application) {
    console.warn(
      "client.application is undefined; are you calling this before `ready`?"
    );
  } else {
    const payload = client.commands.map((cmd) => cmd.data.toJSON());
    await client.application.commands.set(payload);
    log.success(`[READY] ${payload.length} commandes déployées.`);
  }
}```
polar karma

Is it possible it's a command you deployed in a guild scope opposed to global

Also, setting to an empty array and then setting again is a wasted API request

viral cave
sharp ginkgoBOT

If you have duplicate commands on your server, you registered both global and guild commands.

You can remove the duplicates by resetting either the global or guild commands

  • Resetting global commands: rest.put(Routes.applicationCommands(clientId), { body: [] })
  • Resetting guild commands: rest.put(Routes.applicationGuildCommands(clientId, guildId), { body: [] })
tiny condor

Can a bot super react?

polar karma

If they can, I believe it's undocumented

tiny condor

Also one more little thing, is there a component v2 builder for djs?

unborn scarab

does djs have a headless way i can use the permissions calculator without using the full discord.js package? I'm using interactions / slash commands over HTTP only, but I still need to do some perm calculation for an outside thing.

my usecase is making sure a specific user has the permission to see a channel before making a fetch for a specific message

stable sun

I mean, you could just pull the files that it uses

unborn scarab

hmmmm, i guess that's my only option

rose tangle
tiny condor
rose tangle

not official though the djs mappings were made by a team member

tiny condor

oo thanks heart_boost

lunar jewel

what is a easy way to fix this error:

ReferenceError: require is not defined in ES module scope, you can use import instead
``` from this code:
```js
const birthName = await pool.query(`SELECT * FROM birthdays WHERE month = '${currentMonth}'`)
const birthNames = await birthName[0].map(obj => obj.name).join(`\n`)
``` If I have it commented out I don't get the error...I'm not even sure why I get the error to be honest.
rose tangle

not djs related, also that code alone shouldn't cause the error

lunar jewel

I figured it was discord.js related my bad...and I think it would because if I insert the code in that is when I get the error. I mean it's not the code that gets called out but it's the only code that is added when I get the error...I will move to another channel I guess

solemn arch

Is this how I can make me bot multi guilded or there another way? The code of my config.json is below.

"guildId": ["1398758745277730856", "1398760402216812594"]```
rose tangle

what is "multi guilded"?

are you asking about a bot you downloaded somewhere?

solemn arch
rose tangle

bots don't need any configuration to work in multiple guilds

they already do

solemn arch
rose tangle

I don't know, that depends on what you programmed

djs doesn't load any config.json

nor does it check any values from there

the fact that you have one, and a guildId property, suggests you programmed something that uses that

I don't know if you did or didn't, that's up to your code

djs doesn't need any special configuration in order to work in multiple guilds though

solemn arch

Well I import my clientId, token, and guildId to deploy my commands.

rose tangle

so are you asking about how to deploy your commands to multiple guilds?

rose tangle

then yeah you can modify your json to include the guilds you want, and iterate there

or if you basically want them to work in every guild the bot is in, deploy them globally

loud quartz

only 2 guilds for the commands to be in, or is your bot only in 2 guilds

solemn arch
rose tangle

should still help to deploy globally because commands are different, even if they have the same name and everything else exactly the same

loud quartz

if both then it doesn't matter

because those 2 guilds are all your guilds

so you can deploy globally

rose tangle
solemn arch

Or what modifications do I make?

sharp ginkgoBOT

guide Creating Your Bot: Registering slash commands - Global commands
To deploy global commands, you can use the same script from the guild commands section and simply adjust the route in the script to .applicationCommands(clientId)
read more

solemn arch

Thanks for the help.

sweet apex

first time trying to make a bot everythings going good so far just when i use my commands i get errors like this

Error in ping command: DiscordAPIError[10062]: Unknown interaction
    at handleErrors (C:\Development\Projects\ZenithBot\node_modules\@discordjs\rest\dist\index.js:748:13)
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
    at async BurstHandler.runRequest (C:\Development\Projects\ZenithBot\node_modules\@discordjs\rest\dist\index.js:852:23)
    at async _REST.request (C:\Development\Projects\ZenithBot\node_modules\@discordjs\rest\dist\index.js:1293:22)
    at async ChatInputCommandInteraction.reply (C:\Development\Projects\ZenithBot\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:200:22)
    at async Object.execute (C:\Development\Projects\ZenithBot\src\commands\Community\ping.js:14:4)
    at async Object.execute (C:\Development\Projects\ZenithBot\src\events\handlers\interactionCreate.js:129:7) {
  requestBody: { files: [], json: { type: 4, data: [Object] } },
  rawError: { message: 'Unknown interaction', code: 10062 },
  code: 10062,
  status: 404,
  method: 'POST',
  url: 'https://discord.com/api/v10/interactions/1398843044760915969/aW50ZXJhY3Rpb246MTM5ODg0MzA0NDc2MDkxNTk2OTp3aDRYc3BrY1Q1cG1jQWNJbkZ4cnJmZWYxcjQ2WXpEWGRvclo1MEZWcXA2T3dPbDl0cU95bHpBak9FVURab3FCdkw2RFJXT1k4YXlXTDFLOEZNY0FHNFN4dzNnaTFSYjdKaVZ0M3JiQ0JJRDZ0dG82cHh6ZVBvVXVtazM1cXBxaQ/callback?with_response=false'
}
(node:8900) Warning: Supplying "ephemeral" for interaction response options is deprecated. Utilize flags instead.
(Use `node --trace-warnings ...` to show where the warning was created)
Failed to send error reply: DiscordAPIError[40060]: Interaction has already been acknowledged.
    at handleErrors (C:\Development\Projects\ZenithBot\node_modules\@discordjs\rest\dist\index.js:748:13)
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
    at async BurstHandler.runRequest (C:\Development\Projects\ZenithBot\node_modules\@discordjs\rest\dist\index.js:852:23)
    at async _REST.request (C:\Development\Projects\ZenithBot\node_modules\@discordjs\rest\dist\index.js:1293:22)
    at async ChatInputCommandInteraction.reply (C:\Development\Projects\ZenithBot\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:200:22)
    at async Object.execute (C:\Development\Projects\ZenithBot\src\commands\Community\ping.js:38:6)
    at async Object.execute (C:\Development\Projects\ZenithBot\src\events\handlers\interactionCreate.js:129:7) {
  requestBody: { files: [], json: { type: 4, data: [Object] } },
  rawError: {
    message: 'Interaction has already been acknowledged.',
    code: 40060
  },
  code: 40060,
  status: 400,
  method: 'POST',
  url: 'https://discord.com/api/v10/interactions/1398843044760915969/aW50ZXJhY3Rpb246MTM5ODg0MzA0NDc2MDkxNTk2OTp3aDRYc3BrY1Q1cG1jQWNJbkZ4cnJmZWYxcjQ2WXpEWGRvclo1MEZWcXA2T3dPbDl0cU95bHpBak9FVURab3FCdkw2RFJXT1k4YXlXTDFLOEZNY0FHNFN4dzNnaTFSYjdKaVZ0M3JiQ0JJRDZ0dG82cHh6ZVBvVXVtazM1cXBxaQ/callback?with_response=false'
}

not to sure what it means by unknown interaction and I'm fixing the ephemeral warning now

sharp ginkgoBOT

Common causes of DiscordAPIError[10062]: Unknown interaction:

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

Just a question but can you use a events folder and event handling in my index.js file and then have the events in the event folder instead of cluttering up the index.js file.

clear garnet

You can design your event handling any way you see fit

And that is indeed one of the ways people set theirs up

solemn arch

Alr

I'm having problems with my ticket system. I want my select menu ticket system to create a ticket for me in a certain category based off what you selected in the select menu. It is not doing that, it is instead saying "This interaction failed", sending the select menu and embed to the channel works fine but using the select menu doesn't work. Also there is nothing logged to the console like an error or anything. Attached below is my index.js code, and ticket-system.js event code. (This is where my interaction is created for the entire ticket system)

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

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

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

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

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

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

client.login(token)```

Any help would be appreciated.

clear garnet
solemn arch

Screamlord

Why do I copy and paste. SA_madAf

coarse storm

If I use shrads to run the same bot on a few hosts, will it supposedly increase API rate limit? (50 per host)

rigid crest

i cannot remember but can drop downs support custom emojis?

stable sun

Global rate limit is by token when present, which is the majority of endpoints

stable sun
rigid crest

ok neat ty

coarse storm
stable sun
coarse storm
stable sun

Or even webhooks

coarse storm
coarse storm
stable sun

You can try contacting Discord to get a higher limit, although they will likely tell you to consider alternatives

coarse storm
stable sun

Yea, you rly don’t have that much options

coarse storm

We did any possible way to shorten it, we are at a point where the time it takes to be sent to all servers is the same as the rate limit

granite lion

any function in the whole djs library to use to convert between types of the client and api types?

red coral

customInstallURL <- this is the link from what’s in the image when you fetch the ClientApplication?

ivory palm

the bot's ws latency meaning the ping shows very high like 600+ms. What could be the problem?

steel trail
somber dome

27 12:33:13 error: TypeError: channel.permissionsFor is not a function

const channel = interaction.options.getChannel('القناة') as TextChannel
cinder shale

No

manic leaf
rancid elbow

is there a type for these interactions predefined by djs?

I first thought Interaction but that also includes ChatInputCommand

sharp ginkgoBOT
rancid elbow

thank you. do you have a tip on how I could in general find these? 😄

little pebble

Just searching on the docs, but that might have been hard to search up in this case so asking here is fine, it just comes with experience I'd say

rancid elbow
somber dome
rancid elbow
steel trail

Or use the typeguard methods

steel trail

Instead of doing an unchecked cast

fading girder

does guildmemberadd event trigger after the user does the onboarding process?

I basically want to run a script right when the system message "
Immortal
hopped into the server. — 7:03 PM"

pops up

Please tag me when you respond :)

oblique shale

(This will be getting used to log invites, not to count anything) Seems like the InviteCreate event isn't getting run.

import { Events, Invite } from "discord.js"
import { Client } from "../../lib/structures/client"

export default {
    name: Events.InviteCreate,
    async execute(_client: Client, invite: Invite) {
        console.log("Invite created")
        if (!invite) return;
        console.log(invite)
    }
}

Any other event does work.

Edit: I forgot to give the intent for guildInvites, woops.

lean sail

is there an officiial page on the guide for implementing an eval command?

polar karma

No, it's just using the eval function that's native to js, there's nothing related to d.js as far as that

The command handling is handled the same as any other command

lean sail

ok

coarse storm

Do webhooks have different limits than bots in container?
I made the same container as I did with my webhook, it has 12 sections in it. Was sent fine through webhook but in the bot it gives me errors

polar karma

What is the error

coarse storm
polar karma What is the error
ExpectedConstraintError > s.array(T).lengthLessThanOrEqual()
Invalid Array length
Expected: expected.length <= 10

Based on the error that is the problem. just didn't know webhooks had different limits

lavish cedar

It possible to add image inside the container builder?

coarse storm
lavish cedar

Any eg or guide?

sharp ginkgoBOT

guide Popular Topics: Display Components
read more

topaz bluff
stone hollow
const iconURL = message.guild.iconURL({
  extension: "png",
  size: 256,
  dynamic: false 
});```

returns gif still idk why, can someone suggest an alternative or tell the issue here, ty (ping when replying ![1dance](https://cdn.discordapp.com/emojis/1220101431265198182.webp?size=128 "1dance") )
sharp ginkgoBOT
jade portal

How is the ping of a bot calculated? Like the latency or ws??

topaz bluff

forceStatic: true

stone hollow

ty

topaz bluff
jade portal

Yes like when the ping command is used

topaz bluff

Well the client ping and the WebSocket ping aren't necessarily the same. There's many ways to calculate client ping but that's up to you to implement

Websocket ping is the one returned by discord and it's the average of all shards for your application

jade portal
topaz bluff

The guide uses

const sent = await interaction.reply({ content: 'Pinging...', withResponse: true });
interaction.editReply(`Roundtrip latency: ${sent.resource.message.createdTimestamp - interaction.createdTimestamp}ms`);
rose tangle
coarse storm
rose tangle
coarse storm

Yea, seems like I am still on 14.19.1

coarse storm
rose tangle

share the output of npm ls @discordjs/builders

polar karma

Show the code

fading girder
wary coral
fading girder
sharp ginkgoBOT
wary coral

I belive this is it

fading girder

ah perfect

ty

sweet apex

I was trying to find the documentation for the modals but i didn’t see it ive setup my embed system and handlers for modals i just wanna be able to connect the two

wary coral
sweet apex

I wouldn’t say connect but have a modal popup for creating an embed

sharp ginkgoBOT
wary coral

Modals are just another interaction

sweet apex

Thank you

worthy sail

hi there, we are working on a dashboard but run into issues with sharding...

function calculateShardId(guildId, totalShards) {
    const bigGuildId = BigInt(guildId);
    return Number((bigGuildId >> 22n) % BigInt(totalShards));
}```

```js
const shardId = calculateShardId(guildInfo, manager.totalShards);
        const shard = manager.shards.get(shardId);``` 

is this something that will work to search in the shard the server is placed in?
loud quartz

not sure what you need the shard for, but yes, that's the formula to calculate which shard is the guild on

worthy sail

thank you

if i send a post request it fires on all shards therefore i get a rate limit

loud quartz

what post request?

worthy sail

send a message

loud quartz

in a guild?

worthy sail

yes

wary coral

how is the message triggered?

worthy sail

well it worked now so i guess all good

loud quartz

are you just doing broadcastEval to send?

worthy sail

yes using broadcastEval

loud quartz

then either your code in it should check if the shard has the guild or channel in its cache

or pass the shard id from the formula to broadcastEval as a param

worthy sail

alright check, gonna implement this now

thank for your help

loud quartz

first will still run on all shards, but all shards except one will simply not do anything

while the second will only send the broadcast to the specified shard

novel mauve

is editReply the correct way to edit the "bot is thinking" message after having used deferReply for slash commands? my defer is received but i immediately get a Error [InteractionNotReplied]: The reply to this interaction has not been sent or deferred. error when trying to edit it after

loud quartz

sounds like you're trying to edit wrong interaction

show code

novel mauve

there's only one interaction

loud quartz

are you sure this is coming from this code?

also

 const messages = await client.rest.get(`/channels/${interaction.channel.id}/messages?${query.toString()}`)
``` you know you don't need to use `rest` for that, right?
sharp ginkgoBOT

method MessageManager#fetch() discord.js@14.21.0
Fetches message(s) from a channel. The returned Collection does not contain reaction users of the messages if they were not cached. Those need to be fetched separately in such a case.


// Fetch a message
channel.messages.fetch('99539446449315840')
  .then(message => console.log(message.content))
  .catch(console.error);

novel mauve

where else could it come from?

loud quartz

elsewhere

show full error with stack

novel mauve

DiscordAPIError[10062]: Unknown interaction
at handleErrors (C:\Users\suspe\Desktop\suggester-export\node_modules@discordjs\rest\dist\index.js:748:13)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async BurstHandler.runRequest (C:\Users\suspe\Desktop\suggester-export\node_modules@discordjs\rest\dist\index.js:852:23)
at async _REST.request (C:\Users\suspe\Desktop\suggester-export\node_modules@discordjs\rest\dist\index.js:1293:22)
at async ChatInputCommandInteraction.deferReply (C:\Users\suspe\Desktop\suggester-export\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:129:22)
at async Object.execute (C:\Users\suspe\Desktop\suggester-export\commands\export.js:12:9)
at async Client.<anonymous> (C:\Users\suspe\Desktop\suggester-export\index.js:20:13)
node:events:497
throw er; // Unhandled 'error' event
^

Error [InteractionNotReplied]: The reply to this interaction has not been sent or deferred.
at ChatInputCommandInteraction.editReply (C:\Users\suspe\Desktop\suggester-export\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:253:48)
at Client.<anonymous> (C:\Users\suspe\Desktop\suggester-export\index.js:27:31)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
Emitted 'error' event on Client instance at:
at emitUnhandledRejectionOrErr (node:events:402:10)
at process.processTicksAndRejections (node:internal/process/task_queues:84:21) {
code: 'InteractionNotReplied'
}

sweet apex

is there a way to debug modals whenever i try and submit one it says "Something went wrong. Try again"

loud quartz

at async Object.execute (C:\Users\suspe\Desktop\suggester-export\commands\export.js:12:9) matches with the await interaction.deferReply() in the code you sent

loud quartz
novel mauve

i don't understand how it can be unknown considering the defer is received by discord

sharp ginkgoBOT

Common causes of DiscordAPIError[10062]: Unknown interaction:

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

sounds like the third point to me

novel mauve

ah that might be it

sweet apex
loud quartz

what is client.handleModalSubmission = async (interaction) => {

novel mauve
agile nest

Can you set selectable values on a user select menu

sweet apex
loud quartz

well, that is just a random property you attach to the client

your code has to make use of it, discord.js doesn't know about any of that

sweet apex

the modals are stored the same way i store commands

client.commands.set(command.data.name, command); and than i fetch them in my interaction creator const command = client.commands.get(interaction.commandName);

agile nest

Can you set selectable values on a user select menu

sharp ginkgoBOT
rose tangle

or addDefaultUsers if you want to add from previously set users

agile nest

no like instead of select menu having all users from a guild it only has the ones i provided

rose tangle

ah, no that's not possible

use a string select menu instead, and fill it with the users you want

agile nest

well sadly they dont have small avatars

but ig thats the best i can go with

grave pond

How to prevent this ratelimit?

 | 🚨 Rate Limited! {
0|bot  |   global: false,
0|bot  |   method: 'GET',
0|bot  |   url: 'https://discord.com/api/v10/channels/1348255643236171776/messages/1397592910307791022',
0|bot  |   route: '/channels/:id/messages/:id',
0|bot  |   majorParameter: '1348255643236171776',
0|bot  |   hash: '479c05630b7b353bb5c63f707eeef2ee',
0|bot  |   limit: 5,
0|bot  |   timeToReset: 4566,
0|bot  |   retryAfter: 4566,
0|bot  |   sublimitTimeout: 0,
0|bot  |   scope: 'user'
0|bot  | }
0|bot  | 🚨 Rate Limited! {
0|bot  |   global: false,
0|bot  |   method: 'GET',
0|bot  |   url: 'https://discord.com/api/v10/channels/1348255643236171776/messages/1397594420055900180',
0|bot  |   route: '/channels/:id/messages/:id',
0|bot  |   majorParameter: '1348255643236171776',
0|bot  |   hash: '479c05630b7b353bb5c63f707eeef2ee',
0|bot  |   limit: 5,
0|bot  |   timeToReset: 4434,
0|bot  |   retryAfter: 4434,
0|bot  |   sublimitTimeout: 0,
0|bot  |   scope: 'user'
0|bot  | }
rose tangle

don't bulk-fetch messages frequently?

the only way to prevent ratelimits is to not make the requests in the first place

glossy field

if my bot got rate limit how mush time it take to unrate limit or its perm?

rose tangle

it's in the timeToReset property

oh, you're a different person, my bad, you can get that data from the rateLimited event

steel trail

And that log informs you about djs preventing your bot from hitting that ratelimit by queueing the request until it passes

somber dome

that same error

steel trail
drifting pecan

How do I check what roles a given GuildMember have? And is there a way to check if a GuildMember has a specific role?

ripe cloud

member.roles.cache is a collection of the roles they have

Hey here, I have an error that I don't understand, it's this kind of error where the transpiler says something is not valid and even reading it I'm like "... yes it is???"

    Type 'ChannelType' is not assignable to type 'ChannelType.GuildText | ChannelType.GuildVoice | ChannelType.GuildCategory | ChannelType.GuildAnnouncement | ChannelType.AnnouncementThread | ChannelType.PublicThread | ChannelType.PrivateThread | ChannelType.GuildStageVoice | ChannelType.GuildForum | ChannelType.GuildMedia'.

75         methodOptions: (option: SlashCommandChannelOption) => option.addChannelTypes(...guildChannelTypeWithText),

Like... My variable is an array of ChannelType so I really don't understand what's wrong in here?