#djs-help-v14

78874 messages · Page 62 of 79

tardy sable

checking if role.editable is enough to ensure you can add/remove roles

slender spade

for some reason my bot wont show any commands when going into DMs even after trying to set it up to show in DMs

ive tried changing the .applicationGuildCommands to .applicationCommands
ive added the channel message and reaction partials
ive tried using .setContexts in my command

it still doesnt work, how can i fix this?

unique shoal

Have you redeployed commands since setting contexts, and reloaded the app?

slender spade

yes

unique shoal

Can you show one of the commands

Partials are not relevant here, but global deployment and contexts should be sufficient

slender spade

tried it with the ping command

unique shoal

yeah I think that should work if correctly deployed globally

slender spade

it shows nothing when i go into dms but works fine in servers

unique shoal

Can't replicate - I just deployed that exact SlashCommandBuilder and it appears in DMs

cosmic burrow

Typescript Error caused by this code:

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

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

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

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

It would help a lot if you told us *what *TypeScript error was caused by this code

unique shoal
warm charm

we can't get rid the gaps on container right

unique shoal

You can check integrations installed in guilds to make sure the commands are there

unique shoal

How have you built that container?

warm charm
unique shoal How have you built that container?

here

          .addTextDisplayComponents(
            textdisplay =>
              textdisplay.setContent(
                `> Ends: <t:${duration}:R> (<t:${duration}:F>)`,
              ),
            textDisplay =>
              textDisplay.setContent(`> Hosted by: <@${interaction.user.id}>`),
            textDisplay =>
              textDisplay.setContent(
                `> Entires: ${giveaway.getDataValue('participants').length}`,
              ),
            textDisplay => textDisplay.setContent(`> Winners: ${winners}`),
          )
unique shoal

Just use a single text display if you dont want them split

slender spade
unique shoal

Then it hasnt been correctly deployed with that context

slender spade

how would i deploy it correctly?

unique shoal

Very hard for me to answer that since I don't know how you're doing it now, but if its not showing up, I can tell you that it hasnt been

slender spade

im using the deploy-commands.js setup from the guide

unique shoal

Here's how I tested it:

Slightly cut down from the guide but basically the same

warm charm
unique shoal

If thats how you want to format it

warm charm

alr ty for the tips

slender spade
unique shoal

You could try fetching commands to see whats been deployed, client.application.commands.fetch() and log that

slender spade

okay

i just got this

unique shoal

gotta await it

slender spade

oh alright

where would i put it though?

unique shoal

Ready event should work, client will be logged in there

slender spade

ready event can be async?

tried it there, still didnt work

unique shoal

yes it can, what do you mean it didnt work

slender spade

still got the pending promise

unique shoal

still arent awaiting it then

slender spade

its awaited

unique shoal

you're awaiting the console.log, which isnt a Promise

You arent awaiting the fetch, so its logging the Promise

slender spade

oh

that worked

i believe this is the ping command

unique shoal

Yep, looks correct, and it appears to be deployed to the correct contexts

You're trying to use it in the bots DMs, not DMs with someone else right?

slender spade

im trying to use it in someone elses dm

unique shoal

Ahh. then you need to have it installed as a User application type, not into Guilds

It looks like the command has been deployed to be available that way, but you also need to install it that way

slender spade

how would i go about that?

unique shoal

You'll also need the third context type, PrivateChannel

Which is missing

When you install the bot via its link, if its enabled for user installs you can select to install it that way

slender spade

that made it work, thank you so much!

unique shoal

Sorry, I should have thought to ask which DMs sooner

warm charm

did we have method to update textDisplay

sharp ginkgoBOT
warm charm
topaz bluff

Ya. You update the content of the text display and then edit the message in question by sending the entire Container object back with the modifications you wanted

warm charm

alr imma try that

subtle girder

what is ExpectedConstraintError?

the error is threw when embed.addFields

I created a test.js

loud quartz

it's not thrown by using it, it's thrown by using it incorrectly

subtle girder

ik, but idk what incorrect

loud quartz

how do you use it in the first place

subtle girder

an array contains foods' data that user have
and map() to format the foods

[food name] `[amount]` (Saturation: `[Saturation]` <:drumstick:1430440392536490065>)
-# my English is not good

loud quartz

how do you use the addFields()

subtle girder

oh! will the value too long causing this problem?

subtle girder
subtle girder
flint pier

How to get optimal prefix command?

My bot feels slower to reply than other bots

unique shoal

There is no optimal prefix command

Unless you're doing some sort of really terribly inneficient string manipulation

flint pier
// ----- Register Prefix Commands ----- //
const prefixCommandsPath = path.join(__dirname, './commands/prefixs');

fs.readdirSync(prefixCommandsPath).forEach(folder => {
    const folderPath = path.join(prefixCommandsPath, folder);
    if (!fs.statSync(folderPath).isDirectory()) return;

    const commandFiles = fs.readdirSync(folderPath).filter(file => file.endsWith('.js'));

    for (const file of commandFiles) {
        const command = require(path.join(folderPath, file));
        if (command?.data && command?.execute) {
            client.commands.set(command.data.name, command);
        } else {
            console.log(`[WARNING] Lệnh ${file} thiếu "data" hoặc "execute"`);
        }
    }
});```
loud quartz

no, none of this makes any difference

and even if, it's unmeasurably small, compared to the fact that you connect to discord via internet

flint pier

Huh?

loud quartz

you can check a string billions of times per second

doesnt' change anythign if you still have 150 ms ping to discord

flint pier

my bot has ping 300ms

loud quartz

even more then

and this is precisely and exactly why it's slower than other bots

flint pier

so what to do

loud quartz

run it somewhere else

or ignore the problem, it doesn't particularly matter

flint pier

I am hosting the bot on a VPS Linux server in Singapore.

loud quartz

then run it elsewhere

flint pier

For example?

loud quartz

rest of the world

uncut quest

Anywhere else on the planet

loud quartz

maybe besides japan, i guess

unique shoal

In the US would generally be best for Discord server proximity

flint pier

230ms for singapore

unique shoal

Yes

brisk crest

Hey, I'm using @discordjs/core on the latest npm version (2.4.0), and trying to use per-method auth, specifically for UsersApi#getCurrent. However, the function type looks like this: getCurrent({ signal }?: Pick<RequestData, 'signal'>): Promise<discord_api_types_v10.APIUser>; even though the PR to add per-method auth was merged almost a year ago. Am I missing something here?

brisk crest

Actually, it seems like #10682 is not published to @discordjs/rest on npm either

unique shoal

It is a breaking change, which would require a major

core@2.0.0 was Sep 3 2024, so a breaking change would require a 3.0 to release I guess

Not sure why we haven't done one for this though tbh, I don't really maintain core

crimson gale

cc: @golden laurel time to bully people into a core release

golden laurel

What happened

Oh

golden laurel
unique shoal

ahh

k release those too then

brisk crest

Ah, good to know. My use case is OAuth2 using OAuth2APIand UsersAPI from core, which is currently not possible without a custom auth param. Looking forward to a release!

dire rose

Does discord support dropdowns in modals yet? (With auto complete?)

dire rose

ty ty

short mulch

Am I being stupid rn?

const container2 = new ContainerBuilder()
      .addSectionComponents(s => s
      .addTextDisplayComponents(td => td 
      .setContent('User Join Channel'))
      .addActionRowComponents(ar => ar .setComponents(welcomeMenu)))
      .addSectionComponents(s => s
      .addTextDisplayComponents(td => td 
      .setContent('User Leave Channel'))
      .addActionRowComponents(ar => ar .setComponents(goodbyeMenu)));

Error:

Interaction error: TypeError: s.addTextDisplayComponents(...).addActionRowComponents is not a function
steel trail

You have a closing ) at the wrong place, you can't add action rows to sections, you want to add it to the container

Also sections need an accessory

If you just want a menu below textdisplay add the textdisplay directly to the container, no section needed

short mulch

Ah

I assumed it was the same because of the button accessory

Thanks 🫡

tribal birch

wait if i dont have partials in client options for guildmember for example, and member is partial, i wont receive event for it at all ?

or i will but i have to fetch them

red coral

Yes, because discord sends the id for delete events and the new member for update events. You can’t fetch a member which left though

tribal birch
tribal birch

kk ty

leaden wing

how can i solve this problem?
i have nearly 15 bots and i have to make every bot to be connected voice channel

rose tangle

that sounds like a network issue

sharp ginkgoBOT

Errors such as ECONNRESET, ConnectTimeoutError, SocketError: other side closed indicate a network issue

  • Free or shared hosting providers often come with significant limitations
  • Another indication of these issues are 'Unknown Interaction' errors.
rose tangle

or a firewall one

sharp ginkgoBOT

Error [VoiceConnectionTimeout]: Connection not established within 15 seconds.
Make sure you have provided the GuildVoiceStates intent to the client:

import { Client, GatewayIntentBits } = from 'discord.js';
const client = new Client({
    intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildVoiceStates]
});
steel trail

No, not what I was looking for... ip discovery failing is usually a firewall/vpn/proxy blocking UDP ports

late torrent

crySparkle

Matriz

let Matriz: number[][] = [
   [0, 0, 0], 
   [0, 0, 0],
   [0, 0, 0]
];

dogeHaHa

bleak owl
late torrent
bleak owl

yeah no, please troll elsewhere

late torrent

Using array

wet oak

i'm sure all i did should work but for some reason sapphire is yelling at me with 0 context, for sending the message i do enable the componentsv2 flag

message.channel.send({
    components: [
        embed
    ],
    flags: [
        MessageFlags.IsComponentsV2
    ]
})

https://pastebin.com/1FCYrCqW
Errors are in the provided message.txt

wet oak

it's a container

its just called embed becuase it was an embed before and i just turned it into a container

because they look cleaner

wary coral

You have one or more sections without an accessory

wet oak

oh

i didn't think they were required, thanks for the help!

wary coral

Sections are required to have an accessory and one text display

If an accessory is not needed. Just add the text display on its own

wet oak

Yup, that was the issue, thanks for the clarification and sorry for being dum

wary coral

All good

coarse storm

What is the max character limit in the new modal label's descriptions?

sharp ginkgoBOT

documentation suggestion for @coarse storm:
discord Component Reference - Label
A Label is a top-level layout component. Labels wrap modal components with text as a label and optional description.

deep harness

How do i slice embeds properly? For example i have some search results (for example a string[]) and i need to fit them into an embed (and then pagify it)
i need to make sure i wont go over the field limit, field value length limit and the embed character limit

rose tangle

there's no built-in function for that

deep harness
rose tangle

this is for help with the library itself

though tbh it sounds like you already know the solution, just trim the content according to those limits

deep harness
rose tangle
sharp ginkgoBOT

mdn String.prototype.slice()
The slice() method of String values extracts a section of this string and returns it as a new string, without modifying the original string.

deep harness
crystal cargo

why it does not reach the console.log({ btn }) or bellow
uploadInteraction is a ButtonInteraction

rose tangle

collectors don't work well with non fetched ephemeral replies iirc

try adding withResponse: true

sharp ginkgoBOT

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

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

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

then i do response.resource.message.awaitMessageComponent?

rose tangle

yeo

thorn sphinx

um how do i make my bots commands available in dms - like when dming sm1 else i can run a command

hybrid fable

I made a bot that puts users, based on their id, into a queue.

The queue is a simple array. I added a check if the user is in queue, and dont add them if they are.

Added that bot to two different servers (guilds)
And every server had their own queue somehow.

So thats awesome, but does somebody know why?

I didnt implement "per guild" separation, its just a simple array.
So not knowing whats going on is kinda scary

wintry laurel

anyone know why getBoolean('blacklist') gives this error when the reject command is used? TypeError: Cannot read properties of undefined (reading 'getBoolean')

const blacklist = interaction.option.getBoolean("blacklist")

clear garnet

interaction is probably not actually an instance of an interaction

wintry laurel

the rest of my subcommands work fine

(and they all use interaction)

clear garnet
clear garnet
wintry laurel
clear garnet

Ah, yep, there you go, not sure how I missed that, good deal

wintry laurel

yea not sure how i missed that either lol, thanks

hybrid fable
clear garnet
wintry laurel

or just the way vsc works. probably should switch to jetbrains but oh well

hybrid fable
clear garnet We'd need to know how you actually implemented this queue system and what you sp...

ok, I expected there to be some obvious magic that someone knows about, because how I implemented it, it makes 0 sense

Ive used a million singletons and a singleton holds the array
If User A joins the queue on server A, then joins the queue on server B, it should not put him in, cause he is already in

But it puts him in what seems to be a different queue and I dont know why, maybe its a bug after all

clear garnet

Can you share the code for all of this?

hybrid fable

I can share the important parts
from a button handler

await interaction.deferReply({ flags: MessageFlagsBitField.Flags.Ephemeral });
const playerAddedToQueue = queues.addPlayerToQueue(region, interaction.user);

and adding them to an array

public addPlayerToQueue(region: string, user: User, partySize: number = 1)
    const queue = this.state.queues[region];

    if (queue.players.find(player => player.id === user.id)) {
      return false;
    }

    queue.players.push(this.mapUserToPlayer(user, partySize));

really nothing to it
region is the same for both cases

ok I found it, does indeed not work, just looks like it OK
man I was starting to get excited about not having to implement guild separation PepeLa

everything is tied to a discord message, and the message was just overridden
so while nothing broke, it was only working for the last guild that set everything up

silent mirage

can i make a upload file field in forms to only accept a certain file

rose tangle

what would be the point of uploading it?

silent mirage

Its for my dsl plugin file

rose tangle

you mean a certain file type then?

silent mirage

Yes cause i want it to only accept .fsx file

rose tangle

there isn't

though tbf you can't really rely on that anyways, I can rename my .png to .fsx

so you'll still need some kind of validation

silent mirage

Yay i made valudation to verify it content but i still wanted to prevent it but i will keep it how i have it

steel trail

Then they don't have one

scenic berry

Is it better to transfer to typescript or just stay on javascript?

unique shoal

Not really a yes/no or a discord.js question\

If you want the benefits of type-safety, switch to TypeScript

crisp roost
                const workFilesUpload = new FileUploadBuilder()
                    .setCustomId('work_files')
                    .setMinValues(1)
                    .setRequired(true)
                    .setMaxValues(10);
                const workFilesLabel = new LabelBuilder()
                    .setLabel('Upload portfolio files (images, pdf, video)')
                    .setDescription('You can upload up to 10 files')
                    .setFileUploadComponent(workFilesUpload);

this is my current code. once ran and a button is interacted, it gives me this error:

application handler error TypeError: (intermediate value).setLabel(...).setDescription(...).setRequired is not a function
    at Object.execute (/workspaces/nuhuh/events/dashboard/application.js:93:22)
    at Client.<anonymous> (/workspaces/nuhuh/handlers/eventHandler.js:17:50)
    at Client.emit (node:events:531:35)
    at InteractionCreateAction.handle (/workspaces/nuhuh/node_modules/discord.js/src/client/actions/InteractionCreate.js:101:12)
    at module.exports [as INTERACTION_CREATE] (/workspaces/nuhuh/node_modules/discord.js/src/client/websocket/handlers/INTERACTION_CREATE.js:4:36)
    at WebSocketManager.handlePacket (/workspaces/nuhuh/node_modules/discord.js/src/client/websocket/WebSocketManager.js:352:31)
    at WebSocketManager.<anonymous> (/workspaces/nuhuh/node_modules/discord.js/src/client/websocket/WebSocketManager.js:236:12)
    at WebSocketManager.emit (/workspaces/nuhuh/node_modules/@vladfrangu/async_event_emitter/dist/index.cjs:2504:31)
    at WebSocketShard.<anonymous> (/workspaces/nuhuh/node_modules/@discordjs/ws/dist/index.js:1190:51)
    at WebSocketShard.emit (/workspaces/nuhuh/node_modules/@vladfrangu/async_event_emitter/dist/index.cjs:2504:31)
    at WebSocketShard.onMessage (/workspaces/nuhuh/node_modules/@discordjs/ws/dist/index.js:1007:14)
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5)

anyone know what makes it error? any help would be great

halcyon bison
crisp roost
crude mist

is V2 modal file temporary like the file upload option?

File upload stores them for a week im wondering if the V2 modal file upload does the same

stable sun
crisp roost

back again :p | from the FileUploadBuilder, how would i get the url/download the image(s) that were uploaded onto it?

stable sun

interaction.fields.getUploadedFiles(customId)

That will give you a Collection of Attachments that you can derive the .url property from each and fetch yourself

topaz bluff
crisp roost

perfect, thank you both!

azure forge

Is there any plans for Modal Discord System to be able to add images in the formular?

topaz bluff

More of a DDevs question... Discord.js doesn't have any control over stuff like that

But I have not heard what they plan to add but I know they are working on stuff

chrome dune

Hello, I've been trying to create a similar discord embed that adds a right button on the title like next.js does on their Release channel but can't find how they are doing that, any hints? Is that even an embed?

sharp ginkgoBOT

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

azure forge
chrome dune

Is there anyway to have a message show content in iOS notifications when using IsComponentsV2?
Since content is not allowed with IsComponentsV2 flag

wary coral

No. Discord needs to fix the notification implementation of their app

inland sphinx

why does my bot save old menu select selection

topaz bluff

This is a Discord app issue...not anything to do with DiscordJS

shell girder

meguFace

bleak owl
shell girder

I have a question: in the modal generator of the selection menu, instead of collecting only one piece of data, is it possible to select several?

topaz bluff

Select menus can receive multiple selections, yes

silent mirage
topaz bluff

You can set a min and max number of values the user is allowed to submit as well

shell girder

Thank you so much. 😀

tardy sable

to remove all permissions on a role would i do role.setPermissions(0n) ?

hallow mesa
keen monolith
unique shoal

It would help to know from which line

interaction.options.getUser('user') can be null though

keen monolith

It doesn’t state 😭

unique shoal

Errors do state

Show the error stack

keen monolith
unique shoal

Okay so you arent logging the error stack Thonk

Its recommended not to stringify errors

- console.log(`Error handling /balance... ${error}`);
+ console.error("Error handling /balance...", error);

Log it like that

keen monolith

Oki

unique shoal

Great - line 27

Which is as I guess interaction.options.getUser('user').username

Option wasn't supplied and is null

keen monolith

oh but it is at the bottom of the command?

hallow mesa

The command has the option but it's optional. If someone doesn't select the option, getUser will return null

keen monolith

ohhhh... how would I make it so it can send something different then? So if they don't choose to enter it, it sends smth else?

unique shoal

You already do this on line 14

Optional chaining (?.) and null collescing (??)

tardy sable

define the user once and then go from there. will be less confusing

keen monolith

ah okay! I followed a economy bot tutorial so I could understand databases but they only used normal replies but I wanted to make embed replies 😅

oh... i just realised.. since I alr defined targetUserId could I change everything to be that instead?

unique shoal

Well its an id, not the user

But using that style, yes, you could do targetUser = interaction.options.getUser("user") ?? interaction.user

Then whenever you need to, you have access to either targetUser.username, targetUser.id or anything else

keen monolith

okay

unique shoal

You're not passing an array of embeds

tardy sable
keen monolith

omg I can't believe i forgot the brackets! I need to sleep lol

tysm guys!!! 💀

Quick question tho! For like a new command to get currency, how would you make it random?

tardy sable

if currency amount, just do random math 🤷

keen monolith

thanks I didn’t know there was a random math function :D

sharp ginkgoBOT

mdn Math.random()
The Math.random() static method returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1, with approximately uniform distribution over that range — which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user.

tardy sable

btw whoever manages the djs bot /docs is not working

keen monolith

Thanks guys 💕

native plank

Hi, can anyone tell me how to change the status of a voice channel ?

unique shoal

That API is not documented and therefore not supported by discord.js

native plank

Oh, okay... That is surprising, I use a bot that can changes the status

That's weird, no ?

golden ocean

maybe python

halcyon bison

the api not being documented isn't the same as it not existing
it being unsupported does not mean it's impossible

native plank

Oh, okay.. I'll see how else i can do it, thanks for help 👌

little pebble
nimble obsidian

quick question? what are the default interaction types (server, bot DM, any DM)?

unique shoal

Depends on the contexts your app is installed for at the time of deployment, I think its Guild and BotDM for the Guild install and PrivateChannel for the User install

wary coral

what error do you get

unique shoal

years ago

nimble obsidian

I have tried searching but can't find it, ty btw

sharp ginkgoBOT

documentation suggestion for @nimble obsidian:
discord Application Commands - Contexts
Commands have two sets of contexts on the application command object that let you to configure when and where it can be used: - integration_types defines the installation contexts that a command supports - contexts defines the interaction contexts where a command can be used Details for both types of command contexts are in the sections below.

rose tangle

huh looks like it's no longer there

yeah no idea to where they moved it

contexts used to default to all of them, no idea if it's still the case

vagrant marsh

I just new on discord.js version 14.25.1 how to set label using label builder

topaz bluff

That's not a LabelBuilder. That's a TextInputBuilder...which is correct that TextInputBuilder#setLabel is deprecated

sharp ginkgoBOT
vagrant marsh

Tsym !

uncut tangle

are discord tags in discord js, like i waana get my user's tag BOLT

sharp ginkgoBOT
velvet cipher

shoud have a .tag property which would be the guild tag

uncut tangle

alr thanks

primary guild for me shows null

or wait nvm

mb, thanks for help

devout widget

How to make this type ui inside selection menu or buttons

sharp ginkgoBOT

guide suggestion for @devout widget:
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.

pure ridge

hey all .. what do I have to do to get all members on a server with all the information about user status, etc.

Using guild.members.fetch() doesn't give me this

sharp ginkgoBOT
pure ridge

ah awesome.. sorry next time I scroll down a lil more

keen widget

is there a limit to how many options can have an emoji? because my string select menu is casuing the bot to fail to send a message when there is 125 emojis

each for one option

    const rows = Array.from({ length: 5 }, (_, i) => {
      const options = Array.from({ length: 25 }, (_, j) => (
        new StringSelectMenuOptionBuilder()
          .setLabel(`Option ${i * 25 + j + 1}`)
          .setValue(`FID:${id}:select:${i * 25 + j + 1}`)
        //.setEmoji('🤖')
      ));

      if (i === winnerMenu) {
        const winnerOption = Math.floor(Math.random() * options.length);
        options[winnerOption]
          ?.setValue(`FID:${id}:select:${i * 25 + winnerOption + 1}:win`)
          .setLabel(`Option ${i * 25 + winnerOption + 1}`)
          .setEmoji('💎');
        console.log(i * 25 + winnerOption + 1)
      }

the commented line causes the bot to error 500

no matter the emoji I put there

wary coral
keen widget
tardy sable
keen widget

Error starting first-to-win drop: HTTPError: Internal Server Error
at handleErrors (/home/discordbots/xxx/node_modules/@discordjs/rest/src/lib/handlers/Shared.ts:136:9)
at SequentialHandler.runRequest (/home/discordbots/xxx/node_modules/@discordjs/rest/src/lib/handlers/SequentialHandler.ts:417:26)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
at async SequentialHandler.queueRequest (/home/discordbots/xxx/node_modules/@discordjs/rest/src/lib/handlers/SequentialHandler.ts:169:11)
at async _REST.request (/home/discordbots/xxx/node_modules/@discordjs/rest/src/lib/REST.ts:210:20)
at async TextChannel.send (/home/discordbots/xxx/node_modules/discord.js/src/structures/interfaces/TextBasedChannel.js:190:15)
at async _FirstItemDropBuilder.start (/home/discordbots/xxx/src/app/utils/itemDrop.ts:453:21)
at async chatInput (/home/discordbots/xxx/src/app/commands/admin/item-drop.ts:151:9)
at async <anonymous> (/home/discordbots/xxx/node_modules/commandkit/src/context/async-context.ts:36:24)
at async _AppCommandRunner.runCommand (/home/discordbots/xxx/node_modules/commandkit/src/app/commands/AppCommandRunner.ts:151:13) {
requestBody: {
files: [],
json: {
content: undefined,
tts: false,
nonce: undefined,
enforce_nonce: false,
embeds: [Array],
components: [Array],
username: undefined,
avatar_url: undefined,
allowed_mentions: undefined,
flags: undefined,
message_reference: undefined,
attachments: undefined,
sticker_ids: undefined,
thread_name: undefined,
applied_tags: undefined,
poll: undefined
}
},
status: 500,
method: 'POST',
url: 'https://discord.com/api/v10/channels/1363229717511012439/messages'
}

keen widget

told u it's 500, the error stack doesn't help at all

wary coral

could you please provide the full context of your code and discord.js version

keen widget

^14.18.0

wary coral

like the fuction you are executive

keen widget

so .send?

wary coral
wary coral
keen widget
function generateFirstDropComponents() {
const winnerMenu = Math.floor(Math.random() * 5)
    const rows = Array.from({ length: 5 }, (_, i) => {
      const options = Array.from({ length: 25 }, (_, j) => (
        new StringSelectMenuOptionBuilder()
          .setLabel(`Option ${i * 25 + j + 1}`)
          .setValue(`FID:${id}:select:${i * 25 + j + 1}`)
          .setEmoji(':robot:')
      ));

      if (i === winnerMenu) {
        const winnerOption = Math.floor(Math.random() * options.length);
        options[winnerOption]
          ?.setValue(`FID:${id}:select:${i * 25 + winnerOption + 1}:win`)
          .setLabel(`Option ${i * 25 + winnerOption + 1}`)
          .setEmoji(':gem:');
        console.log(i * 25 + winnerOption + 1)
      }

      const menu = new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(
        new StringSelectMenuBuilder()
          .setCustomId(`FID:${id}:select:${i}`)
          .setPlaceholder("Choose an option")
          .addOptions(options)
      );

      return menu;
    });

    return { embed, components: rows };
}```
I am skipping irrelevant code btw, so dw if there are some variables missing
  const { embed, components } = generateFirstDropComponents();
    const message = await channel.send({ embeds: [embed], components })
    if (!message) {
      throw new Error("Failed to send drop message.");
    }```

note: it works without this line .setEmoji(':robot:') so the rest of the code is very irrelevant to the issue I am facing

and the updated djs version also fails

wary coral
keen widget
wary coral
keen widget
wary coral

like is it part of the default set or a custom emoji?

keen widget

default

it's just broken cuz of discord formatting

do u want the .toJson()?

wary coral
keen widget
wary coral

Are your label and value strings 100 or less characters?

keen widget
wary coral

weird. if your try to do .setEmoji({id: '🤖'})

wow inlicode realy not liking emojis today

keen widget

pretty sure it should be in "name"

wary coral

well that is a different error. but that is bad advice on my part you chould just be able to pass the emoji

keen widget

LOL

wary coral

if you put it in name does it give you 500

keen widget

yes

wary coral

I am at a loss it could just be a Discord bug right now.

Maybe worth asking on DDevs

keen widget

btw this works:

      const options = Array.from({ length: 25 }, (_, j) => {
        const menu = new StringSelectMenuOptionBuilder()
          .setLabel(`Option ${i * 25 + j + 1}`)
          .setValue(`FID:${id}:select:${i * 25 + j + 1}`)

        if (j % 2 === 0) {
          menu.setEmoji('🤖')
        }
        return menu;
      });
wary coral
keen widget

if (j % 10 !== 0) {
menu.setEmoji('🤖')
}

THIS ALSO WORKS

wary coral

so only adding emojis to all 25 causes an issue?

keen widget
        if (j % 12 !== 0) {
          menu.setEmoji('🤖')
        }

pretty sure

wait nevermind:
if (j !== 24 && j !== 23) {
menu.setEmoji('🤖')
}
this works

but this doesnt:
if (j !== 24) {
menu.setEmoji('🤖')
}

😭, I will just put 23 options per page and ignore this shit

any thoughts on this mafia?

wary coral

strange, Def sounds like a Discord bug

keen widget

yeah definetely, but how could they make it so buggy?

oh and @wary coral it's only an issue with 125 options, if I do 100 with full emojis it works

actually let me check what is the exact number

wary coral

lol, ok. I wonder does the issue also occure with cv2

keen widget

what is cv2?

sharp ginkgoBOT

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

keen widget

oh components v2, yeah no idea

but since the limit is 119 emojis, it errors on 120 it might mean it's some bug with .length where they forget to do +1

don't u agree? @wary coral

wary coral

I don't know. the issue seems to be on Discords side as they give a 500 error and I can't find written emoji limits for select menus

keen widget
wary coral

maybe but it outside the scope of discord.js. I did raised the issue to the maintainers

keen widget

oh u did? thank you so much, saved me some troublew

cobalt plover

im puzzled, how do you make the same webhook send github notifications to different forum threads, like in #1006698887605653565?

cobalt plover

alr so i've added the thread_id parameter, now i cant make it a github webhook

wary coral

Are your trying to use this in code?

cobalt plover

oh so you first do /github and then pass the thread_id option

no im configuring it in the github repo settings

wary coral

np

tardy sable

if you set channeltypes in a selectchannelmenu and there are no such channeltypes in the guild. what happens?

does it error or discord handles that?

keen widget

😭 why would it error bro?

polar karma
light ibex

hello guys,

what should i use for this fields ? i tried to search about it on discord.js.org, discordjs.guide and the discord.js package.

i don't get it how can i get the values and fields to save them into a data ?

sharp ginkgoBOT
tardy sable
keen widget
tardy sable

yh but thats with search

topaz bluff
keen widget
tardy sable

have you tried my question then?

keen widget
tardy sable

then why are you assuming something if you havent tried it?

keen widget

based on your experience u will say u can, but u haven't tried it, have u?

tardy sable

if you got nothing useful to say dont reply

keen widget

I said something useful, it won't error

that was literally your question, wasn't it?

tardy sable

you didnt. stop it

keen widget
bleak owl

stop with the nonsense

tardy sable

mods deal with this guy smh

keen widget
bleak owl

just, stop

keen widget

sure

light ibex

How can I edit container components the same way I edit embeds?

Also, how can I modify the components inside a container like updating the options in a select menu without causing duplicates?
As shown in the image, whenever I try to edit the select menu inside the container, it ends up duplicating the menus.

hallow mesa

Sounds like you're appending the component to the array instead of putting it in the same spot inside the container

light ibex
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.

wary coral
hallow mesa
light ibex so how can i do this ?

In your for loop on line 75 you're iterating through the components in the message, not the components inside the container. You want to be looping through message.components[0].components instead and then replacing the row you find there

  • message
    • container
      • action row
        • select menu

There's the createComponentBuilder function if you want to use the splice function Mafia mentioned. You'll probably want to do that instead of just pushing the new row in once you've found the old one

light ibex

OKay Thank you 🤍

keen widget

@wary coral in-case u wondered why I needed 125 emojis, am making a drop system with one of the types being find the emoji

alpine token

why
interaction.guild.channels.cache.get('1448028434058973366').setName('A')
it's slow ? is that bcuz rate limit ?

stable sun
stable sun

Bots have a special rate limit for editing name and topic of channels

2 edits / 10 min

alpine token
stable sun

I mean, everything have a rate limit. Not as bad as editing channel name tho

bitter leaf

hello

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMembers,
    // GatewayIntentBits.GuildMessages,
    // GatewayIntentBits.GuildVoiceStates,
    GatewayIntentBits.MessageContent,
    // لو ما تحتاج Presences فعلاً، حاول تشيل:
    // GatewayIntentBits.GuildPresences,
  ],
  partials: [
    Partials.Channel,
    Partials.Message,
    Partials.User,
    Partials.GuildMember,
  ],
  makeCache: Options.cacheWithLimits({
    // لا نحتفظ بأي رسائل في الكاش تقريبًا (أنت تعتمد كثير على DB أصلاً)
    MessageManager: 0,

    // عدد الأعضاء المخزّنين لكل Guild
    GuildMemberManager: 40000,   // عدّل حسب حجم السيرفرات

    // الكاش العام للمستخدمين
    UserManager: 500000,

    // لو ما تحتاج presence في الذاكرة:
    PresenceManager: 0,
  }),
  sweepers: {
    messages: {
      interval: 600,   // كل 10 دقائق
      lifetime: 300,   // امسح الرسائل الأقدم من 5 دقائق من الكاش
    },
     users: {
       interval: 1800,  // كل 30 دقيقة
       filter: () => user => !user.bot, // مثال: امسح المستخدمين العاديين من الكاش
     },
  },
});

what's wrrong in guild cache size exists only 2
that it's me and bot

in guilds there like 20 members

halcyon bison
bitter leaf

keen widget
wide elk

is there any way to put inline fields inside a container?

bleak owl

nope

sharp ginkgoBOT

documentation suggestion for @keen widget:
method RoleManager#fetch() discord.js@14.25.1
Obtains a role from Discord, or the role cache if they're already available.


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

wide elk

bruh

topaz bluff
wide elk
topaz bluff
wide elk
bleak owl

no

topaz bluff
keen widget

How could I not see it in the freaking docs ...

wide elk
keen widget

Phones just hit different

bleak owl

embeds are still existent, they're not going away

wide elk

i dont think i can send an embed + container

bleak owl

you cannot, no

wide elk

i cant use embed in my case, ill find a way to do what im trying to do

ty for ur help

keen widget

am not that brainrot to not know such basics

also while we speak about that, are roles cached on ready?

bleak owl

with the Guilds intent, yes

keen widget

just seperated in djs for memory management freedom

halcyon bison
keen widget okay and is it same endpojnt as guilds?

I'm not totally sure what answer you're looking for here so just to explain a few things
the reason guilds, roles, channels, etc. are cached on ready with the Guilds intent is that with this intent, discord sends the guildCreate event immediately after the gateway's ready event for every available guild your bot is in
djs's clientReady event emits after having received these
djs does not fetch anything on ready via rest, so there isn't an endpoint of any sort involved
there are separate endpoints for fetching a guild and fetching a guild's roles
though I believe fetching a guild does also provide its roles, and djs would cache these roles
however djs also relies on the Guilds intent for many of its features, so in most cases we actually recommend you don't fetch guilds

keen widget
north vale

What is the recommended file/code structure for me to accommodate modal submission logics? Inside the slash command file that triggered it?
Examples are welcome

rose tangle

there's really no "official" recommended code structure

it pretty much depends on what you like and what you need

pretty much the only built-in helper for that in djs is the awaitModalSubmit method, which is easy to use

sudden ridge

hey, i want to build a embed but it seems like addComponents is now deprecated, whats the new way to make modals? my current approach is this:

let modal = new ModalBuilder()
    .setCustomId(`settings_edit_modal_${selected}`)
    .setTitle("Edit Settings");

  switch (selected) {
    case "message_xpp":
    const enabled = new TextInputBuilder()
      .setCustomId("enabled")
      .setLabel("Enabled")
      .setStyle(TextInputStyle.Short)
      .setValue(String(settings.messageXpEnabled))
      .setRequired(true)
      .setMinLength(4)
      .setMaxLength(5);
    modal.addComponents( // <-- deprecated
      new ActionRowBuilder<TextInputBuilder>().addComponents(enabled)
    );
  }
rose tangle

you add a label which contains the text input

sharp ginkgoBOT
sudden ridge

ty, will have a look

languid summit

How many of you use visualization tools like json crack to understand json data and other types of that like XML and such?

velvet cipher

Sounds unrelated to discordjs

stable sun

Never did tbh. I usually just figure it out from observation and context, if no docs are available

keen monolith
const { SlashCommandBuilder, PermissionFlagsBits } = require('discord.js');
const { UserProfile } = require('../../schemas/UserProfile');

module.exports = {
    async execute (interaction) {
        if (!interaction.inGuild()) {
            interaction.reply({
                content: "This command can only be used inside Chonsa!",
                ephermeral: true,
            });
        return;
        };
        
        const addAmount = interaction.options.getNumber('amount');

         try {
             await interaction.deferReply();
             
            let userProfile = await UserProfile.findOne({
                userId: interaction.options.getUser('user').id,
            });

            if (!userProfile) {
                userProfile = new UserProfile({ userId: interaction.options.getUser('user').id });
            }
        
        userProfile.balance += addAmount;
        
        await userProfile.save();
        
        interaction.editReply(
                `${addAmount} was added to <@${interaction.options.getUser('user').id}>'s' balance\nNew balance: ${userProfile.balance}`
            )
        } catch (error) {
            console.log(`Error handling /daily...`, error)
        }

    },
        data: new SlashCommandBuilder()
    .setName('add')
    .setDescription("add currency to someone's balance")
    .setDefaultMemberPermissions(PermissionFlagsBits.Administrator)
    .addUserOption((option) => option
                  .setName('user')
                  .setDescription("Who's balance are adding to?")
                  .setRequired(true))
    .addNumberOption((option) => option
                    .setName('amount')
                    .setDescription('How much would you like to add?')
                    .setRequired(true)),
}```
rose tangle

that's not a djs error

keen monolith

It’s not?!?

Oh… oops okay - I thought it was 😅

rose tangle

"cannot read properties of undefined (reading 'X')" means somewhere you're doing undefined.X

the fact that it says 'findOne' means it's one of your findOne calls

the only usage there is UserProfile.findOne

so UserProfile is undefined

keen monolith

oh okay.. I thought I defined it.. I'll look into it - thx

clear garnet

There's a difference between defining a variable and a variable having a value of undefined - the latter of which is your case

const myVariable = undefined;
// Variable `myVariable` has been defined and can be referenced, but its underlying value is of type "undefined"```
keen monolith

How would I make a command have like 4 different replies all using luck / Math.random()??

tardy sable
keen monolith

interaction.followUp?

tardy sable

or do you mean a random reply based on 4 possible replies?

keen monolith

a random reply based on those 4 possible ones

tardy sable

that isnt really djs related and just basic js. you can put those 4 replies in array and then get random

keen monolith

oh okayyyy I thought it would be

thx tho!

rose tangle

if it has to do with discord, it's djs related

if it doesn't, then it's not

queen goblet

does discordjs support per server profiles for bots yet ?

sharp ginkgoBOT
queen goblet

thx

queen goblet

@unique shoal guild.editMe says not a function

limber quarry

@queen goblet guild.members.editMe

queen goblet

i see wahts wrong

i wasnt on the updated version of djs

limber quarry

hey y'all I need some help. I'm trying to make a work command for my bot. I have the cooldown system finished, now I am trying to figure out how to calculate the timestamp at which the user will be able to work again. Here is my code to reject the user if the cooldown isnt finished:

if (!bot.cooldowns.work(cmd.user)) {
  let remaining = Date.now()-user.workedAt;

            

  let embed = new EmbedBuilder()
  .setTitle(`Chill out`)
  .setDescription(`You can work again at <t:`)
}```

I just need to know how to calculate the time at which the user will be able to work again.
queen goblet

dont think thats djs question

limber quarry

I'm not great at date math.

sharp ginkgoBOT

guide Cooldowns
Spam is something you generally want to avoid, especially if one of your commands require calls to other APIs or takes a bit of time to build/send. This section assumes you followed the Command Handling part of the guide. First, add a cooldown property to your command. This will determine how long the user would have to wait (in seconds) before using the command again. In your main file, initialize a Collection to store cooldowns of commands: 1. now: The current timestamp.

crude mist
delicate needle

We agree that in a v2 component with simple text containing a link, we can't use YouTube's auto-embed feature, right?

topaz bluff

Correct. I don't believe links in TextDisplay components render an embed

delicate needle

Okay, that's what I thought, unlucky

chilly canopy
keen monolith ```js const { SlashCommandBuilder, PermissionFlagsBits } = require('discord.js')...

Try it bro


const { SlashCommandBuilder, PermissionFlagsBits } = require('discord.js');
const UserProfile = require('../../schemas/UserProfile'); // got error here bro 

module.exports = {
    async execute(interaction) {
        if (!interaction.inGuild()) {
            return interaction.reply({
                content: "This command can only be used inside Chonsa!",
                ephemeral: true, 
            });
        }

        const addAmount = interaction.options.getNumber('amount');

        try {
            await interaction.deferReply();

            let userProfile = await UserProfile.findOne({
                userId: interaction.options.getUser('user').id,
            });

            if (!userProfile) {
                userProfile = new UserProfile({
                    userId: interaction.options.getUser('user').id,
                    balance: 0
                });
            }

            userProfile.balance = (userProfile.balance || 0) + addAmount; //safe math 

            await userProfile.save();

            await interaction.editReply(
                `${addAmount} was added to <@${interaction.options.getUser('user').id}>'s balance\nNew balance: ${userProfile.balance}`
            );

        } catch (error) {
            console.log(`Error handling /add...`, error);
        }
    },

    data: new SlashCommandBuilder()
        .setName('add')
        .setDescription("add currency to someone's balance")
        .setDefaultMemberPermissions(PermissionFlagsBits.Administrator)
        .addUserOption(option =>
            option.setName('user')
                .setDescription("Who's balance are adding to?")
                .setRequired(true))
        .addNumberOption(option =>
            option.setName('amount')
                .setDescription('How much would you like to add?')
                .setRequired(true)),
};

calm elm

Can you elaborate on that (connecting through a socks5 proxy)? I am trying to do the same thing in my client, but I get an error about this.dispatch is not a function:

const proxyAgent = new SocksProxyAgent('socks5://127.0.0.1:40000');

//in client
rest:
{
  timeout: 20000,
  agent: proxyAgent
},
                                    
ws: {agent: proxyAgent},```

I have been looking at `https://discordjs.guide/legacy/additional-info/proxy`
Thanks for anything you can do to point me in the right direction 🙂
sand minnow
❌ Failed to register commands: DiscordAPIError: Maximum number of application commands reached (5).
    at RequestHandler.execute (C:\Users\zeinf\Documents\Projects\tryhard\main\tryhard-main\node_modules\discord.js\src\rest\RequestHandler.js:350:13)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async RequestHandler.push (C:\Users\zeinf\Documents\Projects\tryhard\main\tryhard-main\node_modules\discord.js\src\rest\RequestHandler.js:51:14)
    at async ApplicationCommandManager.set (C:\Users\zeinf\Documents\Projects\tryhard\main\tryhard-main\node_modules\discord.js\src\managers\ApplicationCommandManager.js:162:18)
    at async module.exports (C:\Users\zeinf\Documents\Projects\tryhard\main\tryhard-main\handler\slash.js:68:9) {
  method: 'put',
  path: '/applications/1069217203800518727/commands',
  code: 30032,
  httpStatus: 400,
  requestData: {
    json: [
      [Object], [Object], [Object],
      [Object], [Object], [Object],
      [Object], [Object], [Object],
      [Object], [Object], [Object],
      [Object], [Object], [Object],
      [Object], [Object], [Object],
      [Object], [Object], [Object],
      [Object], [Object], [Object],
      [Object], [Object], [Object]
    ],
    files: []
  }
}```

what even is the limit at this point? I barely have like 40 commands, even less

topaz bluff

You're exceeding the context menu command limit

sand minnow
sand minnow
topaz bluff

You can bypass this by using guild and global commands to double it to 10

sand minnow
hybrid fable
thin reef

can I do multiple operations in 1 API call to guild members? like changing nickname & adding a role ?

stable sun
sharp ginkgoBOT
stable sun

Assuming you know their roles beforehand

steel bronze

Does anyone know why this is happening?
Idk if am doing something wrong or

steel bronze
velvet cipher

is the Buffer.from(..., 'base64') necessary? I can imagine that's what's messing it up

steel bronze

I have to buffer it as am building the html

Like this

open night

How can put an attachment on addMediaGalleryComponents

open night

please someone help me

halcyon bison
sharp ginkgoBOT

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

open night
  const pizzaChartAttachment = new AttachmentBuilder(pizzaGraficoBuffer, { 
              name: 'pizza_chart.png' 
             });
  const graph1media = new MediaGalleryBuilder().addItems((mediaGalleryItem) =>
                mediaGalleryItem
                    .setDescription('alt')
                    .setURL('attachment://pizza_chart.png')
                    .setSpoiler(false)
            );
...
.addMediaGalleryComponents(graph1media)
             ```

this way?

halcyon bison

on the assumption you're also sending the attachment alongside the component, yes

open night

i forgot it 💀

But I don't want to send the images if they're not inside the container, how do I do that?

halcyon bison

don't include them in the files array

open night

so.. i need include them in the attachment array?

halcyon bison

no, if you don't want to send an attachment, don't include it at all

open night

but it gives error

components[1].components[3].items[0].media.url[UNFURLED_MEDIA_ITEM_REFERENCED_ATTACHMENT_NOT_FOUND]: The referenced attachment ("attachment://linha_chart.png") was not found
components[1].components[6].items[0].media.url[UNFURLED_MEDIA_ITEM_REFERENCED_ATTACHMENT_NOT_FOUND]: The referenced attachment ("attachment://pizza_chart.png") was not found

halcyon bison

then it sounds like those will be referenced in the media gallery
is it possible your media gallery itself isn't in the container?

open night
const linhaChartAttachment = new AttachmentBuilder(linhaGraficoBuffer, { 
              name: 'linha_chart.png' 
            });
            const pizzaChartAttachment = new AttachmentBuilder(pizzaGraficoBuffer, { 
              name: 'pizza_chart.png' 
             });
             
            const graph1media = new MediaGalleryBuilder().addItems((mediaGalleryItem) =>
                mediaGalleryItem
                    .setDescription('alt')
                    .setURL('attachment://linha_chart.png')
                    .setSpoiler(false)
            );

            const graph2media = new MediaGalleryBuilder().addItems((mediaGalleryItem) =>
                mediaGalleryItem
                    .setDescription('alt')
                     .setURL('attachment://pizza_chart.png')
                    .setSpoiler(false)
            );

            const separator = new SeparatorBuilder().setDivider(true).setSpacing(SeparatorSpacingSize.Small);

            const exampleContainer = new ContainerBuilder()
                .setAccentColor(30206)
                .addTextDisplayComponents((t) =>
                    t.setContent(`### Analytics Influenciador <@${influencerId}>`)
                )
                .addSeparatorComponents(separator)
                .addTextDisplayComponents((t) =>
                    t.setContent(
                        `**Convites do período**\n` +
                        `**+${selectedInvites.data.total - selectedInvites.data.left}** ` +
                        `(+${selectedInvites.data.total}, -${selectedInvites.data.left}, +${selectedInvites.data.fake} novas)\n\n` +
                        `**Clientes:** ${totalUsers}`
                    )
                )
                .addMediaGalleryComponents(graph1media)
                .addSeparatorComponents(separator)
                .addTextDisplayComponents((t) => t.setContent(`## Jogadores qualificados:`))
                .addMediaGalleryComponents(graph2media)
                .addTextDisplayComponents((t) => t.setContent(dataString));

            await interaction.editReply({
                components: [buttonsRow, exampleContainer],
                flags: [MessageFlags.Ephemeral, MessageFlags.IsComponentsV2]
            });
        }```
halcyon bison

you're saying that after adding the files option back, the media gallery appears outside the container?

open night

inside the container and outside

have idea what i can do?

halcyon bison

well this code shouldn't produce that behavior
afaik if an attachment is referenced elsewhere via an attachment:// url it should only appear there
furthermore with components v2, components should be the only thing available in the message
I'm also unable to reproduce this behavior with your code
so this sounds more like an issue with your discord client

open night

What should I do?

safe karma

for some reason...

.setButtonAccessory((button) =>
          button
            .setCustomId("dice_start")
            .setStyle(ButtonStyle.Primary)
            .setEmoji("🎲")
            .setLabel("Start rolling")
        )

using .setButtonAccessory((button) returns validation error for a default emoji. I have to use the buttonbuilder instead

halcyon bison
halcyon bison

or of course just pass a APIMessageComponentEmoji object

safe karma

thanks

mental idol

Can someone answer my question [#1448496950067462287]? I can't post it here because my question won't be clear if I send it here.

gleaming badger
halcyon bison
gleaming badger

it's true, <InteractionResponse>.editReply() doesn't exist
I imagine you were looking for modalInteraction.editReply() (or response.edit() I suppose)

gleaming badger

I thought you edit interactions through interaction.editReply()

halcyon bison

you do, but you called response.editReply(), not modalInteraction.editReply()
response.edit() just calls modalInteraction.editReply() internally

gleaming badger
halcyon bison

the InteractionResponse is a helper object that's intended to represent your response to the interaction (the message itself)
it does also have a few unresolvable issues relating to collectors so it'll be removed in the next major version

gleaming badger

I see, thank you so much
btw the .edit() worked :)

gleaming badger

I'm showing a modal, and having a collector set to two minutes to accept any requests. Once the time is up, it sends an embed saying time is up. However, when the user closes the modal, the collector still keeps running. Is there a way for the collector to stop when the user closes the modal, and have it throw a different exception than "Collector received no interactions before ending with reason: time"

gleaming badger

I see, thanks

vivid oasis

when a bot sends a message, can I make it ping specific mentioned users and make it not ping the others? for example

to <@userA> <-- ping this person

<@userB>, <@userC> has entered the chat. <-- do not ping these people
sharp ginkgoBOT
vivid oasis

thank you!

hybrid fable
loud quartz

Since that's what being set when you do the @silent as a human

hybrid fable

Thanks

north dagger

Hey is it possible to block forqarded messages?

sharp ginkgoBOT
dense jackal

oh no wait isnt there a message flag for it

i think this also has snapshots of messages when someone replies to a message

sharp ginkgoBOT
dense jackal

yeah better to check the flag

north dagger
near siren

what is InviteGuild on InviteCreate / InviteDelete events and is there a typecheck to check if its a Guild?

snow onyx

Represents a guild received from an invite, includes welcome screen data if available.

If you want the full guild, use .fetch() on it

near siren

Just wondering how do I typeguard it, is there anything like inCachedGuild etc

snow onyx

you... dont have the full guild, thats the point
InviteGuild is NOT a Guild object, it has partial data of a guild that is transmitted via the event.

real oracle

I'm having an issue with my bot when I run npm start. It only outputs this and the bot doesn't come online.

topaz bluff

Can you show your index.js?

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.

topaz bluff

Only guess is your token is invalid (or being read wrong) and your ClientReady never fires

real oracle

Does the .env need to be BOT_TOKEN = XXX OR BOT_TOKEN=XXX?

topaz bluff

Both should work but I personally do BOT_TOKEN="XXX"

real oracle

Does the quotes do anything special?

topaz bluff

Try adding a .catch() to client.login()

real oracle

So client.login().catch()?

topaz bluff
topaz bluff
real oracle

I also want to point out that I'm completely new to JS and kinda learning as I go.

topaz bluff

Learn about try-catch functions or the Promise#catch method then

Working with Promises is crucial for JavaScript

near siren
wary coral
azure forge

I understand that there is limitations when it comes to videoes being displayed in embed messages. But shouldn't work in inline messages? Tho?

steel trail

Only if there aren't embeds already. Discord won't add link embeds in that case

Why not use a media gallery in a components v2 container instead?

Oh wait, that's logging messages? Use forwards instead

azure forge
sharp ginkgoBOT

Snipe commands are widely considered a violation of user privacy. If a message is deleted it should stay that way.

  • Logs for moderation purposes are fine
  • Bringing back a deleted message by just anyone to expose or humiliate a user is not
azure forge

and the bot is only for this server. (Guild specific server)

steel trail

Doesn't matter

We won't help with that

azure forge
steel trail Doesn't matter

Alright, but may I get the source of violation line? Because I have seen a relatively big bot such as "Apollo" using it and I got surprised.

steel trail

Just because another bot does it doesn't make it okay. We won't support this. End of story

topaz bluff

We are also not Discord. So we can choose to not help you simply because we believe the commands are an invasion of people's privacy

Regardless of Discord's thoughts on the matter

steel trail

Let's keep this channel djs related, move off-topic elsewhere

azure forge

👍

cobalt plover

what is CacheType for?

topaz bluff

In what context?

cobalt plover

so for example i specify that interaction is of type ChatInputCommandInteraction. But i can also specify that it's of type ChatInputCommandInteraction<'cached'>. What does that change?

topaz bluff

If the interaction originated in a cached guild or not

tardy sable

This is a help channel. Not the place to look for work

median salmon

it refuses to deny what the client shows on forum channels as "Create Posts", i thought it was just CreatePublicThreads but denying that doesn't seem to work

ohh its send messages

that makes sense somewhat

ruby bane

beat me to it

median salmon

looked at requests when setting it on the client

is there a helper function of sorts to sanitise some string into a channel name

wary coral
median salmon

alr

gleaming badger

is there not a ContainerBuilder.from() method that allows me to build a container from a JSON?

tardy sable
zealous sphinx

is there any error with the api? i am trying but it says invalid token where i tried resetting the token 3 times

const { Client, GatewayIntentBits } = require('discord.js');
require('dotenv').config();

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

client.on('ready', () => {
  console.log(`✅ Bot logged in as ${client.user.tag}`);
});

client.login(process.env.DISCORD_TOKEN);

env =
DISCORD_TOKEN=OTEyOTIyMjk3MjU2NTM0MD........

anybody?

nvm i dont know i did nothing and it worked now

zealous sphinx
fading shard

Maybe your IDE auto safe magics

keen monolith

the bot is responding with response 3 but removing balance when that should only happen in response 1 or 2

cobalt plover
keen monolith
cobalt plover

yeah

keen monolith

Alright thank you!!!

If I ever did more than 4 responses though how would that work?

rose tangle

why do you need if (response ===) anyways

the code in all of them is the exact same

you're not doing something particularly different on each random "roll"

pallid badge
zealous sphinx

Dude anyone can use all the permutations and combinations and get your key

zealous sphinx

already reset done pray

steel trail
pallid badge
keen monolith
cobalt plover

for how long are embed buttons able to register interactions when sent as a standalone message? would bot reboot make them inaccessible?

rose tangle

I just noticed one half adds and the other adds though, so that's correct

you'd only need the if for that

keen monolith

The other 2 responses do say different things

rose tangle
keen monolith

It says you’ve gain or lost

rose tangle

so you don't end up with a ton more checks or repeated code

keen monolith

Oh how would you do that?

rose tangle

what part?

keen monolith

Store the successes and fails then grab them

rose tangle

you have a single array for both successes and fails, and you then have to figure out manually which is which

I suggest storing them separately so you don't need to figure that

you already know depending on the if {} branch you are whether it's a success or a failure

or storing them separately but not as strings, but as objects that contain whether it's a success or a failure (and the message), but that's not as straightforward and might be a bit harder if you're not familiar with objects

keen monolith

So like const success = [successes] ?

rose tangle

if successes were the strings that mean success then yeah

const successes = ['', ''];
const failures = ['', ''];

// succeeded would be randomly rolled
if (succeeded) {
  // give money

  const message = // choose randomly from the successes array, you already know how
  editReply(message);
} else {
  // take money

  const message = // choose randomly from the failures array, you already know how
  editReply(message);
}
keen monolith
tardy sable

is there a method to check if bot can send messages in channel? because now i would have to check if bot has the send message, view channel flags right? (and embedlinks for embeds?)

steady hull

Are bot guild profiles supported in discord.js yet?

steady hull

oh okay thanks

deep violet

hey

does anyone know how can i fix the encryption error in discord.js

Unhandled promise rejection: Error: No compatible encryption modes. Available include: aead_aes256_gcm_rtpsize, aead_xchacha20_poly1305_rtpsize    
    at chooseEncryptionMode (file:node_modules/@discordjs/voice/dist/index.mjs:476:11)
    at file:node_modules/@discordjs/voice/dist/index.mjs:668:21

this happened while i was testing my bot in a vc

please ping me if responding

deep violet
deep violet

thanks! ill try it

steel trail

But best case would simply be: latest

deep violet

thanks it worked

bleak owl

this is the discord.js server. this is not a place for recruiting people

cobalt plover
            await interaction.showModal(reasonModal);

            const modalSubmit = await interaction.awaitModalSubmit({ time: 60_000, filter: i => i.user.id === interaction.user.id }).catch(_ => {});

            if (!modalSubmit) return;

            await modalSubmit.deferUpdate();

            const reason = modalSubmit.fields.getTextInputValue('reasonInput');

so i have this piece of code responsible for working with a modal. interaction here is of ButtonInteraction type. 2 questions:

  • is there any point in applying such filter here?
  • i've noticed that this can be abused by constantly triggering and closing the modal, calling the awaitModalSubmit function every time. Should i protect my code from that and if so, how?
tardy sable
indigo yarrow

not related to djs but what's the format to show / commands like this

rose tangle
cobalt plover ```ts await interaction.showModal(reasonModal); const m...
  • yes, awaitModalSubmit will await any modal submit, so you could open modals from two completely different commands at the same time, and once one submits, if the other didn't have a filter it'll also trigger, also applies to two users with open modals of the same command
  • you can add a max: 1 so it only runs for one submit, or you can append the interaction id to the customId and check that in your filter, so only modals sent for that command resolve that await
rose tangle

I don't think you need embed links for embeds though

though it is worth a try

errant quiver

i swear djs errors used to be so much more helpful?? this is so frustrating

tardy sable

i heard errors will get much better in v15

topaz bluff

Received an undefined when expecting a (I think string) at test.ts@112:31

topaz bluff

But yes. v15 should have better error messages...but it's largely undocumented so different problems

bleak owl
topaz bluff
indigo yarrow
errant quiver

so i have to do this jank instead

topaz bluff

Hmm...I remember there being a specific error for that. It still wasn't a great error but a unique one

Like "received 2 errors, expecting value of ButtonBuilder and received null, expecting value of ThumbnailBuilder and received null"

junior compass

ok, so I want to like an embed where if no user is mentioned, it replaces the user with something else.
Before:
User held hands with same user
After:
User held hands with themselves... sad

tardy sable
junior compass

Ok I see it... I have

**${interaction.user.username}** is holding hands with **${user.username}**

so if I can do like

if(user.username === interaction.user.username){
  msg = "with themselves... sad"
} else {
  msg = interaction.user.username
}

would that work?

tardy sable
tardy sable
loud quartz

In this case it doesn't particularly matter if it's id or not

As it's only relevant for the instant of the command use

But overall, yeah. Usernames can change while ids cannot

junior compass

works, I did the
if(user.username === interaction.user.username){
msg = "with themselves... sad"
} else {
msg = user.username
}

topaz bluff

Why aren't you comparing id instead of username? Not that it really makes a difference since usernames are unique

tardy sable

they arent using the user mention or id in the response so yh doesnt matter

cobalt plover
loud quartz
tardy sable
loud quartz

How would you await 2 submits if your code is stuck waiting for a second one before anyhow proceeding, and with the fact that you cannot chain modals

loud quartz
tardy sable

oh okay didnt know good to know

loud quartz
steel trail
keen monolith

sorry I figured it out 😭

stable sun
keen monolith

await interaction.deferReply(); ?

stable sun

You are supposed to use await interaction.editReply(...) then

keen monolith

oh oops yh

sleek mural

Can bots listen to audio in voice calls?
Like a speech to text or something in stages

wary coral
mental idol

How can I make ComponentsV2 never allow mentions?

sharp ginkgoBOT
flint pier

const container = new ContainerBuilder()
                .setAccentColor(parseInt(getRandomColor().replace("#", ""), 16))
                
                .addMediaGalleryComponents((gallery) =>
                    gallery.addItem((item) => 
                        item.setURL('')
                    )
                )
                
                .addSeparatorComponents((separator) => separator)

                .addTextDisplayComponents((textDisplay) =>
                    textDisplay.setContent(itemList)
                )

                .addSeparatorComponents((separator) => separator)

                .addActionRowComponents((row) =>
                    row.setComponents(
                        new ButtonBuilder()
                            .setCustomId("buy_item")
                            .setLabel("Xác nhận mua")
                            .setStyle(ButtonStyle.Success)
                    )
                );

            await message.channel.send({ components: [container.toJSON()], flags: MessageFlags.IsComponentsV2 });```

Why doesn't addMediaGalleryComponents work in Container Builder?
ruby bane

(though one would imagine your editor would catch that)
might wanna try it:

-                    gallery.addItem((item) => 
+                    gallery.addItems((item) => 
flint pier

And image url?

Oh thank you

ruby bane

assuming your image provider renders properly when just sending the link, the url should be fine

gleaming badger

how do I make it so that I can get the actual message content itself instead of the modal interaction?

im trying to edit a specific field of the messageComponent

ruby bane

response.message?

gleaming badger
halcyon bison
gleaming badger
ruby bane

but InteractionCallbackResponse.resource.message does

gleaming badger

ah I see, my bad

ruby bane

just know resource and message are nullable

-# though in your case it should be fine

gleaming badger

thanks 🙏

halcyon bison
gleaming badger
stable sun

I believe Message.edit fails w/o proper permissions

Def can’t edit w/o View Channel

ruby bane
polar karma

-# can't edit another user's message, that doesn't come into play here

ruby bane

misread docs (and a logic error 😭)

-# (it's talking about flag editing requiring MANAGE_MESSAGES)

tropic locust

With Components v2. When creating a StringSelectMenuBuilder is there a limit on the number of options you can add. Or is it just limited by the global limit of 40 components?

loud quartz

options are not components

but as with all selects, the limit is 25 options per select

tropic locust
gleaming badger

how do I use followUp() on InteractionCallbackResource?

I dont see that method on the docs page

topaz bluff

You don't. Because a callback resource is used to see the message data of an interaction response... You would need to use the interaction itself that created the resources

gleaming badger

how do I get the interaction itself that created the resources? This is what I have currently

topaz bluff

modalInteraction

sharp ginkgoBOT
gleaming badger

🤦‍♂️ I feel so dumb, I've really been having a hard time with InteractionCallbackResource vs InteractionResponsevs Interaction

thank you

topaz bluff

You pretty much only ever need an an interaction response if you need to read the data on the message itself. But sending, editing, and deleting of messages is done using the Interaction itself

naive hull

Ok,so if i have this code:


      .addTextDisplayComponents(
        new TextDisplayBuilder().setContent("text")
      )

      .addSeparatorComponents(new SeparatorBuilder().setSpacing(SeparatorSpacingSize.Small).setDivider(true))```
How do i make that there is showed the server picture at size 1024?
topaz bluff

There's 2 ways to show an image in a container.

  1. Use a SectionComponent and add an accessory ThumbnailComponent
  2. Use a MediaGalleryComponent

Neither of which however have any sizing control. Thumbnails are more designed for square images and MediaGalleries are better suited for large images or multiple images

naive hull

Ye,i want square,but i tryed already to use SecionComponent ,and failed

sharp ginkgoBOT

guide Section
Sections represent text (one to three Text Display components) with an accessory. The accessory can either be an image (thumbnail) or button. If you do not want to send an accessory, use a Text Display component instead. You can use the SectionBuilder class to easily create a Section component:...

topaz bluff

You most likely didn't add a TextDisplay...as a Section is required to have 1-3 TextDisplay components

naive hull

So i need to use this:
.setThumbnailAccessory(
(thumbnail) => thumbnail.setDescription('alt text displaying on the image').setURL('attachment://image.png'), // Supports arbitrary URLs such as 'https://i.imgur.com/AfFp7pu.pna' as well.
);
?
As i found in the example

topaz bluff
  1. What error did you get if it "failed"
  2. Can you show the whole container? Or the whole Section at the least?
half night

Hi! There is no api for quests, right?

topaz bluff

Correct

Bots do not have access to the quest related endpoints

pure steeple

Does anyone know how to create this type of "embed" with a dropdown wider than a regular embed?

sharp ginkgoBOT

guide suggestion for @pure steeple:
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.

subtle girder

I'm using discord-player to search and play the song in queue,
but the music is choppy.

should I use @discordjs/opus, opus or opusscript to play sound?
or what should I do?

wary coral
vocal garnet

Is there an event that triggers when the user.primaryGuild of a server member changes?

polar karma

userUpdate

subtle girder
ruby bane

its not specifically the discord-player part thats against the tos, its music bots as a whole

tiny condor

what if u pay for ur music license 🤔

ruby bane

then youre okay

last ore

Should I just use discord.js? Or should I use the discord.js@builders thing?

wary coral
last ore
wary coral
last ore
last ore
topaz bluff

Your workspace is called selfbot-v1

Are you making a self bot?

topaz bluff

That doesn't answer my question

wary coral
last ore CompV2 bot

discord.js full supports cv2. builders is just package to make Discord API compatible objects in a programmer friendly way

more to what we are asking is what does you bot do

topaz bluff

If you're making a gateway connected bot, you probably want to use discord.js but if you're building an oauth app or http-only bot, then you probably don't need the whole discord.js package

last ore
sharp ginkgoBOT

guide suggestion for @last ore:
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.

last ore

SA_catThumbsUp

topaz bluff

Yes

wary coral
last ore
wary coral

sure , but that is why we care

last ore
wary coral
fading hull

hi all, is it ethical to make a bot where it detects something from an api and it dms all of our admins / managers / whoever has admin perms (there’s around 15 total) considering there’s new ratelimits ?

proud arrow

It depends on what you mean by "something" but it is more of a question for ddevs than here

fading hull
proud arrow

If it's an external api, and the recipient expects that information, it should be fine as long as you respect the ratelimits

fading hull
proud arrow

Ratelimits are dynamic and adjust based on usage, ig if you do not message frequently it should be fine. DMs are more regulated than other routes to prevent spam

fading hull

interesting ok, i’ll give it a shot, thanks.

polar karma

It'd be recommended to ping a shared role or something, so it's only one message

last ore

How could I detect if a users ID is another server’s channel where their ID and username would be held and then block them.

topaz bluff

What?

polar karma

That's just an if statement comparing two strings. How you get those values depends on a lot of things that you haven't provided much context for

last ore

Does this help?

polar karma

You'd be better off using a database as a scalable solution, as you're either holding a lot of stuff in memory and/or making a lot of API requests to get those messages

sharp ginkgoBOT

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


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

polar karma

If you do need to fetch a message, and then after that, it's just an if statement to compare strings

velvet cipher
last ore
last ore
bleak owl

why do you need to know that information?

polar karma
last ore
velvet cipher
polar karma

Compare that to the message content

fading hull
topaz bluff

Ya. Sending out DMs in bursts risks your bot being permanently blocked from DMing at all

Plus, it just has much stricter rate limits

fading hull

yeah, i’ve noticed recently. before the new ratelimits we’re a thing, dming our team was actually possible. but unfortunately discord implemented a new ratelimit feature. also wondering , what can you have in modals now, heard they got updated?

topaz bluff

Rate limiting has always been a thing. They might have adjusted it for you due to suspicious behavior

They are all dynamic and take many factors into account. They don't publish any information on how exactly it's done

(like why they don't tell you how an anticheat works)

steel trail
fading hull
steel trail

File Upload, right, forgot that one

fading hull
fading hull
steel trail

And Text Input. That's all. For now

All kinds of select menus

fading hull

I see okay thanks

loud quartz

@verbal plinth secondly, if you're not doign it manually, why write the POST /path -> 404 instead of just the method call and the error you get back from it

real oracle

@topaz bluff, I discovered my error. When I was creating the file(s), I never saved them when I finished. Now that the file(s) are saved the bot turns on.

Also, is there a difference the Bot > Bot Permissions or OAuth2 > OAuth2 URL Generator? Can I put the permissions integer in the code and have it automatically read the permissions it needs?

loud quartz

url generator merely gives you an URL with permissions already filled in

and no, a random integer does not have capacity to scan your entire code and figure out how discord works and what your code would need permission wise

verbal plinth
loud quartz

you could have also just said that it comes from you doing .send(). otherwise i just thought you're using postman or raw fetch()

do you know which call could have caused it? or are you just seeing it in logs

unique ingot
real oracle
unique ingot

After sending the message, we get an error from DiscordAPI "Unknown Message", the stacktrace points back to the channel.send()

Maybe it helps mentioning that we also provide nonceStrings in the call to prevent unnecessary messages

loud quartz

to be fair this does not sound like something that has any relation to discord.js itself

unique ingot

it was just the first idea 😅

lone eagle

setting makeCache as

   ThreadManager: 0,
   ThreadMemberManager: 0,
   GuildTextThreadManager: 0,
   GuildForumThreadManager: 0,

doesnt distrubt bots ability to reply message commands right? (yes i still support them)

and what are default cache settings, where can i find them

this cant be it?

so by default there is no limit to caches except message caches?

rose tangle

correct

rose tangle

maybe if they're in threads but I'm not so sure

worth testing

lone eagle

yeah ig gotta test this out

tiny blade

what hosting paltform is best for big bots and all in one bots

polar karma

That's not a topic for this channel, but we do have a list of recommended hosts in #resources

lone eagle

can i edit a message like this , to avoid cache/fetch

await client.rest.patch(
        Routes.channelMessage(jtc.panelChannel, jtc.panelMessage),
        { body: result.panelJSON }
);

does rest manager also handles ratelimits?

cause im thinking to reduce my messageManager cache or disable it. its either pulling all panel channel ids and set them in keepoverlimit in makecache or this

rose tangle

you only need the channel cached to do that though

sharp ginkgoBOT
lone eagle

why do i need channel cached tho, cant the endpoint take channel id and message id and discord does it internal magic

lone eagle
rose tangle

correct

rose tangle

you only need the channel

lone eagle

yeah, cause i cant mess with channel cache. but there tiny chance for channel to not be cached, so i can save a request by this

thanks a lot for your help

rose tangle

what would the tiny chance be?

lone eagle

is there no edge case where a guild/channel is not cached?

rose tangle

if you have the Guilds intent then they're always cached

or well, channels where you're in obv

if you receive a command from a guild you're not in you don't get much data from discord

which includes the channel

lone eagle

hmmm, ig i could use this too

setting messageManager cache as 0 wont break the bot right? i dont call messages.cache.get anywhere now

rose tangle

afaik the only dangerous ones are the ones mentioned in the guide

lone eagle

oh, then im safe. ig i could reduce my ram a lot now.

thanks again

rose tangle

if you're comfortable with raw api calls and don't want cache then you can just use /core

it's pretty much just the ws and rest manager wrapped in a nicer api but with no cache

lone eagle
rose tangle

yeah that'd require you to rewrite everything, fair enough then

echo wraith
Uncaught Exception: Error: Expected token to be set for this request, but none was present
    at _REST.resolveRequest (D:\Dodi games\Games\node_modules\@discordjs\rest\dist\index.js:1346:15)
    at _REST.queueRequest (D:\Dodi games\Games\node_modules\@discordjs\rest\dist\index.js:1306:46)
    at _REST.request (D:\Dodi games\Games\node_modules\@discordjs\rest\dist\index.js:1272:33)
    at _REST.post (D:\Dodi games\Games\node_modules\@discordjs\rest\dist\index.js:1246:17)
    at TextChannel.send (D:\Dodi games\Games\node_modules\discord.js\src\structures\interfaces\TextBasedChannel.js:182:38)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)```
topaz bluff

What's your DJS version?

Because this looks like an old bug that's been fixed already

echo wraith
topaz bluff What's your DJS version?

v14 and am jest tryn to set new banner heres the code:

if (interaction.customId === "banner") {
            try {
              await interaction.reply("الرجاء ارسال بنر صوره او رابط..");
              const filter = (m) => m.author.id === interaction.user.id && (m.attachments.size > 0 || /^https?:\/\/\S+\.\S+/.test(m.content));
              const response = await interaction.channel.awaitMessages({ filter, max: 1, time: 60000 });

              if (response.size === 0) {
                return interaction.editReply("لا يوجد اي تعديلات.");
              }

              const bannerURL = response.first().attachments.size > 0 ? response.first().attachments.first().url : response.first().content;
              await client.user.setBanner(bannerURL);
              await interaction.editReply("تم تغير بنر البوت بنجاح ✅");
            } catch (e) {
              await interaction.editReply(`ERROR: ${e.message}`);
            }

            collector.stop();
          }```
bleak owl

which specific version?

14 has many versions

echo wraith
bleak owl

that’s quite outdated, try updating

solar furnace

can you check if a user is dm-able without dming them?

solar furnace

ty

naive hull

If i do:

.setThumbnailAccessory(
        (thumbnail) => thumbnail.setDescription('alt text displaying on the image').setURL('SP'),
); ```
Is it correct?
topaz bluff

.setURL('SP'),
You're setting the url to the string 'SP', not the variable

naive hull

So,i needa do
.setURL(SP)?

topaz bluff

Did it fix it?

formal carbon

why i am getting the membercount field undefined ? or null ?
it's casuing me the issue in welcome message

    /**
     * Get the member count for a guild
     * @param guild {Guild} - The guild to get the member count for
     * @returns {Promise<number>}
     * @description Get the member count for a guild
     * @example
     * await this.client.util.safeMemberCount(guild);
     */
    public async safeMemberCount(guild: Guild): Promise<number> {
        try {
            // Use cached count if valid
            if (guild.memberCount && guild.memberCount > 0) {
                return guild.memberCount;
            }
    
            // REST fallback
            const fresh = await guild.fetch().catch(() => null);
            return fresh?.memberCount ?? 0;
    
        } catch {
            return 0;
        }
    }```
stable sun

Shouldn’t have that try catch block tbh, you alr have Promise.catch

Blindly ignoring errors is bad in of itself

stable sun
steel trail

If they typings you use for the parameter array correct this should never be undefined nor null. Showing the code where you use that would help

formal carbon
steel trail If they typings you use for the parameter array correct this should never be und...
    /**
     * Parse a string
     * @param content {string} - The content to parse
     * @param member {GuildMember} - The member to parse the content for
     * @returns {Promise<string>}
     * @description Parse a string
     * @example
     * await this.client.util.parse(content, member);
     */

    public async parse(content: string, member: GuildMember): Promise<string> {
        const guild = member.guild;
        const mention = `<@${member.user.id}>`;
    
        const memberCount = await this.safeMemberCount(guild);
    
        const joinedTimestamp = member.joinedTimestamp ?? Date.now();
    
        return content
            .replaceAll(/\\n/g, "\n")
            .replaceAll(/{server:name}/g, guild.name)
            .replaceAll(/{server:member:count}/g, String(memberCount))
            .replaceAll(/{member:name}/g, member.displayName)
            .replaceAll(/{member:mention}/g, mention)
            .replaceAll(/{member:id}/g, member.user.id)
            .replaceAll(/{member:created_at}/g, `<t:${Math.floor(member.user.createdTimestamp / 1000)}:R>`)
            .replaceAll(/{member:joined_at}/g, `<t:${Math.floor(joinedTimestamp / 1000)}:R>`)
            .replaceAll(/{member:tag}/g, member.user.tag);
    }
stable sun

Can you log the error if guild.fetch() throws?

steel trail

You really shouldn't have to fetch it in the first place. What made you make that function in the first place?

formal carbon
steel trail
formal carbon
steel trail

This is gonna take forever if we keep going like this. This doesn't show any sign of what member is defined as... what djs event does this come from and what properties of what parameter are those? Or is this a result of calling a function/getting from some cache and not from event parameters?

That still doesn't answer my question

brisk crest
steel trail

Alternatively you could console.log(member) and we'll be closer

formal carbon
steel trail

also there is only core. There is no http package

brisk crest

Ah, I mean rest of course

rigid crest

i need help understanding something, in march i checked my bots total users using the client.guilds (8.980k servers) and it was 300k+ i checked couple days ago 23k, with 8.293k servers, how did i go from 339.4k users across total guilds, to 23k users in near the same amount of guild spread just missing a few hundred servers from possible dropped servers, unless my counter is broken now?

https://pastebin.com/Q5Dj5PBi

formal carbon
velvet cipher
rigid crest

thats like 2 users to a server which makes 0 sense

unless theres been a overhaul with how users get broadcasted? i honestly dunno why the numbers lower than server count, i would understand if it said 400 servers and 23k then that would feel average mix

steel trail
steel trail
rigid crest
formal carbon
steel trail Why are you calling toString() on something? That's not the log I asked for

i am calling it on guild.membercount

public async parse(content: string, member: GuildMember): Promise<string> {
        const guild = member.guild;
        const mention = `<@${member.user.id}>`;
    
        const memberCount = await this.safeMemberCount(guild);
    
        const joinedTimestamp = member.joinedTimestamp ?? Date.now();
    
        return content
            .replaceAll(/\\n/g, "\n")
            .replaceAll(/{server:name}/g, guild.name)
            .replaceAll(/{server:member:count}/g, memberCount.toString())
            .replaceAll(/{member:name}/g, member.displayName)
            .replaceAll(/{member:mention}/g, mention)
            .replaceAll(/{member:id}/g, member.user.id)
            .replaceAll(/{member:created_at}/g, `<t:${Math.floor(member.user.createdTimestamp / 1000)}:R>`)
            .replaceAll(/{member:joined_at}/g, `<t:${Math.floor(joinedTimestamp / 1000)}:R>`)
            .replaceAll(/{member:tag}/g, member.user.tag);
    }```
formal carbon
formal carbon
Error in parse for member 1426071500892405781 in guild 927811764895227945: Cannot read properties of undefined (reading 'toString') 
Stack: TypeError: Cannot read properties of undefined (reading 'toString')
    at Util.parse (file:///root/Xieron/dist/Structures/util.js:350:73)
    at Util.buildGreeting (file:///root/Xieron/dist/Structures/util.js:123:61)
    at Job.task (file:///root/Xieron/dist/Queue/GuildMemberAdd/GuildMemberAdd.js:231:64)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
steel trail
steel trail

You're not calling it on guild.memberCount, you're calling it on the result of your function

rigid crest
steel trail

You should simply check for unavailable in that reduce call

acc + (guild.available ? guild.memberCount : 0) or guild.memberCount ?? 0

formal carbon
steel trail
formal carbon
woeful kraken

is actually possibile customize the same bot, but in different server, discord bot has differnt description and logo ?

steel trail
formal carbon