#djs-help-v14

78874 messages · Page 60 of 79

wintry laurel

woah they updated the guide website, looks great!

pin messages are system messages right?

sharp ginkgoBOT
wintry laurel

thanks

rose tangle

(they are system messages but you can check that instead to be more accurate)

wintry laurel

guess im on the docs idk whyu im asking

wintry laurel
lyric moss
api-bot-1  | [2025-11-24T07:07:11.950Z] ERROR b39b56a470ae-1/BOT            : TypeError: fetch failed
api-bot-1  |     at fetch (/app/node_modules/discord.js/node_modules/undici/index.js:113:13)
api-bot-1  |     at process.processTicksAndRejections (node:internal/process/task_queues:103:5)
api-bot-1  |     at async resolveFile (/app/node_modules/discord.js/src/util/DataResolver.js:94:19)
api-bot-1  |     at async resolveImage (/app/node_modules/discord.js/src/util/DataResolver.js:138:16)
api-bot-1  |     at async GuildChannelManager.createWebhook (/app/node_modules/discord.js/src/managers/GuildChannelManager.js:234:27)
api-bot-1  |     at async BotService.handler (/app/services/bot/bot.service.js:596:45) {
api-bot-1  |   [cause]: Error: self-signed certificate; if the root CA is installed locally, try running Node.js with --use-system-ca
api-bot-1  |       at TLSSocket.onConnectSecure (node:internal/tls/wrap:1630:34)
api-bot-1  |       at TLSSocket.emit (node:events:508:28)
api-bot-1  |       at TLSSocket._finishInit (node:internal/tls/wrap:1076:8)
api-bot-1  |       at ssl.onhandshakedone (node:internal/tls/wrap:862:12) {
api-bot-1  |     code: 'DEPTH_ZERO_SELF_SIGNED_CERT'
api-bot-1  |   }

does anyone have an idea on why this happens when I try to fetch webhooks from a channel? 🤔

I am on DIscordJS 14.23.2

stable sun

It is a weird error to be getting if so

lyric moss

yes, other things are working fine, i.e. using existing webhooks

same with latest discordjs version

stable sun

Can you show the code leading up to it?

Oh wait, it’s trying to fetch an image

Prob whatever avatar url you passed in

lyric moss

ahhhhh

now I get it, thank you

was just preparing the code to show, this issue then I can fix on my side, I misunderstood the stack trace -.-

stable sun

Yea, had to rly look at it for a few min

lyric moss

thanks again!

normal flare

np

wide grail

What's the best way of doing this in djs 14?

  if (this.replied || !this.isRepliable() || this.deferred)
      return this.editReply(options);
  else
      return this.reply(options);

where options: string | MessagePayload | InteractionReplyOptions

e.g. can we just cast and let the djs ignore the extra flags?

wraith cedar

module.exports = {
name: 'ready',
once: true,
async execute(client) {
if i had this in djs 14.21 do i replace ready to ClientReady?

quasi ginkgo

I saw that modals support file inputs now, but I couldn't find any docs on it. How do I create a file upload component for the modal?

pale flume

Hello, question, in a modal we can make a select menu that appears if for example we fill out a field?

sharp ginkgoBOT
quasi ginkgo
tardy sable

action rows are deprecated use labelbuilder

quasi ginkgo

oh ok, thanks!

sharp ginkgoBOT
tardy sable
steel trail
pale flume
ivory wasp

Can Webhook.send send the message as if it were replying to another message?

snow onyx
ivory wasp

Yeah I don't believe so either. Thanks

brittle veldt

What type exactly ?

docs are kinda outdated.
they use a function that doesnt even exist

proud arrow

Though the docs seems incorrect right

sharp ginkgoBOT
proud arrow
wide grail
topaz bluff

this is the example version of the InteractionCreate error message handler from the guide

hardy hazel

Good evening! (in my timezone at least)
I would like to delete messages in a specific channel (not the hard part) But only when the message is:

  • only images no text
  • only text no images > got this working using the client.on(Events.MessageCreate event using these lines:
if (msg.channelId !== channelId) return false;
if (msg.attachments.size === 0) {
  await msg.delete();
}

I've tried to use the message.removeAttachments(), I've tried to just message.delete() and some other attempts that I've forgotten
However, a message with only one or more images, without text doesn't seem to trigger the MessageCreate event.

Am I supposed to be using another event, or am I missing something else?

(The bot does have the MessageContent intent, both in the code and in the developer portal)

topaz bluff

what intents and partials do you have on your client?

hardy hazel

Guilds and GuildMessages (And MessageContent)

topaz bluff

try adding the Message partial to your client

polar karma

the partial isn't required for the MessageCreate event

hardy hazel

Alright I added it like this:

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

Then in the MessageCreate Event I tried this:

if (msg.partial) {
    msg.fetch()
    .then(fullMsg => {
        fullMsg.delete();
    });
}

Unfortunately no luck
The Event is not being triggered it seems, I've added the msg.sendTyping() at the top as a test, but nothing

polar karma

your code does not check if the message has attachments but no text. all it does is check if there are no attachments and deletes it, no checks for text or anything else

hardy hazel

I've changed the code to this:

if(msg.content.length === 0 && msg.attachments.size > 0) {
  await msg.delete();
}

if(msg.content.length > 0 && msg.attachments.size === 0) {
  await msg.delete();
}

Which works for messages with just text, no images
It ignores the messages with both images and text
But still nothing for messages with only images, no text

undone lance

does my discord application have to have an online bot instance for oauth to work

bleak owl

oauth2 is not supported by discord.js. you'll want to ask in the discord developers server for that type of question

undone lance

ok

steel trail
hardy hazel
raw sable

If anyone is interested in helping me compile a common list of questions or errors/problems folks run into (doesn't have to be detailed) I'd really appreciate it, trying to build a list I can send to beginners in my community when they ask certain questions

unique shoal
sharp ginkgoBOT
raw sable

Good idea but if y'all have specific ideas that you see here beyond that feel free to lmk

unique shoal

Not to be blunt, but I'm unsure why we'd want an off-site FAQ in another community vs just expanding the one in our guide

raw sable

Of course, just trying to make a list that are thoroughly answered based on the content in my tutorials. They are tailored to relevant methods and cite specific tutorials

I'll be sure to post any finding that could be helpful beyond my needs

unique shoal

Oh you're doing tutorials?

raw sable

Problem is my videos tend to attract VERY new programmers so the answers for common issues have to be very detailed so they can avoid bugging the support team or you guys 🤣

bleak owl

what type of “common issues” are you referring to?

unique shoal

This is really more of an off-topic convo but lets continue it in general

raw sable

k

pulsar jackal

Hi guys,

For years, I used

guild.members.fetch(); 

with a slash command that show infos based on all members of a server. Recently (some weeks), I got some errors telling me that the members could not be fetched. I checked, my intents are good. I think that it is a problem of rate, the problem often happens when two commands are close in time. Anyone have hear something about it ? Any recent changes ?

unique shoal

Yes, the rate limit for this was recently changed to 1/30s

But if you've fetched once there's no reason you should have to keep fetching

pulsar jackal
unique shoal

Yeah this was specifically a change to the get members gateway op

pulsar jackal

Thank you @unique shoal !

dry flame

How do you actually fetch a specific component based on its ID when using V2 components?

topaz bluff

You don't fetch the component using the ID. But you can iterate a component in a message looking for the ID rather than trying to find a specific component using the type and text in it

dry flame

Oh I see got it, thank you

heavy hamlet

Hi guys, how do I use this method requestGuildMembers here . I have tried initializing my client like this in typescript in my index.ts.

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

Then using it in my service like this.

import { client } from '../index';

guildMembers: GuildMember[] = await client.requestGuildMembers({
            guild_id: discordGuildId,
            user_ids: discordUserIds,
        });

But I get the error this method does not exist on Client<boolean>

bleak owl
heavy hamlet

okokty

bleak owl

since this channel is strickly for v14

heavy hamlet

oh wait can I not use that in v14

bleak owl

it's not a method in discord.js itself, only on core it would seem. make sure you set the tag to core on the thread

heavy hamlet

I see that is my problem LOL ty. Is there similar in discordjs?

bleak owl

im sorry, im not familiar with /core so im not sure

heavy hamlet

oh ok all it does it gets all the members from a guild with the given user id's

stable sun
sharp ginkgoBOT
rose tangle

you can pass a user param where you set the users to fetch

it'd be the recommended approach for your case

stable sun

It uses the same underlying call

rose tangle

it'd pass the users to the request

I meant that instead of fetching individually or fetching all and then filtering

heavy hamlet

ok ty guys this is what i was looking for

wraith cedar
spice iris

@snow onyx

snow onyx

</report message:1020072425448284263>

this aint a job board

spice iris
junior ore

(node:11928) Warning: Passing "color" to RoleManager#create() is deprecated. Use "colors" instead.
(Use node --trace-warnings ... to show where the warning was created)

const created = await guild.roles.create({
          name: r.name,
          colors: r.color,
          hoist: r.hoist,
          permissions: BigInt(r.permissions),
          mentionable: r.mentionable,
          position: r.position
        });

is that right? (i changed the code)

sharp ginkgoBOT

method RoleManager#create() discord.js@14.25.1
Creates a new role in the guild with given information. The position will silently reset to 1 if an invalid one is provided, or none.


// Create a new role
guild.roles.create()
  .then(console.log)
  .catch(console.error);

subtle girder

why discordjs.guide will redirect to discordjs.guide/legacy?

wary coral
wary coral
sharp ginkgoBOT
sharp ginkgoBOT
vocal garnet

is it possible to see whether a user is "Engaged in suspected spam activity" with discord.js or not?

sharp ginkgoBOT
wary coral
junior ore
livid sun

Is it recommended to add Redis-based cache on discord.js or is it not worth the effort ?

IK the problem is must change the SYNC to ASYNC but i can make it be SYNC or ASYNC and be the same function easily

topaz bluff

Like convert the built in cache for guilds and channels into a Redis cache? From my understanding, no, it's not recommended at all

As the built in cache needs high reliability and low latency...plus isn't even that big

If you need your own caching for other things, then Redis might be a good idea

You can also just use @discordjs/core and handle all caching yourself

livid sun
topaz bluff

Your memory usage total would still be in the low MB range

livid sun
topaz bluff Like convert the built in cache for guilds and channels into a Redis cache? From...

I made a simple database package that can work with different drivers like JSON, SQLite, or MongoDB. The cool part is that the interface stays the same

For example with JSONDriver:

import { DB, JSONDriver } from 'mypkg'

const db = new DB(new JSONDriver())
const data = db.get('data')
console.log(data) // returns "Hello"

And with MongoDBDriver it’s just as easy

import { DB, MongodbDriver } from 'mypkg'

const db = new DB(new MongodbDriver())
const data = await db.get('data') // async works seamlessly
console.log(data) // returns "Hello"

So whether the driver is sync like JSON or async like MongoDB you can use the same methods and everything just works

steel trail
livid sun
steel trail

Circumventing discord limits is not TOS compliant

topaz bluff

If you need a bot with several identities, then use webhooks to customize the profile picture and username

livid sun

This is just example on discordjs
const user = guild.members.cache.get(..)
Or with redis be
const user = await guild.members.cache.get(…)

steel trail
livid sun
steel trail

No. And for the last time: this is the wrong channel to ask

junior ore

how to use .setEmoji

tardy sable
sharp ginkgoBOT
junior ore

like can u show me example

tardy sable

You can use plain emoji string or object with name and id and if animated

junior ore

oh k

junior ore
tardy sable

No has to be emoji format

so between <> and with id. Name doesnt matter much because its using the id

rose tangle

unicode emojis don't have that format

they're just in unicode

junior ore

owh dang

rose tangle

\😐

rose tangle

😐

there you go

junior onyx

How do I delete a message longer than 2000 letters in Discord.js?

median salmon
tawny roost
sharp ginkgoBOT

method Message#delete() discord.js@14.25.1
Deletes the message.


// Delete a message
message.delete()
  .then(msg => console.log(`Deleted message from ${msg.author.username}`))
  .catch(console.error);

junior onyx

I did that but it didn't work

median salmon

what error did you get

junior onyx
tawny roost

So, your message is not longer than 2000 or bot does not have the permission “ManageMessage”

median salmon

id remove the .catch(() => {});

junior onyx

My bot is translating, but I did it to measure the message sent. Normally, I should have done this for the translated message.

junior onyx
versed current

Guys when I receive an interaction from a user app, how can I check whether the bot can send public messages in that channel?
Just by the channel and the permissions?

tardy sable
junior onyx

const text = ${translated.text} + ${repliedBlock};

const botMember = message.guild.members.me;

const canDelete = botMember.permissionsIn(message.channel).has("ManageMessages");

if (text.length > 2000) {

    if (canDelete) {

        message.delete().catch(() => {});

    }

    return;

} }

await webhook.send({
    content,
    username: message.author.username,
    avatarURL: message.author.displayAvatarURL({ dynamic: true }),
    files
});

};

tardy sable

whats your error?

junior onyx
tardy sable whats your error?

It does not delete the message and tries to send my message with more than 2000 letters. In the console, the webhook exceeds the 2000 letter limit.

tardy sable

remove your silent catch and see what the error then says

halcyon bison
tardy sable
stable sun

channel.permissionsFor(client.user).has(…)

Oh, you mean non ephemeral message?

junior onyx
tardy sable

does bot need permissions to send ephemeral messages?

tardy sable
junior onyx

If the message to be sent is longer than 2000 letters, delete the sent message and stop.

halcyon bison
sharp ginkgoBOT
tardy sable
junior onyx
halcyon bison just so we're all on the same page, could you share the error rather than paraph...

Server marked as running
flags:
message_reference:
attachments: [],
sticker_ids:
thread_name:
applied_tags:
poll:
}
},
rawError: {
message:
code:
errors: { content:
},
code:
status:
method:
url:
}
Çeviri hatası: DiscordAPIError[50035]: Invalid Form Body
content[BASE_TYPE_MAX_LENGTH]: Must be 2000 or fewer in length.
at handleErrors
at async SequentialHandler.runRequest
at async SequentialHandler.queueRequest
at async _REST.request
at async WebhookClient.send
at async translateWebhook
at async Client.

stable sun
tardy sable

also youre probably meant to send the webhook with the text. youre now just sending content

stable sun

So checking text.length does nothing

junior onyx
stable sun
junior onyx

So I don't understand what my mistake was.

stable sun

text.length > 2000 is false

tardy sable
stable sun

And then you go on to send whatever is incontent for some reason, which happens to be too long

junior onyx

const text = ${translated.text} + ${repliedBlock};

const botMember = message.guild.members.me;

const canDelete = botMember.permissionsIn(message.channel).has("ManageMessages");

if (text.length > 2000) {

    if (canDelete) {

        message.delete();

    }

    return;

} }

await webhook.send({
    content,
    username: message.author.username,
    avatarURL: message.author.displayAvatarURL({ dynamic: true }),
    files

});
};

stable sun

Now you just have unbalanced curly braces

Or ig this was always the case

junior onyx
tardy sable

we already told you to put your content as text

stable sun

It’s simply that your checking the length of text, not content

junior onyx
junior onyx
stable sun
tardy sable
stable sun

.send({ content }) is the same as .send({ content: content })

junior onyx
loud quartz

No

This isn't a guessing game

junior onyx
tardy sable

is it the language barrier or youre new to djs? if its djs its best to read the starter docs

loud quartz
junior onyx

Are the replied and translated messages text or content?

stable sun

I don’t know what you defined as content

junior onyx
stable sun

You only have const text = …

Do console.log(content) if you want to see what you’re trying to send

The error suggests it’s a string

junior onyx

I haven't set anything as content and I don't want it to be sent either. I'm trying to do the border part first.

Anyway, good night to all three of you.

loud quartz

and I don't want it to be sent either.
then don't do that. don't use content, in the send()

stable sun

Unless you omitted crucial parts from the code you provided, you are sending content which causes the error

junior onyx
loud quartz

it is

but you're not checking content for that

junior onyx
loud quartz

because you aren't doing it

something you are not doing will not work

junior onyx
velvet flint

What functions have appeared for the new rights?

junior onyx

Finally const content = ${translated.text} + ${repliedBlock}; like this

Anyway, I'll check it out tomorrow.

loud quartz

or just send content: text instead of content

since you already have checks for the text

stable sun

You should prob stop using object entry shorthand if you don’t know what it does

loud quartz
velvet flint
loud quartz

on discord's side, yes

we aren't discord so we don't have those yet in a stable release

or at least we might have the pin one, if it managed to get in

velvet flint

What will the function look like?

loud quartz

function?

stable sun

What functions were you expecting?

loud quartz

it's just 2 permissions

like all other permissions that we have already

stable sun

We alr have methods for changing permissions on roles and channels

All the change would do is add permissions you can use in code

velvet flint
stable sun

Probably. It depends on how Discord names it in their docs

sharp ginkgoBOT
velvet flint

I hope you will have such names so that you don't have to change them in the code in the future.

stable sun

Looks like it is that

stable sun

If they change it, then we change it too

velvet flint

It's sad, changing all the permissions in the code where there are 2 thousand lines will take time.

stable sun

It’s pretty easy to do a find and replace all across files

At least in VSC

Or ig you have to think abt each case since it’s splitting ManageMessages

junior ore

like what is the reason

median salmon

idk but it forced me to rewrite my emoji thingy but also made it more annoying

its now an object with these emoji objects in

function so i dont have to annotate each, this also means i have to use a function if i want it in a string

ugly

wary coral
median salmon

server emojis cos im too lazy to reupload

stable sun
median salmon

tried that but it was a bit messed up and i couldnt be bothered

stable sun

Don’t we have a parseEmoji function?

sharp ginkgoBOT

function parseEmoji discord.js@14.25.1
Parses emoji info out of a string. The string must be one of:* A UTF-8 emoji (no id)* A URL-encoded UTF-8 emoji (no id)* A Discord custom emoji (<:name:id> or <a:name:id>)

stable sun

Just use that to convert the text to object

median salmon

i think using a .toString on a class would be okay but i dont know how well discordjs responds to that

i remember it erroring but forget wxactly why, ill try again
this slowmode is super fun

stable sun

It just pulls the props it needs. 🦆

wary coral
median salmon
flint mason

Hey, on messageCreate I can do if (message.reference?.type == MessageReferenceType.Forward) return but later I want to check content of forwarded message, how to do this?

median salmon

no errors
i dont know why this failed last time

median salmon
sharp ginkgoBOT
flint mason

Oh that's >=14.25.1, i need to update

stable sun

I don’t remember when it was added

The version just shows what the docs is for

It’s guaranteed to be on v14.25.1, but not necessarily exclusive to that version

median salmon
wary coral

or you can just use the function

median salmon

configured the rule to allow my class

i prefer it to be easy to read but also somewhat to type

and i dont want to type a function everytime if i can do this which i dont consider hacky/a bodge

balmy bobcat

is there a slash command in this channel that uses autofill so I can see how it looks on my client

median salmon

yes /github if you mean autocomplete

stable sun
balmy bobcat

oh cool

stable sun
chilly junco

The guide (and all other places I can find) say to specify the application ID used when syncing commands in the bot config.
Is there a good reason for this? Why not get the app id dynamically through the API? I'd be very interested to know!

halcyon edge

I want to ask how to send attachments in modals like the picture I sent.

sharp ginkgoBOT
wary coral
ruby bane
clear garnet

I mean, you could technically just grab the application ID out of the token via Buffer.from(token.split(".")[0], "base64").toString() if you really were against statically storing the ID

chilly junco

It's One More Variable to set in the config, was mainly just curious why it seems to be the only method going around. Thanks for your answers!

ruby bane

its by far the easiest

chilly junco

const { id: appId } = await api.applications.getCurrent(); is not that much harder :p

but fair enough, seems fitting to be what's generally recommended

loud quartz
slim burrow

    return typeof value === "string" ? Result.ok(value) : Result.err(new ValidationError("s.string()", this.validatorOptions.message ?? "Expected a string primitive", value));
                                                                     ^

ValidationError: Expected a string primitive
    at _StringValidator.handle (C:\Users\yusuf\Documents\programming projects\discordbots\nouritytrial\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:2615:70)
    at _StringValidator.parse (C:\Users\yusuf\Documents\programming projects\discordbots\nouritytrial\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:972:90)
    at MixedClass.addChoices (C:\Users\yusuf\Documents\programming projects\discordbots\nouritytrial\node_modules\@discordjs\builders\dist\index.js:2947:25)
    at C:\Users\yusuf\Documents\programming projects\discordbots\nouritytrial\src\commands\util\feedback\main.js:38:14
    at MixedClass._sharedAddOptionMethod (C:\Users\yusuf\Documents\programming projects\discordbots\nouritytrial\node_modules\@discordjs\builders\dist\index.js:3261:50)
    at MixedClass.addStringOption (C:\Users\yusuf\Documents\programming projects\discordbots\nouritytrial\node_modules\@discordjs\builders\dist\index.js:3233:17)
    at Object.<anonymous> (C:\Users\yusuf\Documents\programming projects\discordbots\nouritytrial\src\commands\util\feedback\main.js:33:10)
    at Module._compile (node:internal/modules/cjs/loader:1546:14)
    at Object..js (node:internal/modules/cjs/loader:1689:10)
    at Module.load (node:internal/modules/cjs/loader:1318:32) {
  validator: 's.string()',
  given: 1
}

clear garnet

You're adding a string option, but the values you're specifying for its choices are numbers

slim burrow

i tried that but Ig i didnt save the file like a dumbass when i restarted it. Thanks tho ❤️

tardy sable

is channel.permissionsFor(client.user).has(PermissionsBitField.Flags.SendMessages) sufficient to check if bot can send messages in channel? or also add isSendable to it?

rose tangle

isSendable checks that the send method exists, not that you have enough permissions

depending on where you get the channel it may be required

there's also implicit permissions so you also need ViewChannel, and maybe some others, check the guide

sharp ginkgoBOT

guide Implicit permissions
Some Discord permissions apply implicitly based on logical use, which can cause unwanted behavior if you are not aware of this fact. The prime example for implicit permissions is ViewChannel. If this flag is missing in the final permissions, you can't do anything on that channel. It makes sense, right? If you can't view the channel, you can't read or send messages in it, set the topic, or change its name. - Text Channels require ViewChannel as detailed above.

dry flame

Am I not allowed to update the response to an interaction more than once?

rose tangle

you can

but if you mean literally calling update() twice then no

update() is a reply, you can't reply twice

if you want to edit after an update(), do editReply()

dry flame

Gotcha, thank you!

subtle falcon

Is it possible to make an option with choices but these choices are from an autocomplete ?

rose tangle

so basically just an autocomplete?

subtle falcon

Yeah but lock all options that are not from the autocomplete

unique shoal

no

You'd have to do that validation yourself

subtle falcon

Okay

sturdy epoch

quick question, is it still possible to make message-prefix commands even using djs v14, assuming message content intent is approved (or for just a private bot so no need to apply for intents as long as it does not exceed 100 servers)

outer plume
outer plume

np heartWumpus

languid shoal

its pretty late rn so im very stupid but so far i've been copying code directly from the documentation
my ready event just does not execute it seems, no prints or any logs
event handler:

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));
    }
}

ready.js:

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

module.exports = {
    name: Events.ClientReady,
    once: true,
    execute(client) {
        console.log(`Ready! Logged in as ${client.user.tag}`);
    },
};
rose tangle

and is that ready.js in the events folder

languid shoal
languid shoal
rose tangle

and you're sure that event handler is executing?

languid shoal
rose tangle

well the event handler is just javascript, nothing djs specific

if you're a beginner to js as well you should learn that first, otherwise you'll just copy and paste and it'll be more difficult for you

languid shoal

okay dont laugh but i just figured out the problem
i misclicked and didnt save the file 🤦‍♂️
mb for the time waste lol

rose tangle

no worries, it's not the first time it has happened lol

ionic dome

Hi, I want to ask how to enable sending image attachments directly through modals, like in the example image I sent.

sharp ginkgoBOT
rose tangle

add a label which holds the file upload component

tiny condor

Is that always 100mb or server limit

hazy agate

Is it possible to modify the current guild member to change avatar and banner and bio yet?

sharp ginkgoBOT
proud arrow
hazy agate

are file uploads supported yet?

yes ok found it

can I set my avatar from an Attachment object?
it says it requires a base64 or buffer object, can I convert it somehow?

tiny condor

Is that also a Label?

hazy agate

not mentioned here though

stable sun
sharp ginkgoBOT

typealias BufferResolvable discord.js@14.25.1
Data that can be resolved to give a Buffer. This can be:* A Buffer* The path to a local file* A URL When provided a URL, discord.js will fetch the URL internally in order to create a Buffer. This can pose a security risk when the URL has not been sanitized

stable sun

Not sure why it’s being formatted weirdly

Basically, under this type, string is interpreted as file path or url that d.js will automatically fetch for you

stable sun
cobalt solstice

hey, quick question

<Guild>.roles.everyone returns the ID of the role or the role itself? and would that ping the role in a command reply?

steel trail

The role and yes, if allowed in allowedMentions

loud quartz
cobalt solstice
twin bane

Hey, I keep reading everywhere that .fetch checks the cache before actually fetching it from the api... But I keep getting Rate Limit errors when repeatedly fetching the same guild? Why is that?

steel trail

Fetching a guild or fetching all members of a guild?

twin bane

await client.guilds.fetch(id)

Oh wait.. later I do await guild.members.fetch({user: membersData.map((member) => member.id)})

steel trail

Yeah, that's the one getting you rateLimited

twin bane

But why isn't it using the cache for that one?

steel trail

Because you don't fetch a single user. You fetch multiple. That's not using REST but instead the gateway

And thus it won't use cache because it's not a simple has() call to check if all of those are cached already and we assume that when you fetch multiple like that you want current data

twin bane

Ok.. so I guess I need to return the data with just the ids and have the user fetch it with their own access token

steel trail

Why are you doing all this fetch in the first place? Guilds your bot is in are all cached on ready, so you can always get that from cache. And depending on what else your bot does the members might be too

steel trail
twin bane
steel trail

Then do a cache check yourself before the fetch

sharp ginkgoBOT

method Collection#hasAll() discord.js@14.25.1
Checks if all of the elements exist in the collection.

steel trail

Or probably even better to get the array of ids not cached and fetch those

twin bane

Hmm.. Thanks

But if I only fetch one user, it uses the cache?

tardy sable
twin bane

Ok thanks

It works! Thanks you two 😅

normal flare
const choiceInteraction = await interaction.editReply({
  content: config.getSelectionMessage(query),
  components: [selectRow, buttonRow],
});

const collector = choiceInteraction.createMessageComponentCollector();

collector.once('collect', async (componentInteraction) => {
  if (componentInteraction.isStringSelectMenu()) {
     // redacted
  } else if (componentInteraction.isButton()) {
    console.log('Documentation command cancelled by user.');
    await choiceInteraction.delete(); // Error: 'Unknown Message'
    // this works: await interaction.editReply({ content: 'Command cancelled.', components: [] })
  }
});

am I doing something wrong here?

wary coral
normal flare

DiscordAPIError[10008]: Unknown Message
when I click on "Cancel"

I prefer deleting the interaction instead of editing it with this:

await interaction.editReply({ content: 'Command cancelled.', components: [] })```
red coral

.deleteReply instead of .delete

topaz bluff

Since it's ephemeral, you can't treat it at a message. You can only respond/edit using the interaction webhook

normal flare

should I be deleting the main interaction instead of choiceInteraction?

wary coral

deleteReply is on the interaction like editReply

normal flare

okay thanks, interaction.deleteReply works, I guess assigning interaction.editeply to choiceInteraction isn't needed

nvm I'm usng it for the collector

icy mica

can we get data from textdisplaybuilder in modal? I wanna make a data transfer with it. Like; Reported User ID: 123 and when i handle the model in another file i need the read that text display

sharp ginkgoBOT
uneven plover

Working with a user select option in a command....interaction.options.getMember('user') this returns as GuildMember | APIInteractionDataResolvedGuildMember | Null. I can deal with the Null, but how do I narrow on the other? And What is the diffence in them?

wary coral

The API interaction data resolved. Guild member object will only occur if the guild is not cached. The easiest way is to remove it with a cached guild type guard on the interaction

sharp ginkgoBOT
valid pulsar

Help with compoments v2 type

sharp ginkgoBOT

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

valid pulsar

What

dense jackal

read the guide

valid pulsar

Ty

indigo storm

I need help with components v2 type.
Not the usual one, but the one where everything is built with Type for example: Type 14 for dvdier

wary coral
indigo storm
sharp ginkgoBOT

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

indigo storm

Yes i chat that but i not found how to use in types

wary coral

I don't understand what you mean by types

indigo storm
wary coral

No, I am here in this channel

tardy sable
wary coral

If you could share code example of what you're trying to do. I think that might help

indigo storm
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.

unique shoal

why would you need types in javascript

indigo storm

Like this: ```js
const thumbnail = {
type: 11,
media: {
url: client.user.displayAvatarURL()
},
description: "Drix Logo"
};

const titleSection = {
  type: 9,
  components: [titleText],
  accessory: thumbnail
};
wary coral

I recommend using the component builders(as shown in the guide) as they will be converted to the component json form for you

indigo storm

I don't want to use what's on the site that was sent first by the bot because it doesn't look as good when it's not using Type like in the code I sent which is like Json.

wary coral

What do you mean doesn't look as good? When using the builder versus the raw json

Anyway, but I digressed what particularly are you having an issue with in regards to sending the component json

indigo storm
wary coral

I guess I still don't understand what's wrong? Or what issue you're having?

unique shoal

type: 9 looks far worse than at a minimum using the ComponentType enum

sharp ginkgoBOT
severe pumice
wary coral
rose tangle

also you shouldn't deploy on every start

you'll get ratelimted very fast

that's why the guide uses a separate script called manually

severe pumice
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
unique shoal

Well since it says "redirect_uris" it must be a primary launch command or something

wary coral

Apps can only have one of those right?

severe pumice
tacit veldt
hazy raft

im trying to make it so if the user selects "off" first, it no longer shows options. is that possible with this?

  s.setName("ban")
    .setDescription("Mass-ban protection.")
    .addStringOption(o =>
      o.setName("state")
        .setDescription("on/off")
        .setRequired(true)
        .addChoices(
          { name: "on",  value: "on"  },
          { name: "off", value: "off" }
        ))
    .addIntegerOption(o =>
      o.setName("threshold")
        .setDescription("Ban limit")
    )
    .addStringOption(o =>
      o.setName("do")
        .setDescription("Action")
        .addChoices(
          { name: "ban",        value: "ban"   },
          { name: "kick",       value: "kick"  },
          { name: "stripstaff", value: "strip" }
        )
    )
    .addBooleanOption(o =>
      o.setName("commands")
        .setDescription("Detect mod commands?")
    )
)
unique shoal

no, additional options are not dynamic

You could use subcommands though?

hazy raft
sharp ginkgoBOT

guide suggestion for @hazy raft:
guide Subcommands
Subcommands are available with the .addSubcommand() method. This allows you to branch a single command to require different options depending on the subcommand chosen.

tardy sable

im kinda confused about channel.isSendable(). whats a non sendable channel?

tardy sable

or do i just use channel.permissionsFor() has sendmessages?

tardy sable

thanks, also does bot need embed perms to send embed messages? or that only applies for embedding links?

stable sun

You will get a Missing Permissions error if you try to send embeds w/o the perm

neon gust

What I'm doing wrong here, trying to send attachments with webhook

DiscordAPIError: Invalid Form Body
attachments[0]: Attachment data not found

const webhookPayload = {
      content: cleanContent,
      files:
        targetMessage.attachments.size > 0
          ? targetMessage.attachments.map((a) => a)
          : [],
    };

await webhook.send(webhookPayload);

Also tried

targetMessage.attachments.map((a) => a.url)
webhookPayload.files: [
  MessageAttachment {
    attachment: 'https://cdn.discordapp.com/attachments/...',
    name: 'xxxxxxxx.jpg',
    id: 'xxxxxxxxxxxxx',
    size: 222750,
    url: 'https://cdn.discordapp.com/attachments/...',
    proxyURL: 'https://media.discordapp.net/attachments/...',
    height: 2270,
    width: 1290,
    contentType: 'image/jpeg',
    description: null,
    ephemeral: false,
    duration: null,
    waveform: null,
    flags: AttachmentFlags { bitfield: 0 },
    title: null
  }
]
rose tangle

what's the error with a.url

neon gust
rose tangle

is that the entire code? why is the payload in a different property and not directly in the method, are you using it before sending?

wicked flax

would any of you all know what api url I should use to grab how many users have my bot installed (user installed apps)

rose tangle

api url or djs method?

wicked flax
rose tangle

are you using djs at all?

wicked flax

yeah

sharp ginkgoBOT
rose tangle

oops, wrong approximate

wicked flax

that looks right though

sharp ginkgoBOT
rose tangle

the other one is for oauth

wicked flax

oh yeah

rose tangle

ClientApplication is on Client#application

wicked flax

Thanks

carmine hearth

Hey, i’m getting this error: DiscordAPIError[10062]: Unknown interaction

Console Logs:

2025-11-27T07:29:27.493040021Z [inf]  Start button already exists, skipping post.
2025-11-27T07:29:27.493121559Z [inf]  ✅ Logged in successfully.
2025-11-27T07:29:27.493130067Z [inf]  ✅ Bot logged in as Homeland Security Helpers BETA#7445!
2025-11-27T07:29:27.493132949Z [err]  (node:1) DeprecationWarning: The ready event has been renamed to clientReady to distinguish it from the gateway READY event and will only emit under that name in v15. Please use clientReady instead.
2025-11-27T07:29:27.493192220Z [err]  (Use `node --trace-deprecation ...` to show where the warning was created)
2025-11-27T07:29:27.493202299Z [inf]  Successfully registered /timestamp command to guild: 1437715430545428553.
2025-11-27T07:29:27.497996821Z [inf]  ✅ Successfully registered /activityreport command to guild: 1437715430545428553.
2025-11-27T07:29:28.737164262Z [inf]  Successfully registered /logarrest command in guild: 1437715430545428553
2025-11-27T07:29:28.737173234Z [inf]  Successfully registered /availablecallsigns command in guild: 1437715430545428553
2025-11-27T07:29:28.737181791Z [inf]  Successfully registered /autorole command in guild: 1437715430545428553
2025-11-27T07:29:28.737193457Z [inf]  [ROBLOX] Bot logged in successfully.
2025-11-27T07:29:29.687922818Z [inf]  ✅ /shift manage registered
2025-11-27T07:29:29.687933719Z [inf]  ✅ All modules ready.
2025-11-27T07:30:50.322664228Z [inf]  [DEBUG] Shift manage command triggered by ryannuggets3
2025-11-27T07:30:50.322673477Z [inf]  [DEBUG] Interaction received: type=2, user=ryannuggets3
2025-11-27T07:30:50.322679973Z [inf]  [DEBUG] Command interaction: shift
2025-11-27T07:30:50.322686559Z [inf]  [DEBUG] Shift manage UI sent for ryannuggets3
2025-11-27T07:30:52.204418293Z [inf]  [DEBUG] Shift button clicked: SHIFT_START_DHS by ryannuggets3
2025-11-27T07:30:52.206340906Z [inf]  [DEBUG] Interaction received: type=3, user=ryannuggets3
2025-11-27T07:30:52.206347785Z [inf]  [DEBUG] Button interaction: SHIFT_START_DHS
2025-11-27T07:30:53.258127204Z [err]  [WARN] deferUpdate failed: DiscordAPIError[10062]: Unknown interaction
2025-11-27T07:30:53.258128784Z [err]      at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
2025-11-27T07:30:53.258139630Z [err]      at handleErrors (/app/node_modules/@discordjs/rest/dist/index.js:762:13)
2025-11-27T07:30:53.258146965Z [err]      at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
2025-11-27T07:30:53.258153460Z [err]      at async BurstHandler.runRequest (/app/node_modules/@discordjs/rest/dist/index.js:866:23)
2025-11-27T07:30:53.258160609Z [err]      at async _REST.request (/app/node_modules/@discordjs/rest/dist/index.js:1307:22)
2025-11-27T07:30:53.258169175Z [err]      at async ButtonInteraction.deferUpdate (/app/node_modules/discord.js/src/structures/interfaces/InteractionResponses.js:305:22)
2025-11-27T07:30:53.258172720Z [err]    method: 'POST',
2025-11-27T07:30:53.258187066Z [err]    url: 'https://discord.com/api/v10/interactions/1443504333227425882/aW50ZXJhY3Rpb246MTQ0MzUwNDMzMzIyNzQyNTg4MjpOYUZUNXJBMFdmNUh4bDRmQjVoSDhvNzFEMURjM2V2WGt3aXhENjFxM2VVU2UzeFNUU0VWMW5zN2t1N095TEk5emg4OTdJMURmOHZ1T3V5cU14SlhtTTc3VjFTSFVIS3JJeGhhM0tvZ21KV25CNm0yTFBpcE94TDZ3bmNrczVXcA/callback?with_response=false'
Z21KV25CNm0yTFBpcE94TDZ3bmNrczVXcA/callback?with_response=false'
2025-11-27T07:30:53.263417692Z [err]  }```
2025-11-27T07:30:53.258200839Z [err]      at async Client.<anonymous> (/app/index.js:84:13) {
2025-11-27T07:30:53.258210883Z [err]  ❌ Error handling interaction: TypeError: shiftManageModule.handleShiftButtons is not a function
2025-11-27T07:30:53.258217506Z [err]    requestBody: { files: undefined, json: { type: 6 } },
2025-11-27T07:30:53.258230000Z [err]    rawError: { message: 'Unknown interaction', code: 10062 },
2025-11-27T07:30:53.258230470Z [err]      at Client.<anonymous> (/app/index.js:89:37)
2025-11-27T07:30:53.258239782Z [err]    code: 10062,
2025-11-27T07:30:53.258247360Z [err]    status: 404,
2025-11-27T07:30:53.263298817Z [err]  ❌ Error in handleShiftButtons: DiscordAPIError[40060]: Interaction has already been acknowledged.
2025-11-27T07:30:53.263307876Z [err]      at handleErrors (/app/node_modules/@discordjs/rest/dist/index.js:762:13)
2025-11-27T07:30:53.263315284Z [err]      at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
2025-11-27T07:30:53.263321617Z [err]      at async BurstHandler.runRequest (/app/node_modules/@discordjs/rest/dist/index.js:866:23)
2025-11-27T07:30:53.263328878Z [err]      at async _REST.request (/app/node_modules/@discordjs/rest/dist/index.js:1307:22)
2025-11-27T07:30:53.263335681Z [err]      at async ButtonInteraction.update (/app/node_modules/discord.js/src/structures/interfaces/InteractionResponses.js:354:22)
2025-11-27T07:30:53.263343081Z [err]      at async handleShiftButtons (/app/Features/ShiftManagement/shiftmanage.js:182:13)
2025-11-27T07:30:53.263350013Z [err]      at async Client.<anonymous> (/app/Features/ShiftManagement/shiftmanage.js:72:17) {
2025-11-27T07:30:53.263356226Z [err]    requestBody: { files: [], json: { type: 7, data: [Object] } },
2025-11-27T07:30:53.263363852Z [err]    rawError: {
2025-11-27T07:30:53.263371806Z [err]      message: 'Interaction has already been acknowledged.',
2025-11-27T07:30:53.263378383Z [err]      code: 40060
2025-11-27T07:30:53.263386089Z [err]    },
2025-11-27T07:30:53.263391710Z [err]    code: 40060,
2025-11-27T07:30:53.263398754Z [err]    status: 400,
2025-11-27T07:30:53.263404849Z [err]    method: 'POST',
2025-11-27T07:30:53.263411574Z [err]    url: 'https://discord.com/api/v10/interactions/1443504333227425882/aW50ZXJhY3Rpb246MTQ0MzUwNDMzMzIyNzQyNTg4MjpOYUZUNXJBMFdmNUh4bDRmQjVoSDhvNzFEMURjM2V2WGt3aXhENjFxM2VVU2UzeFNUU0VWMW5zN2t1N095TEk5emg4OTdJMURmOHZ1T3V5cU14SlhtTTc3VjFTSFVIS3JJeGhhM0tv```

Anyone know how to fix this? Im genuinely going crazy. The bot simply when command is run it has three buttons, its a shift management bot so when i click the button, instead of doing what its supposed to do, it does nothing and sends that in console

sharp ginkgoBOT

tag suggestion for @carmine hearth:
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
  • DiscordAPIError: Interaction has already been acknowledged
  • [InteractionAlreadyReplied]: The reply to this interaction has already been sent or deferred.

You have already replied to the interaction.

  • Use <Interaction>.followUp() to send a new message
  • If you deferred reply it's better to use <Interaction>.editReply()
  • Responding to slash commands / message components
pliant forum

Looking around on the interwebs and I'm not finding anything about Discord bot directory conventions--are there any links I could find about them?
I'm used to (or trying to get used to) the standard project convention--src/, lib/, build/, whatnot, at root level--but I'm looking around at other bot repo's and I'm not finding a consistent pattern

velvet cipher
pliant forum

Ah, gotcha. Thanks for the pointer

wary coral
pliant forum

+👍

vagrant rampart

How can I convert 36953089 to PermissionsBitField so i can use .has()?

subtle girder

If i use try, catch
err.stack only shows this:

Error: Received one or more errors
    at _ArrayValidator.handle (/app/node_modules/@sapphire/shapeshift/dist/cjs/index.cjs:1254:70)
    at _ArrayValidator.parse (/app/node_modules/@sapphire/shapeshift/dist/cjs/index.cjs:972:90)
    at EmbedBuilder.addFields (/app/node_modules/@discordjs/builders/dist/index.js:239:31)
    at rpg_commands.eat (/app/cogs/rpg/msg_handler.js:1408:27)
    at process.processTicksAndRejections (node:internal/process/task_queues:103:5)
    at async rpg_handler (/app/cogs/rpg/msg_handler.js:2008:20)
    at async Object.execute (/app/cogs/rpg/msg_handler.js:2085:13)
    at async DogClient.run_execute (/app/utils/load_cogs.js:11:13)

but iirc, It will show what errors received when the error is threw and the process exited

how to show more detail using try catch?

wary coral
wary coral
sharp ginkgoBOT
vagrant rampart
wary coral

Which endpoint are you hitting? If you're using djs, you should be able to hit the endpoint as part of the library and get get it back as an object

wary coral

I think you would do

const bitfield = new PermissionsBitField(36953089)
vagrant rampart
ivory wasp

Can someone tell me how to properly type narrow channels so I can call message.channel.fetchWebhooks()? I've found ChannelType.GuildText too restrictive as it does not include Forums and I can't find any combination of the channel.isX() variants to work

sharp ginkgoBOT
wary coral

use it in the negative

!channel.isDMBased()
ivory wasp

Ok I'm perhaps doing something a little more nuanced. I want to send a webhook to a channel, but the webhook can exist on the parent in the case of threads and forums. So I have:

let guildChannel = message.channel;
  const isThread = message.channel.isThread();
  if (isThread && message.channel.parent && !message.channel.parent.isDMBased()) {
    guildChannel = message.channel.parent;
  }

But the last assignment still gets a type error: Type 'ForumChannel' is missing the following properties from type 'TextChannel': setType, lastMessage, lastPinAt, messages, and 7 more.ts(2322)

wary coral

why not get the webhook from the guild level

sharp ginkgoBOT

method Guild#fetchWebhooks() discord.js@14.25.1
Fetches all webhooks for the guild.


// Fetch webhooks
guild.fetchWebhooks()
  .then(webhooks => console.log(`Fetched ${webhooks.size} webhooks`))
  .catch(console.error);

ivory wasp

Dunno, I guess I figured it was more narrowed to find the webhook on the channel the message is in, since that's the only place it would be for my use case

I don't need to check every webhook, but if the typing is easier to work with I'll switch it

Oh, actually, I do need to call channel.createWebhook in another flow, so that's why

With isDM negation, trying to call channel.createWebhook() gets

  Property 'createWebhook' does not exist on type 'PublicThreadChannel<boolean>'.```
wary coral

I am over thinking it. 'fetchWebhooks' in channel should work

ivory wasp

I think so too. Just need the proper type narrowing

wary coral

well it is on these types NewsChannel | StageChannel | TextChannel | VoiceChannel

halcyon bison

tbh it could also be easier to just use a non-null assertion
it doesn't seem like there are any channel types in which you could receive a message and also be unable to have a webhook on that channel or its parent in the case of threads
so on the assumption you have the Guilds intent, message.channel or message.channel.parent should exist and have that method
you'd therefore only really need to check channel.isDMBased() (or message.inGuild()) and determine if you need the parent or not

warped ferry

That's a property you're trying to narrow there.

Use ```
const parent = message.channel.parent;
if (!parent.isDMBased()) {
// parent is properly typed here
}

normal delta

Hi, does anyone knows why role.permissions.any() returns true when the role ascends in the hierarchy of roles?
And how to avoid that

wary coral
normal delta
wary coral what permissions are you checking for?
const perms = newRole.permissions.any([
    PermissionsBitField.Flags.Administrator,
    PermissionsBitField.Flags.ModerateMembers,
    PermissionsBitField.Flags.MentionEveryone,
    PermissionsBitField.Flags.ManageGuildExpressions,
    PermissionsBitField.Flags.KickMembers,
    PermissionsBitField.Flags.BanMembers,
    PermissionsBitField.Flags.ManageChannels,
    PermissionsBitField.Flags.ManageGuild,
    PermissionsBitField.Flags.ManageRoles,
    PermissionsBitField.Flags.ManageWebhooks,
    PermissionsBitField.Flags.ManageMessages]);

"perms" return true

wary coral

that will return true as long as the role has one of those perms

normal delta

It doesn't have any of those roles, it's a newly created role

little pebble

Show where you're creating the role

normal delta
little pebble Show where you're creating the role

Just pressing the "Create Role" button on Roles, the code is using roleUpdate method
Let me add one detail: this only happens when the role style is a gradient; if the role has a solid color, it allows you to move it normally.

halcyon bison

if I had to guess with only the information provided, I'd guess this code is executing for the wrong role(s) as you rearrange roles through the ui
when you change the position of a role, this often affects other roles' positions, and the roleUpdate event does fire for each individual role affected
at no point should something other than a role's permissions affect how <Role>.permissions.any() behaves

normal delta
normal delta
abstract forge

I'm probably being blind but is there a way to create a scheduled event (pictured below) aand make it staart instantly via a bot?

sharp ginkgoBOT
abstract forge

thank you ❤️

tribal hatch

How to add multiple flags to intraction.reply?

topaz bluff

With an array

wary coral
tribal hatch
wary coral
tribal hatch

Can I make it so that people mentioned in a message don't receive notifications?crySparkle

stable sun
sharp ginkgoBOT
stable sun

Preferably in the send method for one-off situations

Guide doesn’t seem too descriptive. I’ll just send docs

sharp ginkgoBOT
wary coral

Could also add the silent flag which I believe prevents the push notification. But will still notify (red) the user of a mention. But I have a feeling that allow mentions is what you're looking for

sharp ginkgoBOT
tribal hatch

I added

allowedMentions: {},

My problem was that I mention all clan members, and each of them receives a notification : D

Tysm

ivory wasp
export function getWebhookableChannel(message: Message) {
  let result: typeof message.channel | ForumChannel | MediaChannel =
    message.channel;
  if (result.isDMBased()) return null;
  if (result.isThread() && result.parent) {
    result = result.parent;
  }
  if ('fetchWebhooks' in result && 'createWebhook' in result) {
    return result;
  }
  return null;
}

This is quite ugly. Open to suggestions tho.

halcyon bison

though if you're allowing null, then I suppose it's unnecessary to assert non-null and you could just return result regardless

ivory wasp

function getWebhookableChannel(message: Message): NewsChannel | StageChannel | TextChannel | VoiceChannel | ForumChannel | MediaChannel | null

Seems fine for now I guess

wary coral
ivory wasp ```js export function getWebhookableChannel(message: Message) { let result: ty...

I think this does the same as your function but look a little nicer

export default function getWebhookableChannel(message) {
    if(!message.inGuild()) return null
    const channel = message.channel.isThread() ? message.channel.parent : message.channel
    return channel
}

I don't think the last check is required as their is no case where that is is true and the above is false nv that is not right. but mine has that case covered

clever hazel

how many componenets can u have in Container?

rose tangle

the whole message can only have 40 components

there's no specific limit for components in containers, as long as there isn't more than 39 (the container itself counts as 1)

lean sail

what event do i listen to if i want to know when a scheduled event ends?

sharp ginkgoBOT
viscid hill
jagged rock

Whenever someone changes their profile picture
It for some reason checks everything in their profile again
And logs any customizations in the server like server name as if they just happened

this is for guild memmebr update event

How to fix?

rose tangle

djs doesn't log anything by itself

jagged rock

if soemoen changes their global avatar it triggers with random stuff?

rose tangle

you must've put some listener somewhere that logs the member

if that's what's being logged

rose tangle
jagged rock
rose tangle

like I mentioned, djs doesn't do that by itself, you must've put some console.log somewhere and forgotten about it

if it did then it would've been caught by a lot of people by now

unique shoal

How are you checking what changed

jagged rock

but i get false positives

unique shoal

If the member wasnt cached previously you might be comparing to a partial

opaque mason
Property 'label' is missing in type '{ customId: string; placeholder: string; required: true; style: TextInputStyle.Paragraph; type: ComponentType.TextInput; }' but required in type 'TextInputComponentData'.

Any solution? This text input component is within a label component, meaning the label is defined there, and the code actually runs fine, but this is appearing in the problems tab in the IDE.

jagged rock
rose tangle

if you don't want partials then don't enable them

if you do want partials then check if it's one, in case you don't want that specific check to execute with partial members

sharp ginkgoBOT
night kayak

What are partials used for?

sharp ginkgoBOT

guide Partials
One example leveraging partials is the handling of reactions on uncached messages, which is explained on this page. Prior you had to either handle the undocumented raw event or fetch the respective messages on startup. The first approach was prone to errors and unexpected internal behavior. The second was not fully fail-proof either, as the messages could still be uncached if cache size was exceeded in busy channels.

tardy sable

what does this error mean?

.setStringSelectMenuComponent(
    new StringSelectMenuBuilder()
    .setCustomId('id')
    .addOptions(
        interaction.message.embeds[0].description
        .split('\n')
        .map(line =>
            new StringSelectMenuOptionBuilder()
            .setLabel(truncate(`${line.split('.')?.[0] || '0'}. ${line.match(/\[(.*?)\]/g)?.[1]?.slice(1, -1) || 'None'}`, 100)) // name
            .setValue(line.match(/title\/(.*?)\)/)?.[1] || '0') // id
        )
    )
)

ive logged the label and values separately and theyre all valid strings

wary coral
tardy sable
wary coral

What are the lengths of the name and value for each option?

tardy sable

also no dupe values

wary coral

How's your label set up? Also, is this the only element in the modal?

tardy sable

atleast v15 is gonna improve error messages dogeHaHa

rose tangle

can you share the value of interaction.message.embeds[0].description that's erroring

tardy sable
rose tangle can you share the value of interaction.message.embeds[0].description that's erro...
name: 21. Hotel Rwanda | value: tt0395169
name: 22. Monsters, Inc. | value: tt0198781
name: 23. Squid Game | value: tt10919420
name: 24. Bodyguard | value: tt7493974
name: 25. Lion | value: tt3741834
name: 26. Don't Fk with Cats: Hunting an Internet Killer | value: tt11318602
name: 27. Arrival | value: tt2543164
name: 28. Iron Man | value: tt0371746
name: 29. Monsters | value: tt13207736
name: 30. From | value: tt9813792
name: 31. All Quiet on the Western Front | value: tt1016150
name: 32. Captain Phillips | value: tt1535109
name: 33. Wreck-It Ralph | value: tt1772341
name: 34. American Manhunt: Osama bin Laden | value: tt35630036
name: 35. Good Girls | value: tt6474378
name: 36. Frankenstein | value: tt1312221
name: 37. Weapons | value: tt26581740
name: 38. Sinners | value: tt31193180
name: 39. Hotel Mumbai | value: tt5461944
name: 40. Toxic Town | value: tt28631067

it must be a specific line cuz it sometimes works with other values

does maybe indexing the name causes for issues?

rose tangle

what about truncate()?

tardy sable

there arent any issues with that, tried without

stable sun

Are you sure there aren’t duplicate values?

tardy sable
stable sun

Prob easier to just do options.forEach(o => o.toJSON()) just to make sure it isn’t an issue w/ the options

Force the option validators to run

tardy sable
stable sun

Weird. Ur not even using emojis

tardy sable

yes ill try adding emoji to it and see

stable sun

Can you show ur imports?

tardy sable
tardy sable
rose tangle

I can't reproduce with

import { ModalBuilder, LabelBuilder, StringSelectMenuBuilder, StringSelectMenuOptionBuilder } from 'discord.js';

const description = `name: 21. Hotel Rwanda | value: tt0395169
name: 22. Monsters, Inc. | value: tt0198781
name: 23. Squid Game | value: tt10919420
name: 24. Bodyguard | value: tt7493974
name: 25. Lion | value: tt3741834
name: 26. Don't Fk with Cats: Hunting an Internet Killer | value: tt11318602
name: 27. Arrival | value: tt2543164
name: 28. Iron Man | value: tt0371746
name: 29. Monsters | value: tt13207736
name: 30. From | value: tt9813792
name: 31. All Quiet on the Western Front | value: tt1016150
name: 32. Captain Phillips | value: tt1535109
name: 33. Wreck-It Ralph | value: tt1772341
name: 34. American Manhunt: Osama bin Laden | value: tt35630036
name: 35. Good Girls | value: tt6474378
name: 36. Frankenstein | value: tt1312221
name: 37. Weapons | value: tt26581740
name: 38. Sinners | value: tt31193180
name: 39. Hotel Mumbai | value: tt5461944
name: 40. Toxic Town | value: tt28631067`;

const truncate = (str) => str;

const options = description
    .split('\n')
    .map(line =>
        new StringSelectMenuOptionBuilder()
            .setLabel(truncate(`${line.split('.')?.[0] || '0'}. ${line.match(/\[(.*?)\]/g)?.[1]?.slice(1, -1) || 'None'}`, 100)) // name
            .setValue(line.match(/title\/(.*?)\)/)?.[1] || '0')
    );

new ModalBuilder()
    .setCustomId('interaction.customId')
    .setTitle('Options')
    .addLabelComponents(
        new LabelBuilder()
            .setLabel("Option")
            .setDescription(`Select the option`)
            .setStringSelectMenuComponent(
                new StringSelectMenuBuilder()
                    .setCustomId('id')
                    .addOptions(options)
            )
    )
    .toJSON();

make sure it's the correct erroring code

stable sun

Yea, for the builders mainly

tardy sable
stable sun In the file
const { ApplicationCommandType, ApplicationCommandOptionType, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, TextInputStyle, ModalBuilder, TextInputBuilder, ContainerBuilder, SectionBuilder, TextDisplayBuilder, SeparatorSpacingSize, MediaGalleryBuilder, MediaGalleryItemBuilder, MessageFlags, AttachmentBuilder, LabelBuilder, StringSelectMenuBuilder, StringSelectMenuOptionBuilder } = require("discord.js");
const axios = require('axios');
rose tangle

so it's the text

I'll try to figure out what

can you share your truncate method?

tardy sable

its from a package but that isnt causing the problem. you can do without

rose tangle

thing is on my side, after narrowing down, the actual error is

CombinedPropertyError (1)
  Received one or more errors

  input.options
  | CombinedPropertyError (1)
  |   Received one or more errors
  | 
  |   input[5]
  |   | CombinedPropertyError (1)
  |   |   Received one or more errors
  |   | 
  |   |   input.label
  |   |   | [ExpectedConstraintError: s.string().lengthLessThanOrEqual()]
raven hearth

yeah idk some weird stuff has been happening recently but randomly stopped

can't be ratelimit, but for some reason certain actions just broke such as role granting or thread closing. works now 🤷‍♂️

tardy sable

i still have same error message without truncate

rose tangle

if you don't truncate then it's very obvious that a "lengthLessThanOrEqual" error is understandable

and my truncate is just (str) => str

hence why I wanted to know yours

tardy sable

i logged just the options and youd think they all valid Thonk

rose tangle
CombinedPropertyError (1)
  Received one or more errors

  input.label
  | ExpectedConstraintError > s.string().lengthLessThanOrEqual()
  |   Invalid string length
  | 
  |   Expected: expected.length <= 45
  | 
  |   Received:
  |   | '26. Don\'t Fk with Cats: Hunting an Internet Killer'
tardy sable
rose tangle

hmm the docs says it is

not sure why it's validating against 45

tardy sable

truncating to 45 fixed it

wary coral
dry flame

I'm getting a [TAG_FIELD_MISSING]: Field "type" is required to determine the model type. error when creating a slash command group, not sure what I'm doing wrong here:

public override registerApplicationCommands(registry: Subcommand.Registry) {
    registry.registerChatInputCommand(
        new SlashCommandBuilder() //
            .setName(CommandName.Admin) //
            .setDescription('Administrative commands.')
            .setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild)
            .addSubcommandGroup(
                new SlashCommandSubcommandGroupBuilder() //
                    .setName(CommandName.AdminMines)
                    .setDescription('Administrative commands related to the mines game.')
                    .addSubcommand(
                        new SlashCommandSubcommandBuilder() //
                            .setName(CommandName.AdminMinesStressTest)
                            .setDescription('Initializes a stress test in the specified channel.')
                            .addChannelOption(
                                new SlashCommandChannelOption() //
                                    .setName(CommandParameterName.Channel)
                                    .addChannelTypes(...this._minesGameStressTestChannelTypes)
                                    .setDescription('The channel in which to run the stress test.')
                                    .setRequired(true)
                            )
                            .addIntegerOption(
                                new SlashCommandIntegerOption() //
                                    .setName(CommandParameterName.GameCount)
                                    .setDescription('The amount of games to simulate.')
                                    .setMinValue(1)
                                    .setMaxValue(100)
                                    .setRequired(true)
                            )
                    )
            ),
    )
wary coral
tardy sable
wary coral

I think it is a validator bug with modal

dry flame
sharp ginkgoBOT

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

tardy sable
topaz bluff
polar karma

I feel like the validation error is known but can't confirm

rose tangle

not sure how that hasn't been fixed already kek

guess nobody's doing long select menu options?

tardy sable

yh weird guess im the first one

wary coral

there is an open issue #11310 not sure it is covered this particular issue
probable would not hurt to open an issue for it in particular

jagged rock

how come message logs dont work in old old channels which where created like before after restarting my bot and caching was introduce to my bot but when i create a new it logs fine if i delete a message in a new channel

wary coral
rose tangle
jagged rock
rose tangle

correct

it's already gone

jagged rock

annoying, does it do it with any other logs guessing like role updates, channel updates etc.

rose tangle

in general discord doesn't share the old state on any delete or update

the only reason you can get it on djs is because the object is cached

if it isn't (it's a partial) then you don't get anything besides ids

jagged rock

but every other log event should be fine like my voice state change event works normal and others.

rose tangle

because you do have the old state cached

jagged rock
gaunt patrol

Is there any issue in my code because after adding the separator, my bot completely stopped sending this container replies not even errors just no response at all

new ContainerBuilder()
        .addSectionComponents(
          new SectionBuilder()
            .addTextDisplayComponents((td) =>
              td.setContent(`### Lyrics\n**${client.utils.sliceText(title)}**\nby **${artist}**`)
            )
            .setThumbnailAccessory((th) => th.setURL(thumbnail))
        )
        .addSeparatorComponents((s) => s.setSpacing(2))
        .addSectionComponents(
          new SectionBuilder()
            .addTextDisplayComponents((td) => td.setContent(chunk))
            .addTextDisplayComponents((td) => td.setContent(`**Page ${i + 1}/${chunks.length}**`))
        )
polar karma

Node (and d.js) don't silently error, it either works or throws an error. Something is likely stopping execution prior to that being reached

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
gaunt patrol
subtle girder
wary coral Your error occurred in your file MSG handler line 1408 when you used the functio...

yea ik
but using try catch will output:

Error: Received one or more errors
    at _ArrayValidator.handle (I:\VSCodefile\Discord\DogBot\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:1254:70)
    at _ArrayValidator.parse (I:\VSCodefile\Discord\DogBot\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:972:90)
    at EmbedBuilder.spliceFields (I:\VSCodefile\Discord\DogBot\node_modules\@discordjs\builders\dist\index.js:275:31)
    at EmbedBuilder.setFields (I:\VSCodefile\Discord\DogBot\node_modules\@discordjs\builders\dist\index.js:291:10)
    at Object.<anonymous> (I:\VSCodefile\Discord\DogBot\myCode.js:5:10)
    at Module._compile (node:internal/modules/cjs/loader:1554:14)
    at Object..js (node:internal/modules/cjs/loader:1706:10)
    at Module.load (node:internal/modules/cjs/loader:1289:32)
    at Function._load (node:internal/modules/cjs/loader:1108:12)
    at TracingChannel.traceSync (node:diagnostics_channel:322:14)

but when not using try catch:
https://pastebin.com/hCsCvTpm

stable sun
subtle girder
stable sun

The former

And log the result

subtle girder

ty :)

verbal vine

is discord.js.Role["members"] Work? dogeHaHa

crimson gale

i'd recommend reading documentation instead of guessing... what in tarnation is that even supposed to do or be

torn plinth

how to get a command id?
like this one
</suggest: 1397893686502621204>

crimson gale

right-click on the upper bar when using a cmd

torn plinth

i dk i cant

crimson gale

alternatively, request the command list via the API

torn plinth
torn plinth
crimson gale

i don't think they're cached on ready, try .fetch() on the .commands manager

and also make sure client.application is even a thing in that scope, seeing that you optional chain it, that could also be why it's undefined

torn plinth

ok .

torn plinth

thanks fetch() works :3

dry flame

Is it possible for a command to have a subcommand and subcommand groups each with their own subcommands or is it that if you have at least one subcommand group, all subcommands must be under one?

craggy needle

Hello

I'm new to Discord.js, how do you prefer me to learn it so that I can grasp it quickly?
I was using Aoi.js before and I could create advanced systems on it, but I forgot about it after not using Discord for a year.

How can I learn this faster?

subtle girder

How can I let bot send message without enabling markdown?
like the bot is going to show user's username (some with _xxx_)

Do I have to use function to remove or there is an option?

sharp ginkgoBOT
wary coral
wary coral
sharp ginkgoBOT

documentation suggestion for @dry flame:
discord Application Commands - Subcommands and Subcommand Groups
For those developers looking to make more organized and complex groups of commands, look no further than subcommands and groups. Subcommands organize your commands by specifying actions within a command or group. Subcommand Groups organize your subcommands by grouping subcommands by similar action or resource within a command. These are not enforced rules. You are free to use subcommands and groups however you'd like; it's just how we think about them.

craggy needle
wary coral
craggy needle

What is the latest version of discord.js right now?

wary coral

v14.25.1

craggy needle

Thx

novel mauve

is it possible to reply to a button interaction, then do something that takes a while, and once thats done edit the result in the originial message the button was attached to? which method should i use to edit the original message and not the first response

topaz bluff

Just to be clear. You want to send a reply but then update the original message after rather than editing the reply?

Is the message with the button ephemeral?

novel mauve

yes that's what i wanted to do, unless there's a better alternative because i found defering a button doesn't show any loading state which isnt ideal and looks like its broken when it's just loading behind the scenes

the original message is not ephemeral

shut musk

Using sharding for the first time. I've changed any instances of client.guilds, client.users etc

Is there any docs with events for sharding manager?

tardy sable
novel mauve

oh right, thanks

rose tangle

editReply passing the original message as target could also work

rose tangle
shut musk

Yes. Also I'm facing an issue 🤔 ShardingReadyTimeout

steel trail

do you need/want a shardingmanager? or did you just add it because you thought it's the only option for sharding?

shut musk

Sorry maybe this is a dumb issue though I am too new with this sharding manager. Trying to understand this thing

Uhh, so I've used internal djs sharding for a while but thought I should switch to sharding manager.

topaz bluff

How many servers is your bot installed to? Are you skipping interactions due to CPU limitations?

shut musk

Currently it is in 9.7k servers. Am i skipping interations as in?

Things have logged in now. I think the problem was I forgot to remove the djs internal sharding so it was doing some funky thing there. Now I'm facing other issues with the database 💀

warm bane

Hi, i'm registering some ApplicationGuildCommand using the REST class, im also using typescript, and i what to know what type i should assgin to the costant data

const data: WhatTypeShuldIUse = await rest.put(
            Routes.applicationGuildCommands(
                process.env.DISCORD_CLIENT_ID!,
                process.env.DISCORD_GUILD_ID!
            ),
            { body: commands }
        );

        console.log(
            `Successfully reloaded ${data.length} application (/) commands.`
        );

The rest.put method return and Promise<unknown> type, but the discord api docs say that the applicationGuildCommands route returns list of application command objects.

So, what type should I use for the data constant?

sharp ginkgoBOT
steel trail

nvm, amgelo's type is more correct

dapper cave

Hey I might be silly but there is no auditlogevent for a channel moving right? You'd have to use the clientevents

stable sun
dapper cave

Oh yeah my bad I meant moving a channel to a diff category or under another one channel etc

stable sun

Both has an audit log iirc

Channel update has audit logs

tardy sable

is there a way to get the subcommand from a command without doing getsubcommand?

stable sun

Parse the data yourself

tardy sable

wasnt there something like interaction metadata?

sharp ginkgoBOT
stable sun

interaction.options.data

tardy sable

thanks

stable sun

Why tho?

tardy sable
stable sun Why tho?

for my error logging i just want to know from which subcommand it came from if it was a subcommand

stable sun
dapper cave
tardy sable
stable sun
tardy sable

ok thanks ill try that

tardy sable
dapper cave

yeah I dont mind

as long as I can do something when channel parent_id updates or position ill try it with the client event

onyx ember

i need help with this string

polar karma

Log interaction

sharp ginkgoBOT

tag suggestion for @onyx ember:
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
dense jackal

this is most likely the cause

dry flame

Is there a way to have a GIF in an embed that doesn't loop?

wary coral
dapper cave

guild.members.fetch() fetches all members right or is there a limit like on msg fetch

rose tangle

it's probably different since bulk fetched members arrive through the gateway

instead of through the http response like other bulk fetches

kindred moon

do i need intent's for the entitlement event's?

steel trail

No

jagged rock

(node:48) UnsupportedCacheOverwriteWarning:
Overriding the cache handling for ChannelManager is unsupported and breaks functionality.

how to fix i use channel manager which is core js but i need itr

peak reef

how many buttons can i add with actionRowBuilder?

const row = new ActionRowBuilder()
.addComponents(button1, button2, button3, button4, ...);
peak reef

i need, because im adding buttons automatically, its up to 10-15 buttons

halcyon bison
rose tangle
peak reef
jagged rock
halcyon bison

yes

jagged rock
halcyon bison yes

remvoed it i use guildmembermanager for cache and messages tho to reduce MiB

rose tangle

you mean you customize the cache?

"I use the manager for cache to reduce mb" doesn't make much sense

you customize the cache to reduce mb

jagged rock

bc my bot kept crashing due to it being over the limit for the web host i use

rose tangle

then the warning is correct, you should not customize the channel manager's cache

that's mentioned in the cache customization guide

jagged rock
rose tangle

what is a core djs feature?

ah, you mean like something internal

jagged rock
rose tangle

yeah it's used by a bunch of managers, you should not customize it

jagged rock

yeah my bot is a logging bot anything i could include or add to my code or any docs to make the bot stable for logging as sometimes it can be too much on the bot such as rising the MiB causing it to crash

rose tangle

if you just want simple logging and no caches you might want to use @discordjs/core instead

it's a replacement to discord.js that pretty much simply connects to ws and lets you do requests easily, nothing else (like caches)

jagged rock

ye its probs faster ill have to re write tho

i use sweepers tho

keen monolith

Hii I am having this error:

                       ^

TypeError: Cannot read properties of undefined (reading 'channels')
    at Object.<anonymous> (C:\Users\reina\Documents\Discord Bot\commands\utility\ticket.js:4:24)
    at Module._compile (node:internal/modules/cjs/loader:1761:14)
    at Object..js (node:internal/modules/cjs/loader:1893:10)
    at Module.load (node:internal/modules/cjs/loader:1481:32)
    at Module._load (node:internal/modules/cjs/loader:1300:12)
    at TracingChannel.traceSync (node:diagnostics_channel:328:14)
    at wrapModuleLoad (node:internal/modules/cjs/loader:245:24)
    at Module.require (node:internal/modules/cjs/loader:1504:12)
    at require (node:internal/modules/helpers:152:16)
    at Object.<anonymous> (C:\Users\reina\Documents\Discord Bot\deploy-commands.js:18:19)```

with this code

```const { SlashCommandBuilder } = require('discord.js');
const { EmbedBuilder } = require('discord.js');
const { client } = require('../../config.json')
const channel = client.channels.cache.get('1444130021290807429');

const imageEmbed = new EmbedBuilder()
    .setColor(0x0099ff)
    .setImage('https://media.discordapp.net/attachments/1444130394424475688/1444130444588093571/San_-_guide_banner.webp?ex=692b96c8&is=692a4548&hm=ff4e4d46cec8af69604d3a06eb6731d51d960194590552c936ef1e4a64d8c4f5&=&format=webp');

module.exports = {
    data: new SlashCommandBuilder().setName('ticket').setDescription('sends an embed'),
    async execute(interaction) {
        await interaction.reply(
channel.send({embeds: [imageEmbed] }), 'embed sent');
    },
};```
topaz bluff

client is undefined

keen monolith

I defiened client tho? It's now saying the channels one

topaz bluff

that error message is somewhat backwards....it means youre trying to read the value of channels on an undefined object of client

you're trying to read the client from a json file...why are you doing that?

keen monolith

it’s the config file. I thought that’s how you do it. Sorry I’m still learning lol

topaz bluff

the client is a massive object, and it's only stored in memory

just do interaction.client instead...the client object can be accessed by many objects in DJS

keen monolith

thanks so much!

topaz bluff

another error, you have a channel.send() as a parameter of interaction.reply()

topaz bluff

yes. interaction.reply() is used when responding to an interaction (aka, when someone uses a slash command) and channel.send() is used whenever the bot wants to send a message in a specific channel at any random time

if you're using a slash command, you have to give a reply at some point or else discord will say that the interaction failed

keen monolith

Okay

So I put the channel.send outside of the interaction.reply and it will do both?

topaz bluff

you can use it before or after...you just cant use it INSIDE of the interaction.reply

keen monolith

Alright thanks so much

It's still giving me the channels error... this is my new code

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

const imageEmbed = new EmbedBuilder()
    .setColor(0x0099ff)
    .setImage('https://media.discordapp.net/attachments/1444130394424475688/1444130444588093571/San_-_guide_banner.webp?ex=692b96c8&is=692a4548&hm=ff4e4d46cec8af69604d3a06eb6731d51d960194590552c936ef1e4a64d8c4f5&=&format=webp');

module.exports = {
    data: new SlashCommandBuilder().setName('ticket').setDescription('sends an embed'),
    async execute(interaction) {
        const { client } = interaction.client;
        const channel = client.channels.cache.get('1444130021290807429');
        await interaction.reply('embed sent');
        channel.send({embeds: [imageEmbed] });
    },
};```
topaz bluff

your syntax is wrong. defining a variable by using const { var } = obj is called destructuring. what youre essentially doing is the same as const var = obj.var

so in your example, you're trying to define const client = interaction.client.client

destructuring is used more when you want to pull several values off of an object on a single line

like const { var1, var2, var3 } = obj which is why it's used with require() for const { EmbedBuilder, SlashCommandBuilder } = require("discord.js");

keen monolith

oh okay

so there is nothing wrong with the const {client}?

topaz bluff

yes, just remove the {}

keen monolith

okie tysm again

wary coral

What Samtino is saying is the you have to chose one of the below

const { client } = interaction;

or

const client = interaction.client;
keen monolith

ahhhh makes sense now - thank you!

keen monolith

Is it possible to have multiple channel.send() in one interaction to be able to send multiple

content:
embeds: 

??

topaz bluff

channel.send() does not have a limit, other than the rate limit (sending too many too fast)

keen monolith

Alright thanks

Sorry one last question.

Is there a way to create commands without having to be a slash command

ruby bane

i mean you can do prefix commands, but you need the message content intent. Theyre wildly less preferred than slash commands though

keen monolith

How would I set one up?

This bot is mainly going to be used by just me in my own server and I’m trying to send an embed message without having to use a slash command

viral kestrel

Hey guys have any way with API ou discord.js that i can recive an event when some audit log are generated? (Like i ban someone and i get informations of that audit log)

sharp ginkgoBOT
topaz bluff

damnit conrad beat me...stupid bad internet not loadig messages

keen monolith

tysm

topaz bluff

-# while prefix commands are easier to set up, theyre much harder to work with

ruby bane

about the only entry that still mentions prefix commands, though the existing command handler guide could definitely be reworked

topaz bluff

-# slash commands are generally still recommended for all use cases as they have many advantages over prefix commands

keen monolith

Okay

pearl hazel

is there any way to fix move member and disconnect events ?

bleak owl

what do you mean "fix"

pearl hazel

disconnect event trigger once, if a member disconnect 2 members at the same time it will only send one event
same for move

like this, in the audit log it's not created new log, it's only update user counts

keen monolith

okay I am sorry I am back but this is really confusing for me...

I get an error saying that 'report' isn't accessible before initialisation


const { SlashCommandBuilder, 
    EmbedBuilder, 
    ActionRowBuilder,
    PermissionFlagsBits,
    ButtonBuilder,
    ButtonStyle,
 } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
    .setName('ticket')
    .setDescription('sends an embed')
    .setDefaultMemberPermissions(PermissionFlagsBits.Administrator),
    async execute(interaction) {
        const client = interaction.client;
        const channel = client.channels.cache.get('1444130021290807429');

        const report = new ButtonBuilder()
        .setCustomId(report)
        .setLabel(report)
        .setEmoji(1444167362449244261)
        .setStyle(ButtonStyle.Secondary);

        const apply = new ButtonBuilder()
        .setCustomId(apply)
        .setLabel(apply)
        .setEmoji(1444167360436113488)
        .setStyle(ButtonStyle.Secondary);
        
        const row = new ActionRowBuilder().addComponents(report, apply);

        const imageEmbed = new EmbedBuilder()
    .setColor(15511231)
    .setImage('https://media.discordapp.net/attachments/1444130394424475688/1444130444588093571/San_-_guide_banner.webp?ex=692b96c8&is=692a4548&hm=ff4e4d46cec8af69604d3a06eb6731d51d960194590552c936ef1e4a64d8c4f5&=&format=webp');


        await interaction.reply('embed sent');
        channel.send({
            content: "_ _\n_ _\n_ _\n_ _\n_ _\n_ _\n_ _\n_ _\n_ _",
            embeds: [imageEmbed],
         })
         
         channel.send({
            content: "_ _\n_ _\n_ _\n",
            embeds: [imageEmbed],
            components: [row],
         })
         ;
    },
};```
topaz bluff

because that is just how audit logs work...when multiple happen quickly, discord combines them...no fixing it

viral kestrel

i dont recive de correct message when i delete it

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

client.on(Events.GuildAuditLogEntryCreate, async (auditLog) => {
const { action, extra: channel, executorId, targetId } = auditLog;

if (action !== AuditLogEvent.MessageDelete) return;

const executor = await client.users.fetch(executorId);

const target = await client.users.fetch(targetId);

console.log(`A message by ${target.tag} was deleted by ${executor.tag} in ${channel}.`);

});

polar karma

Do you have the correct intents and permissions?

viral kestrel
ruby bane
keen monolith
pearl hazel

i know discord combines them, my question is how to fix that to get exact event

topaz bluff

there's not a disconnect event...but there's a voicestateupdate event

deep harness

can i add multiple dropdowns + buttons on an embed message?

subtle girder
wary coral
wary coral
dry flame

Is there a way to get the invite a member used to join a server?

wary coral

Not to my knowledge. Server mods can see it in the members page but apps dont have access to that page and info

dry flame

Ok, one way I can think of doing it is fetching all of a guild's invites and storing them in memory, then whenever a guild member joins I fetch the invites again and try to find one where its uses property incremented... Doesn't seem like a very reliable method though

rose tangle

that's pretty much the only "supported" way currently

sharp ginkgoBOT

Discord does not provide the invite that a member used to join through the bot API.

  • Tracking the uses of invites through the inviteCreate and guildMemberAdd events is unreliable and we recommend against it.
  • Discord has not shared any plans to make the members tab available for bots.
dim estuary

Hey yall, i need to fetch all of the members in the server but recently it starts to timeout or to get ratelimited. The usecase is to update a counter channel for member statistics. I saw a query option and my question is can i query users by roleid or other properties?

red coral

You can’t query by role id, the query is for things like nicknames and usernames. The timeout is because of the new rate limit introduced by discord. Plus you only need to fetch members once

Members didn't arrive in time (was finding this)

astral prismBOT
red coral Members didn't arrive in time (was finding this)

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

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

i can use | to check for multiple permissions right? .has(PermissionsBitField.Flags.SendMessages | PermissionsBitField.Flags.ManageWebhooks)

obtuse laurel

yeah looking at the code for it, you can use |

unique heron

how do i invite my bot to the discord server

sharp ginkgoBOT

guide suggestion for @unique heron:
guide Adding Your App
After you set up a bot application, you'll notice that it's not in any servers yet. So how does that work? Before you're able to see your bot in your own (or other) servers, you'll need to add it by creating and using a unique invite link using your bot application's client id.

unique heron

its an bot

tiny condor

Yep the guide above is for a bot

unique heron

and when i invite it i dont see it

tiny condor

Did you check the bot scope

unique heron

whats that

tiny condor

Please follow the guide linked above thoroughly

dry flame

Does a bot need any other intents other than GatewayIntentBits.GuildInvites to get inviteCreate/inviteDelete events?

red coral

Guilds? But everyone should really have that anyway

dry flame

I'm using Sapphire and registering them like this:

import { Listener, Events } from '@sapphire/framework';
import { Invite } from 'discord.js';
import InvitesController from '../controllers/invites/InvitesController.js';

export class InviteCreatedListener extends Listener<typeof Events.InviteCreate> {
    public constructor(context: Listener.LoaderContext, options: Listener.Options) {
        super(context, {
            ...options,
            event: Events.InviteCreate
        });
    }

    public async run(invite: Invite) {
          // ...
    }
}

Added a breakpoint inside run but it never gets hit

polar karma

It also requires the manage channel permission for the channel the invite is for

The API docs list any required intents and permissions for each event

dry flame
dry flame

Oh I see, thank you so much!

keen monolith

const { SlashCommandBuilder, 
    EmbedBuilder, 
    ActionRowBuilder,
    PermissionFlagsBits,
    ButtonBuilder,
    ButtonStyle,
    MessageFlags,
 } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
    .setName('ticket')
    .setDescription('sends an embed')
    .setDefaultMemberPermissions(PermissionFlagsBits.Administrator),
    async execute(interaction) {
        const client = interaction.client;
        const channel = client.channels.cache.get('1444193008424583259');

        const report = new ButtonBuilder()
        .setCustomId('report')
        .setLabel('report')
        .setEmoji('1442480872543617154')
        .setStyle(ButtonStyle.Secondary);

        const apply = new ButtonBuilder()
        .setCustomId('apply')
        .setLabel('apply')
        .setEmoji('1442483680487538851')
        .setStyle(ButtonStyle.Secondary);

        const claim = new ButtonBuilder()
        .setCustomId('claim')
        .setLabel('claim')
        .setEmoji('1442483530012819456')
        .setStyle(ButtonStyle.Secondary);
        
        const row = new ActionRowBuilder().addComponents(report, apply, claim);

        const imageEmbed = new EmbedBuilder()
    .setColor(15511231)
    .setImage('https://media.discordapp.net/attachments/1440497257828057199/1442850744603512942/chonsa_desk.png?ex=692c34f8&is=692ae378&hm=ac4714180d8421ddd4c1b81a7a0840335e3fcb49ccc690ae2701c6f10b047d87&=&format=webp&quality=lossless&width=846&height=282');

    const dividerEmbed = new EmbedBuilder()
    .setColor(2895153)
    .setImage('https://media.discordapp.net/attachments/1440497257828057199/1440579193477005463/image.png?ex=692c832c&is=692b31ac&hm=0b647591690a8e34b98cf030ab1cb9667034f3b753fadea53fbd5063b1098692&=&format=webp&quality=lossless&width=960&height=39');


        await interaction.reply({ content: 'embed sent', flags: MessageFlags.Ephemeral });

        await channel.send({
            content:
`_ _
_ _
_ _
_ _
-# ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣾⠉⢳⣰⠋⠙⡆⠀⠀⠀⠀ open 4 **help**
-# ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠘⡀         ⡀⠘
-# ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⠷⠋  __report__   app   **claim**   prt/sib/p4p   :headphones:
-# ⣰⠟⠉⠙⢦⡀⢀⣾⡟⠉⠳⣆
-# ⣿⠀⠀⠀⠀⠛⠛⠁⠀⠀⠀⡿      do NOT open ticket and leave unresponsive
-# ⠸⣇⠀⠀⠀⠀⠀⠀⠀⠀⣰⠃
-# ⠙⢧⡀⠀⠀⠀⠀⠀⢀⡴⠃       🩷   no response within 24hr = close & warn
-# ⠀⠀⠀⠙⠶⣄⣀⠴⠋
_ _
_ _`,
embeds: [imageEmbed]
});

await channel.send({
    content: "_ _\n_ _\n_ _\n_ _",
    embeds: [dividerEmbed],
});

await channel.send({
    content:
`_ _
_ _
**open ʚ(。˃ ᵕ ˂ )ɞ**
_ _
_ _`,

    components: [row],
});
         ;
    },
};``` 

is responding with this?

sorry they over the place lol as too long for discord

vagrant mortar

not related to v14 but rather @djs/rest:

where do I place with_counts?

rest.get(Routes.userGuilds())

there is no such property specified in the query object, so where?

oh i'm just fucking stupid query is URLSearchParams object 🤦

didn't look on types

wary coral
mild oar

Oh sorry

wary coral
wary coral
keen monolith

I figured it out... I moved all my files to another pc and it wouldn't work.. now being back on my laptop --> it works.. 😭

wary coral

BTW you should not uses discord CDN links in your code that will sop working

keen monolith

yh I noticed that

on my laptop they not cdn and it works... just so confusing it only works on my laptop

wary coral
steel trail

Not really, this is a djs/rest question

vagrant mortar

after all

wary coral

oh, I am sorry I thought your asking about which property to add.

trying to much 😅

vagrant mortar

i usually don't use REST but sometimes i got to 😅

spiral wasp

67

bleak owl
wary coral
normal flare

like media.discordapp? are there others?

clear garnet

Any CDN URL for an attachment hosted within Discord

shell girder

Hi, does anyone know about modal components? 🙂

sharp ginkgoBOT

guide Modals
With modals you can create pop-up forms that allow users to provide you with formatted inputs through submissions. We'll cover how to create, show, and receive modal forms using discord.js! This page is a follow-up to the interactions (slash commands) page. Please carefully read that section first, so that you can understand the methods used in this section.

unique shoal

If you have specific questions feel free to ask

sleek mural

Is there any way to quickly get a users color/theme? Like their avatar main color

sharp ginkgoBOT

documentation suggestion for @sleek mural:
property User#hexAccentColor discord.js@14.25.1
The hexadecimal version of the user accent color, with a leading hash The user must be force fetched for this property to be present

tardy sable

i think you mean this

sleek mural

Yes thanks

subtle girder
async function choose_job_row(userid) {
    const { jobs } = require("./config.js");

    const selectMenu = new StringSelectMenuBuilder()
        .setCustomId(`job_choose|${userid}`)
        .setPlaceholder("選擇職業")
        .addOptions(
            ...await Promise.all(
                Object.entries(jobs).map(async ([id, data]) => {
                    const emojiObject = await get_emoji_object(id);

                    return {
                        label: get_name_of_id(id),
                        description: data.desc,
                        value: id,
                        emoji: emojiObject ? {
                            id: emojiObject.id,
                            name: emojiObject.name,
                            animated: emojiObject.animated || false
                        } : "❓"
                    };
                }),
            ),
        );

    const cancel_button = new ButtonBuilder()
        .setCustomId(`cancel|${userid}`)
        .setLabel("取消")
        .setStyle(ButtonStyle.Danger);

    const row1 = new ActionRowBuilder()
        .addComponents(selectMenu);

    const row2 = new ActionRowBuilder()
        .addComponents(cancel_button);

    return [row1, row2];
};
            const embed = new EmbedBuilder()
                .setColor(embed_job_color)
                .setTitle(`${emoji_job} | 請選擇你的職業`)
                .setDescription
                (`
轉職後一個禮拜不能更動職業!

${emoji_nekoWave} 如果出現紅字 Invalid Form Body 的錯誤訊息
,請確認 Discord 有更新到最新版本
                `);

            const rows = choose_job_row(userid);

            if (mode === 1) return { embeds: [embed], components: rows };
            return await message.reply({ embeds: [embed], components: rows });
TypeError: this.options.components?.map is not a function
    at MessagePayload.resolveBody (/app/node_modules/discord.js/src/structures/MessagePayload.js:150:49)
    at TextChannel.send (/app/node_modules/discord.js/src/structures/interfaces/TextBasedChannel.js:189:32)
    at Message.reply (/app/node_modules/discord.js/src/structures/Message.js:971:25)
    at rpg_commands.job (/app/cogs/rpg/msg_handler.js:1889:34)
    at process.processTicksAndRejections (node:internal/process/task_queues:103:5)
    at async rpg_handler (/app/cogs/rpg/msg_handler.js:2121:20)
    at async Object.execute (/app/cogs/rpg/msg_handler.js:2198:13)
    at async DogClient.run_execute (/app/utils/load_cogs.js:12:13)
bleak owl

components takes an array

subtle girder

It seems I should use pastebin

subtle girder
halcyon bison

choose_job_row is async and therefore returns a Promise, but you're not awaiting it

subtle girder

oh, my fault

thx :D
because

sleek mural
tardy sable
fleet chasm

could someone help me with adding a permission overwrite to a channel for a user for the BYPASS_SLOWMODE permission? I know it's not officially within the PermissionFlagsBits yet

sharp ginkgoBOT

guide Adding overwrites
To add a permission overwrite for a role or guild member, you access the channel's TextChannel#permissionOverwrites and use the .create() method. The first parameter is the target of the overwrite, either a Role or User object (or its respective resolvable), and the second is a PermissionOverwriteOptions object. Let's add an overwrite to lock everyone out of the channel. The guild ID doubles as the role id for the default role @everyone as demonstrated below:...

fleet chasm

ah im on the wrong version of the docs 🤦‍♂️

little pebble

Yep

fleet chasm

thank you !

wary coral
subtle girder

what I want:

  1. User click button
  2. bot update message

I use:

await interaction.deferReply();
// ...
await interaction.editReply(...)

but the bot send a followUp message

and I use:

await interaction.deferUpdate();
// ...
await interaction.update(...)

I got

Error [InteractionAlreadyReplied]: The reply to this interaction has already been sent or deferred.
    at StringSelectMenuInteraction.update
...

Actually Idk what's the difference of reply and update
and Do I have to use interaction.message.edi?

tardy sable
little pebble

Yeah, editReply after deferUpdate should work

subtle girder

work for SelectMenu and Button Interaction?

little pebble

Yes

subtle girder

using update

little pebble

Show your code

What do you mean by using update? We told you to use deferUpdate and editReply

subtle girder

interaction.deferUpdate() and interaction.update()
I also tried to use editReply

little pebble

And what happens?

subtle girder

u mean editreply?

little pebble

Yes

subtle girder

wait a minute

subtle girder
polar sun

is it possible to change the way that BaseChannel#isSendable() to also make it check if that the bot can send messages in that channel not just that it's a channel type that supports sending messages to while keeping the typescript typeguard

topaz bluff

you'll probably want to make a custom helper function for channelIsSendableFor(channel, userId) or something similar which checks the GuildChannel#permissionsFor and checks if it's sendable and if the user has permissions to send in said channel

polar sun

I made this check as a quick test for something

await channel.sendTyping().catch((error: Error) => {
  if (error.message === 'Missing Access') {
    throw new KathUtilsError('I cannot send messages in that channel');
  }
  throw error;
});

But there might be a better way but i'm not 100% sure if extending also will be the best idea

topaz bluff

doing channel.sendTyping() seems like an unnesseary API call as you should already have the channel, channel overrides, and guild roles cached...you can use the existing helper to compare the permissions for the channel to ensure that the user/role of the bot has permissions to send messages

sharp ginkgoBOT
polar sun

Isn't there some max requests per day

topaz bluff

shouldn't matter since you can keep guild channels and roles updated in real time without any api calls using the gateway events (djs does this automatically) and you should always have the bot user cached...since its the bot...

polar sun

Id still need to fetch the bot to use as a guild member. Would that still not an api call? So just making a different way to do it

topaz bluff

but the limit is also 50/second globally...everything else is dynamic so no garentee

you can also fetch all guild members of any guild once every 30/seconds per guild...so you can do that once on startup and use gateway events to keep it updated from there after

polar sun
const bot = await guild.members.fetchMe();
const perms = channel.permissionsFor(bot, true);
if (!perms.has('SendMessages')) {
  throw new KathUtilsError('I cannot send messages in that channel');
}

That's my current setup

topaz bluff

the fetch should check the cache first before hitting the api...so worst case scenario, that hits the api once per bot restart and then uses the cache for every other request

polar sun

Yeah okay
Where sendTyping will always be an api call compared to fetching the bot what could be cached

topaz bluff

Exactly

it's also extendable to work for users as well if you ever need that (like a "you cant use [command] there since you cant access that channel")

polar sun
const bot = await guild.members.fetchMe();
const perms = channel.permissionsFor(bot);
console.log(perms.has('SendMessages'));

This is always returning true? Tested in both a channel the bot has perms in and a channel that the bot doesn't have perms in? Am I just being stupid?

topaz bluff

No that looks fine to me...probably something simple both of us are missing

polar sun

@discord.js maintainers is this wrong clueless

I guess back to my sendTyping method for now

rose tangle

sounds like you do have perms for it

you can serialize to an array to see the exact perms you have

sharp ginkgoBOT
crisp token

hi there, does anyone know if components v2 has the ability to mention and give people notifications using the textdisplaybuilder?

rose tangle

that's how it behaves by default

rose tangle

didn't Danial already help you?

rose tangle
subtle girder

last thing you sent was this with no further explanation, and most of us don't know chinese to know what's going on there

I assumed it was solved already

subtle girder

I want the bot edit the message when user interact with it
but when I call editReply, the bot replied my message just like followUp

rose tangle

editReply edits though, it doesn't create a new message

are you sure you didn't have a followUp before and didn't save the changes?

or deferReply and editReply like you said before

like Danial and BakeWithMe said, you'd want a deferUpdate and editReply

subtle girder

User: &job
bot -> embed with button and select menu

User select a job

await interaction.deferReply()
...
return await interaction.editReply(...)

bot: edit the message to confirm message (with a button)

User click confirm button

await interaction.deferReply()
...
return await interaction.editReply(...)

bot: edit the message and save data

rose tangle

if you want to edit immediately just use update

otherwise deferUpdate and later on editReply

yeah like I said, deferReply is not what you want

deferReply creates a new reply

a new message

subtle girder

but interaction.deferUpdate() and interaction.update throw an Error

Error [InteractionAlreadyReplied]: The reply to this interaction has already been sent or deferred.
    at StringSelectMenuInteraction.update
...
rose tangle

that sounds like you're deferring and then updating

stable sun

You should be using editReply, not update

rose tangle

or only an update

rose tangle

just update, not deferReply and then update, nor deferUpdate and then update

subtle girder

oh