#djs-help-v14

78874 messages · Page 68 of 79

sharp ginkgoBOT

tag suggestion for @slim prairie:
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
tardy sable

whats your issue?

sharp ginkgoBOT
wary coral
zinc forge

😮‍💨

median ferry

hey

how can I get a gif's URL? Because message.content is just https://cdn.discordapp.com/attachments/xxxx/xxxx/gif.gifand message.attachments is empty

message.embeds also has the same. I need the expiration parameters and that to query for the gif data

tardy sable
median ferry

oh yea it is

thanks youu

orchid radish

Can bots pull connection info from profiles (eg YouTube channel links?)

polar karma

Only with oauth2

orchid radish

Thanks :)

mighty marten

is there a guide somewhere for the v2 components? Or perhaps a list of interfaces/classes to reference in the docs?

sharp ginkgoBOT

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

mighty marten

cheers

humble crystal

(this is within a collection)

          const Modal = new ModalBuilder()
              .setCustomId('webhookPopper')
              .setTitle('Please input the link to your webhook')
          
          const Template = new LabelBuilder()
              .setLabel('Lorum Ipsum blah blah blah')
              .setDescription('Pls gimmie webhook link')
          
          Modal.addLabelComponents(Template);
          
          await i.showModal(Modal)
```When I try to show a Modal to test, the error in the included attachment shows up. Where is my problem at? I am not sure where to look.
tardy sable
humble crystal

Aha, thank you.

jolly radish

How do I put an image inside the ContainerBuilder?

sharp ginkgoBOT
jolly radish

thanks!

azure forge

Is there a blog site or discord official page on transferring bot ownership to someone else? Or is there ToS conflict on this part?

I am not informed well on this part

polar karma
tiny condor
azure forge
balmy kraken

is there a way to restrict the modal file submission field to only accept images?

balmy kraken

and how can i check the mime type when parsing? Im using

const picture = interaction.fields.getUploadedFiles("proof_screenshot")

interaction being the modal

sharp ginkgoBOT
stable sun

Get an Attachment from the Collection, then access the .contentType

slim prairie

is there anyway to get the owner of a bot or like when the bot is in a team you get the people who own the bot

sharp ginkgoBOT
frosty dagger

does bots now allow having its avatar different in different guilds ?

sharp ginkgoBOT
vast nymph
jolly radish

am I able to check if someone is typing?

sharp ginkgoBOT
jolly radish

thanks

jolly radish
const typingHandler = (typing: Typing) => {
        console.log("Typing");
        if (typing.channel.id === context.channel.id && typing.user.id === userId) {
            hasStartedTyping = true;
        }
    };

    console.log("Registering Event");

    weky._client.on("typingStart", typingHandler);

for some reason it console.logs that it registers the event but when I start typing it does nothing. and yeah, weky._client is a discord.js client

muted aspen

Can I access the primary_guild tag of a user via discord.js somehow?

sharp ginkgoBOT
muted aspen

tyty ❤️

unique shoal
jolly radish

the guild one?

unique shoal

GUILD_MESSAGE_TYPING | GuildMessageTyping

jolly radish

thanks it works now

torpid marsh

Why is 'emoji' returning that is may only specify known properties...

client?.user!.setPresence({
          status: "online",
          activities: [
            {
              emoji: "shield"
              name: "Protecting the server 24/7",
              type: ActivityType.Custom
            }
          ],
        });

Ignore that I put 'shield' in, as I also tried the original emoji...

bleak owl

you can't put an emoji in a custom status

torpid marsh

Oh.

tiny condor

Hey what is the method to update guild profile?

sharp ginkgoBOT

documentation suggestion for @tiny condor:
method Guild#setIcon() discord.js@14.25.1
Sets a new guild icon.


// Edit the guild icon
guild.setIcon('./icon.png')
 .then(updated => console.log('Updated the guild icon'))
 .catch(console.error);

tiny condor

The bot profile, but I found it np

sly trench

Anyone wanna be my dev friend am dev too

bleak owl
sly trench
turbid flame

how can i tell if a discord user is using a mobile device? (for example im on DnD but im on mobile device)

sharp ginkgoBOT
tribal birch

any help with error: Could not resolve the code to fetch the invite.
all im doing is Guild#invites.fetch() and catching error

rose tangle

can you show your exact code

tribal birch

oh no actually nvm

but await guild.fetchVanityData(); never returns anything

rose tangle

like, the promise doesn't resolve or?

tribal birch

yep

const vanityData = await Promise.race([
  guild.fetchVanityData(),
  new Promise<never>((_, reject) =>
    setTimeout(() => reject(new Error('Vanity data fetch timeout')), 3000)
  )
]);```
rose tangle

that usually happens with ratelimits, I'm unsure how strict that endpoint is though

tribal birch
this.container.client.rest.on('rateLimited', (rateLimitData) => {
  console.log('rateLimited', rateLimitData);
});

i do have this, but its not logging anything

rose tangle

you can try listening to the rest rateLimited event with client.rest.on('rateLimited', console.log) next to wherever you create your Client

tribal birch

ye not logging anything

rose tangle

hmmm just in case are you sure that's executing?

tribal birch

100% sure!

red coral

I want to have my bot check that a message come from a forward thing like this, how can I check it did?

rose tangle

can you show your client constructor?

tribal birch

i mean, i was working on invite tracker, i did restart bot like 100 times but that shouldnt be the case

const client = new SapphireClient({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMembers,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
    GatewayIntentBits.GuildModeration,
    GatewayIntentBits.GuildInvites
  ],
  partials: [Partials.User, Partials.GuildMember, Partials.Channel],
  loadDefaultErrorListeners: false,
  loadMessageCommandListeners: true,
  caseInsensitiveCommands: true,
  defaultPrefix: container.config.prefix,
  typing: true,
  disableMentionPrefix: true,
  cronTasks: {
    defaultTimezone: 'America/New_York'
  }
});
rose tangle

it should at least emit the event if you are ratelimited

bleak owl

tbf you can view invites and who used a specific code in the members tab

rose tangle

oh sapphire, no idea how that works

tribal birch
proud arrow
red coral

There's a reference for those types of messages? Gonna guess the webhook id is the same for all servers?

oh yh interesting

halcyon bison

there is a reference, but most specific I believe would be a message flag
that being MessageFlags.IsCrosspost

red coral

Ah, that works way better as it will always be one of those

What does the reference lead to? The original message that was crossposted?

rose tangle

yeah just tested, it has that flag

red coral

Nice, thank you all 🙏

crude mist

Is there an object variable that returns an array of server IDs your bot is in?
for example like {Guild.serverIDs}

halcyon bison

<Client>.guilds.cache is a Collection of Guilds your bot is in, keyed by id
if you specifically need an array, you can create an array from <Collection>.keys() in the same way you would from .values() (the last bullet below)

sharp ginkgoBOT
crude mist

okay thanks

tiny condor

What is this due to? Unhandled promise rejection: Error: Used disallowed intents

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

tiny condor

Now how did that happen randomly what

rose tangle

you must've added a privileged intent to your client or disabled a privileged one in the dev panel

tiny condor

Not sure, anyways one more thing;

How come
editOptions.avatar does not exist under GuildMemberEditOptions

bleak owl

i’m not too sure i understand, but doesn’t it make sense that you cannot edit a guild members avatar ?

i assume this is why it’s not there

tiny condor

But I can send it to update the bot's avatar

cuz editMe takes GuildMemberEditOptions

bleak owl

that’s GuildMemberEditMeOptions

not GuildMemberEditOptions

tiny condor

makes so much more sense ❤️
i love typesciprt

One more thing, why can't we set the guild pronouns

bleak owl

it was never documented

and bots can’t do it anymore

tiny condor

Only the pronouns right?

bleak owl

i’m not aware of any undocumented routes besides voice status at this time

tiny condor

Oh I meant about editing the guild profile but np thanks for that too

main mason

in discord.js v14, the ephemeral argument was deprecated, so I now need to pass flags: MessageFlags.Ephemeral instead of a boolean value if I want to make my message ephemeral. is there still a way in v14 to make the message ephemeral depending on the value of a variable?

polar karma

Same logic, set the flag or not based on your trigger

topaz bluff

I personally often use a ternary operator

condition ? valueIfTrue : valueIfFalse

main mason
topaz bluff

You can also pass an empty array
(Flags can be a value, a union, or an array)

magic mural

i just moved my bot to another server and i don't know why i keep getting unknown role error, i have the roles defined by their exact name, yes its in the new server, yes i double checked, but its still showing the role as unknown, here is the code, i don't understand the issue

const interactionMember = client.guilds.cache.get('939319168690442301').members.cache.get(interaction.user.id)

                let welcomeRole3 = interaction.guild.roles.cache.find(r => r.name === "✅ Member")
                let welcomeRole4 = interaction.guild.roles.cache.find(r => r.name  === "✅ TOS")
                interactionMember.roles.add(welcomeRole3.id)
                interactionMember.roles.add(welcomeRole4.id)```


error

```DiscordAPIError[10011]: Unknown Role
    at handleErrors (C:\Users\Christopher Young\Desktop\customs-bot\node_modules\@discordjs\rest\dist\index.js:640:13)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async SequentialHandler.runRequest (C:\Users\Christopher Young\Desktop\customs-bot\node_modules\@discordjs\rest\dist\index.js:1021:23)
    at async SequentialHandler.queueRequest (C:\Users\Christopher Young\Desktop\customs-bot\node_modules\@discordjs\rest\dist\index.js:862:14)
    at async REST.request (C:\Users\Christopher Young\Desktop\customs-bot\node_modules\@discordjs\rest\dist\index.js:1387:22)
    at async GuildMemberRoleManager.add (C:\Users\Christopher Young\Desktop\customs-bot\node_modules\discord.js\src\managers\GuildMemberRoleManager.js:131:7) {
  requestBody: { files: undefined, json: undefined },
  rawError: { message: 'Unknown Role', code: 10011 },
  code: 10011,
  status: 404,
  method: 'PUT',
  url: 'https://discord.com/api/v10/guilds/939319168690442301/members/797367889324933161/roles/1459708632194093135'```
tardy sable

Or 0 too

tardy sable
polar karma
polar karma

Because that's not gonna work

magic mural
polar karma

Then why do you get a guild from the cache instead of just using interaction.member

magic mural

when i have interaction.member it says its undefined

TypeError: Cannot read properties of undefined (reading 'roles')

polar karma

It looks like you're trying to use a role from a different guild

magic mural
polar karma

interaction.member should exist if interaction.guild exists

Can you please log interaction and both of those above values

magic mural
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.

polar karma

interaction and .guild and .member

magic mural

yeah one sec

polar karma

Make separate pastes please because they should all be long if present

magic mural
polar karma

So they're both present

magic mural
main mason

also, is interaction.client.users.cache.get(userId) effectively the same as doing interaction.client.users.fetch(userId);, or does the latter not fetch from cache if it's already available?

magic mural

so i don't understand how the role is unknown when its in the server with the exact name i copy pasted

topaz bluff
polar karma
magic mural

yes

polar karma

The one with undefined

clear garnet
magic mural
    at Client.<anonymous> (C:\Users\Christopher Young\Desktop\customs-bot\events\interactionCreate.js:80:36)
    at Client.emit (node:events:531:35)
    at InteractionCreateAction.handle (C:\Users\Christopher Young\Desktop\customs-bot\node_modules\discord.js\src\client\actions\InteractionCreate.js:97:12)
    at module.exports [as INTERACTION_CREATE] (C:\Users\Christopher Young\Desktop\customs-bot\node_modules\discord.js\src\client\websocket\handlers\INTERACTION_CREATE.js:4:36)
    at WebSocketManager.handlePacket (C:\Users\Christopher Young\Desktop\customs-bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:354:31)
    at WebSocketManager.<anonymous> (C:\Users\Christopher Young\Desktop\customs-bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:238:12)
    at WebSocketManager.emit (C:\Users\Christopher Young\Desktop\customs-bot\node_modules\@vladfrangu\async_event_emitter\dist\index.js:282:31)
    at WebSocketShard.<anonymous> (C:\Users\Christopher Young\Desktop\customs-bot\node_modules\@discordjs\ws\dist\index.js:1103:51)
    at WebSocketShard.emit (C:\Users\Christopher Young\Desktop\customs-bot\node_modules\@vladfrangu\async_event_emitter\dist\index.js:282:31)
    at WebSocketShard.onMessage (C:\Users\Christopher Young\Desktop\customs-bot\node_modules\@discordjs\ws\dist\index.js:938:14)
Emitted 'error' event on Client instance at:
    at emitUnhandledRejectionOrErr (node:events:402:10)
    at process.processTicksAndRejections (node:internal/process/task_queues:84:21)```
polar karma

What's line 80 of your interactionCreate file

magic mural
                interaction.member.roles.add(welcomeRole4.id)```
clear garnet
magic mural
clear garnet

Show that code of you logging it

magic mural
                console.log(interaction.guild)```
clear garnet

Now log just interaction

magic mural
polar karma

The guild id in your initial error does not match that log

tardy sable

be sure youre saving your code before deploying

magic mural
polar karma

Your logs imply otherwise

magic mural

well then i just don't know what the issue is ig

ill just delete all the code and write it again and see if that fixes somehow

polar karma

You should check what's actually going on

Because the guild id from the error is the same one you hard coded in your initial code that I questioned

So it looks like you're on at least two guilds

crude mist

command refreshes fine but it doesnt respond

topaz bluff

Show your interactionCreate handler

polar karma

-# don't deploy commands every time your bot starts

crude mist
topaz bluff

This script is intended to be run separately, only when you need to make changes to your slash command definitions - you're free to modify parts such as the execute function as much as you like without redeployment.
From: Register Commands

rose tangle

the fact that it doesn't reply seems to imply they didn't read the guide closely lol

ah they left nvm

neat nimbus

?

stable sun
neat nimbus

?

you cant put select menus in the modals? unless thats new

stable sun

It's relatively new

Only came out last year

neat nimbus

tf any docs or help?

sharp ginkgoBOT

guide Select menu
Select menus allow you to limit user input to a preselected list of values. Discord also offers select menus linked directly to native Discord entities like users, roles, and channels. Since they behave very similarly to how they do in messages, please refer to the corresponding guide page for more information on configuring select menus. Here again, you wrap the select menu with a label component to add context to the selection and add the label to the modal:...

neat nimbus

never seen that but that is still a bug that needs fixign

neat nimbus
stable sun

There is

sharp ginkgoBOT
rose tangle

you really need better names than b, c, cfg, i, a, d

otherwise your code is an unreadable mess

neat nimbus

yeah not full updated from old v13 i didnt code it from the start

stable sun

You might want to use deferReply/editReply and deferUpdate/editReply patterns for all of the interactions that make db calls

rose tangle

that's something you decide

neat nimbus

not me the old person who did it

stable sun

You might start to get issues during prod when multiple ppl are using the bot

rose tangle

ah, I understand

neat nimbus

yeah i having to update to v14 and fixing varable and db over 1000 of code lines 🤣

rose tangle

might as well just start from scratch anyways

since you're also doing other changes than just updating

neat nimbus

yea

strong shore

Hi, noob question here, i'm trying to make my first bot and I'm confused by the guide. There's a part where it says to use a deploy-commands script, then it says "Once you fill in these values, run node deploy-commands.js in your project directory to register your commands to the guild specified." Which values do I need to fill in?

if it's talking about the token, clientId and guildId from the previous paragraph, I already did that and the command still isn't responding

clear garnet

It is indeed talking about those values

clear garnet
strong shore

Ok cool, so now what's wrong

clear garnet

Is your bot actually online?

strong shore

yesI can type the slash command into the server and it'll give me the option to run it, but then it times out

wait, it says it's offline

clear garnet

That would be why then - your bot needs to be running in order to process interactions

strong shore

Ok I have got it online now

and now it works! Thanks, glad it was so simple

rose tangle

deploying only tells discord what commands the bot has, not what they do

strong shore

now to figure out how to program the actual command I want it to do...

neat nimbus

how do i allow more then one role?

rose tangle

in select menus?

neat nimbus

yeah

module.exports.run = async function (b, c, cfg, i, a, d) {
  var arg = a.split('-');

  switch (arg[0]) {
    case 'Add': {
      i.showModal(
        new b.djs.ModalBuilder()
          .setCustomId('tickets_setup_modal')
          .setTitle('Ticket System Setup')
          .addLabelComponents(
            new b.djs.LabelBuilder()
              .setLabel('Select a category for tickets')
              .setChannelSelectMenuComponent(
                new b.djs.ChannelSelectMenuBuilder()
                  .setCustomId('ticket_category')
                  .setPlaceholder('Select a category...')
                  .setChannelTypes([b.djs.ChannelType.GuildCategory])
              ),
            new b.djs.LabelBuilder()
              .setLabel('Select staff roles')
              .setRoleSelectMenuComponent(
                new b.djs.RoleSelectMenuBuilder()
                  .setCustomId('staff_roles')
                  .setPlaceholder('Select staff roles...')
              ),
            new b.djs.LabelBuilder()
              .setLabel('Select ping roles')
              .setRoleSelectMenuComponent(
                new b.djs.RoleSelectMenuBuilder()
                  .setCustomId('ping_roles')
                  .setPlaceholder('Select roles to ping...')
              )
          )
      );
      break;
    }
  }
};```
sharp ginkgoBOT
neat nimbus

Ty its different for others

rose tangle

it's called the same in the other select menus

sharp ginkgoBOT
rose tangle

eg

neat nimbus

it had .setMinValues(0)
.setMaxValues(10)
which was breaking it

rose tangle

yeah

that shouldn't break it pretty sure

just makes it so you can send no option

which may or may not be what you want

neat nimbus
data.components[2].component.min_values[COMPONENT_REQUIRED_ZERO_MIN_VALUES]: Components marked as required cannot have a min_values of 0```
gives that

if i leave them in

sharp ginkgoBOT
rose tangle

you need to set that to false

topaz bluff

Or set min values higher than 0

neat nimbus

correct in saying only allow 5 modals one?

odd stirrup
odd stirrup
neat nimbus

ok

odd stirrup

so 5 labels + text displays

neat nimbus
topaz bluff

What type is i

snow onyx
neat nimbus

interaction

whats the best way todo it

topaz bluff

interaction is not a type. It's a base type. There's many different types of interactions. ChatInputCommandInteraction, ButtonInteraction, ModalSubmitInteraction

But ya. As gort said. Looks like i is a ModalSubmitInteraction... Which cannot open a modal

neat nimbus

i just do a modal then upddates embed then add new button for rest

odd stirrup

does channel.isThreadOnly() mean a forum channel?

steel trail

Forum Or media channel

odd stirrup

wtf is a media channel

this?

stable sun
lament moss
halcyon bison
indigo yarrow

why cant i use my User install bot in dms but i can use it on any servers

unique shoal

Because your commands aren't deployed for DM usage

sharp ginkgoBOT
muted vector

hello sorry, I find information about Button inside embed like this, anyone can I ....

sharp ginkgoBOT

guide suggestion for @muted vector:
guide Container
A Container is a layout component which groups its child components inside a visually distinct rounded box with an optional accent color on the left, similar to the message embed look. Unlike embeds, not specifying a color will make the left side of the Container component match the background color. You can mark Container components as spoiler, which blurs all content inside the container. You can use the ContainerBuilder class to easily create a Container component. - a Separator component;...

loud quartz
odd stirrup this?

No, it's a largely forgotten/unseen feature of a media-only forum channel available only to servers with subscriptions

shell girder

Hi 👋 Is there any documentation or a place where I can see all the available permissions on Discord servers, especially those related to roles and channel permissions? I want to better understand how each permission works and its scope.

sharp ginkgoBOT

discord Permissions
Permissions are a way to limit and grant certain abilities to users in Discord. A set of base permissions can be configured at the guild level for different roles. When these roles are attached to users, they grant or revoke specific privileges within the guild. Along with the guild-level permissions, Discord also supports permission overwrites that can be assigned to individual roles or members on a per-channel basis.

shell girder

Thank you so much ❤️

pearl hazel

is there an update about client.users.fetch() ?

tardy sable
pearl hazel

it's return unknown user

tardy sable
pearl hazel

it is valid i'm sure

tardy sable
muted aspen

Bots (Apps) can't create guilds anymore, right?

bleak owl

that is correct

muted aspen

ty

dry flame

Can you set the flags property on an editReply after flags have already been set in a deferReplycall?

snow onyx

you kinda have to if you want to provide any flags
only ephemeral can be set in deferReply

indigo hearth

can you set componenttype v2 to be ephemeral? im trying to make a system where you can choose wether the reply is ephemeral or not and its just not working

topaz bluff

Yes. Components V2 messages don't effect if it cannot can't be ephemeral

indigo hearth

wdym

ah i see

so

            if (isEphemeral) {
                response = await message.reply({
                    components: components,
                    flags: MessageFlags.IsComponentsV2 | MessageFlags.Ephemeral,
                    failIfNotExists: false
                });
            } else {
                response = await message.reply({
                    components: components,
                    flags: MessageFlags.IsComponentsV2,
                    failIfNotExists: false
                });
            }```

`const isEphemeral = channelInfo.watched ? channelInfo.ephemeral : false;`
topaz bluff

flags: MessageFlags.Ephemeral | MessageFlags.IsComponentsV2

indigo hearth

yea i got that and its not working

topaz bluff

What is message? Is it an interaction?

Because ephemeral can only be used on interactions. You can't send an ephemeral message by Message#reply

indigo hearth

ahh then thats why

dang alr thanks

topaz bluff

Slash Commands. Just use em

indigo hearth

yea but, basically user sends an image, bot reacts to it and if someone reacts to the same reaction it sends a component (i'll call it embed)

odd stirrup

maybe dont call it embed if its a component, theres enough confusion between the two already

shell wharf
sharp ginkgoBOT
shell wharf

ty bot

wary coral
shell wharf

yeah ofc haha

I mean if the user is offline, not the bot

wary coral

lol, yes, you would still get the event if the user is offline

fossil aurora

im not sure that userUpdate event fired when people change tag

tardy sable

it does

fossil aurora

alright

shell wharf

mh maybe I did something wrong then, ty

tardy sable

primaryguild is on user so that makes sense

tiny condor
wary coral
shell wharf

yea its fine I fixed it, my code was wrong, it works now even if the user is offline

dry flame

If my bot gets app quarantined due to sending DMs, does it ever get re-unlocked on its own or do I need to actually submit a ticket for it to ever be lifted? I'm not doing any unwanted mass DM sending, just simple welcome messages when members join a server

polar karma

that's a question for discord, nothing the library can answer. you can try asking in ddevs in #useful-servers (and don't send welcome DMs)

eternal moth
topaz bluff
dry flame

Ok I see, fair enough. Thank you

autumn tendon

Hi. I'm developing my bot and I store the moderation roles in a database to identify mods and admins. But I'm not sure if role ids are unique, are they?

velvet cipher

Yes they are

All snowflakes are unique

autumn tendon

Even between servers? Or they're unique for that server

velvet cipher

They're globally unique

autumn tendon

Ok. Thank you very much

pizzaCat

thin pagoda

I have a discord bot which have 5k servers and its a all in one bot but its constantly getting rate limited after 2-3 days operation can you guys tell me why?? is it code issue or smthing ? bcz we tried to fix all the code and even we put limits on everything that rate limits...

thin pagoda
tardy sable
thin pagoda
tardy sable

you should console log your ratelimits to properly find out whats causing it. to me it looks like youre fetching messages too many times, switch to cache instead

thin pagoda
wary coral

Well where in you code do you fetch a message?

thin pagoda

also purge delete 100 messages even if it is not in cache

unique shoal

This is attempting to fetch single messages

thin pagoda

also we added a batch system in purge to avoid the rate limits

thin pagoda
unique shoal

I mean if you don't know, we certainly dont know

thin pagoda

bcz I'm not the one working in this code

unique shoal

We can just help you narrow it down by identifying what sort of functionality is here

thin pagoda
thin pagoda
ruby bane

just look for any messages.fetch call since youre likely calling it but passing in a single value

i mean you could also be calling message.fetch but thats.... unlikely

thin pagoda

7_pinkskull

wary coral

what type of functions are you using the calls for?

thin pagoda
wary coral

I mean how are you using the fetch in your code?

thin pagoda

const fetched = await ctx.channel.messages.fetch({ limit: 100 }).catch(() => null);

wary coral

that does not really tell us how you are using the data from the fetch

ruby bane

why are you fetching the messages to delete them...?

wary coral
thin pagoda

the problem is this code is not made by me... i mean some of the commands

const message = await channel.messages.fetch(messageId);

ig probably its from here...

wary coral

whether or not you wrote it we are trying to help you work the problem

thin pagoda
wary coral
thin pagoda

pepehappy I'm not sure what he trying to do...

tardy sable

you should also ask the ones who made that

wary coral

seems line this fuction is your problem. Next you should look to were fetchPromise is used

thin pagoda

i will try to figure out

he returning the fetchPromise

wary coral

also this message cache seems to me a little odd. djs already caches messages. seems redundant but that is out side the scope of this help channel

ruby bane

djs does that natively

thin pagoda

7_pinkskull I didn't see this thing "_" i have to ask him why he added this

so this is the one giving me rate limits these whole time

Pepecry

wary coral

seems likely but impossible for us to tell with certainty

ruby bane

i mean that one function by itself is likely not what is causing ratelimits but rather how and when its used, as mafia said, you should be looking where fetchPromise is called, not just the function itself

unique shoal

did this get vibe coded in or something?

thin pagoda
wary coral
ruby bane
thin pagoda
wary coral

I don't want to hold your hand thought the whole debug. You going to have to follow the object to where it is used.

thin pagoda

this is just initialized here and nothing doing after this....

tardy sable

you should be asking the people who made that code, we cant clarify that for you

thin pagoda

also there another thing it is not only fetches the messages members and channels also saving "_"

wary coral
thin pagoda

he is not in online

thin pagoda
wary coral

then you have another fetch in your code. if this code never runs

tardy sable

yh looks like that was vibe coded in

thin pagoda

and also its not only one rate limit btw its just did somuch global rate limits

I'm looking on the log

pearl roost

Well uh... is there any way to hide or do something to prevent this Added .. to the Thread stuff appear? I was making private thread and then adding people by the role...

Or it's just like impossible to hide?

pearl roost

And will the bot get rate limit by this?

pearl roost
tacit nacelle

why not use channels rather than threads for this use case?

marble plover

idk if bots add it, i only have done it via user client

pearl roost
marble plover

i agree, threads are waya better for dynamically making

pearl roost

Oh it's actually work

marble plover

yooo

pearl roost

They instantly added to the thread

tacit nacelle

right, just mentioning the role should add the members

tropic yoke

how can i manage the bot profile per guild in the server ?

sharp ginkgoBOT
tropic yoke

thanks

marble plover
pearl roost
pearl roost They instantly added to the thread

Okay so I can add them instantly by mentioning their role, but when I View Server As Role I can't send a message? Why? I don't even see any option / setting to disable permission on the Thread

wary coral
pearl roost Okay so I can add them instantly by mentioning their role, but when I *View Serv...

https://support.discord.com/hc/en-us/articles/4403205878423-Threads-FAQ

When mentioning a small role in a message in a thread, all of the members of that small role that are able to view the thread will be added to it and notified.

These roles must have less than 100 members each, and only 10 roles can be mentioned per message.

Threads also only allow 1,000 members to be added to them. So if the mentioned role would not fit in the thread, the role members will not be added.

pearl roost

Oh oh

The permission Send Messages in Threads is disable in that channel. I just saw that 🙍‍♀️

tardy sequoia
tacit nacelle

correct me if i'm wrong but color scheme looks like Tokyo Night

normal flare

is there a flag or a property that tells you if a message is either a simple text (like this one), contains only an attachment, or contains both? or can I only check message.content and message.attachments?

normal flare

thanks

fluid ferry

is there any reason this has to be as severe of an error as it is? it's not really too big of an issue, so I don't see why it has to kill my process whenever it happens

like I can put a .catch() on it no problem, but it doesn't feel like I should have to

polar karma

if it's an awaitX collector, then yes, you should have to because it's promisfied. if it's a non-promisfied collector, then that shouldn't kill your process

topaz bluff

And that's how the Collectors guide shows how you should handle expired awaitX collectors...by a .catch(console log("Nothing was collected"))

civic tartan

does anyone know if there is a way to tell if a message has been forwarded?

sharp ginkgoBOT
topaz bluff

I think that

sharp ginkgoBOT
tribal hatch

Is it possible to update Display Component?

wary coral

yes

tribal hatch
wary coral

same way any message is updated

tribal hatch
sharp ginkgoBOT

method Message#edit() discord.js@14.25.1
Edits the content of the message.


// Update the content of a message
message.edit('This is my new content!')
  .then(msg => console.log(`Updated the content of a message to ${msg.content}`))
  .catch(console.error);

tribal hatch

I can't change it like that?

let UpdatedComponent =
  new ContainerBuilder(await interaction.message.components[0])
      .setAccentColor(COLORS.SUCCESS)
      .addSeparatorComponents((separator) => separator)
      .addTextDisplayComponents((textDisplay) =>
          textDisplay.setContent(`Accepted | ${userMention(interaction.member.id)} (${interaction.member.id})`)
      )
sharp ginkgoBOT
burnt orbit

Is there a built-in for detecting Discord server invites in a message?

ruby bane

no but you can just match the content with regex, personally i used:

  const DISCORD_INVITE_PATTERNS =
        /(?:https?:\/\/)?(?:discord\.gg|discord(?:app)?\.com\/invite)\/([\w-]+)/gi;```
tiny condor
stable sun
tiny condor

how do you fetch an invite if you detect it in a message

sharp ginkgoBOT

method Client#fetchInvite() discord.js@14.25.1
Obtains an invite from Discord.


client.fetchInvite('https://discord.gg/djs')
  .then(invite => console.log(`Obtained invite with code: ${invite.code}`))
  .catch(console.error);

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

grave trench

its a createTranscript file, which saves all messages to the db, but this continaer part is not working, means a container was in ticket but my bot is only saving in db that its container, but not saving componets inside it like text display/buttons etc

stable sun

Are you not converting this to json when putting it in the db?

ruby bane

gonna already say this since im going to have to look these up but try not to use magic numbers in your code, instead of stuff like c.type === 4, try using the existing ComponentType enum from DJS

stable sun

Message.components is json-serializable

You could convert the entire message if you didn’t care abt structure

JSON.stringify(message)

Or you can select the props from message before stringifying it

JSON.stringify({ author: message.author.id, guild: message.guild.id, components: message.components, … })

tardy sequoia
grave trench

nvm fixed

damn 8 views on my srcbin

grave trench

if (comp.type === ComponentType.Section) {
const raw = comp.data ?? {};

if (raw.text?.content) {
    res.text = {
        type: ComponentType.TextDisplay,
        c: raw.text.content
    };
}

if (raw.accessory) {
    res.acc = mapComponent(raw.accessory);
}

return res;

}

just this part left, why its not saving thub/text insdie container

tribal hatch
ruby bane

splice your existing container and remove the textDisplay at whatever index you inserted it at iirc

tribal hatch
ruby bane

so for example

const container = new ContainerBuilder()
  .addTextDisplayComponents(() => /**/) // 0
  .addTextDisplayComponents(() => /**/) // 1
  .addTextDisplayComponents(() => /**/) // 2

// i want to replace 1
container.spliceComponents(1, 1, new TextDisplayBuilder().setContent("new content"))```
wary coral
tribal hatch

Tysm :Dblobreach

grave trench
wary coral

what do you want the raw message for? Message#toJSON() not good enough?

median ferry

heyy. why message.channel.nsfw sometimes fails? TypeError: Cannot read properties of null (reading 'nsfw') it isn't even on the typedocs Property 'nsfw' does not exist on type 'DMChannel | PartialDMChannel | PartialGroupDMChannel | NewsChannel | StageChannel | TextChannel | PublicThreadChannel<...> | PrivateThreadChannel | VoiceChannel'. Property 'nsfw' does not exist on type 'DMChannel'.

tardy sable
median ferry

I don't use ts so don't rely on that. It is the automod file and it is called on messageCreate filtering dm messages

tardy sable

dms dont have nsfw setting

median ferry

I meant that that is a message sent from a server

tardy sable

show the relevant code

median ferry
async function runImagesChecks(message, guildDb) {
    const isNsfwEnabled = guildDb.automod.nsfw_filter.enabled
    const isOcrEnabled = guildDb.automod.anti_scam.ocr.enabled
    if (!isNsfwEnabled && !isOcrEnabled) return false
    // @ts-ignore
    if (isNsfwEnabled && !isOcrEnabled && message.channel.nsfw) {
        return false
    }
  ``` which is called from performAutomod, and it is called from messageCreate
which is
```js
if (message.guild != null) {
            // message.content
            [big chunk of code]
            if (!message.author.bot && !message.system) {
                await performAutomod(message)
                return
            }
            //if (message.author.bot) return
        }```
tardy sable

where are you calling the runImagesChecks function. looks like you arent passing the message properly

console log message channel in that function to be sure

median ferry

runImagesChecks(message, guildDb)

median ferry

only issue is that it only happens sometimes

the only thing I can think of is maybe the message was deleted before my bot passed the check

tardy sable
halcyon bison

the thing that's most curious is the error you receive TypeError: Cannot read properties of null (reading 'nsfw')
this suggests message.channel is null, but afaik, none of the message events emit if djs can't find the channel (this being the very reason the Channel partial is needed to receive dm messages)
so I'd be curious whether either message isn't a Message, or if something is potentially modifying message in the omitted code (leaning towards the latter given message.author.bot doesn't error)

eternal moth

How can I set a server-specific avatar for a bot?

I know that Dyno does this, but I searched the docs and couldn't really find how.

sharp ginkgoBOT
tribal birch

does members.fetch({ query: }) work with display name?

sharp ginkgoBOT
clear garnet

Discord doesn't actually have a concept of "display name", that's sort of d.js specific as a waterfall of nickname, global name, and username respectively

turbid flame

how do i make a /reload command? i don't wanna be restarting my bot each time for new changes on that code.

sharp ginkgoBOT

guide suggestion for @turbid flame:
guide Command Handler
The command handler, dynamically reads the command files and executes commands.

wary coral
turbid flame

thanks

main sail

hi how do i put audio file or a file inside container? im using the latest djs

odd stirrup

you can use a file component to put a downloadable file into a container, but it will not render as an audio player unfortunately, discord limitation

main sail

aw.. so it wont be clicable like a user sending mp3 file to chat yeah?

odd stirrup

if you want an actual audio player you just have to stick with non-components-v2

odd stirrup

they can download it, view it in a browser, whatever and play it like that

the file component lacks those nice features like an audio player or being able to quickly view the contents of a text file

main sail

yeah 💔 i applied and thanks, faceboy

grave trench

can we send components v2 in dms?

crimson gale

yes, why would you not?

send a dm is no different from sending a message to a channel in a server

grave trench

and can a message have 2 containers?

ye nvm it can

normal flare

in the event Events.MessageDelete, if the message is partial, there's no way to get its content right?

lunar quiver

if im setting the user roles with member.edit (array of multiple roles), but a role in the array is one the bot is below (no perms to grant such role), will all the other roles be still applied but still the action is gonna throw error, or non will apply?

crimson gale

latter, the api returns an error and discord.js rejects the returned promise

normal flare

is there a helper function to output a date like "Today at 4:00"

if not, how should I do it?

sharp ginkgoBOT

documentation suggestion for @normal flare:
function time discord.js@14.25.1
Formats a date into a short date-time string.

normal flare

yeah just saw is has more overloads, thought it only accepted 1 param (the date)

thanks

uneven plover

In general, how long does it take for djs to update to support a new feature (like the new invites endpoints)? I am legit curious. I love all the devs here do, and realize they are volunteers.

polar karma

it's varied from a few days or a week to months. the goal is to be quick about it, but sometimes it doesn't happen

tiny condor
uneven plover
polar karma

some things yes, others no

uneven plover
tribal hatch

Can anyone show me an example of using .addMediaGalleryComponents in ContainerBuilder? 😄

sharp ginkgoBOT

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

tribal hatch

blobreach

cerulean fable

do you guys put in the .env file also the guild and client id?

tiny condor

I have a config file where I have both env variables and non secrets

tardy sable
cerulean fable
require('dotenv').config();

module.exports = {
  token: process.env.DISCORD_TOKEN
  clientId: '123456789012345678',
  guildId: '987654321098765432'
};

like this?

tiny condor

Yeah that works

cerulean fable

so, it's like when you export functions in javascript, right? I am learning : )

tiny condor
cerulean fable

Oh ok

tiny condor
topaz bluff
cerulean fable
tiny condor
tiny condor
cerulean fable

Oh now I do

done

cinder osprey
tardy sable
cinder osprey

Hey, any idea? I just try to create a channel :

const newChannel = await guild.channels.create({
    name: `Channel de ${member.displayName}`,
    topic: `Channel privé (${member.id}) - créé <t:${Math.floor(Date.now() / 1000)}:F>`,
    type: ChannelType.GuildVoice,
    parent: autoVoiceCategory,
    permissionOverwrites: [
      {
        id: guild.roles.everyone,
        allow: [
          PermissionFlagsBits.Connect,
          PermissionFlagsBits.ViewChannel,
          PermissionFlagsBits.Speak,
        ],
      },
      {
        id: member.user.id,
        allow: [
          PermissionFlagsBits.Connect,
          PermissionFlagsBits.ViewChannel,
          PermissionFlagsBits.Speak,
          PermissionFlagsBits.DeafenMembers,
          PermissionFlagsBits.MuteMembers,
        ]
      },
    ],
});

And I get this error : ```bash
topic[CHANNEL_TOPIC_INVALID]: Field contains at least one word that is not allowed.

cinder osprey
tardy sable

try to remove the accents, if that doesnt work try to remove "prive"

cinder osprey

Oh

cinder osprey

Is it impossible to set a topic to a voice channel ?

jagged rock

is it possible to show ban length under guildbanadd event?

steel trail
tardy sable
steel trail

guildBanAdd emits for one single added ban

cinder osprey
steel trail

That's the error the API sends. Would need to tell discord

cinder osprey

Ahahah yea

jagged rock
crimson gale

firHmm not in guild_ban_add
if it's anywhere, then it's in the audit log

steel trail

If you mean the messages deleted by banning them that would be a messageDeleteBulk event, wouldn't it?

jagged rock
steel trail

That's not part of a GuildBan. Those are two separate actions stemming from a single API call. Banning and deleting messages. So unless the ban is done by your bot there is no way to know the timespan they selected

jagged rock
wary coral

The API routes are separate from gateway events. So while the ban route has an option to delete messages it does not mean that the gateway event Guild Ban Add should contain data of the deleted messages

prisma nest

i have this basic slash command which gets loaded but it doesnt run

import { SlashCommandBuilder } from "discord.js";

export const data = new SlashCommandBuilder()
 .setName("ping")
 .setDescription("Replies with Pong!");

export const execute = async (interaction) => {
 await interaction.reply("Pong!");
};

this in my index.js file

for (const folder of commandFolders) {
  const commandsPath = path.join(foldersPath, folder);
  const commandFiles = fs
    .readdirSync(commandsPath)
    .filter((file) => file.endsWith(".js"));

  for (const file of commandFiles) {
    const filePath = path.join(commandsPath, file);

    const command = await import(pathToFileURL(filePath).href);

    if ("data" in command && "execute" in command) {
      client.commands.set(command.data.name, command);
      console.log(`Loaded command ${command.data.name}`);
    } else {
      console.log(
        `[WARNING] The command at ${filePath} is missing "data" or "execute".`
      );
    }
  }
}```

Here when running the file i see the log `Loaded command ping` but when i do /ping in my server i see `bot doesnt respond in time`

my deploy-commands.js file - https://github.com/Shitanshukumar607/cp-dc-bot/blob/main/deploy-commands.js
on running the deployent file - 
```js
Started refreshing 1 application commands.
Successfully reloaded 1 commands.```
wary coral

look like you bot is not runing the execute fuction

odd stirrup

when in doubt, keep adding console.logs
everywhere from the start of the program up to the command

wary coral
wary coral

your bot is not running the command on the interaction create event. are you logging that event? Also you should read the guide

sharp ginkgoBOT

guide Command Handling
Unless your bot project is small, it's not a very good idea to have a single file with a giant if/else if chain for commands. If you want to implement features into your bot and make your development process a lot less painful, you'll want to implement a command handler. Let's get started on that! For fully functional slash commands, you need three important pieces of code:...

prisma nest

previously I was ngrok so I set the interaction endpoint on my bought removing that fixes

wary coral

👍

prisma nest

where did my thread go

wary coral

I closed it

prisma nest

okay thanks

fallow flax
wary coral
fallow flax

alright then, thanks

are there plans to support this in the future?

polar karma

ask discord

fallow flax

ok so it's a them thing

modest surge

quick question do i need to deploy global commands to use user-install commands

clear garnet

Yes. User-installed apps don't reside in guilds, so it doesn't make sense to deploy guild-specific commands

tame dagger

how to view server tag through api request

sharp ginkgoBOT
tame dagger

from server object not user one

bleak owl

it’s not documented

tame dagger

:( so theres no way i can show guild tag of the server in server info command

bleak owl

not at the moment, no

tame dagger
normal flare

how does dyno show deleted images? I tried implementing it but after a while the image would be 404

like this is from 2021

normal flare
tardy sable
normal flare

it's a cdn.discordapp.com link

topaz bluff
tardy sable

but they will expire once deleted?

topaz bluff

Looks like not immediately.. I went back in my own logs and saw several weeks back, deleted messages using discord CDN urls that were still funcitonal... when I went a month back, they were all image.png or something like that

unique shoal

They should be expiring much quicker than that, because the attachment is genuinely deleted

normal flare
rose tangle

like BakeWithMe said, it's resent

it's not the original image, that one is gone

a new attachment is created with the same data as the old image

normal flare
rose tangle

no, it's resent in the message

it's not linking the old image, it's resending it

scenic berry

Hello good evening everyone, i would like some help about cache limits, like how can i track welcome events without caching the members. And logging messages without caching the chats/message.

sharp ginkgoBOT

guide suggestion for @scenic berry:
guide Cache Customization
Sometimes, you would like to be able to customize discord.js's caching behavior in order to reduce memory usage. To this end, discord.js provides you with two ways to do so: 1. Limiting the size of caches. 2. Periodically removing old items from caches. Customization of caching behavior is an advanced topic. It is very easy to introduce errors if your custom cache is not working as expected.

stable sun
scenic berry

And i dont want to use the member cache so i wont use so much ram

stable sun

You need to keep the member cached while they are pending

Then you can sweep them afterwards

sharp ginkgoBOT
stable sun

Or just uncache them yourself I guess

scenic berry

I cant uncache it everytime🥲

So btw i just use the time sweeping like that?

stable sun
stable sun
scenic berry

Ok thanks, btw how can i use the limit and timer when the old cache to be deleted?

stable sun

Prob should have the timer bc certain events will cause members to be cached

stable sun

Limit is just a maximum number of items that the cache is allowed to hold

scenic berry

Ok thank you

vague tendon

how can i reconstruct an interaction from json?

loud quartz

reconstruct? from what json?

vague tendon

lets say i want to use certain methods on an interaction after i restart the bot

i thought of storing the toJSON() of it

but then i would need to create a new instance of the interaction class

tardy sable

what exactly is the use case cuz theres probably a better way than storing the entire interaction?

loud quartz

that would be replaying same interaction

and that's rarely a good idea because of how they work

vague tendon
loud quartz

you have 3 seconds to respond to all interactions, and after you do so the interaction token stays up for only 15 minutes

you'd have to have separate handling for replayed ones because you can't treat them as new ones

vague tendon

didn't know it had a time limit of 15 minutes, i won't try to do it anymore

tardy sable

better to store the message id then and do with it what you want later

loud quartz

that isn't really useful though

interaction doesn't have much use of message id, because it's just a fancy webhook and its token expires

and to reply to that message you would need a bot member in the channel

which goes quite against the flexibility of app commands

jagged rock

can you show role ids when accepting invite in the invite create event

tardy sable
wheat gulch

how to make a special command such as /restart only to be seen by some specific persons. I mean I know how to deny users' commands and fail them but I want my restart cmd only to be seen from me not by any1 else

loud quartz

or expose that anywhere

tardy sable
wheat gulch

wb setDefaultMemberPermissions?

tardy sable
wheat gulch
tardy sable
wheat gulch

I want to apply it generally moreover does "setDefaultMemberPermissions" does it hide the command?

tardy sable
wheat gulch
wheat gulch
tardy sable

personally i wouldnt have a restart command if your bot is in multiple servers

wheat gulch

so wait you say setDefaultMemberPerms makes the command hidden except the perm writen there

loud quartz
wheat gulch

alright alr thanks yall

lunar quiver

when you create a new custom emoji, of which icon is from an already uploaded emoij ( publicly available cdn url)
is the next uploaded emoji id randomly generated, or will it have the same id?

proud arrow

Wouldn't be unique if it was same

median ferry
median ferry
lunar quiver

Can u access bot uploaded emojis through the new client, or can it be only through rest api?

sharp ginkgoBOT

method ApplicationEmojiManager#create() discord.js@14.25.1
Creates a new custom emoji of the application.


// Create a new emoji from a URL
application.emojis.create({ attachment: 'https://i.imgur.com/w3duR07.png', name: 'rip' })
  .then(emoji => console.log(`Created new emoji with name ${emoji.name}!`))
  .catch(console.error);

lunar quiver

the ones you can manually upload here I mean

polar karma

if you want to access ones that are already present, then you need to fetch them to populate the cache, then you can get them from the cache afterwards

lunar quiver

but can i do that thorugh the client or only rest api?

tardy sable
boreal olive

is this a known issue?

error occured when i joined in the vc defined in JTCConfig.channelId

channel was created..

zinc folio

@analog grail

rose tangle

that's not an "issue", it's how javascript works

you need to bind it again or just not store setChannel separately

sharp ginkgoBOT

mdn Function.prototype.bind()
The bind() method of Function instances creates a new function that, when called, calls this function with its this keyword set to the provided value, and a given sequence of arguments preceding any provided when the new function is called.

boreal olive
halcyon bison
median ferry
halcyon bison the thing that's most curious is the error you receive `TypeError: Cannot read p...

the only modified message values of message are this

    // @ts-ignore
   message.start = Date.now();
    const guildDb = await guild.getGuild(message.guildId, message.guild.name);
    // @ts-ignore
    message.dbconnection = Date.now() - message.start;```
to be able to access such values inside the automod functions. Other than that the message is not modified and message has to exist somewhere because if not the db query would fail so idk this is very weird
median ferry
halcyon bison
median ferry the only modified message values of `message` are this ```js // @ts-ignore ...

even if it's to access such values inside automod functions, I wouldn't recommend modifying djs structures

Other than that the message is not modified
it's hard for us to verify this given that we can't see your code, so it'll be really hard to help further
as mentioned previously, messageCreate shouldn't emit without the channel, so feel free to log throughout to see if/when message.channel becomes null
it'd also probably help if you were able to reproduce the error

stable sun

You should use helper functions rather than sticking stuff onto classes you didn’t make

turbid flame

can the ContainerBuilder() hold an embed? Reason why i'm asking is because I don't like how to image looks using the ImageGallary, but with embeds the image stays in one size.

loud quartz

embeds are a different and a mutually exclusive thing than components v2

turbid flame

alright, thanks

analog grail
jagged rock
wary coral
jagged rock
wary coral

ya but it is not in the api docs

pulsar venture

can a bot check a user's tag?

sharp ginkgoBOT
wary coral
crimson gale
crimson gale
wary coral

ya, they send the whole role object

proud arrow
loud quartz

but doesn't the new thing allow selecting more than one role?

proud arrow

Otherwise just the id doesn't tell you anything if you can't fetch roles

crimson gale

true, prob. needs it to display the role(s) on accepting the invite, good point

loud quartz

-# missed opportunity for an InviteRole

tiny condor

invite role added??

OMG IT ISSSSSSSSSS
(wrong chat forgive me)

jagged rock

yup now discordjs pls add

bleak owl
jagged rock
bleak owl

no

jagged rock

autoroles kinda pointless now wonder what happens if its a diff invite link

bleak owl

feel free to ask discord

tribal birch

is it worth fetching new member if its partial on guildMemberRemove

bleak owl

what information do you need from that event?

loud quartz

what member would you fetch when in that event they explicitly stop existing as a member

loud quartz

no, you can't fetch what no longer exists

tribal birch

i would need joinedAt and roles

loud quartz

same as you can't fetch a deleted message

then you need to have that in cache

discord only sends user and guild ids in the event

slender stag
ruby bane

the property youre looking for lies on the ForumChannel class

sharp ginkgoBOT
slender stag

thank you

ruby bane

(the setter is also on that class)

slender stag

wait i know this guy Susge

ruby bane

:)

subtle girder

why BaseInteraction<CacheType>.channel might be null?

ruby bane

if the interaction isnt in a (cached) guild, channel can be null/nullable

subtle girder

okay thx

autumn tendon

Hi. I'm trying to get channel's name from ChatInputCommandInteraction's property channel, but I don't know where it's the name. I don't see a name property or anything like that

Where can I get it?

ruby bane
autumn tendon
ruby bane

could just do an if check with channel.type

autumn tendon

cupcakeCat

warm charm

hey, did component v2 can use animated emoji?

steel trail

It can all markdown, yes

warm charm

oh ty, cause im trying use it but doesnt work

topaz bluff
warm charm

Because that's not how you render custom emoji

<:NAME:ID> for static emoji and <a:NAME:ID> for animated emoji

warm charm

ty

low spear

is it still possible to have your bot appear as typing?

sharp ginkgoBOT
low spear

cheers

spiral wyvern

Is there a enum for intents?

hallow mesa
sharp ginkgoBOT
dry flame

Anyone else's apps getting a bunch of internal server errors from Discord's API?

zinc folio
vague tendon

how can i listen for removed reactions using a reaction collector?

tardy sable

nvm probably when you enable dispose in the collector

sharp ginkgoBOT
vague tendon

so i can listen for both remove and collect with the same collector??

topaz bluff

Yes but they're separate events. So collector.on("create", (reaction, user) => {}) and collector.on("remove", (reaction, user) => {})

upbeat cedar

Hi, Discord added a new feature when creating an invite to choose which role to assign to the user. How can I see through the bot what roles the user has selected when creating an invite?

topaz bluff

DJS does not yet support that... if you want to use any part of that change, you'll have to use RAW API requests

upbeat cedar
const res = await fetch(
  `https://discord.com/api/v10/channels/${CHANNEL_ID}/invites`,
  {
    method: "POST",
    headers: {
      "Authorization": `Bot ${BOT_TOKEN}`,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      max_age: 0,
      max_uses: 5,
      temporary: false,
      flags: 0,
      role_ids: []
    })
  }
);

const invite = await res.json();
console.log(invite);```
topaz bluff
analog grail
stable sun

You will have to find the endpoint to fetch the invite yourself with the roles field

bleak owl
analog grail

hello, ok

zinc folio
bleak owl
frosty epoch

an interaction reply can only be setn to the same channel it happened, or is there a way to override it to another channel?

wary coral

Correct

odd stirrup

i hate this language

rose tangle
frosty epoch

tho i can send a message as ephemeral, regardless if it's an interaction? or ephemeral are only allowed on interaction replies?

bleak owl

ephemeral messages are only allowed from an interaction reply

frosty epoch

bummer
It'd be quite cool to send any message as ephemeral

crimson gale

true, it'd also be absolutely horrific

topaz bluff

that could be easily abused

tiny condor

It would be nice if we could send ephemeral messages as a reply to messages that mention the bot

rose tangle

I'm pretty sure that gets you ratelimited

why would you want that anyways

even if it didn't

odd stirrup

yea assuming you need some up to date record of whats going on with ur members, you should be able to just cache them and only do a full fetch on startup

tribal birch

i mean

when i do is fetch them on startup and i have all intents enabled like Guilds, GuildMembers

then i have guildMemberRemove event and i send log to channel when someone leaves

in embed i use data like joinedAt and member role names

and sometimes it displays as N/A like member wasnt ever cached even they should be

frosty epoch
tribal birch

but how can it be partial if i fetched everyone and i have all the intents + partials

frosty epoch

thought that data came directly from discord

rose tangle

can you show your client constructor?

tribal birch
rose tangle

what?

tribal birch
const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMembers,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
    GatewayIntentBits.GuildModeration
  ],
  partials: [Partials.User, Partials.GuildMember, Partials.Channel]
});
topaz bluff

you have the GuildMembers intent... you don't need to fetch the member list more than once

rose tangle

how do you know you're getting partial members on leave?

tribal birch
tribal birch

and also member.joinedTimestamp ?? 'N/A' returns N/A sometimes

rose tangle

are you sure you aren't touching the cache somewhere?

tardy sable

also youre sure youre fetching members once on startup? @tribal birch

tribal birch

my bot is small its just for this

tardy sable

show the code where youre fetching members and where youre using members

tribal birch
private async fetchMainGuildMembers() {
  const mainGuild = await getGuild();

  if (!mainGuild) {
    this.container.logger.error('Main guild not found');

    process.exit(1);
  }

  const members = await getMembers();

  this.container.logger.info(`Fetched ${members.length} members from the main guild`);
}
export async function getMembers(guildId = process.env.GUILD_ID) {
  try {
    const guild = await getGuild(guildId);

    if (!guild) {
      return [];
    }

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

    return Array.from(members.values());
  } catch {
    return [];
  }
}

and then i just have guildMemberRemove event for sending embed as mentioned above nothing special

tardy sable

isnt anything wrong with that, maybe memory leaks idk?

when is the max length error getting fixed for modals string select menu labels? has been reported for a while and still no fix pushed

might be low priority cuz im the only one using strings longer than 45 charc in labels?

shrewd basin

The ready event has been renamed to clientReady to distinguish it from the gateway READY event and will only emit under that name in v15. Please use clientReady instead.

I keep getting this, im using gcommands (10.0.0) alongside discord.js (v14.25.1). Is this just a warning that can be ignored if I already use clientReady instead of ready?

Does this show regardless until v15?

topaz bluff

yes, that's what a Deprecation warning is... it means something is no longer recommended to use and is planned to break in the future

given that literally all you need to do is rename a string from "ready" to "clientReady".... you have no reason not to do it

shrewd basin
topaz bluff

no it doesnt... it only shows if the "ready" event is being used

shrewd basin

but it's not lol

topaz bluff

it should tell you the flag to add to your run script to trace where it's being called

rose tangle
grave trench

can we fetch a discord message author using message link

clear garnet

You can parse the guild, channel, and message ID out of the message link, and use those to fetch the message itself which would then give you the author

indigo yarrow

is there any guide for embed v2 ?

clear garnet

There is no embed v2

indigo yarrow
clear garnet

That would be components v2

indigo yarrow

yea

sharp ginkgoBOT

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

indigo yarrow

ty

grand bridge

How to edit button of an action row on button press in ContainerComponent?
I am adding it like this, but on button interaction how do I edit it?

containerBuilder.addActionRowComponents(
    new ActionRowBuilder<ButtonBuilder>()
        .addComponents(
            new ButtonBuilder()
                .setStyle(ButtonStyle.Primary)
                .setCustomId(`book-paginate-left-${ books.totalPages }`)
                .setEmoji({ id: "1461417930804822098" })
                .setDisabled(true),
            new ButtonBuilder()
                .setStyle(ButtonStyle.Primary)
                .setLabel(currentPage.toString())
                .setCustomId("current-page")
                .setDisabled(true),
            new ButtonBuilder()
                .setStyle(ButtonStyle.Primary)
                .setCustomId(`book-paginate-right-${ books.totalPages }`)
                .setEmoji({ id: "1461417743608971306" })
                .setDisabled(books.totalItems < 20),
        )
);
stable sun
grand bridge
stable sun

A helper function that returns the components

You could convert interaction.message.components to builders, but editing nested components isn’t pretty

grand bridge

yeah, it’s just seem like really inefficient if i need to rebuild every time

stable sun

That’s how the Discord api is

Can’t just tell Discord "only update this button text"

grave trench
snow onyx

fetching the message includes the content, if you have the message content intent

stable sun

*intent

snow onyx

yes

unreal stone

Hi! I have a question :)
I want to make a command from my bot that can be used in all context (guild, botDM & privateChannel), but I noticed that the commands "appear two times" in the bot list if the bot is installed on the server. It is possible to prevent that?

snow onyx

just create global ones

rough sinew

I have a question regarding bot connectivity, why does my bot keep disconnecting when i run a specific Slash Command

ionic lance

its probably crashing

do you have any logs in the terminal when this happens?

rough sinew

Yes

ionic lance

show them

rough sinew

I didnt run it today codes on usb and thats with someome rn, i was just asking for the purpose of when i rerun it again what should i do

But ill send as soon as i get on it

ionic lance

do you have the code of it? the error is most likely where the slash command code is running

rough sinew
ionic lance

just the code of the slash command that is failing

coral maple

Is there any timeout limit for autocomplete? because I keep getting an Unknown Interaction error

tardy sable
coral maple
topaz bluff

Caching. And expect that the first interaction will fail

There's no way to defer an autocomplete interaction

grave trench

can we make a slash command disabled in a guild?

and can we edit its aruguments per guild? like in a guild a arg is required in another its not

tardy sable

and yes you can register commands per guild

grave trench

okeee

grave trench
tardy sable
grave trench

autocomplete? i don't want that? i am talking about different strings like one server will have string laptop and other guild do have PC

halcyon bison

yes you can have predefined choices (not just for string options)
no they cannot be different per guild

sharp ginkgoBOT

guide Choices
The String, Number, and Integer option types can have choices. If you would prefer users select from predetermined values rather than free entry, choices can help you enforce this. This is particularly useful when dealing with external datasets, APIs, and similar, where specific input formats are required. If you specify choices for an option, they'll be the only valid values users can pick!

steel trail

Of course they can be different per guild. You'd just need to deploy them as guild commands then, not global

grave trench

okee

wheat gulch

.setDefaultMemberPermissions(PermissionFlagsBits.KickMembers | PermissionFlagsBits.ManageGuild),

is this a valid thing in discordjs?

abstract mortar

Would anyone happen to know why my bot is receiving messageUpdate on like multi year old messages

I got one for a message from 2021. But the kicker is that the message wasn’t even changed at all, no edit according to discord. What the hell is going on?

wheat gulch
topaz bluff
wheat gulch it didnt work. I wanna add OR ( || )

|| is logical OR and returns a Boolean which is not a valid input for that method

| is BITWISE OR, which is used in this circumstance to combine the permission bit flags of several permissions into a single int (which is how permissions are defined and used)

wheat gulch

so I cant set both manageguild and kickmembers to see a slashcommand

steel trail
wheat gulch

since there is no perm hierarchy between them and considered different

topaz bluff

No. You can't set it so they need both

abstract mortar
tardy sable

messageupdate does not always mean the message has been edited

abstract mortar
bleak basin

Hi everyone. I have a question about the 'Per Guild Bot Profiles' feature (#1040031099860045854 message & #announcements message) . I am planning to allow my premium users to customize my bot's avatar and bio for their specific servers via my web dashboard. My concern is about Trust & Safety: If a user uploads a ToS-violating image (NSFW, etc.) as the bot's guild avatar via my dashboard, is my bot application held responsible for this action since the API request comes from my bot? Does Discord differentiate between the bot owner's action and a user-triggered action in this context? Thanks!

tardy sable
topaz bluff
hardy minnow

what does this error mean?

trying to use components v2 with 3 containers with content inside of each

topaz bluff

Do you have the IsComponentsV2 flag on your send payload?

hardy minnow

oh, idt so, let me add that

so like this?

topaz bluff

flags: MessageFlags.IsComponentsV2

hardy minnow

That worked! Thank you!

topaz bluff

Be aware that, adding that flag is irreversible and removes the content and embeds field from the message. You can't later remove the flag and for an embed

bleak basin
hardy minnow
untold skiff

Can a discord bot upload custom emojis to the discord developer portal by itself?

sharp ginkgoBOT

method ApplicationEmojiManager#create() discord.js@14.25.1
Creates a new custom emoji of the application.


// Create a new emoji from a URL
application.emojis.create({ attachment: 'https://i.imgur.com/w3duR07.png', name: 'rip' })
  .then(emoji => console.log(`Created new emoji with name ${emoji.name}!`))
  .catch(console.error);

topaz bluff

@untold skiff yes... you can create Application Emoji by using that above (the ClientApplication object can referenced from the bot Client using Client#application)

untold skiff

Appreciate it

queen vale

Remind me - bots can post in embeds 4000 chars right?

topaz bluff

6000 total characters across the entire embed

queen vale

Thanks - is it the same for containers too?

topaz bluff

No. Text Displays max at 4000 characters

queen vale

4000 is good enough for me - better than 2000

    await indexChannnel?.send({
      components: [
        new SectionBuilder().addTextDisplayComponents(
          (text) => text.setContent(`# (${thread.name})[${thread.url}]`),
          (text) => text.setContent(content[0].join("\n")),
        ),
      ],
      flags: [MessageFlags.IsComponentsV2],
    });

What am I doing wrong here?

      throw er; // Unhandled 'error' event
      ^

CombinedError: Received one or more errors
bleak owl

your section is missing an accessory like a button or thumbnail. if you dont need to use either of those, just use a text display itself

onyx lagoon

Is there an way of mocking the discord.js client for unit tests in vitest?

rose tangle

what do you want to test specifically?

serene robin

Am I able to make a command with the name coins enable and coins disable or would it have to coins as the command name then sub commands for the disable and enable?

rose tangle

the latter

command names can't have spaces

serene robin

SA_catThumbsUp

odd stirrup
topaz bluff

From my understanding, yes. But feel free to test it to confirm

odd stirrup

oh thats not easy to test when my bot is user installed on my account

odd stirrup

viewing server as role, only manage guild doesnt show it, but manage guild + roles does

odd stirrup

do check for yourself just in case using this, but i believe specifying multiple permissions for defaultMemberPermissions does require them all

ionic lance

those permissions dont work outside guilds anyway, unless im misunderstanding you

odd stirrup
ionic lance invite it to a guild

it's in a guild, i had to uninstall it from my account for my own user-installed access to that command to stop masking the access to that command from the bot being in the server

sharp ginkgoBOT

discord Application Commands - Application Command Permissions Object
The default_member_permissions field can be used when creating a command to set the permissions a user must have to use it. The value for default_member_permissions is a bitwise OR-ed set of permissions, serialized as a string. Setting it to "0" will prohibit anyone in a guild from using the a is...

rose tangle

the permissions a user must have to use it
sounds like it requires both

marble plover
noble cairn

I swear you used to be able to embed members... is there another way or am I just SOL

rose tangle

you can't in field names

sharp ginkgoBOT

You can use markdown syntax to display clickable links without showing the url:

"[text](url)"
'[text](url "optional hovertext")'
"[text](url 'optional hovertext')"
  • Embeds only support this in description and field values

Some parts of an embed will not properly resolve mentions (leave them in the @sharp ginkgo format):

  • Author name
  • Footer text
  • Embed title
  • Embed field name
noble cairn

thanks 🙏

noble cairn

and I'm back!

I'm receiving "Interaction has already been acknowledged." when it, as far as I know, should have been caught by the or:

return (interaction.replied || interaction.deferred)
    ? await interaction.followUp(options)
    : await interaction.reply(options) // error occurs here
;
noble cairn

any help appreciated, as always 🙏

agile birch

HELP ME
How can I attach buttons on an embed?

sharp ginkgoBOT

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

coarse storm

Does the WebhooksUpdate event include deleting a webhook?

stable sun
steel trail

But the event doesn't tell you what changed. Just where it changed

worthy plaza

How to register slash commands to user install using <Client>.application.commands

naive hull

hello

can someone explain me how to make a wehbook send cv2?

opal river
Argument of type 'Guild | null' is not assignable to parameter of type 'Guild | null | undefined'.
Type 'import("d:/DRX/Visual Code Studio/DRX/v2.1/Estate/node_modules/discord.js/typings/index").Guild' is not assignable to
type 'import("d:/DRX/Visual Code Studio/DRX/v2.1/Estate/node_modules/discord.js/typings/index").Guild'.
Two different types with this name exist, but they are unrelated.
Types have separate declarations of a private property '_sortedRoles'.```
[#djs-help-v14 message](/guild/222078108977594368/channel/824411059443204127/p/1459919287329361971/#msg-69bccd7c9519181909620bb7)

I'm about to lose my mind
Does anyone know why this happens?

I tried so many things
and it's still the same

marble plover

you seem to be having some weird paths going on? did you clone "DRX" many times?

d:/DRX/Visual Code Studio/DRX/v2.1/Estate/node_modules/discord.js/typings/index
d:/1 DRX/Visual Code Studio/DRX/v2.1/Estate/node_modules/discord.js/typings/index
opal river
topaz bluff
marble plover

i still dont understand why discord make webhooks have to add that query param, everywhere else its fine to just use flag

opal river
opal river ```js Argument of type 'Guild | null' is not assignable to parameter of type 'Gu...

In case anyone else encounters a similar issue, it is related to a library called CommandKit
Happens when you pass a Discord.js class that comes from CK to a function that references Discord.js type
In this case I was trying to pass in Guild | null (which comes from EventHandler's client -> client.guilds.cache) to a function in another file
and in that file I was importing Guild from discord.js
Using "module": "preserve" and "moduleResolution": "node" fixed it for me

naive hull
topaz bluff

What's the error? Can you show the code?

wary coral
sharp ginkgoBOT
crystal tiger

not related to v14, but how do i install 15 dev?

topaz bluff

npm install discord.js@dev?

But importantly, why do you want to use v15 dev?

It is not intended to be used in a production environment and has little to no documentation

crystal tiger

It is not intended to be used in a production environment
as long as its an internal endpoint who tf cares lmao

why do you want to use v15 dev?
because it has some features the v14 doesn't have

can't remember exactly what i used from it, but i forgot how i installed the dev package

it was something related to profile store stuff iirc

collectibles !

topaz bluff

v14 should have all documented API features other than the new invite methods

sharp ginkgoBOT
topaz bluff

Collectibles are very much available in v14

wary coral
naive hull

idk, it shows me that the ContainerBuilder() isnt availbale

topaz bluff

What version of DJS do you have installed?
npm ls discord.js

naive hull

ohk

i'll try

"Webhooks that are not owned by an application cannot use interactive message components"

topaz bluff

Exactly as the error states. You cannot use interactive components with a webhook that wasn't made by the bot

That means no buttons or select menus... Just text and pictures

naive hull

oh,ok

wary coral

* link buttons will work

sharp ginkgoBOT

method TextChannel#createWebhook() discord.js@14.25.1
Creates a webhook for the channel.


// Create a webhook for the current channel
channel.createWebhook({
  name: 'Snek',
  avatar: 'https://i.imgur.com/mI8XcpG.jpg',
  reason: 'Needed a cool new Webhook'
})
  .then(console.log)
  .catch(console.error)

topaz bluff

You can create a webhook using the app for things like that to work... Or just send a message to the channel instead of it being a webhook at all

naive hull

but how can i make an app own a webhook?