#djs-help-v14

78874 messages · Page 36 of 79

crimson gale

that's such a dick move

primary guild will be part of User int he next release

cerulean jay

Haii, to add more presences, do i just include them after each , like in ``` client.user.setPresence({
status: 'online',
activities: [{ name: Serving ${client.guilds.cache.size} servers, type: 0 }],
more...more

Before closing completely with `});`, or how should I go about setting more than one which would change?
red coral

You can’t have more than one?

cerulean jay
red coral

Sure you can do that… that’s not a problem. But afaik you can’t have multiple statuses.

crimson gale

there is a reason why it's setPresence (singular) and activities (plural)

abstract flint
import {SlashCommandBuilder} from 'discord.js';

export default {
    data: new SlashCommandBuilder()
        .setName('get-txt')
        .setDescription('s'),
    async execute(interaction) {
       
    }
}

export const data = new SlashCommandBuilder()
    .setName('get-txt')
    .setDescription('s');


export async function execute(interaction) {
    interaction.reply({content: 'Hello'})
}```

Hello guys, according to ES6 Modules, which syntax is better? I mean, which is the best optimized and the one suggested for discord.js?
wooden carbon

does Discord validate if the role is actually from the guild, or do we have to validate it ourselves? (in slash command)

red coral
abstract flint
wooden carbon
red coral
red coral
wooden carbon

Also, what about the role mention? Is it also validated if provided as a mention inside a string option?

red coral

If you have a string option and @ a role then discord obviously won’t pass that no. You’ll have to pass it yourself

wooden carbon

thats not what i mean....

red coral

Then what did you mean, you said mention inside a string option

wooden carbon

won't i get that string in my app?

red coral

Yes, ofc you will. But to get the actual role instance you’ll have to get the id from the @ then do all of the passing yourself

wooden carbon

How do i get interaction user's id?

worthy drift

interaction.user.id

wooden carbon

does fetch look into the cache before actually fetching it from discord?

I am doing this right now btw,
channel = client.channels.cache.get(unResolvedchannel.id) ?? client.channels.fetch(unResolvedchannel.id);

polar karma

Fetching one does, for the most part. Fetching many will always be an API request

wooden carbon
polar karma

Fetching one checks cache

wooden carbon

k

daring coral

But ultimately it's just syntactic sugar, when you import you get it as an object anyway

bitter pivot

Hi, if I use

const linkedRole = interaction.guild.roles.cache.find(role => role.name === "Linked");

A) The bot's only in 2 servers, does it fetch roles automatically on startup / build the cache
B) What happens if the role isn't already looked up/cached? Will it fetch and do I need to await this?

loud quartz

Do you have the guilds intent?

If yes, they're already cached

bitter pivot
loud quartz

.cache.find() doesn't fetch anything

bitter pivot
loud quartz

Same way trying to access 5th element of an array will not make a request to internet to ask what should be there

bitter pivot

Ohhh of course, I see. Thanks!

bitter pivot

Because surely that's better to do if the server can handle it, I'm not bothered about a bit of a slower startup

Infact, cache.get might not work for me, as I need to check how many members were in a role at the time of running the command, not at startup/cache time

polar karma

Roles are cached on ready, when the guild payload is sent. Members would need to be fetched in bulk once per guild, and then the cache would be continuously updated as new data is received from the API

tidal ravine

I need to implement sharding for my bot and I have a shared MongoDB database for guilds and I saw shard id is calculated with server id >> 22 % shards so how should I go about this should I store the shardid as an attribute of each server

outer plume

djs does sharding automatically for you. Use the key in client options

tidal ravine

Mainly just figuring how to prevent extra requests to the database and wasting bandwidth for guilds that aren’t even in the shard

sharp ginkgoBOT

class ShardingManager discord.js@14.21.0
This is a utility class that makes multi-process sharding of a bot an easy and painless experience. It works by spawning a self-contained ChildProcess or Worker for each individual shard, each containing its own instance of your bot's Client. They all have a line of communication with the master process, and there are several useful methods that utilize it in order to simplify tasks that are normally difficult with sharding. It can spawn a specific number of shards or the amount that Discord suggests for the bot, and takes a path to your main bot script to launch for each one.

steel yacht

Hi,
When adding multiple select menus to a message, how to show a label next to each of them ?
The placeholder doesn't fit this need because it disappears when an item is selected.
Thanks

dense jackal

with the use of components v2 you can set labels above the select menus with a text display component

steel yacht

Oh right, above, because a select menu must be alone. So above is possible ? Not just above the first select menu, but above each select menu ?

rose tangle

sure

add the text display, add the select menu, add the second text display, add the second select menu

bitter pivot
wooden carbon

but you do need to know role id.

worthy drift

Actually no. You can do as he did. Using id is just more precisely because it’s unique

rose tangle

the role is cached because they have the Guilds intent

their questions were only whether it'll fetch separately and if a manual fetch is needed, both were already answered

wooden carbon

lets not complicate, ask amgelo he will surely solve this

bitter pivot

My only concern was the role counts realistically. I did consider doing { force: true }, but didn't want to hardcode IDs.

Further down in the code, I'm assigning a user a colour - either Red, Yellow, Blue, Green, and I wanted to get the role with the least amount of users in it.

Because it's not majorly important to be cardinally correct, I'm just relying on the cache at startup to tell me the approximate amount of members in the role and doing this:

async function getAssignmentCounts(interaction, client) {
    // For each of the teams in the setup array
    const teams = client.config.teams;
    const assignmentCounts = {};

    for (const team of teams) {
        // Get the role, and the member count
        const role = interaction.guild.roles.cache.find(r => r.name === team);
        if (role) assignmentCounts[team] = role.members.size;
        else assignmentCounts[team] = false;
    }

    return assignmentCounts;
};```
rose tangle

you have the GuildMembers intent so you'll first need to fetch all members

then role counts will always be kept up to date

bitter pivot
rose tangle

the order doesn't matter, and yeah I noticed you have it, that's why I'm saying you only need to fetch all members

bitter pivot

Oh so I still need to manually fetch all members?

rose tangle

if you didn't have it then you'd need to fetch per role

yeah, discord doesn't send all members on start, regardless of intents

bitter pivot

If the bot's only in 2 servers can I just recursively fetch all members

Or wiser to hardcode the ID of the server I need to know about maybe?

rose tangle

well that's just your choice, how you want it to work

only in some guilds or in all of them

bitter pivot

The only purpose of it being in the 2nd guild is to check their roles for eligibility

So realistically it's probably wise to fetch every member so that I have both the role count info and the user role info from the other server

bitter pivot

That's just in my ready event for ease

rose tangle

you can just iterate over the guilds cache

otherwise yeah

if you want all members from all your guilds

in order to have the role counts

bitter pivot
rose tangle

the ready event is emitted after everything is ready

bitter pivot

I went for this but it logs undefined D:

I'm fairly sure the first await is useless but it's not in a promise so I wanted to be sure it was finished

rose tangle
  • forEach doesn't await for their callback promise to finish
  • you're wrapping in { } so if you want to return something you need to explicitly have a return statement

and forEach doesn't return anything, hence the undefined

you most likely meant map

bitter pivot

Oh shoot, of course. I forgot about returning in nested functions, whoops.
So if I leave the forEach in the background it'll be fine?

The console log's only there for the next 10s to make sure the code worked

rose tangle

you most likely want to map and await the promises with Promise.all

or use a for of loop instead which does wait for the inner block to finish

bitter pivot

Looks like it's working now! Thanks.
I used

const guilds = await Promise.all(client.guilds.cache.map(async (g) => {
            await g.members.fetch();
            return g;
        }));```

And just logged it out temporarily underneath
rose tangle

just to be clear for the future in case you want to implement it in some other bot, you only need to fetch once because you have the GuildMembers intent: the bot will receive member update events to update the roles cache

if you didn't have it then you would've needed to fetch every time you wanted the role count

wooden carbon
bitter pivot
split thunder

How can I check if a member was moved by someone or they moved on their own? (voice)

rose tangle
steel yacht
wooden carbon

why all so obsessed with cache ?

wooden carbon
loud quartz

it is

the answer was ambiguous

guild.members.fetch(id) will check cache
guild.members.fetch() will not check
member.fetch() also doesn't check because that's against the entire idea

rose tangle

and if they're up to date anyways

topaz bluff
wooden carbon
loud quartz

because some might need it

i need it, for example

rose tangle

you can also re-use memory instead of needing another instance per member

steel yacht
wooden carbon
loud quartz
wooden carbon
loud quartz

role changes

thanks for waiting

rose tangle

Jack's issue in the first place requires that, I'm not sure why that isn't an example

topaz bluff
rose tangle

discord doesn't send amount of members per role, you need to know all members

rose tangle

and in order to keep track of old state you need a cache

topaz bluff
sharp ginkgoBOT

guide Popular Topics: Display Components - Container
read more

topaz bluff
steel yacht

Is ContainerBuilder backwards-compatible with EmbedBuilder ?

loud quartz

no

they are completely different things

you cannot compare them, besides look and the settable color

steel yacht

😭

topaz bluff
rose tangle

like Samtino also mentioned, "almost everything can be recreated"

steel yacht

Yeah, but that's so much migration work

rose tangle

namely it doesn't have author, footer or fields replacements

wooden carbon
rose tangle

just do it when you need it, no need to change all at once

loud quartz
wooden carbon

role updates?

topaz bluff
wooden carbon role updates?

It won't contain oldMember if they aren't cached. The event does not contain the whole user object because users are not cached by default

loud quartz

uh

it does contain the entire object

what it doesn't contain is the old data

or the changes explicitly

it just sends the state after update

loud quartz

that's so not how that works

rose tangle

you'd also need an extra intent for that

loud quartz

and permission

rose tangle

in general update events don't have the old state

you need a cache for that

discord only sends the new state

loud quartz

you can stop now. some people need cache, and if you don't understand why they would ever need that, there's no need to push for weird solutions that don't solve anything at all

wooden carbon

yea you do need cache for that....

steel yacht

How to check whether an interaction has been switched to components V2 ?

sharp ginkgoBOT
loud quartz

it's not interaction either

interaction is just a way to create a message

topaz bluff

That's not what I asked for @sharp ginkgo

loud quartz

it's the message that contains components

loud quartz
steel yacht

How to check from a CommandInteraction object ?
Like there's replied, is there something like replyIsV2 or something

loud quartz

again

topaz bluff
loud quartz

interaction has nothing do to with flags on message

steel yacht

Well, it affects what you can do with editReply

loud quartz

which means you need to check the message

loud quartz

but to message it edits

steel yacht

Okay, so how to get the message from the interaction ?

loud quartz

i am not explicitly saying: check message flags

from interaction?

or interaction response?

steel yacht

Interaction

loud quartz

you can't edit that well, depends, sometimes you can (button), sometimes you can't (contexts)

so not what you want

rose tangle

how do you have the interaction but not know whether you replied with cv2 tho

topaz bluff

If you set withResponse: true in your reply, then you can check the InteractionCallbackResponse to see if the message contains the IsComponentsV2 flag

But you should really be in more control of your interaction flows so that you never have to check this state, it should be assumed

steel yacht

In order to improve my development experience, I created functional functions that work regardless of state, such as this one :

respond = async (
    interaction: CommandInteraction<'cached'> | MessageComponentInteraction<'cached'> | ModalSubmitInteraction<'cached'>,
    payload: InteractionEditReplyOptions | InteractionReplyOptions = {},
    isResetPayload: boolean = true
): Promise<Message> => {
    if(isResetPayload)
        payload = {
            ...payload,
            content: payload.content || (payload.embeds || payload.files || payload.components ? '' : '** **'),
            embeds: payload.embeds || [],
            files: payload.files || [],
            components: payload.components || []
        };
    if(interaction.deferred || interaction.replied)
        return interaction.editReply(payload as InteractionEditReplyOptions);
    else if(interaction instanceof MessageComponentInteraction)
        return (await interaction.update(payload as InteractionUpdateOptions)).fetch();
    payload.flags = [MessageFlags.Ephemeral];
    return (await interaction.reply(payload as InteractionReplyOptions)).fetch();
},

But this non-reversible backwards-incompatible V2 thing, is killing me

rose tangle

yeah major bumps aren't meant to be reversible or backwards compatible

the point of them is that they're breaking

steel yacht

Yeah, but at the very least, downgrading should be possible.

rose tangle

discord says otherwise, and I think they have a good point but that's unrelated either way

steel yacht

Does that mean embeds will also become deprecated ?

rose tangle

honestly I'm not sure what's the use case where such a method is needed, but as we said you'll need the original message (which you can fetch or get depending on your interaction type), then check if it has the flag, you could also just pass it

rose tangle

and no, discord hasn't shared any plans to do that

steel yacht

Yeah, I was asking about the future.
Because if Discord is really treating this as versioning (I thought "Components V2" was just a brand name), then there's potential for "V1" to eventually get deprecated, as that's what happens to versioned stuff.

rose tangle

it's unmaintained but not deprecated

deprecation usually happens if it's harder to keep it working, but a lot of their infra still uses embeds, like url embeds

dense jackal

Discord did not name it “components v2” afaik, it was either an intern project name or the community named it like so

the official announcement was titled “new components for messages” as well

and ofc the message flag, but ig that wasn’t a smart move to call it IS_COMPONENTSV2

but they had to distinguish those somehow

rose tangle

it's the project name, but the flag sticked around for some reason

steel yacht

Well, if "V2" isn't a thing, then the "major bump" argument no longer holds, actually

rose tangle

it's meant to be a major bump, but it's not named after it

doesn't need to be named after its versioning in order to be breaking

steel yacht

I guess breaking anytime is the Discord standard operating procedure indeed

rose tangle

some libraries even can't implement it yet because it's breaking to them since they coded everything around the fact that action rows were the only top level component

which discord actually debunked a long time ago (mentioning that more components could eventually arrive)

rose tangle

if you don't want to, don't use it, simple

steel yacht

I don't have a choice, they didn't provide a feature that solves my issue without it

rose tangle

which issue?

steel yacht

Labeling each select menu.

rose tangle

if it's a short description you could use the placeholder

otherwise yeah you do need to switch

the cost of better features is that you have to code around them

steel yacht
rose tangle

you're out of luck then, switch to cv2 and their features/limitations

rose tangle

the docs never mention "components v2"

only for the flag name

icy surge
obtuse laurel
steel yacht

So, from a Message object, how do I check whether it was switched to V2 ?

steel yacht

Also, if I call deleteReply from an interaction, can I then use reply again ?

clear garnet
steel yacht
clear garnet

If you're performing the flag check on a reply you sent, shouldn't you already know whether it has the flag or not without needing to fetch it again?

steel yacht
clear garnet

Okay, well in that case, then yes, that would be what you'd use

steel yacht

Okay thanks

modest iron

can we embed to html

like this

steel yacht
export type BitFieldResolvable<Flags extends string, Type extends number | bigint> =
  | RecursiveReadonlyArray<Flags | Type | `${bigint}` | Readonly<BitField<Flags, Type>>>
  | Flags
  | Type
  | `${bigint}`
  | Readonly<BitField<Flags, Type>>;

How to reliably check whether the V2 flag is present with this diversity of types ?

sharp ginkgoBOT
red coral

message.flags.has, if that’s what you mean

hazy agate

Whats the best way to add a shard number field to a json logger like pino?

maybe tie it to the client

cuz its not like a global value im guessing

red coral

Can use like message.guild.shard, since the shard is attached to the guild. So whatever has the guild property will have a shard

sharp ginkgoBOT
hazy agate

okay but i dont really want to pass the shard id at every logger call, id rather want to initialize the logger at program start with the shard id

maybe by passing the shard id as an env or argv

red coral

Not possible unless you can do like shardLogger.get(message.guild.shardId). Since each guild will have a shard

hazy agate

what would work is put the logger on the client

client.logger = logger(client.shard.ids[0]) or something

red coral

You can pass it in like an “extra” section or something

But imo having like a map of 5 loggers for 5 shards then getting one is a bit pointless

hazy agate
red coral

Because you can have multiple shards?

hazy agate

okay i guess depends on the sharding method

red coral

I very much doubt it would be different really

hazy agate

im pretty sure for me the array only has one id on each client in each shard
but theres also a strategy where you shard on one worker where it would probably show multiple ids

red coral

I mean I’m no expert on sharding, but you should have one client which will spawn multiple gateway instances. So regardless client.shard.ids should be all shard ids

hazy agate

no im using the ShardingManager, which will start up a file on multiple threads , so theres one client for each shard

causes me headaches sometimes cuz i have to use shard.broadcastEval to access some values

red coral

Yes, but to my knowledge the main client will still have the shard ids for each shard. I’m interested in this too since one day I’ll have to shard so I’ll be happy if someone more knowledgeable would say what is and isn’t

hazy agate

hyg

red coral

hyg?

hazy agate

here ya go
its only one id
slow mode mad annoying

this is literally a help channel why would they restrict messages

red coral

Oh, right. But I suppose that means ids is 8 since it’s 8 shards? I would’ve thought it would be different but… yh. Will be nice to see why it’s an array then and how it all works

hazy agate

no it means its the 8th shard

red coral

Ahhh, ok right. Ig that’s right then, interesting

hazy agate

like we said before, you can also shard on one client with multiple gateways, where it would probably show mutliple shard ids

red coral

I suppose it would? That’s cool either way

hazy agate

yea

actually having a bigger problem than the shard ids right now

red coral

Maybe you could use some class with a map of loggers then use like getLogger(<shardId>)

hazy agate

i think id rather just use client.logger, i have the client accessible in most contexts
but i was just wondering if it could work with just import logger

if i could pass a seperate env or argv to each shard then that could work

red coral

I believe there’s options to do it when you make a sharding manager, to pass argv

hazy agate

yea but not a different one to each

sharp ginkgoBOT
red coral

Ah true

hazy agate

my pino logger is not logging debug logs

import pino from 'pino';
import path from 'path';


export const pinoTransport = {
    targets: [
        {
            target: 'pino-pretty',
            options: {
                colorize: true,
                translateTime: 'SYS:standard',
                ignore: 'pid,hostname',
            },
        },
        {
            target: 'pino/file',
            options: {
                destination: path.resolve(`logs/${new Date().toISOString().split('T')[0]}.log`),
                mkdir: true,
            },
        },
    ],
};

const logger = pino({ level: process.env.LOG_LEVEL || 'info', transport: pinoTransport });
logger.info(`[Pino] Logger initialized at level: ${process.env.LOG_LEVEL || 'info'}`);
logger.debug('[Pino] Debug');

export default logger;

now my other problem is that i dont log debug logs
this is only inside a shard, if i run this file standalone it logs fine

or maybe its to do with docker idk

its not the shards, the first logger initialization is from main.js where i set up all the shards and it still doesnt log debugs

tribal orbit

can anyone help me with adding a raid-protection into my moderation bot?
how should i detect raids? how does other bots does this?

we have 2 server where 300+ users joining since 5 days, newly created accounts

polar karma

Generally, the built-in stuff in discord is pretty robust, including the settings to require verified email, etc. Otherwise, you'd need to tailor it based on what you want to filter, such as by account age

tiny condor

Heya, can I get a user's tag? clan tag thing

polar karma

Not yet, will be in the next release

outer plume
cinder shale
[2025-08-14 23:47:30] TypeError: The "options.env" property must be of type object or one of undefined, null, or worker_threads.SHARE_ENV. Received type symbol (Symbol(nodejs.worker_threads.SHARE_ENV))
    at Worker (unknown)
    at new Worker (node:worker_threads:155:35)
    at spawn (/home/container/node_modules/discord.js/src/sharding/Shard.js:141:27)
    at spawn (/home/container/node_modules/discord.js/src/sharding/Shard.js:123:15)
    at spawn (/home/container/node_modules/discord.js/src/sharding/ShardingManager.js:227:27)
    at processTicksAndRejections (native:7:39)``` what could be causing this error?
outer plume
cinder shale
outer plume

is it smth like

const TOKEN = options.env.TOKEN

?

if yes, seems like .env isn't an object

cinder shale
outer plume
cinder shale

ah sure

trail raven

Was the import or type Interaction removed? It tells me that there isnt such expor for Interaction

stable sun
trail raven

Oh ok

sharp ginkgoBOT
split thunder

Yo, is there a way to know if a user was moved by someone or if they moved themselves (voice channel)?

crimson gale

which is at best a correlation, move audits just have the number of members moved, iirc

waxen walrus

is there some convenient way of editing replies to interactions without keeping interactions in memory somewhere? I'm sending an ephemeral reply that I later want to edit when a button inside the ephemeral reply is pressed, but editing it as a message does not work, and I'm not sure how I'd get access to the interaction object again...

crimson gale

each button press is its own interaction and specifically buttons and select menus have the "update" response type that will update the message the button or menu is on

crimson gale

as per usual you have to respond within 3 seconds or 15 minutes* after defer (there is also a deferred update variant)

waxen walrus

👍

tribal orbit
polar karma

You'd have to ask their support

steel yacht

Hi,
On a non-string select menu with a default value and a submit button, how to distinguish between the user not editing the value and the user removing the value ?
Thanks

rose tangle

if the user doesn't edit it then you won't receive a select menu interaction

steel yacht

Yes, but if the user clicks the X mark to remove the value, I also don't receive a select menu interaction

waxen walrus
    execute: async (client, interaction, subId, page) => {
        if (!interaction?.message || !subId || !page) return interaction.reply({
            embeds: [newEmbed().setDescription(`This button is not ready to be clicked.`)],
            flags: MessageFlags.Ephemeral,
        });

        interaction.showModal(
            new ModalBuilder()
                .setCustomId(`dashboard_add_confirm:${interaction.user.id}:${subId}:${page}`)
                .setTitle(`Add ${page.charAt(0).toUpperCase() + page.slice(1)}`)
                .addComponents(
                    new ActionRowBuilder().addComponents(
                        new TextInputBuilder()
                            .setCustomId(`title`)
                            .setRequired(true)
                            .setMaxLength(100)
                            .setStyle(TextInputStyle.Short),
                    ),
                    new ActionRowBuilder().addComponents(
                        new TextInputBuilder()
                            .setCustomId(`content`)
                            .setRequired(true)
                            .setMaxLength(2000)
                            .setStyle(TextInputStyle.Paragraph),
                    ),
                ),
        );
    },

why might this be producing the error "ValidationError: Expected a string primitive"?

halcyon bison
rose tangle
steel yacht
waxen walrus
rose tangle

it should but it's kinda hard to read

builders v2 uses zod v4 which supports better error formatting

but since builders v2 is breaking it won't be used in djs until v15

waxen walrus

I see

steel yacht

How many rows can a V2 message have ?
Thanks

rose tangle

the only component amount limit is 40 components per message

either top level or nested

steel yacht

Alright, thanks !

soft lance

What version is MessageFlags.IsComponentsV2 added in?

rose tangle

or at the very least 14.19.3 which has a couple of fixes for that release

safe wigeon

When creating a voice channel, will the "topic" option set the "channel status" or does "topic" only work for text channels which is their channel descriptions?

loud quartz

Given how setting status is undocumented, serious doubt topic will set it

Especially as the status also isn't valid at the time of creation but when someone in it sets it, and is a status not a topic

And setting it has a separate endpoint to do it

wooden carbon

Right Click (Desktop) / Long Press (Mobile) > Apps > some command

How do i make those command?

sharp ginkgoBOT

guide Other Interactions: Context Menus
read more

coral river

How would I get the last message sent in a channel by my bot or should I just save it in a variable?'

modest iron

Hello does someone know how can i embed to html to have the same as how discord show embed

halcyon bison
coral river
halcyon bison
halcyon bison
coral river

all I want to do is put like a post it note that is always the last message in the channel

so everytime someone sends a message, old one gets deleted, new one gets sent

halcyon bison

then assuming you don't want it to break when your bot restarts, it sounds like you'll want something more persistent than a variable
that being said, you'll want to keep in mind "stickied message" features always have the potential to be incredibly spammy on the api and encounter rate limits, especially depending on the activity in the channel

coral river

Yeah thats the other thing I was going to ask

how would I avoid hitting rate limits and because of that the system breaking?

halcyon bison

avoid them completely without affecting the feature and regardless of channel activity?
you don't

rose tangle

such a feature is not possible to make reliably though

coral river

I want to do it as reliably as possible

rose tangle

by the time your message arrives, another one could've been sent

coral river

What if

rose tangle

I'd make a debouncer so it only actually works some seconds after the last message received

coral river

I wait a little when a message is sent to see if another one is sent and repeat that process until a message hasnt been sent for a bit

rose tangle

yeah that's a debouncer

coral river

few seconds maybe

uneven crater

Honestly, I would CRON it. Run every 10 minutes and check if bot authored last message.

coral river

nice, the guy who asked me to do it only now just randomly said nvm

soft lance
rose tangle

and from where are you importing MessageFlags?

rose tangle
rose tangle

can you npm ls discord-api-types

soft lance
│ └── discord-api-types@0.37.93 overridden
├─┬ @discordjs/voice@0.18.0
│ └── discord-api-types@0.37.93 deduped
└─┬ discord.js@14.21.0
  ├─┬ @discordjs/builders@1.11.3
  │ └── discord-api-types@0.37.93 deduped
  ├─┬ @discordjs/formatters@0.6.1
  │ └── discord-api-types@0.37.93 deduped
  ├─┬ @discordjs/ws@1.2.3
  │ └── discord-api-types@0.37.93 deduped
  └── discord-api-types@0.37.93 deduped```
coral river

is there a way to better do what the discord.js guide base code does and in a more professional way cause I have just been using that for my base code for a while

soft lance
rose tangle
bold imp

can someone help me my bot wouldnt come online

coral river
coral river
bold imp

in the code no

coral river

in the terminal

bold imp

i tried nodemon and it crashed

rose tangle
rose tangle
coral river
bold imp
coral river
bold imp
kindred moon

also not a discord.js issue

bold imp
coral river
rose tangle

do you know javascript? it looks like you just copied and pasted non sensical code

coral river

^

bold imp

srry im in high school

kindred moon

you need to learn javascript before using a library like discord.js

rose tangle

the guide has some resources you can use to learn js more in-depth

coral river
bold imp

gimme

coral river
bold imp

thanks to all of u

rose tangle

you could just ask first if they're interested, though I'm not a mod

bold imp

i am intressted

coral river

sent

viral hinge

one q in the Subcommands cant i make it one command instead it of its creating 2 commands? like if the user choose custom it shows options for the customs only but for default it shows another strings?

cinder shale

can I get a user bio with djs ?

kindred moon

no

cinder shale

ah

rose tangle
rose tangle
cinder shale

i see

sharp ginkgoBOT
tidal ravine

this only works with the number right not like the emebd builder

humble fern

Is it possible to know how many boosts a user gave on a server? 1 or 2?

outer plume

the type signature doesn’t have that. At least

sharp ginkgoBOT
tidal ravine
rose tangle

in case it's user input or something

tidal ravine

oh i did some parseint stuff

rose tangle

if it's a hardcoded value I'd just use the number

yeah that's basically what that does

tidal ravine

do u think in the future it will be like embeds

rose tangle
rose tangle
tidal ravine do u think in the future it will be like embeds

probably not, since djs has moved away from extending builders classes from @discordjs/builders in discord.js (they're two different packages), and that "string color resolution" only worked like that, the base EmbedBuilder in /builders has never accepted strings

tidal ravine

checked the code it's basically the same thing im' doing so

rose tangle

yeah and djs also provides one which I don't think will be removed

tidal ravine
rose tangle

yeah setColor(resolveColor(...))

rose tangle
tidal ravine

alright thank you

rose tangle
rose tangle
sharp ginkgoBOT

The Discord API does not provide a dedicated event for guild boosts, but you can check for it in the guildMemberUpdate event:

client.on("guildMemberUpdate", (oldMember, newMember) => {
    // Check if the member wasn't boosting before, but is now.
    if (!oldMember.premiumSince && newMember.premiumSince) {
        // Member started boosting.
    }
});
rose tangle

and that event for detecting when it starts

outer plume
velvet portal

is it possible to escape backticks inside of an inline code block?

rose tangle

it isn't as far as I'm aware but that isn't djs related

velvet portal
delicate spindle

Do shard IDs start from 0 or 1 or are they Discord-like IDs?

red coral

0

delicate spindle
worldly violet

Hi there!
Does someone know why is this event: GuildAuditLogEntryCreate is not working?


import { AuditLogEvent, Events } from 'discord.js';

export default {
    name: Events.GuildAuditLogEntryCreate,
    async execute(interaction) {
        console.log(interaction);
    }
};

I tried it to test: creating and deleting a channel, a message and a role. And no one has execute log and nothing. I have a switch later but it does not matter because it does not execute log neither.

I attach bot permissions.

loud quartz

Those are permissions of the default invite, not the bot

People inviting the bot might uncheck the boxes, or even be unable to check them in the first place

worldly violet

I am the only one using it in a test server. BTW where should I check It then? Because audit log is not working. And the bot has those rights on the server

steel trail

Do you have the GuildModeration intent?

toxic moat
SyntaxError: Unexpected end of JSON input
    at <parse> (:0)
    at json (unknown)
    at parseResponse (/home/container/node_modules/@discordjs/rest/dist/index.js:264:30)
    at processTicksAndRejections (native:7:39)

I have this in console, I have no idea why and where and when it happened, any ideas what is it?

steel trail

Do you use a rest proxy?

toxic moat

? im using discord.js

steel trail

Yes. I know that. I was asking about your configuration. Show your client constructor if you're unsure

toxic moat
intents: [
            GatewayIntentBits.Guilds,
            GatewayIntentBits.GuildMembers,
            GatewayIntentBits.GuildMessages,
            GatewayIntentBits.MessageContent,
        ],
        partials: [
            Partials.Channel,
            Partials.Message,
            Partials.User,
            Partials.GuildMember,
            Partials.Reaction,
        ],
        presence: {
            status: "dnd",
            activities: [
                {
                    type: ActivityType.Watching,
                    name: "/dating",
                },
            ],
        },

just this

toxic moat
steel trail

That error means that a response from discord wasn't valid JSON although having a 200 status code.

toxic moat

so is it issue on my end or

steel trail

I don't have enough information to tell you that. I told you what I can from what you showed

toxic moat
rose tangle

that's entirely unrelated

toxic moat

i was js curious

because i can't debug this error ^^^
no way of knowing how or where it happens

rose tangle

does it happen frequently?

toxic moat

i think this is first time it happened
but it logged that error 10-15 times in a row

rose tangle

are you hosting it on a vps or?

toxic moat

dedicated server

rose tangle

do you have any kind of proxy setup?

toxic moat

i mean its normal
normal installation of server

as i said it worked perfectly before

worldly violet
wooden carbon
    const channel = await client.channels.fetch(channelId);
    if (!channel || !channel.isSendable())
      return interaction.reply({ embeds: [badChannel] });
    const message = await channel.messages.fetch(messageId);
message.edit({embeds: []})

So, I have to make a round trip three times and use the rate limit from a bucket just to edit a message…

I already know the messageId and channelId. Can't I just request to edit it directly, without the object overhead?

rose tangle

dogeHaHa

wooden carbon

oh sh*t, I do need to fetch message.

i am using message as a database, to cut a bit of storage 🌹

rose tangle

Thonk are you hosting on an arduino nano so you have no ram and no storage

also I'm pretty sure using discord as storage is against the dev tos

wooden carbon

64mb ram and 1gb storage 😊

wooden carbon

I am really really low of storage, and a bit of cut is fine

rose tangle

if you're storing text it's really compresable

1 gb should be more than enough for most bots

mellow marsh

hi

I have a slash command that accepts an attachment as an argument, but I can't find a way to access the full name of that attachment

the original name contains Korean characters, but the attachment object doesn't
when I try to download this file via the attachment link, I get a file named «69.zip»

{
  attachment: Attachment {
    attachment: "https://cdn.discordapp.com/ephemeral-attachments/.../69.zip?...",
    name: "69.zip",
    size: 9032489,
    url: "https://cdn.discordapp.com/ephemeral-attachments/.../69.zip?...",
    ...
  },
}

however, if I send the file in a chat and download it from there, the file name «살아남은 왕녀의 웃음 뒤에는_69화.zip» remains. even though the link to the file in the chat also does not contain these Korean characters.

so how does the discord app know which file name to use when downloading the file locally, and is it possible to restore the original file name (before removing non-ascii and other prohibited characters)?

karmic hedge

Hi, just looking at the documentation, is there any way to see whether a guild has an entitlement from events such as messageCreate?

For example, a way to check from a guild which entitlements it has (there is no Guild.entitlements or anything from what I can see)

Well, specifically is there a way to achieve this without using the entitlement events I suppose or will I need to go down that route :P

proud arrow

I believe entitlement is only sent with interactions. You can fetch the entitlements for your application and check if there is any for the particular guild

sharp ginkgoBOT
karmic hedge

Ah this wouldn't work, nor would ClientApplication.subscriptions I dont think

proud arrow

It would be added as it is recieved, whether it was fetched or recieved from an event

karmic hedge

Okay, so the recommended way to implement this would be listening to the entitlementCreate and entitlementUpdate events (for any bot that also uses other events)

proud arrow

What is your goal?maybe I can help you better that way.

karmic hedge

Just trying to add subscriptions to my bot to be compliant with the monetization terms. The bot has some features tied to other events (for example presence update) which should only work if they have a subscription. I need to be able to check whether they have a guild subscription from that event (in this example from a presence update event)

proud arrow

Just to be sure, you want to check subscription or entitlement? Because those two are different things

karmic hedge

What's the difference? Sorry I am clearly uninformed here, I just want to know whether there is an active subscription to my application for that guild

Ah subscriptions is a subscription to the guild. Sorry for the confusion, I am referring to entitlements.

worldly violet
bleak owl

in your client constructor where you do new Client

worldly violet
modest surge

quick question can u send component v2 in the dms

rose tangle

sure

there's no restrictions for dm messages

modest surge

alr thx

worldly violet
bleak owl in your client constructor where you do `new Client`

it worked, thanks!
Now, I have this in a separated file:


import translate from '../translation/es.js';
import interpolate from '../auxiliar/interpolate.js';
import logEmbed from '../auxiliar/embeds.js';
import { AuditLogEvent, Events } from 'discord.js';

export default {
    name: Events.GuildAuditLogEntryCreate,
    async execute(auditLog) {
        console.log(auditLog);
        const { action, extra: channel, executorId, targetId } = auditLog;
        const executor = await client.users.fetch(executorId);
        const target = await client.users.fetch(targetId);
        let message;

        switch (action) {
            case AuditLogEvent.MessageDelete:
                message = interpolate(translate.events.GuildAuditLogEntryCreate.messageDeleted, { target: target.tag, executor: executor.tag, channel: channel });
                logEmbed.description = message;
                logEmbed.fields[0].value = executor.id;
                break;
            case AuditLogEvent.MemberKick:
                message = interpolate(translate.events.GuildAuditLogEntryCreate.userKicked, { target: target.tag, executor: executor.tag});
                logEmbed.description = message;
                logEmbed.fields[0].value = executor.id;
                break;
        }

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

2n question: how do I import client from index.js (following https://discordjs.guide that guide).

3rd question: I have not tried "channel.send" but, how do I configure in which channel do I send the message?

proud arrow
worthy drift
steel trail
sharp ginkgoBOT
steel trail

The second parameter is a Guild, which has a .client property you can use

And to your third question: client.channels.cache.get(channelId) and you get the channel you want

karmic hedge

To achieve the ability to get the entitlements of a guild would you have to filter / find in that collection?

proud arrow

Entitlement id

Yes

karmic hedge

oh okay

karmic hedge
proud arrow Yes

Okay one more question, if you fetch will it only return active entitlements (non expired ones)

sharp ginkgoBOT
steel trail

You can fetch by guild id etc.

And also decide what to exclude

karmic hedge

Thanks :)

trim topaz

Hey there ✌️
I'm having weird errors today and Discord seem super laggy...
Everything was fine for months and we didn't push any changes into production... Think_Eyes
I'm having a lot of those DOMException [AbortError]: This operation was aborted at new DOMException (node:internal/per_context/domexception:53:5) at AbortController.abort (node:internal/abort_controller:391:18) at Timeout.<anonymous> (/home/Bots/ArtyBot/node_modules/@discordjs/rest/dist/index.js:680:47) at listOnTimeout (node:internal/timers:581:17) at process.processTimers (node:internal/timers:519:7)
Version 14.15.2

Anyone with the same errs ?

karmic hedge
worldly violet

thanks @worthy drift and @steel trail 🙂 I will come back

With official troller answer, it gets the console.log but not with Qjuh one... or I implemented it wrong 🙂

steel trail
karmic hedge

Okay thanks I believe I misunderstood his/her/their earlier message

bleak owl
proud arrow
karmic hedge
trim topaz
bleak owl

there aren't breaking changes with that

loud quartz

There are breaking type changes

queen vale

How do I edit a message component (V2) from a modal interaction? According to TS I cant do .update on the modal interaction

humble fern

Is there any way to know how many boosts a user has given in a server?

sharp ginkgoBOT
queen vale

Thanks!

white bridge

I've never used node.js before (I've made a button for a website, that's about it). Figured a bot would be a cool way to learn how to use JS. I'm completely unable to install, or remove discord.js because a dependency that discord.js does actually have. I'm very confused

rose tangle

it says it added it successfully though?

white bridge

So I can disregard the error?

rose tangle

it's only notifying you about the possible security vulnerabilities, which are on code that djs doesn't use

red coral

Mootools? Doesn’t npm install <> also install packages which aren’t installed but in the package.jsom?

white bridge

I'm just doing a global install if that matters

rose tangle
rose tangle
rose tangle

looks like you installed a package called "discord"

thought it was another "vulnerability" djs does have in one of its dependencies, which comes from code djs doesn't use at all

white bridge
red coral

What’s the issue

rose tangle

tbf you really just need discord.js, nothing else

but if you want a guide there's an official one

outer plume
white bridge
white bridge
outer plume

oh. you're on windows. uhhhhh. i can try to help then i guess

rose tangle

I'd recommend just following the guide if you're really stuck, it should help with most of the stuff

but it does assume you already have some level of understanding of js and node

outer plume

he needs help setting up node. djs is out of the question for now...

rose tangle

from their questions I understood they already have node, given npm works

they're asking how to setup an environment for djs

outer plume

shi you're right

i wonder where that "discord" lib came from when they typed "discord.js"

outer plume
steel yacht

Hi,
Can a slash command be directly replied with a modal ?
Thanks

rose tangle

sure

sharp ginkgoBOT
warm widget

not really help but a question, but what is the type of interaction?

async execute(interaction) {
  // interaction.guild is the object representing the Guild in which the command was run
  await interaction.reply(`This server is ${interaction.guild.name} and has${interaction.guild.memberCount}members.`);
},
warm widget

oh yeah i forgot to mention i was using typescript

clear garnet
solid acorn
warm widget
clear garnet

Where is this execute function being called?

clear garnet

Then look for the same classes

solid acorn

bruh, lol thank you man

warm widget

its a normal slash command builder using the handling from the discord.js guide website, i just converted some of the code to be typescript compatible

import { SlashCommandBuilder } from 'discord.js';

module.exports = {
    data: new SlashCommandBuilder()
        .setName('server')
        .setDescription('Provides information about the server.'),
    async execute(interaction) {
        // interaction.guild is the object representing the Guild in which the command was run
        await interaction.reply(`This server is ${interaction.guild.name} and has ${interaction.guild.memberCount} members.`);
    },
};


rose tangle

ChatInputCommandInteraction then

warm widget
rose tangle

I'd recommend making a generic Command type to let you type your exports object

solid acorn

is there something like you can associate some data with a button? like a user's email so i know who clicked the button in a button interaction event?

clear garnet

interaction.user.id tells you who clicked the button in a ButtonInteraction event

rose tangle

you're supossed to add some kind of id in the customId and then store data like that in your own database

solid acorn
rose tangle

or the user id yeah since that'd make more sense for an email

solid acorn
rose tangle

the only data you can append is the customId, but it's not big enough to store much data, and you shouldn't store anything sensitive either, it's not a secret

white bridge
solid acorn

yes, i understand. i think for such things interaction event is not useful

rose tangle

for an email it'd make much more sense to have in your db a relation from the user's id to their email

solid acorn

i would need to use the other way which has timeout so i can know the context of where this button was clicked

solid acorn
rose tangle

yeah, it should be fine to implement with the approach I said

you extract the user id like TAEMBO said, query your db to get the details and you're done

should defer before querying given the response overall may take longer than expected

solid acorn

got it, another question theres no way to accept images in the modal?

rose tangle

the only thing you'd need to store in the customId would be whether it's the reject or confirm button, and the "confirmation session" id maybe (though not if you use collectors)

solid acorn

then how would i listen for the button interaction with a random id

quick question theres no way to accept images in the modal?

rose tangle

you can only listen to interactions overall, you don't listen to interactions with a single id

there isn't

currently modals only support text inputs, and select menus in the future

solid acorn

to respond to the interaction.isButton i need to know which button was clicked and i do that with id == "do this", right? so this would fail in case the custom id is not known

rose tangle

well you can do anything you want with the customId

you can split it, you can check if it starts with something, you can serialize it...

solid acorn

ah

rose tangle

you know how your customIds look like so you'll know how to handle it

solid acorn

yep. makes sense

untold locust

I'm not experienced with interaction at all and its shown can someone please assist me without having a closed answer, explain what i did wrong please
https://sourceb.in/eHUB1rqOGq

sharp ginkgoBOT

tag suggestion for @untold locust:

  • DiscordAPIError: Interaction has already been acknowledged
  • [InteractionAlreadyReplied]: The reply to this interaction has already been sent or deferred.

You have already replied to the interaction.

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

Is something else also handling this slash command?

Can you add console.logs before each usage of interaction.reply to see where it errors?

Line 105 and 111 based on your errors

shrewd wraith

hi, sorry, maybe not djs related
i have a type for slash command:

import type { SlashCommandBuilder } from "discord.js"

type Command = {
    data: SlashCommandBuilder,
    execute: (...args: any[]) => void
}

but when trying to create a command, getting this typescript error:

but without addStringOption it works fine

rose tangle

you can use SlashCommandOptionsOnlyBuilder | SlashCommandSubcommandsOnlyBuilder

because the SlashCommandBuilder gets narrowed down to one of the two depending on whether you have "normal" options or subcommands

shrewd wraith

oh thanks

rose tangle

and all three are mutually exclusive: if you add options it'll turn into SlashCommandOptionsOnlyBuilder which isn't assignable to SlashCommandBuilder, which is your issue

delicate prairie

I'm trying to register commands with my discord bot and for some reason they aren't registering. I've waited hours - restarted my client - restarted my bot - checked on my phone... nothing I do gets them to register.

This is my command I am running to register them...

require('dotenv').config();
const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const bot = require('../config/bot.json');

module.exports = {
  name: 'createcommands',
  execute(message) {
    const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_TOKEN);

    (async () => {
        try {
            // Convert Map to array of command objects
            const slashCommands = [];
            
            if (message.client.slashCommands) {
                message.client.slashCommands.forEach((cmd) => {
                    let object = {};
                    if (cmd.name) object.name = cmd.name;
                    if (cmd.description) object.description = cmd.description;
                    if (cmd.options) object.options = cmd.options;
                    slashCommands.push(object);
                });
            }

            console.log(`Registering ${slashCommands.length} slash commands...`);

            // Create guild commands
            const result = await rest.put(
                Routes.applicationGuildCommands(bot.id, bot.serverId),
                { body: slashCommands },
            );

            // Create global commands
            const globalResult = await rest.put(
                Routes.applicationCommands(bot.id),
                { body: slashCommands },
            );

            console.log(`Successfully registered ${result.length} guild commands!`);
            console.log(`Successfully registered ${globalResult.length} global commands!`);
            message.reply(`Successfully created ${result.length} slash commands!`);

        } catch (error) {
            console.error('Command registration error:', error);
            message.react('❌');
            message.reply({content: `There was an error: ${error.message}`});
        }
    })();

    message.reply({content: 'Created the commands!'});
  }
}

Is there something wrong with this command?

rose tangle

why are you registering both in the guild and globally? that'll just cause duplicates

choose one or the other, not both

delicate prairie

Okay, I only need this in one server so I will do the guild commands

rose tangle

apart from that I think it looks fine, after you choose one, log its data and show its output

delicate prairie

I was having issues with guild commands registering so I was trying to get them to register at all

rose tangle

make sure to delete the global commands

sharp ginkgoBOT

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

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

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

I will. Already have a command for that. I logged everything and no errors - they just don't register.

rose tangle

modify it so it only has one or the other and show that code

and also log the data you receive (result or globalResult)

delicate prairie
require('dotenv').config();
const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const bot = require('../config/bot.json');

module.exports = {
  name: 'createcommands',
  aliases: ['startslash', 'create-commands'],
  description: 'Allows Erin to create the Slash Commands.',
  execute(message) {
    const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_TOKEN);

    (async () => {
        try {
            // Convert Map to array of command objects
            const slashCommands = [];
            
            if (message.client.slashCommands) {
                message.client.slashCommands.forEach((cmd) => {
                    let object = {};
                    if (cmd.name) object.name = cmd.name;
                    if (cmd.description) object.description = cmd.description;
                    if (cmd.options) object.options = cmd.options;
                    slashCommands.push(object);
                });
            }

            console.log(`Registering ${slashCommands.length} slash commands...`);

            // Create guild commands
            const result = await rest.put(
                Routes.applicationGuildCommands(bot.id, bot.serverId),
                { body: slashCommands },
            );

            console.log(`Successfully registered ${result.length} guild commands!`);
            message.reply(`Successfully created ${result.length} slash commands!`);

        } catch (error) {
            console.error('Command registration error:', error);
            message.react('❌');
            message.reply({content: `There was an error: ${error.message}`});
        }
    })();

    message.reply({content: 'Created the commands!'});
  }
}
|-----------------------------------|
          Logging In...             
|-----------------------------------|
   Erin's Helper Bot#1301 is
   logged in and ready!
|-----------------------------------|
             Error Logs...           
|-----------------------------------|
Bot is ready! Loaded 74 slash commands.
|-----------------------------------|
   Slash commands loaded successfully  
|-----------------------------------|
✅ 74 slash commands ready for registration
💡 Use "++createcommands" in Discord to register all commands
🎯 Commands will be available after registration
Registering 74 slash commands...
Registering 74 slash commands...

It stops at the first log

rose tangle

sounds like you're ratelimited then

can confirm by logging on the rateLimited event: client.rest.on('rateLimited', console.log)

iirc the limit is 100 daily commands

you have 74 so you shouldn't be able to register all of them twice per day

delicate prairie

When does the day reset?

plush eagle

I have an issue: I can only change the channel name once. If I try to change it again, the name doesn’t update, and I don’t get any error — really strange.

const newName = `closed-${channel.name}`;
      //await channel.setName(newName);
       let ch = interaction.guild.channels.cache.get(channel.id)
       console.log(ch)
       ch.setName(newName).then(() => console.log('done')).catch(() => console.error);
rose tangle
rose tangle
delicate prairie

Hm... I moved it to my ready event (cause I was planning to anyway) and I'm not seeing anything about the rate limiting.

config stuff

module.exports = { ...
        const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_TOKEN);

        (async () => {
            try {
                // Convert Map to array of command objects
                const slashCommands = [];
                
                if (client.slashCommands) {
                    client.slashCommands.forEach((cmd) => {
                        let object = {};
                        if (cmd.name) object.name = cmd.name;
                        if (cmd.description) object.description = cmd.description;
                        if (cmd.options) object.options = cmd.options;
                        slashCommands.push(object);
                    });
                }
                console.log(`Registering ${slashCommands.length} slash commands...`);
                // Create guild commands
                const result = await rest.put(
                    Routes.applicationGuildCommands(bot.id, bot.serverId),
                    { body: slashCommands },
                );
                console.log(`   Am I rate limited?`); // i see this
                client.rest.on('rateLimited', console.log); // but not this
                console.log(`Successfully registered ${result.length} guild commands!`);
    
            } catch (error) {
                console.error('Command registration error:', error);
            }
        })();
...

Entire console... Actually I'm not seeing either of those now...

rose tangle

if you see the "Am I rate limited" then that's not consistent with what you had before

rose tangle

also if you are ratelimited then that rest.on line will never reach

or well, not when you want to

it would be reached after it has expired, which is not what you want

delicate prairie

If it doesn't reach - wouldn't that stop the load in its tracks and I wouldn't see the successful log after it?

rose tangle

if you see "Am I rate limited" then it's now proceeding after that, maybe you aren't ratelimited anymore

plush eagle

Is there a way for me to know if it’s a rate limit, or do I just have to assume it and handle it with a cooldown?
@rose tangle

rose tangle

and you shouldn't deploy on start anyways, just do it when you actually change commands

you have 74, it sounds like you're well past the dev stage where you needed to deploy constantly

otherwise if you get ratelimited it may block your bot from fully starting (since the promise won't resolve)

rose tangle
sharp ginkgoBOT

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

rose tangle

new Client({ ..., rest: { rejectOnRateLimit: ... }});

delicate prairie
rose tangle you have 74, it sounds like you're well past the dev stage where you needed to d...

I figured it out - I am not rate limited. I got rate limited for a minute but I ran the command again (cause you were right - it shouldn't be in my ready event so I went back to having a command) and I'm not rate limited - it just never logs after creating the commands.

config stuff

module.exports = {
  name: 'createcommands',
  aliases: ['startslash', 'create-commands', 'cc'],
  execute(message, client) {
    const rest = new REST({ version: '10' }).setToken(token);

    (async () => {
        try {
            // Convert Map to array of command objects
            const slashCommands = [];
            
            if (message.client.slashCommands) {
                message.client.slashCommands.forEach((cmd) => {
                    let object = {};
                    if (cmd.name) object.name = cmd.name;
                    if (cmd.description) object.description = cmd.description;
                    if (cmd.options) object.options = cmd.options;
                    slashCommands.push(object);
                });
            }

            console.log(`Registering ${slashCommands.length} slash commands...`);

            // Create guild commands with automatic retry handling
            const result = await rest.put(
                Routes.applicationGuildCommands(bot.id, bot.serverId),
                { body: slashCommands },
            );

            console.log(`✅ Successfully registered ${result.length} guild commands!`);
            message.reply(`✅ Successfully created ${result.length} slash commands!`)

        } catch (error) {
            console.error('Command registration error:', error);
            message.react('❌');
            message.reply({content: `There was an error: ${error.message}`});
        }
    })();

    message.reply({content: 'Created the commands!'});
  }
}
rose tangle

if it isn't ratelimited then it should log the successful message

console.log will never error

if it doesn't log it then it really sounds like you are ratelimited, that's how it'd behave

the request would be queued to run only after the ratelimit expires, and only then the promise will resolve

delicate prairie

Does that mean I'll get rate limited again whenever it rolls over?

Cause I can't see how long the rate limit is. Nothing logs

rose tangle

where did you place your rateLimited listener?

delicate prairie

oops - it got lost - okay now it is logging the rate limit

Thanks! At least now I know what is going on.

lilac basin

So, I have a question, Basically every time that I make this report command run, It spits out an error message, Which I will show, And it makes 3 copies of the same command, What do I do?

I used AI btw 😭

hallow mesa
halcyon bison

the error can also be caused by multiple things trying to respond to the interaction, so I'd definitely focus on the latter issue
especially since the error points towards deferReply being called somewhere

lilac basin

I am using PM2 as a server hoster, Could that be why there could be multiple operations?

lilac basin
hallow mesa

"Not work" how?

lilac basin

So, everytime I put the image file into the query, It just doesn't show up

hallow mesa

How are you trying to send it?

sudden cedar
sharp ginkgoBOT

tag suggestion for @lilac basin:
Common causes of DiscordAPIError[10062]: Unknown interaction:

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

Two processes handling the same command

waxen walrus

I'm wondering, does anyone know how long an attachment link/url will work when using a slash command? Normally when uploading files discord hosts them indefinitely, but I'm not quite sure whether that's the case for attachments in slash commands

waxen walrus

Would you say it's viable/reasonable to instantly make my bot reupload and save the url of its own reupload for longer access?

rose tangle

you should use an actual cdn or have the files locally and upload them when needed

waxen walrus
rose tangle

attachments haven't always expired, that's a relatively recent change

waxen walrus

Well yeah but that's only for ephemeral or slash command ones, no?

rose tangle

people used discord as a cdn, like for bots or other stuff, so they wanted to avoid that and introduced expiration

waxen walrus

Like I can still view random images from many years ago.. so I don't see anything like expiration?

rose tangle

ephemeral attachments last much less yeah but it's not only for those cases

the client has a token it uses to refresh the url

the images exist, only the urls stop working

waxen walrus

Dym expiration of access rather than removal of the file?

rose tangle

something like that, you still have access, just the url isn't valid anymore

waxen walrus

Yeah okay that's expected

waxen walrus
rose tangle

yeah if you fetch it you get a valid one, the point is mostly to avoid hardcoding urls and making it harder to use discord as a cdn

waxen walrus

fair, it's not much harder but yeah

it's still easier than setting up a separate cdn (even if it fits within free tier) 😭 (in the case that the attachments go via discord anyway)

rose tangle

you could just save the images locally and upload

or whatever file you have

waxen walrus

meh tbh that's messy as hell

though I'm thinking of something, if I enable usage of the command in DM only, and make the user upload the image separately, I should also jsut be able to forward it, no?

rose tangle
waxen walrus
waxen walrus

o

thanks for the help 🙏

worldly violet

Hello,
with GuildAuditLogEntryCreate on AuditLogEvent.MessageDelete action, how do I get the channel and the original message that has been deleted?

I tried this for the channel:

const { action, extra: channel, executorId, reason, targetId, changes } = auditLog;```

as it is suggested on the guide but it does not work. It throws ```[object object]```
crimson gale

don't stringify that and it wil indeed be an object

you won't get the content from either, as the content is gone at that point in time and the event just provides the channel and message id so the subscribed client can clean up and evict that data fro memory

so unless the message was cached before (in the same session), you are out of luck

worldly violet

thanks you!

this event: MessageDelete and GuildAuditLogEntryCreate with AuditLogEvent.MessageDelete are not the same, right?

Should I make a specific event for messageDelete to get what I want?

worldly violet

I fixed my problem with both events and with chatGPT, thanks for your help souji 🙂

glossy lion

Hello, I have a small discord app that sends different text based emotes like: ᯠ_ ̫_ᯄ੭ by doing a slash command like /catsighflat

I have been able to make this work in any server even if the bot isn't there, but I would like for this to also work in private DMs.

What is the thing that I would need to change? I already gave the intent for private messages ts const client = new Client({ intents: [ GatewayIntentBits.DirectMessages, GatewayIntentBits.DirectMessageTyping, GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, ], });

And added the dm_permission: true to the command body, any other thing I need to add for it to work on private messages?

This is the way I am registering the commands:


try {
  console.log('Started refreshing application (/) commands.');

  await rest.put(Routes.applicationCommands("CLIENT_ID"), { body: commands });

  console.log('Successfully reloaded application (/) commands.');
} catch (error) {
  console.error(error);
}```

And this is the way I am listening for interactions:

```ts client.on(Events.InteractionCreate, async interaction => {
  if (!interaction.isChatInputCommand()) return;

  if (interaction.commandName === 'catsigh') {
    await interaction.reply('/ᐠ - ˕ -マ Ⳋ');
  }}``` 

For each one of the commands
crimson gale

where you can use the command is part of contexts and not shown here (it needs to be in the command itself)
#setContexts if using builders

glossy lion
  {
    name: 'catsigh',
    description: '/ᐠ - ˕ -マ Ⳋ',
    dm_permission: true
  }, ``` You mean the body for the commands I suppose like this?
crimson gale

yes, contexts

sharp ginkgoBOT
crimson gale
wary coral
glossy lion
wary coral

no, InteractionContextType is not a property of a application command object

I recommended that you use the builder

kindred moon

it would be more like contexts: [InteractionContextType.Guild, InteractionContextType.BotDM] etc

sharp ginkgoBOT

documentation suggestion for @glossy lion:
class SlashCommandBuilder discord.js@14.21.0
A builder that creates API-compatible JSON data for slash commands.

glossy lion

Okey, I was able to figure it out and it works, thank you very much :D

safe pasture

Hey guys ! Can someone tell me why I am not getting the guildId when I delete a channel and retrieve the GuildAuditLogEntry ?

wary coral

First check that it was not a DM
!channel#isDMBased()
and then is has guildId
channel#guildId

sharp ginkgoBOT
loud quartz

Why would dm channel be in audit log

wary coral
loud quartz

sure

but the question isn't really "why is channel.guildId not there", but it reads more like "i already accessed channel.guild.fetchAuditLogs()"

unless it is really badly formed and forces an XY problem

wary coral

@safe pasture could you clarify where your issue is by sharing your code and error

safe pasture

Here's my code :

export async function execute(client, auditLogEntry) {
    console.log(auditLogEntry);

    switch (auditLogEntry.action) {
        case 10 :
            await prisma.guildEvent.create({
                data: { guildId: auditLogEntry.target.guild.id, type: "CHANNEL_CREATE", label: `Salon créé: ${auditLogEntry.target.name}`, meta: { channelId: auditLogEntry.targetId, type: mapChannelType(auditLogEntry.target?.type) } }
            }).catch(() => {});
            break;
        case 12 :
            await prisma.guildEvent.create({
                data: { guildId: auditLogEntry.target.guild.id, type: "CHANNEL_DELETE", label: `Salon supprimé: ${auditLogEntry.target.name}`, meta: { channelId: auditLogEntry.targetId, type: mapChannelType(auditLogEntry.target?.type) } }
            }).catch(() => {});
            break;
}}

and the error :

GuildAuditLogsEntry {
  targetType: 'Channel',
  actionType: 'Delete',
  action: 12,
  reason: null,
  executorId: '256892994504884224',
  executor: User {
    id: '256892994504884224',
    bot: null,
    system: null,
    flags: null,
    username: null,
    globalName: null,
    discriminator: null,
    avatar: null,
    banner: undefined,
    accentColor: undefined,
    avatarDecoration: null,
    avatarDecorationData: null
  },
  changes: [
    { key: 'name', old: 'test42' },
    { key: 'type', old: 0 },
    { key: 'permission_overwrites', old: [] },
    { key: 'nsfw', old: false },
    { key: 'rate_limit_per_user', old: 0 },
    { key: 'flags', old: 0 }
  ],
  id: '1406666904453779550',
  extra: null,
  targetId: '1406639192116560023',
  target: {
    id: '1406639192116560023',
    name: 'test42',
    type: 0,
    permission_overwrites: [],
    nsfw: false,
    rate_limit_per_user: 0,
    flags: 0                                                                                                                                                                                                                        
  }
}
[17:52:05.028] ERROR: uncaughtException 
    err: {
      "type": "TypeError",
      "message": "Cannot read properties of undefined (reading 'id')",```
wary coral

Guild object is include in the event

sharp ginkgoBOT
shrewd wraith

is it possible to add file to message with interaction.editReply?

wary coral
safe pasture

Ohhh, okay ! thanks for the help !

hallow mesa
safe wigeon
.addChannelTypes(ChannelType.GuildText, ChannelType.GuildAnnouncement, ChannelType.AnnouncementThread, ChannelType.PublicThread, ChannelType.PrivateThread)
```Is there a better way to just only show text channels?
tiny condor

Hey, how can I get a user's tag?

Oh mark responded already no worries

For the next release, which has tags, will there be an event when someone equips a guild tag?

loud quartz

yes, an already existing one - user update

also, it's not "tag", but "guild tag" if anything, as "tag" is a property that has existed for years on a User

wary coral
somber dome

DiscordAPIError[50001]: Missing Access
at handleErrors (/root/FAHAD/OutBotGamesV3Main/node_modules/discord.js/node_modules/@discordjs/rest/src/lib/handlers/Shared.ts:148:10)
at processTicksAndRejections (node:internal/process/task_queues:95:5)
at SequentialHandler.runRequest (/root/FAHAD/OutBotGamesV3Main/node_modules/discord.js/node_modules/@discordjs/rest/src/lib/handlers/SequentialHandler.ts:417:20)
at SequentialHandler.queueRequest (/root/FAHAD/OutBotGamesV3Main/node_modules/discord.js/node_modules/@discordjs/rest/src/lib/handlers/SequentialHandler.ts:169:11)
at _REST.request (/root/FAHAD/OutBotGamesV3Main/node_modules/discord.js/node_modules/@discordjs/rest/src/lib/REST.ts:210:20)
at GuildMessageManager._fetchMany (/root/FAHAD/OutBotGamesV3Main/node_modules/discord.js/src/managers/MessageManager.js:112:18)
at TextChannel.bulkDelete (/root/FAHAD/OutBotGamesV3Main/node_modules/discord.js/src/structures/interfaces/TextBasedChannel.js:349:20) {
requestBod

wary coral
wide elk

Guys, im trying to put a proxy on my client

How do i do it exacly

fallow pivot

Hello, I'm a beginner in front-end programming. Learn html css js. If there is someone who helps me create projects together and cooperate in projects.

bleak owl
dense frost

okay huh this might just be a discord issue, but if i simply type the following *

// like this
`*`

on discord, it works
HOWEVER
in an embed field value, having an/multiple asterisks (*) inside a single-backtick codeblock breaks (and escapes) the codeblock
I have tried putting text around/between the asterisks inside the codeblock and even backslashes for both the asterisk and backticks (and even the backslashes themselves) but nothing does it right
any ideas ?

fiery crag

Is there a way to use footer and author in Discord.js v14?

unique shoal

uhh yes?

same way that has always existed

sharp ginkgoBOT
loud quartz

unless you mean a container, in which case - no. embed is not a container

dense frost
unique shoal

Why? Because theyre entirely different devices, aspect ratios, resolutions...

Probably codebases

dense frost

no but it's different for such stupid things (such as markdown)

*text * on desktop gives *text *
but on mobile it gives *text *
(and many more cases)

fiery crag
loud quartz

nothing we can do about that

loud quartz

container has nothing to do with embeds

fiery crag
loud quartz

container is merely a, well, container for new components

radiant epoch

But yeah, if you are feeling crazy; you can even mask it as circular and then make it an emoji to use as container’s author else it will be in square

loud quartz

creating an emote out of an avatar just because someone joined sounds like a quite bad of an idea

radiant epoch

I’m just giving ideas if they want to make it work out

loud quartz

they can also just use an embed

those weren't removed

radiant epoch
loud quartz

and the button is under it anyway

loud quartz
radiant epoch
bleak owl

no its not okay

spamming the api is never okay

radiant epoch

You can upload emojis in row as user, so why not as bot

loud quartz

or you can just not do that

and use an embed

why are we even discussing this

fiery crag
loud quartz
unique shoal

There are so many reason an emoji per user is a bad idea, if nothing else the 50 per server / 2000 per app limit immediately caps how scalable that solution can ever be

Rate limits aside

radiant epoch

Embed is obsoleted meguFace
But yeah, that’s the idea if you wanted to make profile pictures inside containers for now

unique shoal

Embed is not obsolete

As evidenced by this very discussion where its the better solution for a specific use-case and still is the web standard for embedding content from websites (its original intended purpose)

radiant epoch
loud quartz

then use better words

the ones you actually want to use

unique shoal

Anyway, lets all move on

daring coral
sudden prawn

ل

bleak owl
solemn arch

My close button in my ticket system doesn't reply. Here is the code to the handling of my ticket system.

Also there is nothing in the terminal.

Help me out SA_prayge

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.

solemn arch

One sec

topaz bluff

Where are you loading this file? You also have 0 logging in this file to debug it

topaz bluff

Can you share a snippet of the loader?

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

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

I will mention everything works fine except the closing part of the ticket system.

topaz bluff

Ya I'm on mobile, I can't read that...it's hard to follow

You should start by adding some debug logging and seeing where the interaction flow is stopping

solemn arch

I put a try catch in there and nothing came to the terminal.

topaz bluff

console.log("Interaction ID:", interaction.customID)

Or just console.log("got to here") type logging to see at what point it stops working.

Just kinda put them everywhere. You can delete them when you're done, but if you don't know why it's not working, it's helpful to figure out WHERE it's not working

solemn arch

Alr

Weird

Still nothing in the console. I put like 6 of them in.

topaz bluff

Then it's failing even earlier than you thought. Did you put one with at the start of your execute function?

solemn arch

Then it stopped.

topaz bluff

Line 47 on your pastebin. You check if (interaction.IsStringSelectMenu()) and the rest of your code is nested in that

So it's impossible for any buttons in there to run...because they can't be both a select menu and a button

solemn arch
topaz bluff

Well at least you'll need to move your button code to outside of that if (interaction.IsStringSelectMenu()) check

But you're also checking if it's a button way too much...you have 4 of them

solemn arch

Lemme test rq.

topaz bluff

Code structure is more of a quality of life thing...but it would probably be beneficial to do some refactoring of this.

You're doing a lot of stuff in your interactionCreate event file...making a handler to send the interaction event to other files would make it a lot easier to maintain.

Adding more buttons or modifying existing ones would be much more organized. Like src/buttons/deleteTicket.js

And would prevent bugs like this, where you're trying to handle a button interaction inside of a select menu handler

solemn arch

Also is there any benefit to have a src folder before the buttons one?

topaz bluff

src is simply just good practice to separate your actual code away from configuration files/folders. It also matters more when you have secondary services running alongside your main app...but that's besides the point

But actually implementing this is up to you...but you can copy the automatic command loader from the discord js guide and modify it to be for buttons...in the API, they're almost the same thing

solemn arch

Ok

And also thanks for the help.

topaz bluff

Ofc

wide elk
0|Complexo | RATE LIMIT: {
0|Complexo |   global: false,
0|Complexo |   method: 'POST',
0|Complexo |   url: 'https://ptb.discord.com/api/v10/channels/1403628284201275432/threads',
0|Complexo |   route: '/channels/:id/threads',
0|Complexo |   majorParameter: '1403628284201275432',
0|Complexo |   hash: '7ced0bc5b612b6797114f6ffc4b5fe04',
0|Complexo |   limit: 50,
0|Complexo |   timeToReset: 160928,
0|Complexo |   retryAfter: 161050,
0|Complexo |   sublimitTimeout: 161050,
0|Complexo |   scope: 'shared'
0|Complexo | }

What can i do? 😢

Can nirn-proxy help me with that? Should i buy a proxy?

rose tangle

you're ratelimited, you have to wait

topaz bluff

No a proxy will not get around a rate limit...

rose tangle

in the future don't make many requests, change your code to avoid hitting it

worldly violet

Hello,

const serverChannels = await guild.channels.fetch();
const channel = serverChannels.filter(c => c.type === ChannelType.GuildText).find(x => x.position == 0);
await channel.message({ content: translate.logs.noChannelFound, flags: MessageFlags.Ephemeral });

how to make that message ephemeral?

snow onyx
worldly violet
wooden carbon

const member = await guild.members.fetch(memberId);

does discord return roles with it? or do i have to fetch for it separately?

snow onyx

It does return roles with it.

wooden carbon

will discord throw error, if i try to set role which the user already has?

snow onyx

no

But it doesn't hurt to check beforehand.

wooden carbon

what if i don't want to cache any member?
await guild.members.fetch(memberId); will fetch the member.

But what about the roles of member?

well, idk how explain

unique shoal

yes, that includes which roles they have

sharp ginkgoBOT
kindred moon

you can see all of the things that that would return here

wooden carbon

So, when fetching a member, Discord returns roles as an array of role Id.

Does Discord.js look into the roles cache and grab the full role objects to put them into the member's roles cache? I think that’s what happens.

But if I turn off all the cache, what happens? Will it still fetch the roles? I don’t actually need the full role objects, just the role IDs returned by Discord, along with member fetch are enough for me.

unique shoal

kind of yes

dont turn off the guild cache

wooden carbon

yea

unique shoal

which is where roles come from

wooden carbon

ok but i don't want member to be cache they are kinda useless for me

unique shoal

so dont cache them, thats fine

the roles arent related

the caching of them isnt anyway

wooden carbon

btw, I wonder how much ram will consume to cache single guild?

unique shoal

fuck all

wooden carbon

lol

wooden carbon
unique shoal

a couple of fuck alls

I dont know how many guilds your bot is in

wooden carbon

gpt 😅

unique shoal

yeah thats what I said

😄

wooden carbon
kindred moon

realistically you don't need to worry about this until you have a large application

wooden carbon
unique shoal

the problem then is that node itself will reserve about that much

wooden carbon

64mb*

unique shoal

why so tiny?

wooden carbon

idk

snow onyx

I'm at a usage of ~120mb with a few thousand members cached, no cache limited and constantly playing something in voice, so I would say it doesn't really matter unless you reach a massive user/server base

near dove

is there a way to make a user select menu within a role, so for example i have a role called vips so the selectmenu would only show the users with the role

unique shoal

no

near dove
wooden carbon
storm gorge

Anyone else's .setPresence on clientuser no longer working? As in it doesn't show what I ask it to set + no errors or anything

polar karma

How often are you changing it?

Have you confirmed the code is being reached and executed? console.log() statements before and after?

storm gorge

It's only being changed once every two minutes to update a certain value. It was all working fine before somewhere last week and suddenly it stopped. To add it did for two different bots of mine running a different codebase/ framework set up

wheat forge
loud quartz

if you don't want an accessory, don't use a section

just use text display directly

wheat forge
solemn arch

I have a error in my closing portion of my ticket bot. The error is TypeError: Cannot read properties of undefined (reading 'send') the code for handling of my ticket system is in the link below. https://sourceb.in/CN9CDuaMyg

wary coral
solemn arch
wary coral Could you provide the full stack trace of the error

This? ```node:events:497
throw er; // Unhandled 'error' event
^

TypeError: Cannot read properties of undefined (reading 'send')
at Object.execute (C:\Programming + Coding\DiscordBots\Bot\src\events\ticket-system.js:215:45)
at Client.<anonymous> (C:\Programming + Coding\DiscordBots\Bot\src\index.js:42:44)
at Client.emit (node:events:531:35)
at InteractionCreateAction.handle (C:\Programming + Coding\DiscordBots\Bot\node_modules\discord.js\src\client\actions\InteractionCreate.js:101:12)
at module.exports [as INTERACTION_CREATE] (C:\Programming + Coding\DiscordBots\Bot\node_modules\discord.js\src\client\websocket\handlers\INTERACTION_CREATE.js:4:36)
at WebSocketManager.handlePacket (C:\Programming + Coding\DiscordBots\Bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:351:31)
at WebSocketManager.<anonymous> (C:\Programming + Coding\DiscordBots\Bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:235:12)
at WebSocketManager.emit (C:\Programming + Coding\DiscordBots\Bot\node_modules@vladfrangu\async_event_emitter\dist\index.cjs:287:31)
at WebSocketShard.<anonymous> (C:\Programming + Coding\DiscordBots\Bot\node_modules@discordjs\ws\dist\index.js:1190:51)
at WebSocketShard.emit (C:\Programming + Coding\DiscordBots\Bot\node_modules@vladfrangu\async_event_emitter\dist\index.cjs:287:31)
Emitted 'error' event on Client instance at:
at emitUnhandledRejectionOrErr (node:events:402:10)
at process.processTicksAndRejections (node:internal/process/task_queues:84:21)```

wary coral
solemn arch
wary coral

On line 205 interaction does not have that property.

solemn arch
vestal sun

but you wouldnt get it via "const generalSupportChannel = interaction.generalSupportChannel" you need to either get the actual id of it and save it somewhere or if the name is unique get it by name

wary coral
wide elk
outer plume
wide elk
wary coral

Write better code? I don't know your code and am not writing it for you.

outer plume
wary coral
sharp ginkgoBOT
wide elk
rose tangle

what are you doing specifically?

you shouldn't hit that ratelimit in the first place

rose tangle

yeah but that's just a general description, I wanted something more specific

outer plume

i assume creating editing deleting

or a combination

wide elk
rose tangle what are you doing specifically?

It's a game that works as follows: let's say you and I want to go 1v1 in Valorant, so we go to the bot and click "Play". When both players click, it will create a thread within a text channel. Upon confirmation, the bot will add a mediator to the thread who will be responsible for creating the match and monitoring possible cheating. That's basically it. The problem is that there were about 200 simultaneous matches and +3,500 per day.

rose tangle

maybe you could re-use channels or do they need to be empty?

outer plume

lol

wide elk

they need to have no messages and no people inside it until both join it, thats it

wary coral
solemn arch Yeah

Try this on line 205.
const generalSupportChannel = interaction.channel;
You were calling interaction.generalSupportChannel which doesn't exist

outer plume

if you don’t need history, that’s a better option

wary coral
solemn arch Thanks

Next time check the documentation to validate the properties exists linked by the bot above

solemn arch

ok

fading girder
    console.log(orderInfo.CoachPic);

    const embed = new EmbedBuilder()
        .setColor('#0c941c')
        .setTitle(`Welcome ${orderInfo.CustomerName}!`)
        .setAuthor({ name: 'Clash School', iconURL: client.user?.displayAvatarURL() })
        .setThumbnail(`${orderInfo.CoachPic}`)```

here the thumbnail is not working, not sure why. this is the pic btw

`https://www.clashschool.com/wp-content/uploads/2020/01/BRADDERS-1.png`

I logged it btw
wary coral
fading girder

thumbnail didn't appear

wary coral

I know nasa images blocks Discord. Is it possible that the site you link also blocks it

wooden carbon

logically it should be in channel.

sharp ginkgoBOT

method GuildInviteManager#create() discord.js@14.21.0
Create an invite to the guild from the provided channel.


// Create an invite to a selected channel
guild.invites.create('599942732013764608')
  .then(console.log)
  .catch(console.error);

snow onyx

logically it should be on guild :P

wooden carbon

nah

it should be in channel caz, invites are created based on a channel

so, channel.createInvite() or something seems resonable

halcyon bison

that does also exist

sharp ginkgoBOT

documentation suggestion for @wooden carbon:
method BaseGuildTextChannel#createInvite() discord.js@14.21.0
Creates an invite to this guild channel.


// Create an invite to a channel
channel.createInvite()
  .then(invite => console.log(`Created an invite with a code of ${invite.code}`))
  .catch(console.error);

snow onyx

why is it not on guildchannel then potatotriggered

wooden carbon
halcyon bison

'cause not all guild channels can be invited to, just the text based ones mmLol

wooden carbon

and invites can only be in text or voice based

snow onyx

then you can still add it to guildchannel and omit it from categories mmlol

also #justiceforcategories

wooden carbon

if(channel.isTextBased()) channel.createInvite

Seems like i also need to exclude Dm thingy, but is there any combined type guard ?

f

HELP!!!

IT DOESN'T EXITS ON ANYTHING
Property 'createInvite' does not exist on type 'DMChannel | PartialDMChannel | NewsChannel | StageChannel | TextChannel | PublicThreadChannel<boolean> | PrivateThreadChannel | VoiceChannel'.

rose tangle

that's the whole union

wooden carbon

well, there is only one way if("createInvite" in channel)

rose tangle

further below it should say on which exact element it isn't

probably DMChannel | PartialDMChannel

and I think VoiceChannel as well like mentioned above

wooden carbon

i typ gaurd dm thingy still show err

wooden carbon

yep you can

rose tangle

no idea, it was mentioned above so I assume so ¯_(ツ)_/¯

the error should tell you exactly on which it isn't present

rose tangle
wooden carbon

sometime ts is such a biatch

rose tangle

I mean it's there to avoid making a runtime mistake

if you did receive a dm channel then it would've errored

wooden carbon
if ("createInvite" in channel)
          channel.createInvite({
            maxAge: 0,
            maxUses: 0,
            unique: true,
            reason: "Making your discord public :D",
          });

well well, this is a problem it will create invite each time

oh nvm

unique false should do the magic

fading girder

is it possible to get the string that the user has selected during autocomplete?

say, my field_1 is autocomplete too and user chooses "text1"

now when he goes to field_2 which is also an autocomplete, I want to be able to customise the option based on what he selected for field_1. is this possible?

sharp ginkgoBOT

guide suggestion for @fading girder:
guide Slash Commands: Autocomplete - Accessing other values
read more

rose tangle

consider that options are cached

fading girder

tyy

rose tangle

if the user types text1 and you'll reply with some options, it'll show those same options if they type text1 again

regardless of what they've typed in other options

there's no way around that

fading girder

okay got it

kind plume

Hey, whenever I get guild's data from cache or by fetching it, it seems that I'm missing the description property though my guild has the description set in settings. It was working when I was making this feature, but now for some reason it has stopped

loud quartz

from cache or by fetching it
how are you fetching it?

kind plume

It is in the screenshot

Originally I was getting the data from the cache but after I noticed that the description property is blank then I changed it to fetch

loud quartz

since fetch used this way checks cache first

kind plume

Oh yeah you're right actually

i always forget about that, now it works

west finch

I got this error

sharp ginkgoBOT

Error: Used disallowed intents
If you are using the GuildMembers, GuildPresences, or MessageContent intents, you need to enable them via Developer Portal > Your app > Bot > Privileged Gateway Intents

neat nimbus
/**
 * @param {import('../init').bot} bot
 * @param {import('../init').con} con
 * @param {import('discord.js').GuildChannel} oldChannel
 * @param {import('discord.js').GuildChannel} newChannel
 */
module.exports = async function (bot, con, oldChannel, newChannel) {
    if (!newChannel.guild) return;
    con.query(`SELECT * FROM data WHERE id = ?`, [newChannel.guild.id], function (e, data) {
        if (!data[0]) return;
        con.query(`SELECT * FROM logging WHERE logType = ? AND guildId = ?`, ['Channel', newChannel.guild.id], function (e, logs) {
            if (!logs[0]) return;
            newChannel.guild.fetchAuditLogs({ limit: 1, type: 11 }).then(function (AuditLogFetch) {
                var Entry = AuditLogFetch.entries.first();
                newChannel.guild.channels.cache.get(logs[0].channelId)?.send({
                    embeds: [
                        new bot.discord.EmbedBuilder()
                            .setColor(data[0].color)
                            .setAuthor({ name: `Action Logs - Channel Updated`, iconURL: newChannel.guild.iconURL({ dynamic: true }) })
                            .addFields(
                                { name: `Actioned By:`, value: `${Entry.executor.tag || "someone"}` },
                                { name: `Before Changes:`, value: `\`Name:\` ${oldChannel.name}\n\`Type:\` ${oldChannel.type}\n\`ID:\` ${oldChannel.id}\n\`Created:\` ${oldChannel.createdAt.toLocaleString()}` },
                                { name: `After Changes:`, value: `\`Name:\` ${newChannel.name}\n\`Type:\` ${newChannel.type}\n\`ID:\` ${newChannel.id}\n\`Created:\` ${newChannel.createdAt.toLocaleString()}` },
                            )
                            .setTimestamp()
                            .setFooter({ text: newChannel.guild.name, iconURL: newChannel.guild.iconURL({ dynamic: true }) })
                    ]
                });
            });
        });
    });
}```