#djs-help-v14

78874 messages · Page 71 of 79

loud quartz

if not, not really much we can do here

give your bot an admin and try again

if it works, then something is up somewhere, but completely on discord's side

if it doesn't.. well, exactly the same but slightly worse

red coral

I’m just trying to prevent errors ig, missing permission errors I feel can be easily checked for and prevented. I don’t think I’m missing any permissions as I remember having a chat about it here a while back

loud quartz

there are sometimes cases of state mismatch on discord's side, that's possible too albeit quite rare

okay, but

red coral

I can also update djs too. And yes I’m aware you can’t prevent all errors

loud quartz

it's not even about that, really

few people here looked, none can see from what you provided why would that be the case for sending a message

red coral

I did fetch the channel too

Ok, I can see if I’m missing anything else but I basically gave everything tbh

loud quartz

wdym

red coral

As in I gave all relevant pieces of code so I can’t see anything else. But I can check again when we reboot later

loud quartz

give the bot admin and try again

coral siren

Hello, I'm at a loss, apparently my way of handling pings stopped working for some people using the desktop version of Discord. While investigating why my regex wasn't working, I wasn't seeing anything wrong, and I came across something interesting. I tried logging the bytes array, and sure enough, there were intruders.
The correct one was this :
3c403533373939363132303437313736353031383e
⁨@spring cypress
And the incorrect one is this :
e281a83c403533373939363132303437313736353031383ee281a9
⁨@spring cypress⁩
Did someone notice any change in how discord sees pings?

halcyon bison
coral siren Hello, I'm at a loss, apparently my way of handling pings stopped working for so...
  1. no there hasn't been any recent change in how discord formats/parses mentions
  2. given that you appear to be asking about your own custom regex, and I'm unsure at what point you'd receive message content as hex from discord.js, I'd guess this isn't related to discord.js
  3. if you are using discord.js (or frankly even if you're not), you may want to look into ⁨MessageMentions.UsersPattern
coral siren
halcyon bison 1. no there hasn't been any recent change in how discord formats/parses mentions...

Hmmm ok, thank you, I mean it's still weird because it started happening to several people recently but ok YaeThink_Karandrawz
My regex is just ^<@!?\d+>$ so it should work (I think?), and apparently it's more or less the same that's used in the UsersPattern ? I didn't know about this though, thanks.
And I am using discord.js, I just tried to do new Buffer(message.content).toString("hex") just to see if there were additional characters that aren't displayed correctly, because I couldn't see what else could be different

sharp ginkgoBOT
halcyon bison

@mint eagle please use #app-commands for personal use of the bot

halcyon bison
coral siren

I totally agree with you, and here I only noticed it because I wanted to match only a mention without any additional characters
Which is why I asked about if there was an update or something
Funnily enough, when the person for whom it didn't work tried on their phone, it worked KokoroThinking

coral siren
iron needle

Can you detect an activity start with interactionCreate or some kind of similar event?

lunar pasture

without action rows, how are you supposed to put multiple inputs in the same row in a modal now?

unique shoal

You still use action rows... I dont understand the question

lunar pasture

Okay, I'm struggling a bit with what method to use on a ModalBuilder to insert a row

unique shoal
lunar pasture

I was aiming to have two adjacent tiny text inputs

unique shoal

Sorry, Im mixing it up with containers

Adjacent text inputs arent a thing

tardy sable
dark canyon

i can't fix this without downgrading to discordjs v13 should i even care about these "vulnerabilities"

unique shoal

no

lunar pasture
languid flax

Guys whats the best free or cheap Website to host bit 24/7

languid flax
coral siren
versed bobcat
coral siren

I'm just trying to grab the mention, but because it was failing my check for no apparent reason, I looked into it, and it appears that it's because of some random added characters..?
And those added characters are only there for people on pc or browser, not on mobile (I think)

Like, instead of getting <@....>, I get 0xe281a8<@....>0xe281a9

unique shoal

As in the person sending the mention?

coral siren

As in it appears that something is added when someone pings someone else and the bot reads the message ThinkGura

(so it fails when I try to match it with a regex and I'm sad)
I mean, an "easy" fix would be to add those characters to my regex as optional, but that doesn't sound like a very good idea if it's a bug or something already

shut musk

I've heard discord has broken something with mentions adding some kind of invisible characters to the front of the message

Unsure if that's the case here or not but that's surely the message from Poketwo devs however that's the first time I've seen anyone mention it so I doubt it's exactly the case but keep aware

shut musk
golden laurel
golden laurel
shut musk

So I expect this to be rolled out to all versions soon or later too

coral siren

And from my browser : ⁨@golden laurel⁩

amber spruce

is there a type that is compatible with ⁨Message#toJSON⁩? ⁨APIMessage⁩ doesn't seem to fit that bill since it uses pascal_casing, while toJSON is outputting camelCasing

candid quail

how would i remove a cooldown if the command ran unsuccessfully?

unique shoal

Cooldowns are custom implementation, so I'm not sure how to answer that

Simply... dont set it

golden laurel
coral siren Sure, here's a ping from my phone : <@618976181026422814>

Interesting, I see it in your mobile message! I CNR on stable, PTB, and canary on desktop, but I can reproduce on mobile alpha. This is unfortunate lol. But regardless, it shouldn't break how one uses a regular expression for mentions as the mention is still there fine. Would suggest you investigate into it

unique shoal

Would only break if you're using start/end qualifiers or something

Testing that a message is ONLY a mention

coral siren
loud quartz

So you're saying twice that it doesn't happen on desktop but on mobile, and Jira confirms they can do that only on mobile too

coral siren

The thing is :
The person who initially reported this to me said it didn't work on desktop, and it works on mobile
When I try it, it worked on my phone and not in my phone's browser
Someone else tried on their phone and it didn't work
So I don't know what to believe anymore psyko_think

But as long as it's fixed sooner or later, it's fine..?
And I can tell my users to use the ID instead of the mention in the meantime (since it works as well)
Of course, it would be best if it was possible to fix it or if the change was consistent

loud quartz

Browser has different versions too but at the end of the day.. it's not mobile app

Desktop app is just browser (that's what electron is, basically)

Anyway, it's a mobile thing

rustic seal

Hello little question is there a way to make a protection against self bots like the bot can recognize a self bot?

crimson gale

a self bot is just a program that listens for incoming messages with a specific pattern on a user account and responds with a rest call to the discord api
i'm not sure how you expect to discern those?

if you can find some good heuristics on it, sure, but it's not a native thing

or do you mean user-installed slash commands? (since that confusion happens quite often)

dire iris

TypeError: guild.members.editMe is not a function
Are you joking me 😭
js await guild.members.editMe({ avatar: imageUrl || null, });

this was working few days ago now it's not

😭

have discord already updated it?

crimson gale

probably not using the right version of discord.js

dire iris
vocal garnet

is there an event that fires when a user changes their guild tag?

dire iris

was a mismatch

dire iris
rustic seal
crimson gale

recognizing implausible behaviour isn't trivial. that being said "changing role color every second" was typically done through bots, not automated user accounts

fleet spire

this might be more of a node question then a djs question but, is there some sort of tick/loop I can hook into? I essentially want to be semi frequently do xyz

for example, every 5 minutes or so update the bots status based on certain stuff

velvet cipher

You could just use a ⁨setInterval⁩, no?

lament moss

how to track boosters using messageCreate

polar karma

Check the message.type

fleet spire
sharp ginkgoBOT
lament moss

thanku

polar karma
fleet spire

no worries, thanks

rustic seal
marble plover

discordjs can send & build components v2 messages!

pseudo kettle

Hey, is there a utility method to get all the guilds a member is in AND where the client is part of?

tardy sable
pseudo kettle

Yea that was plan B haha, but before I did that I was curious if there isn't already a build-in method for that

tardy sable

Thats pretty much the easiest way and isn’t something difficult

pseudo kettle

True

marble plover
pseudo kettle

normal bot querying

marble plover

cool cool, isnt the "where the client is part of" inherent then, as you cant casually see other servers data

also if your bot is in big servers that may be fun because surely you dont want to cache everything

(and assuming you even have guild members intent to get more knowledge about them)

pseudo kettle

The idea was just 'How can I get all the guilds where a user and my client are mutually part of'. Sure I can iterate over the client guilds, but I was wondering if there is not a utility method for that.

marble plover

ya, i wish discord themself gave us the api that normal users can use (there is a request on the github)

thin reef

is there a builder for polls?

proud arrow

There is but it seem to be only available in the dev version of the builders

earnest forge

Is there any new information on this?

loud quartz

if anything, i'd rather disable npm audit instead

earnest forge

okay thanks for the info.

neat nimbus

when i restart my bot then and try delete messagges it doesnt log it ?

sharp ginkgoBOT

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

neat nimbus

⁨⁨⁨```js
super({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.GuildVoiceStates,
],
partials: [
Partials.Message,
Partials.Channel,
Partials.Reaction
]
});

[ERROR]: Could not fetch partial message: DiscordAPIError[10008]: Unknown Message
[ERROR]: Could not fetch partial message: DiscordAPIError[10008]: Unknown Message ?

tardy sable

On bot startup old messages are out of cache so partial

neat nimbus

?

⁨⁨```js
module.exports = async function (bot, con, cfg, m) {
if (!m.author || m.author.bot) return;
con.query(SELECT * FROM data WHERE id = ?, [m.guild.id], async function (e, row) {
m.guild.fetchAuditLogs({ limit: 1, type: 72 }).then(function (Logs) {
if (!row[0]) return;
SendAudit(m, 'messageDelete', new bot.djs.EmbedBuilder()
.setColor(row[0].color)
.setAuthor({ name: "Message Deleted", iconURL: bot.user.displayAvatarURL() })
.addFields([
{ name: "Author:", value: ${m.author.tag} (${m.author.id}) },
{ name: "Channel:", value: <#${m.channel.id}> },
{ name: "Deleted By:", value: Logs.entries.first().executor.tag },
{ name: "Content:", value: m.content ? m.content.substring(0, 1024) : "No content" }
])
.setTimestamp()
);
});
});
}

super({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.GuildVoiceStates
],
partials: [Partials.Message, Partials.Channel, Partials.Reaction]
});

iron fable

I want to delete the message & give timeout the executed user and this bot is not inside the server but it spamming and this feature i wanted to implement in my bot

tardy sable
iron fable
radiant tulip

.setDMPermission(false), this is removed right? what I should use now?

sharp ginkgoBOT
tardy sable
neat nimbus
topaz bluff
marble plover
tardy sable
neat nimbus any idea?

As i already said theyre gone from the memory on startup. So unless youre not saving them anywhere you have to fetch them before they get deleted

neat nimbus

what i mean is the message still in discord server and the bot restart but when i delete that message doesnt work

tardy sable

Doesnt mean its in discord thats it also in your bot

neat nimbus

thats stupid

tardy sable
neat nimbus
crimson gale

discord emits MESSAGE_DELETE with message id and channel id only
we can only emit it on discord.js with the message payload if we had that message cached before

you cannot fetch it, if the data is not cached, because it was deleted off discord's service

neat nimbus

just stupid if i delete a message on discord it should still log

crimson gale

you don't listen

neat nimbus

ik what your saying but still stupid

crimson gale

you don't

else you wouldn't be calling it stupid

where are we supposed to get data that's been deleted?

neat nimbus

I have not got a clue just other bots i did for logs have never did thisa

crimson gale

there is literally no way to do this

you are misinterpreting what other bots do then

neat nimbus

guess i just have to stay how it us

marble plover

they generally have a huge message cache in things like redis, but that gets decently expensive

esp as there has to be some age cut of point where they may just give up and not store it anymore

neat nimbus

I understand how it works technically now, I’m not disputing that. I just mean from a user perspective it feels frustrating like if the bot restarts for an update and someone deletes a message from a couple of hours ago, it doesn’t get logged. I get why that happens, I just think it’s annoying behaviour, that’s all.

topaz bluff
neat nimbus

true but dont want to make everyone setup a redis server just todo that

steel trail

Then don't make everyone self-host your bot

neat nimbus

fair

this only for messsage logs right?

topaz bluff

I mean there's other things that the bot loses on startup. Like thread channels and guild members... There's a lot that can be lost on restart

Just depends on your application and what you want stored after restart

neat nimbus

I have all role channel and message events and voice events to

marble plover

sometimes i wish more people used @discordjs/core to realise how much cache powers all and have to implement stuff themself, but i know they will generally implement cache worse than djs does normally

topaz bluff
neat nimbus
super({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
    GatewayIntentBits.GuildMembers,
    GatewayIntentBits.GuildMessageReactions,
    GatewayIntentBits.GuildVoiceStates
  ],
  partials: [Partials.Message, Partials.Channel, Partials.Reaction]
});
```my intents

Forms i dont see a point

topaz bluff

Then yes. At first glance of your event listeners, only message update/delete and guild member remove are going to possibly be partial

neat nimbus

i ask them on poll of what they want

marble plover

you can try to manually fetch last 100 messages from each channel on startup fwiw

i think that should populate cache (i forgot ratelimits on it tho)

topaz bluff
marble plover

i was trying to go off whatever the max for one request was haha

marble plover
shell girder

Hi everyone! I have a question about the behavior of ⁨ActivityType.Streaming⁩. I've noticed that the "Streaming" state (the purple dot/UI) is only triggered when providing a Twitch URL. If I use a YouTube or Kick URL, the default state is standard, or the "Watch" button isn't displayed. Is this a whitelist/strict limitation of Discord's own API, or is there a specific way for other platforms to trigger the streaming state in v14?

steel trail

The former. Bots really shouldn't be streaming at all

versed bobcat

yo, how do i mention a command?

clear garnet
versed bobcat
ocean portal

Can I still ask for help if I used Typescript? Not just JavaScript?

unique shoal

yes

twin mantle

Guys, i have a problem sending container:
DiscordAPIError[50035]: Invalid Form Body
data.components[0][MODEL_TYPE_CONVERT]: Expected an object/dictionary.

bleak owl

can you show your code please?

twin mantle
ruby bane

youre passing an array into an array into the components property of the reply options

either remove the array block around const container = [] into const container = new ContainerBuilder() or just pass container by itself into components, not [ container ]

twin mantle

Thank you very much, it worked

noble oak

is discord.js@15 planned? does it make sense rn to upgrade my whole bot from 13 to 14 or should i wait for 15? i dont really have the time to do it twice

fallow finch

13 to 14, 15 probably won't be out for a long time

noble oak
bleak owl

v14 still receives updates

and is still actively maintained

v15 will release when there is a need for it

fallow finch

And Discord API doesn't have any breaking changes that would prevent you from using new features

noble oak
bleak owl

v13 is no longer supported

noble oak

since there is v14 now.. but it got updates till v14 launched so thats not really a mark for how long a version will stay

bleak owl

v15 is planned, at some point. it will release when there is a need for it

right now you can stick with using v14

there's no estimated time on when a new major release will happen

noble oak
bleak owl right now you can stick with using v14

as stated in my initial message, im still running v13 and considering upgrading since i will finally have some time to spend on the bot. now what im asking is, is it worth upgrading now or in the next months, if theres already a v15.0.0 on github, so its already under development

bleak owl

yes its worth updating

again, v15 will release when there is a need for it

noble oak

okay, so you dont know of any announcements of a discord v11 api or similar things.. gotcha

bleak owl

api v11 doesn't exist yet

noble oak

thats what im saying

fallow finch

Besides going v13 to v15 would probably require you to sidetrack v14 as well

bleak owl

we're not discord so we don't know

noble oak
rose tangle

iirc 13 has some unfixed bugs anyways

unique shoal

Its not an immediate cutover

raven hearth

all that happens is the shards get ready then ⁨console.log(command?.name);⁩ is executed, logs is just heartbeat

unique shoal

yeah heartbeat logs are normal

raven hearth

status is never set, just set to the one that's in the constructor

basically nothing is happening besides heartbeat

rose tangle

you're probably ratelimited

raven hearth
halcyon bison

const client = require("../index.js");
is it possible you have some circular import resulting in this code not executing?

raven hearth
rose tangle

setting already deletes missing commands, it's unnecessary to delete all of them individually beforehand

raven hearth
unique shoal

not if you use set...

rose tangle

which they do

raven hearth

alright, still confusing why nothing is happening

unique shoal

10 seconds is too frequent for a presence update

That method is always kinda unreliable

raven hearth

true but not like the presence info really needs to be up to date

could lower the interval

unique shoal

as in, make it longer?

raven hearth

here is all that happens, it was just functional an hour or so ago, no ratelimit in the logs 🤷‍♂️

rose tangle

are you also listening to client.rest('rateLimited')?

raven hearth

just added, nothing in logs still

rose tangle

I say just place some logs and see if it reaches that line

raven hearth

await applicationCommands.set(commandsArray).catch(console.error);

stops here

rose tangle

yeah you're ratelimited then, that makes sense

raven hearth

interesting

topaz bluff

You shouldn't be modifying your application commands on startup

raven hearth

how long is the ratelimit? never happened to me before

topaz bluff

24 hours

raven hearth

shouldn't it at least error that i'm ratelimited?

topaz bluff

Ya. The guide recommends having the deploy-commands.js (or any related scripts) be run only with human input as the data is rarely modified and the rate limit is so strict

raven hearth

the rate limit is so strict
weird how i've never gotten it, been using this for years

topaz bluff

200 updates (add, remove, edit) ever 24 hours

unique shoal

By default discord.js just waits for rate limits, unless you set rejectOnRateLimit

raven hearth

alright thank you for the help everyone 👍

earnest rock

Hello, I am facing the following problem: I have a system that creates many rooms on Discord, but what happens is that it works perfectly during the day, but at a certain point it simply starts to “freeze” and creates rooms very slowly, but that's all. Can you tell me what might be causing this? It just happens, and I don't know anything about it. I've seen other servers with many more rooms being created simultaneously, and they don't have this problem.

bleak owl
tiny condor
torn herald

is there a way to change the background color of code blocks?

tiny condor

As in the color of the text?

torn herald

This is the one that shows up when I try to post a message,
However this is what the background of the code block looks like in a different message I found (from a different bot)

tiny condor

This isn't Discord.js related

However it could be `` vs using a codeblock

torn herald

ah, rip, ⁨⁨inline block⁩⁩⁩⁩
doesnt seem to add the copy button unfortunately

tiny condor
modern shell

Is there an updated documentation page on intergrating a music bot/commands?

sharp ginkgoBOT

guide Life Cycles
Two of the main components that you'll interact with when using @discordjs/voice are: - VoiceConnection – maintains a network connection to a Discord voice server - AudioPlayer – plays audio resources across a voice connection Both voice connections and audio players are stateful, and you can subscribe to changes in their state as they progress through their respective life cycles. Their individual life cycles with descriptions of their states are documented on their respective pages.

low spear

any reason why users wouldnt be able to see commands after I set setDefaultMemberPermissions, but they have the permission I set? the bot is in two servers, in one server users with the permission can use it fine, but in the second server they also have the permission but they cant see the command

turbid osprey

How do you create a message like an embed and have a button in it?

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.

unique shoal

Containers

kind halo

can u do mobile status on bots with djs v14?

loud quartz

No

thin forge

Hello, everyone!
I'm having a problem with my application: I have an embed (components V2) with buttons attached to manage various functions of my tickets (claim, unclaim, put on hold, close, etc.). The small problem is that after performing two actions (on the same button or on two different buttons), none of the buttons work anymore. Discord displays “Interaction failed” or simply nothing happens. Could you help me?

loud quartz

(it's not an embed, it's a container)

And we need way more info than that

Does your code error out and exit?

thin forge
loud quartz

Well, does the code run

If it responds twice but no more, it means it either crashes or is coded to stop responding one way or another

thin forge
loud quartz

Out of curiosity, are you running your bot in cmd or PowerShell?

thin forge
loud quartz

Is the issue occuring in cmd or PowerShell

proud arrow
thin forge
proud arrow

Then that's the issue

sharp ginkgoBOT

Channel name and topic changes are limited to roughly 2 times per 10 minutes.
If your channel changes are not going through, this might be why.

thin forge

I'll try to change that and add a two-minute cooldown. Thank you both very much 🙏

proud arrow

It's 2 times per 10min

thin forge
proud arrow

5 min would also work

thin forge
proud arrow

Yeah

versed current

Guys my string select in my modal isn't sending. Any idea why? If required is false then it somehow works.
The label builder in question when required:

LabelBuilder {
  data: {
    component: StringSelectMenuBuilder {
      data: {
        type: 3,
        custom_id: "1467823749339287553",
        min_values: 0,
        max_values: 1,
        required: true,
      },
      options: [
        StringSelectMenuOptionBuilder {
          data: {
            label: "Option 1",
            value: "value-1",
            description: undefined,
            emoji: undefined,
          },
        }
      ],
    },
    type: 18,
    label: "New Select Menu",
  },
}

is it because of the min_values: 0 ? Because when it's required it has to be at least 1?

tardy sable

Maybe, you dont have to specify the min value in your code snippet

stable sun
versed current

the docs didn't state that - I made a PR in the discord docs repo

stable sun

required shouldn’t be part of select menus tbh

versed current

modal

stable sun
versed current modal

In hindsight, it’d make sense if you chose a higher min values. For example, required: false min_values: 3 would mean no selection is allowed or you must select at least 3 items

versed current

yeah, but I'm talking about when it's required.

I just noticed this because users can configure their own modals with my bot and I had set 0 as the default for min values.

turbid osprey

why can't my bot use component v2?

versed current

you didn't pass the flags probably

you gotta pass flags: MessageFlags.IsComponentsV2 and if ephemeral then flags: MessageFlags.IsComponentsV2 | MessageFlags.Ephemeral

flint lava

Any one can help me

How to add select menus to a modal?

I cant find the dosc for this

modern shell

Is there a way to write this using the module type in my nodejs app?
⁨⁨```javascript
const filePath = path.join(commandsPath, file);
const command = require(filePath);

sharp ginkgoBOT

documentation suggestion for @modern shell:
mdn import()
The import() syntax, commonly called dynamic import, is a function-like expression that allows loading an ECMAScript module asynchronously and dynamically into a potentially non-module environment.

proud arrow

Use this ^, otherwise this is not d.js related, so might be best to use #1081585952654360687 in the future

flint lava

Can any one write my a small code with a command Thats shows modal with stringselect function inside ?

I tryied but it says the .setlebel is not a function

And the same for .setlabel

tardy sable
sharp ginkgoBOT

guide suggestion for @flint lava:
guide Modals
Modals are pop-up forms that allow you to prompt users for additional input. This form-like interaction response blocks the user from interacting with Discord until the modal is submitted or dismissed. In this section, we will cover how to create, show, and receive modals using discord.js! This page is a follow-up to the interactions (slash commands) page. Reading that page first will help you understand the concepts introduced in this page.

flint lava

Not a textinput

bleak owl

please check the guide

flint lava

Im new

bleak owl

please check the guide

flint lava

Idk i dont understand im new to the disord.js libeay sory

bleak owl

the guide is very helpful for what you want to do

bleak owl

if language is an issue, translate the page to your native language

i understand that you’re new, but the guide is very helpful to what you want to do

flint lava

Thanks

tawny roost

Uh, i completely forgot to include the code snippet in the pastebin 🤦‍♂️

  • If the code is required, ill send an additional pastebin.
topaz bluff

Can you show your interactionCreate listener?

tardy sable

Do you maybe have client.once instead of client.on for your interaction create?

topaz bluff

My thought too

stray magnet

How can I check if server hit ratelimit of adding emojis ?

rose tangle

you can't get your current ratelimits

you'll know if you've hit it once you try to do it

stray magnet

I mean when i am adding an emoji and the server is ratelimited i dont get any error

rose tangle

by default the request will be queued, if you want it to reject (throw an error if awaited) then you can specify it through your client options

sharp ginkgoBOT

propertysignature RESTOptions#rejectOnRateLimit discord.js@14.25.1
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

crystal cargo

can i make the menu option disabled? similer to button

sharp ginkgoBOT
rose tangle

though you can only disable the whole select menu, not just one option

stray magnet
rose tangle

¯_(ツ)_/¯

you can listen through client.rest.on('rateLimited' though

stray magnet
rose tangle

how are you sure you're hitting it?

tidal rune

Can you suppress notifications on componentsv2 messages? The SuppressNotifications flag doesn't seem to work.

sharp ginkgoBOT

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

{ ..., allowedMentions: { parse: ["users", "roles"] } }
stray hull

Does anyone have an idea how I can use the bitfield as flags?

// Sammle Permission-Overwrites const permissionOverwrites = [ { id: member.id, allow: [ PermissionsBitField.Flags.Connect, PermissionsBitField.Flags.Speak, PermissionsBitField.Flags.ManageChannels, 1n << 48n // SetVoiceChannelStatus (Bit 48) - direkt als numerisches Bitfield ], },

tidal rune
tidal rune

thank you!

stable sun

Feel free to define your own constant in the mean time

wary coral
tidal rune

Ah ok, so allowed mentions is what actually makes it not ping

stray magnet
rose tangle

and how do you know that's due to a ratelimit?

stray magnet

because this only happens after adding many emojis then then the bot stop adding anymore without any errors, and i try also and get error

rose tangle

getting actual ratelimit data would be more useful though, can you show how you added the rejectOnRateLimit option?

raven hearth
short granite
      at triggerClientReady (R:\xt\R:\xt\b\node_modules\discord.js\src\client\websocket\WebSocketManager.js:389:15)
      at checkShardsReady (R:\xt\R:\xt\b\node_modules\discord.js\src\client\websocket\WebSocketManager.js:368:10)
      at <anonymous> (R:\xt\R:\xt\b\node_modules\discord.js\src\client\websocket\WebSocketManager.js:198:16)
      at emit (node:events:92:22)
      at checkReady (R:\xt\R:\xt\b\node_modules\discord.js\src\client\websocket\WebSocketShard.js:184:12)
      at gotGuild (R:\xt\R:\xt\b\node_modules\discord.js\src\client\websocket\WebSocketShard.js:158:10)
      at <anonymous> (R:\xt\R:\xt\b\node_modules\discord.js\src\client\websocket\WebSocketManager.js:238:15)
      at emit (R:\xt\R:\xt\b\node_modules\@vladfrangu\async_event_emitter\dist\index.cjs:2504:31)
      at emit (R:\xt\R:\xt\b\node_modules\@vladfrangu\async_event_emitter\dist\index.cjs:2504:31)

how to fix

ruby bane

the warning tells you, change the name of the ready event to clientReady

red coral

If you ping a role, do you need any permissions for that like mention everyone? (I’d imagine that’s only for mentioning the everyone role?)

raven hearth

it has been 24h and still ratelimited ig

rose tangle

the rateLimited event emits with the ratelimit data

raven hearth
rose tangle

it emits but with no data, or...?

raven hearth

doesn't emit

rose tangle

can you show your listener?

unique shoal
loud quartz

if it isn't mentionable, you can still mention it if you have the mention everyone permission

since as its description says, "mention @everyone, @here and all roles"

raven hearth
const client = require("../index");
const { Events } = Discord;

client.on(Events.RateLimit, async (rateLimitData) => {
    console.log("test");
});

"test" is never printed

rose tangle

it's client.rest.on

raven hearth

hm

rose tangle

there's also no Events.RateLimit

raven hearth
loud quartz

anyone can make an object with a property

rose tangle

maybe you saw RESTEvents.RateLimited

raven hearth

ofc

rose tangle

also weird that it doesn't error with client.on(undefined) lol

probably because node's doesn't either but I'd say that should throw, what would be the use case

raven hearth

still nothing

const client = require("../index");

client.rest.on("rateLimited", async (rateLimitData) => {
    console.log("ratelimit", {
    timeout: rateLimitData.timeout
  });
});
rose tangle

are you sure that line is executing? exporting and requiring your client is known to cause issues with circular dependencies

raven hearth

are you sure that line is executing
all the others are executed such as the debug event

no reason for it not to execute

rose tangle

and you're triggering the ratelimit?

raven hearth

I mean you guys are saying it's a ratelimit, but yes it's hitting it

unique shoal

is this the same one from yesterday with the setting commands rate limit? Are you using the client's rest instance to do that?

raven hearth
rose tangle
raven hearth
unique shoal

Our guide uses a separately declared REST constructor/instance to deploy commands

It doesnt use client/client.rest so yeah

raven hearth

yeah I don't use that

unique shoal

You could turn on rejectOnRateLimit and catch that error to make sure its still limited

Not sure why it wouldnt emit here though

raven hearth

one second

RateLimitError[/applications/:id/commands]
    at onRateLimit (/home/container/node_modules/@discordjs/rest/dist/index.js:304:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async SequentialHandler.runRequest (/home/container/node_modules/@discordjs/rest/dist/index.js:1101:7)
    at async SequentialHandler.queueRequest (/home/container/node_modules/@discordjs/rest/dist/index.js:980:14)
    at async _REST.request (/home/container/node_modules/@discordjs/rest/dist/index.js:1293:22)
    at async ApplicationCommandManager.set (/home/container/node_modules/discord.js/src/managers/ApplicationCommandManager.js:171:18)
    at async Client.<anonymous> (/home/container/events/ready.js:46:5) {
  timeToReset: 30100,
  limit: 2,
  method: 'PUT',
  hash: 'Global(PUT:/applications/:id/commands)',
  url: 'https://discord.com/api/v10/applications/1001391997719949383/commands',
  route: '/applications/:id/commands',
  majorParameter: 'global',
  global: false,
  retryAfter: 30050,
  sublimitTimeout: 30050,
  scope: 'shared'
}

and it has been way more than 24h 🤔

unique shoal

That also says the limit is 2... not 200

Is there a new 2/30s limit? That's what this looks like

Have you spammed it so hard that you've been given stricter dynamic limits? idk

raven hearth

i've restarted it way more in the past

unique shoal

Probably going to have to go to ddevs with this one

raven hearth
unique shoal

ya

flint lava

Any one have a tutorial for discord.js but not the official site

rough sky

hey, i'm trying to write a bot using Typescript. i've got a bit of a weird setup, so i'll paste in my main.ts here: ```ts
// @ts-ignore
import {Bot} from "../../auth/modbot.ts";
// "Bot" has all my authentication information
import {Client} from "discord.js";

const client = new Client({intents: [/* here's where the problem starts... */]})
```i can't seem to import GatewayIntentBits from discord.js, WebStorm doesn't recognize it as an export. any ideas, or a full list of intents i could browse to manually add them as strings?

marble plover
tiny condor
rough sky
flint lava
tiny condor

Google

rough sky
flint lava

Nah

rough sky
marble plover
rough sky
marble plover

i have no idea then

somehow your setup is broken or idk

rough sky

thanks for the enum, found an additional workaround in manually creating an IntentsBitField and invoking .add to add intents (i hope)

flint lava

Any one can help me build a modal with a stringselectmenubuilder i cant understand the guide

ruby bane
flint lava

Ye wait

golden laurel
unique shoal
unique shoal
flint lava

@unique shoal

unique shoal

Yeah, is there something about this page you're not understanding? Happy to help

rough sky

alright, new issue -- bot cannot send me a message (presumably because we don't share a server). is there a way to make it so it can send me DMs without adding it to a server? i'm planning on doing the latter anyways, but the former could help with what i plan to do with it (yet another automod bot)

unique shoal

It can respond to user interactions but otherwise no

ruby bane

I doubt there is, but i wouldnt recommend it whatsoever

flint lava
ruby bane

Could you share the related code snippet?

flint lava

I cant rn

ruby bane

Nobody can really help you then unfortunately

flint lava

I would send tmrw

ruby bane

The only thing i can assume from what you've shared is that you literally have .setvalue() instead of .setValue()

flint lava

Oh maybe

red coral
flint lava

any one can help me with this ? i have require("doenv").config()and its givieng me this error

dotenv

tiny condor

You don't need dotenv in newer versions of node

flint lava

so i have to do npm i dotenv@latest?

red coral

I don’t believe you saved the file, the white thing at the right of the filename

tiny condor

You don't need means you don't need to install it, or use it

red coral

No you can specify a .env file on newer node versions

flint lava

how

red coral

I mean first you should save the file

flint lava

i saved the file

red coral

But it’s node --env-file=.env index.js or whatever

flint lava

?

red coral

index.js can also be like .

flint lava

what do i have to do ?

red coral

node --env-file=.env deploy-commands.js

flint lava

the same error

red coral
flint lava

its giving me this
[dotenv@17.2.3] injecting env (0) from .env -- tip: 👥 sync secrets across teammates & machines: https://dotenvx.com/ops Started refreshing 1 application (/) commands. DiscordAPIError[50035]: Invalid Form Body application_id[NUMBER_TYPE_COERCE]: Value "undefined" is not snowflake. guild_id[NUMBER_TYPE_COERCE]: Value "undefined" is not snowflake. at handleErrors (C:\Users\ros99\Documents\first bot\node_modules\@discordjs\rest\dist\index.js:762:13) at process.processTicksAndRejections (node:internal/process/task_queues:103:5) at async SequentialHandler.runRequest (C:\Users\ros99\Documents\first bot\node_modules\@discordjs\rest\dist\index.js:1163:23) at async SequentialHandler.queueRequest (C:\Users\ros99\Documents\first bot\node_modules\@discordjs\rest\dist\index.js:994:14) at async _REST.request (C:\Users\ros99\Documents\first bot\node_modules\@discordjs\rest\dist\index.js:1307:22) at async C:\Users\ros99\Documents\first bot\deploy-commands.js:36:16 { requestBody: { files: undefined, json: [ [Object] ] }, rawError: { message: 'Invalid Form Body', code: 50035, errors: { application_id: [Object], guild_id: [Object] } }, code: 50035, status: 400, method: 'PUT', url: 'https://discord.com/api/v10/applications/undefined/guilds/undefined/commands'

red coral

Remove the dotenv line and make sure your files are saved

flint lava

like i should remove the require('dotenv').config()?

red coral

^ yes

Also make sure it’s exactly application_id=1234 in your file, 1234 should be your app id

flint lava

ok

application_id[NUMBER_TYPE_COERCE]: Value "undefined" is not snowflake.
    at handleErrors (C:\Users\ros99\Documents\first bot\node_modules\@discordjs\rest\dist\index.js:762:13)
    at process.processTicksAndRejections (node:internal/process/task_queues:103:5)
    at async SequentialHandler.runRequest (C:\Users\ros99\Documents\first bot\node_modules\@discordjs\rest\dist\index.js:1163:23)
    at async SequentialHandler.queueRequest (C:\Users\ros99\Documents\first bot\node_modules\@discordjs\rest\dist\index.js:994:14)
    at async _REST.request (C:\Users\ros99\Documents\first bot\node_modules\@discordjs\rest\dist\index.js:1307:22)
    at async C:\Users\ros99\Documents\first bot\deploy-commands.js:36:16 {
  requestBody: { files: undefined, json: [ [Object] ] },
  rawError: {
    message: 'Invalid Form Body',
    code: 50035,
  code: 50035,
  status: 400,
  method: 'PUT',
  url: 'https://discord.com/api/v10/applications/undefined/guilds/1467881360843608268/commands'
}
PS C:\Users\ros99\Documents\first bot> ^C
PS C:\Users\ros99\Documents\first bot>
PS C:\Users\ros99\Documents\first bot> node --env-file=.env deploy-commands.js
[dotenv@17.2.3] injecting env (0) from .env -- tip: 🔐 encrypt with Dotenvx: https://dotenvx.com
Started refreshing 1 application (/) commands.
DiscordAPIError[50035]: Invalid Form Body
application_id[NUMBER_TYPE_COERCE]: Value "undefined" is not snowflake.
    at handleErrors (C:\Users\ros99\Documents\first bot\node_modules\@discordjs\rest\dist\index.js:762:13)
    at process.processTicksAndRejections (node:internal/process/task_queues:103:5)
    at async SequentialHandler.runRequest (C:\Users\ros99\Documents\first bot\node_modules\@discordjs\rest\dist\index.js:1163:23)
    at async SequentialHandler.queueRequest (C:\Users\ros99\Documents\first bot\node_modules\@discordjs\rest\dist\index.js:994:14)
    at async _REST.request (C:\Users\ros99\Documents\first bot\node_modules\@discordjs\rest\dist\index.js:1307:22)
    at async C:\Users\ros99\Documents\first bot\deploy-commands.js:36:16 {
  requestBody: { files: undefined, json: [ [Object] ] },
  rawError: {
    message: 'Invalid Form Body',
    code: 50035,
    errors: { application_id: [Object] }
  },
  code: 50035,
  status: 400,
  method: 'PUT',
  url: 'https://discord.com/api/v10/applications/undefined/guilds/1467881360843608268/commands'
}

```
red coral

I don’t think you did what I said since that first line is there, injecting the dotenv. You probably didn’t save the file. #how-to-get-help and #rules atp about knowing JavaScript

ruby bane

It also just may not be there at all or an empty line

red coral

What does node -v output?

flint lava

v24.12.0

wary coral
red coral

poggies

flint lava

ye but i have it defined in .env

wary coral

Could you share your ⁨deploy-commands.js

flint lava

application_id=(id) like this

yeah

its 1;1 from dosc

const { REST, Routes } = require('discord.js');
const fs = require('node:fs');
const path = require('node:path');

const commands = [];
// Grab all the command folders from the commands directory you created earlier
const foldersPath = path.join(__dirname, 'commands');
const commandFolders = fs.readdirSync(foldersPath);

for (const folder of commandFolders) {
    // Grab all the command files from the commands directory you created earlier
    const commandsPath = path.join(foldersPath, folder);
    const commandFiles = fs.readdirSync(commandsPath).filter((file) => file.endsWith('.js'));
    // Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment
    for (const file of commandFiles) {
        const filePath = path.join(commandsPath, file);
        const command = require(filePath);
        if ('data' in command && 'execute' in command) {
            commands.push(command.data.toJSON());
        } else {
            console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
        }
    }
}

// Construct and prepare an instance of the REST module
const rest = new REST().setToken(process.env.TOKEN);

// and deploy your commands!
(async () => {
    try {
        console.log(`Started refreshing ${commands.length} application (/) commands.`);

        // The put method is used to fully refresh all commands in the guild with the current set
        const data = await rest.put(Routes.applicationGuildCommands(process.env.USER_ID, process.env.GUILD_ID), { body: commands });

        console.log(`Successfully reloaded ${data.length} application (/) commands.`);
    } catch (error) {
        // And of course, make sure you catch and log any errors!
        console.error(error);
    }
})();
wary coral

process.env.USER_ID⁩ is undefined

flint lava

ohhhh

its working thanks

wary coral

np

civic jungle

is there any good article or something that i can read on components v2 with discord.js

how to use them

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.

wintry laurel

can someone tell me what is causing this error? i have no clue at all since theres no refrence to path in my code, which makes me think its a issue with djs instead. i havn't ever had this error, and this exact code has worked before but dosn't sometimes??

  • the channel is a fourm channel
  • client.guild is defined
unique shoal

Known issue with the AttachmentBuilder right now unfortunately

I think thats it

wintry laurel
unique shoal

No, you'd need multiple attachment builders

I think you can attach files without the builder though

wintry laurel

dang alright

guess ill just wait for a update

wintry laurel
wary coral
wintry laurel
wary coral

I mean if your uploading data as an attachment you would have the data. I am not sure what your asking

wintry laurel
civic jungle

is this warning message in modal going to show every time someone opens it?

civic jungle
unique shoal

Better for users

wintry laurel
wary coral

what is the type of attachment

wintry laurel

discord attachment class

wary coral

you would need to fetch the data from the URL

wintry laurel

here, this is what i was going to do but it seems like a bit much for something like this so im jusst wondering if there is a simpler way

let data;
        if (files) {
            let data = await axios.get(files.url, { responseType: 'arraybuffer', timeout: 5000, maxContentLength: 500000000 });
        }

files: files ? [{ attachment: Buffer.from(data), name: files.title }] : null,

oh wait i declared data twice lol

unique shoal

attachment accepts URLs as buffer resolvable

No need to do that

wintry laurel

thanks

wary coral

one other thing to not if you are reuploading Attachments is users can have higher upload limit than your app

wintry laurel

hmm true, the modal limit is 500mb right? and discord bot message limit is less than that i presume?

let me check make sure i can limit file size i would hope

oh you cant change it with FileUploadBuilder?

wary coral

no Discord does not provide a method to limit size before upload

The bots upload limit can very based on server

wintry laurel

rip alright guess large files will have to go then

wintry laurel

ok 100 mb so still not enough but good i guess

sharp ginkgoBOT
wintry laurel

i scrolled past it lol

idk how i missed it, genuinely

sharp ginkgoBOT
wary coral

to check the boost of the server

wintry laurel
wary coral

yes

wintry laurel

ok good

wintry laurel
wary coral

np

wintry laurel
wary coral

Sorry, I dont know

rough sky

i'm looking for a database for a bot i'm developing. i need data persistence and typescript compat, and i'm looking to run it on the same machine and connect via localhost for now, so something that i can run from node is ideal, but a minimum-uptime-power-cost server i can run as a standalone application would be a solid compromise. i'm not terribly worried about a learning curve, since i know a little SQL already. any recommendations?

rough sky
civic jungle

is it possible to "listen" to a value change in modal?
or its just on submit

polar karma

Submit only

chilly canopy

hey how can i make like this model with menu

sharp ginkgoBOT

guide Modals
Modals are pop-up forms that allow you to prompt users for additional input. This form-like interaction response blocks the user from interacting with Discord until the modal is submitted or dismissed. In this section, we will cover how to create, show, and receive modals using discord.js! This page is a follow-up to the interactions (slash commands) page. Reading that page first will help you understand the concepts introduced in this page.

chilly canopy

it not working i tryed

loud quartz

With this much info best we can say is "try harder"

chilly canopy
loud quartz

Why would ai know if d.js guide snippet works for d.js

tawny roost
loud quartz

Ai doesn't run your code

Node does

chilly canopy
loud quartz
loud quartz

?

chilly canopy

i will try and let you know

it worked

toxic hornet

Hi im struggling to make a simple stringselectmenu 😭

const userPurchases = await getPurchasesWithProductFromUserId(
    user.id,
);

const stringMenu = new StringSelectMenuBuilder()
    .setCustomId('retrieve_product')
    .setPlaceholder('Select a product');

console.log(userPurchases, userPurchases.length); // [] 0

if (userPurchases.length === 0) {
    stringMenu.setDisabled(true);
} else {
    userPurchases.map((purchase) => {
        stringMenu.addOptions(
            new StringSelectMenuOptionBuilder({
                label: purchase.storeProduct.name,
                value: purchase.id,
            }),
        );
    });
}

interaction.followUp({
    flags: [MessageFlags.IsComponentsV2],
    components: [
        new ContainerBuilder()
            .addTextDisplayComponents(
                new TextDisplayBuilder({
                    content: `### ![skyedownload](https://cdn.discordapp.com/emojis/1466511683089334465.webp?size=128 "skyedownload")  ${interaction.user.username}'s Downloads\n_ _`,
                }),
            )
            .addActionRowComponents(
                new ActionRowBuilder<StringSelectMenuBuilder>().setComponents(
                    stringMenu,
                ),
            ),
    ],
});

when the user has 0 products and the list is empty; it doesn't show a disabled stringselectmenu instead it errors with

@skye/client:dev: [] 0
@skye/client:dev: /Users/x/Projects/Skye/node_modules/.pnpm/@discordjs+rest@2.6.0/node_modules/@discordjs/rest/dist/index.js:762
@skye/client:dev:       throw new DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData);
@skye/client:dev:             ^
@skye/client:dev: 
@skye/client:dev: DiscordAPIError[50035]: Invalid Form Body
@skye/client:dev: components[0].components[1].components[0].options[BASE_TYPE_BAD_LENGTH]: Must be between 1 and 25 in length.

Both the customid and placeholder are well under 25 characters which i don't seem to understand

wary coral

you have too many options max of 25 per menu

toxic hornet

but the addOptions shouldnt run since the list is empty and it should run stringMenu.setDisabled(true); ?

wary coral

Than it would still throw bc looks like the validator is looking for it to have atlest one option

try adding a dumby option when it is disabled

toxic hornet

Oh I see, so there always has to be an option in the select menu even if its disabled

Thank you very much

wary coral

yes, np

wary coral
sharp ginkgoBOT
toxic hornet

Thanks!

wary coral

If you're using d.js for modals with select menus, you should be at least on version 14.23 when they were added

pearl roost

Can the bot automatically delete the Ephmeral reply so user don't need to hit the Dismiss message?

sharp ginkgoBOT
pearl roost

Thank you

steel trail
strange ore

Thank you

flint lava

hello im starting out rn with discord.js and i cant understand what cooldown for commands should do i think it shold send a ephermal message with how much you should wait before executing this command but its not working for me can any one help me

thats mt interaction.js file in events//interaction.js

const { Events, MessageFlags, cooldowns, Collection } = require('discord.js');

client.cooldowns = new Collection();


if (!cooldowns.has(command.data.name)) {
    cooldowns.set(command.data.name, new Collection());
}
const now = Date.now();
const timestamps = cooldowns.get(command.data.name);
const defaultCooldownDuration = 3;
const cooldownAmount = (command.cooldown ?? defaultCooldownDuration) * 1_000;
if (timestamps.has(interaction.user.id)) {

    const expirationTime = timestamps.get(interaction.user.id) + cooldownAmount;
    if (now < expirationTime) {
        const expiredTimestamp = Math.round(expirationTime / 1_000);
        await interaction.reply({
            content: `Please wait, you are on a cooldown for \`${command.data.name}\`. You can use it again <t:${expiredTimestamp}:R>.`,
            flags: MessageFlags.Ephemeral,
        });
    }  
timestamps.set(interaction.user.id, now);
setTimeout(() => timestamps.delete(interaction.user.id), cooldownAmount);
}

    // ...


module.exports = {
    name: Events.InteractionCreate,
    async execute(interaction) {
        if (!interaction.isChatInputCommand()) return;

        const command = interaction.client.commands.get(interaction.commandName);

        if (!command) {
            console.error(`No command matching ${interaction.commandName} was found.`);
            return;
        }

        try {
            await command.execute(interaction);
        } catch (error) {
            console.error(error);
            if (interaction.replied || interaction.deferred) {
                await interaction.followUp({
                    content: 'There was an error while executing this command!',
                    flags: MessageFlags.Ephemeral,
                });
            } else {
                await interaction.reply({
                    content: 'There was an error while executing this command!',
                    flags: MessageFlags.Ephemeral,
                });
            }
        }
    },
};

anyone

proud arrow

Not working for you how? You are very vague. Unless that code snippets you provided is taken from two different context, that is going to error, where are you getting your command and interaction object from for your cooldown logic?

flint lava

guide

Can anyone help me

I dont understand the cooldown Logic where do i import it ?

velvet cipher

What exactly isn't working and what part do you not understand? The guide isn't some magic code you can just copy-paste and import somewhere, it's a guide that you should follow and understand, then implement it to align with your project's setup.

flint lava

I dont understand where i have to put the cooldown Logic

velvet cipher

Does the guide not tell you that?

wary coral

The guide puts the logic in the InteractionCreate event

flint lava

But where is the interaction create event

loud quartz

where you coded it to be

or did you copy paste that without understanding as well, so now you're lost

flint lava

I tried to understand everythink but i think i broke somethink and i tried to copy paste IT i was lost and im lost

topaz bluff

client.on("eventName", function) create an event listener. Find the one you have for "interactionCreate"

flint lava

And then create the cooldown system ?

Under IT ?

topaz bluff

You put the logic there, yes

flint lava

Thank you

twin mantle

Hello guys, i have problem (another). Im trying to send a message to a specified channel but what i get is:
"TypeError: Cannot read properties of undefined (reading 'channel')" at line 225.
All i want to get is: setup > selecting channels > sending a message to first channel and logs to second (logs will be done later)

halcyon bison

the interactionCreate event only emits with 1 param, the interaction
it does not emit a message
why not use the specified channel you defined?

halcyon bison

how so?
you code doesn't even reference the channel variable after you define it

twin mantle

Hold on

topaz bluff

Your issue is this line here, await message.channel.send({

As message is undefined because you initialized it in the event callback but since the event does not emit a message variable, it is still undefined

twin mantle
topaz bluff

No

Replace message entirely and do interaction.channel.send

halcyon bison

it doesn't sound like they're trying to send to the interaction's channel, but rather the channel they're getting from the cache

which is to say, channel

topaz bluff

Oh ya. Just do channel.send

I missed that you're defining a channel variable right above that

twin mantle

Now it says:
TypeError: Cannot read properties of undefined (reading 'send')

sharp ginkgoBOT
topaz bluff

setapp is a collection not a value

bitter leaf
          if (rendered?.buffer) {
            const name = rendered.filename || `banner_${String(bannerKey)}.gif`;
            embed.setImage(`attachment://${name}`);
            files.push({ attachment: rendered.buffer, name });
          }

sim what's wrrong?
file it's sended not in the embed
should to be in the embed????

twin mantle
halcyon bison

getSelectedChannels returns a Collection of the selected channels
no need to get from the cache
if you extract the id, you'd effectively be using the channel object to get the same channel object

bitter leaf

hm any1 h any idea?

wary coral
flint lava

where do i add the interactioncreate handler ?

anyone?

topaz bluff

Wherever the path is for events

flint lava

what ?

topaz bluff

But it looks more like you have a typo (if you copied this from the code) on the first line of that.

Should be path.join(__dirname, "events")

flint lava

it is on the top

topaz bluff

...

flint lava

idk i odnt under stand the handler meaning

sory if im annoying

sharp ginkgoBOT

guide Reading event files
Next, let's write the code for dynamically retrieving all the event files in the events folder. We'll be taking a similar approach to our command handler. Place the new code highlighted below in your index.js. fs.readdirSync().filter() returns an array of all the file names in the given directory and filters for only .js files, i.e. ['ready.js', 'interactionCreate.js']. In most cases, you can access your client instance in other files by obtaining it from one of the other discord.js...

topaz bluff

I highly suggest reading the text on the guide, not just the code. It explains what the code does, and how to use it

flint lava

ok i will try again

idk i dont understand it

rose tangle

what part of it?

flint lava

like i understand whats a event handeler but i cant under stand where you put the cool downs in the interactionCreate file and where to add a new collection for cooldows craig_cat

@rose tangle im sooryyy for ping

loud quartz
wary coral
flint lava

any one can help why is my return interaction.reply my return is lighting red why

const { cooldowns } = interaction.client;

if (!cooldowns.has(command.data.name)) {
    cooldowns.set(command.data.name, new Collection());
}

const now = Date.now();
const timestamps = cooldowns.get(command.data.name);
const defaultCooldownDuration = 3;
const cooldownAmount = (command.cooldown ?? defaultCooldownDuration) * 1_000;

client.cooldowns = new Collection();
if (timestamps.has(interaction.user.id)) {
        const expirationTime = timestamps.get(interaction.user.id) + cooldownAmount;
    if (now < expirationTime) {
        const expiredTimestamp = Math.round(expirationTime / 1_000)
        return interaction.reply({
            content: `Please wait, you are on a cooldown for \`${command.data.name}\`. You can use it again <t:${expiredTimestamp}:R>.`,
            flags: MessageFlags.Ephemeral,
        });
    }
timestamps.set(interaction.user.id, now);
setTimeout(() => timestamps.delete(interaction.user.id), cooldownAmount);
}

and it says that interaction.client;is not defined

halcyon bison

why is my return interaction.reply my return is lighting red why
if you mouse over it, your ide will tell you why
and it says that interaction.client;is not defined
is this from your ide, or an error in your console?
is this in your interactionCreate handler like the guide mentions?

frankly, I worry you're still opting to copy-paste without reading and understanding the code
if this is the case, consider asking questions to help you understand the code and the guide's explanations rather than solely asking for direct solutions to issues caused by not understanding the code
it'll be much more useful in the long run if you actually understand the code you're writing

flint lava

Thanks for helping i figiure it out by my self

sigmasong

sharp ginkgoBOT

guide Modals
Modals are pop-up forms that allow you to prompt users for additional input. This form-like interaction response blocks the user from interacting with Discord until the modal is submitted or dismissed. In this section, we will cover how to create, show, and receive modals using discord.js! This page is a follow-up to the interactions (slash commands) page. Reading that page first will help you understand the concepts introduced in this page.

bleak owl
warm charm

or use hide: true

rough sky

i can't seem to import Routes from discord.js in my project, but can import REST just fine. what's the correct string to provide as a RouteLike to register commands for a particular server?

unique shoal

What's the issue with importing Routes?

And which IDE do you use?

rough sky
topaz bluff

WebStorm is known to have issues with DJS for some reason involving how the ⁨discord.js⁩ package re-exports the other packages (like ⁨@discordjs/builders⁩ and stuff like that

loud quartz

you can use d.js ways to register a command in a server

no need to do an almost-raw REST request

rough sky
loud quartz

exactly that method

unique shoal

guild.commands.set is the other

rough sky

does commands.set() support an optional guild resolvable?

loud quartz

Sets all the commands for this application or guild.
if you check the second overload

rough sky

couldn't figure out how to resolve to a guild from client alone from the docs, i'll look into ApplicationCommandManager

sharp ginkgoBOT

property Client#guilds discord.js@14.25.1
A manager of all the guilds the client is currently handling - as long as sharding isn't being used, this will be *every * guild the bot is a member of

loud quartz

and this Manager's cache at .cache is a Collection

rough sky

thanks, i'm probably just going to rely on GuildManager.fetch() to get the test server, this is mostly for deploying dev commands specifically to the dev server

loud quartz

then you shouldn't do that, really

you should not fetch a guild just for that

instead, use what i linked

sharp ginkgoBOT

method ApplicationCommandManager#set() discord.js@14.25.1
Sets all the commands for this application or guild.


// Set all commands to just this one
client.application.commands.set([
  {
    name: 'test',
    description: 'A test command',
  },
])
  .then(console.log)
  .catch(console.error);

loud quartz

it can take a second parameter which is just the guild id

on top of that.. you shouldn't really fetch guilds at all unless you have pretty good reasons to. it comes with more issues than solutions

tribal birch

is client.users gonna fill up too when i fetch all members of one guild

atomic schooner

Hello!

im trying to use d.js with the latest version (14.25.1)

code:

const client = new Client({
            intents: ['Guilds', 'GuildMessages', 'GuildMembers', 'MessageContent', 'GuildMessageReactions'],
            partials: [Partials.Channel, Partials.GuildMember, Partials.Message],
            allowedMentions: {parse: ["users", "roles", "everyone"]},
        });

        client.on('error', (error) => console.error(error));
        client.on('warn', (s) => console.log(s))
        client.on('debug', (e) => console.log(e))
await client.login(token);

// whaat I see in console

I start 5 instances but none works. I tested the code on windows, that worked perfectly. This is running on ubuntu

Anyone got a clue of what I can do?

just to show that it works on windows:

@marble plover u here aswell 😄 u are everywhere

vague plaza

Is it possible to capture when someone presses cancel on a modal using an interaction collector?

fallow finch

No it doesn't send any interaction event

vague plaza

Alright, thank you.

atomic schooner

which to my opinion is very odd

oke nvm it's not that aswell cause I tried a minimal example:

if(cluster.isPrimary) {

    for(let i=0; i<navigator.hardwareConcurrency; i++) {
        cluster.fork({IS_LAST_CORE: i === navigator.hardwareConcurrency-1});
    }
} else {
    const client = new Client({
        intents: ['Guilds', 'GuildMessages', 'GuildMembers', 'MessageContent', 'GuildMessageReactions'],
        partials: [Partials.Channel, Partials.GuildMember, Partials.Message],
        allowedMentions: {parse: ["users", "roles", "everyone"]},
    });

    client.on('error', (error) => console.error(error));
    client.on('warn', (s) => console.log(s))
    client.on('debug', (e) => console.log(e))

    await client.login(process.env.DC_TOKEN)
}```

this works fine aswell on ubuntu, soo going to continue with research...

Okay I got new clue of why it works now, but it works in ubuntu using node:cluster and being in a docker container. not sure why it didnt work in the beginning but sure

shadow violet

Hey I want an option to upload files from a form[modal ] in my discord.js bot so that any user can upload files from the same form. Is it possible to do so?

sharp ginkgoBOT
sleek mural

Discord has added the new thing where you can give people roles through invites. They for some reason let people give admin roles like that which someone could use to nuke your server, is there any way to track roles given to people through invites? Or would I just need to scan them right after they join for unsafe roles

topaz bluff
sleek mural Discord has added the new thing where you can give people roles through invites....

The new invite methods are not yet available to DJS... but the official docs show that the INVITE_CREATE event shows an array of ⁨⁨⁨role_ids⁩⁩⁩ attached to an invite... you can track that to instantly deactivate invites with suspicious roles on it

However, they do still limit the allowed roles that can be assigned the same way normal roles can be assigned (aka, can't assign equal or higher roles than your own)

ocean portal

Hey, i faced some issue while trying to make message commands, i realized they did not work at all, and the debug just shows everything is fine, for issues like this, is there anything else to check or something? or should i show you the code?

bleak owl

do you have the GuildMessages and MessageContent intents?

bleak owl

what do you mean "they do not work"

ocean portal

not responding or either it is the code

bleak owl

can you show the related code?

ocean portal
bleak owl can you show the related code?
class CommandLoader {
  constructor(client) {
    this.client = client;
  }

  async loadPrefix() {
    const baseDir = path.join(__dirname, 'commands', 'prefix');
    if (!fs.existsSync(baseDir)) {
      log.warn('Prefix commands directory not found');
      return { loaded: 0, failed: 0, aliases: 0 };
    }

    const stats = { loaded: 0, failed: 0, aliases: 0 };

    this.client.prefixCommands.clear();
    this.client.aliases.clear();

    const loadFile = (filePath) => {
      try {
        delete require.cache[require.resolve(filePath)];
        const cmd = require(filePath);

        if (!cmd.name || !cmd.execute) return;

        this.client.prefixCommands.set(cmd.name, cmd);
        stats.loaded++;

        if (Array.isArray(cmd.aliases)) {
          cmd.aliases.forEach(alias => {
            this.client.aliases.set(alias, cmd.name);
            stats.aliases++;
          });
        }
      } catch (err) {
        stats.failed++;
        log.error(`Failed loading ${path.basename(filePath)}: ${err.message}`);
      }
    };

    const walkDir = (dir) => {
      const entries = fs.readdirSync(dir, { withFileTypes: true });
      for (const entry of entries) {
        const fullPath = path.join(dir, entry.name);
        if (entry.isDirectory()) {
          walkDir(fullPath);
        } else if (entry.name.endsWith('.js')) {
          loadFile(fullPath);
        }
      }
    };

    walkDir(baseDir);
    return stats;
  )
...```
bleak owl

i dont really see where you respond to anything there.

ocean portal

i thought you mean to show how i loaded them

sharp ginkgoBOT

tag suggestion for @ocean portal:
If you aren't getting any errors, try to place console.log checkpoints throughout your code to find out where execution stops.

  • Once you do, log relevant values and if-conditions
  • More sophisticated debugging methods are breakpoints and runtime inspections: learn more
bleak owl

have you done any debugging to see where your code stops and to know where it stops responding? 🐌

rose tangle

well where does it stop

ocean portal

ill run the server again to check, wait a moment

ocean portal
bleak owl

what do you mean by that?

ocean portal

i checked the path and it is the correct one

rose tangle

that doesn't answer our question

ocean portal
rose tangle

we asked you to put some logs and see where it stops logging

start putting them at the top of your listener to see if at least that executes

ocean portal

alright

rose tangle

then once you try to use the command, it'll stop logging at some point and you'll know where it stops working

ocean portal

the only thing that does work is slash commands

rose tangle

can you show your listener and the console.log line?

ocean portal

sure

ashen moat

Is it possible to create a voice channel and set the position directly when creating the channel? Or just after the creation with .setPosition?

ocean portal
rose tangle can you show your listener and the console.log line?
// debug.js linked to commands and bot file
const fs = require('fs');
const path = require('path');

class Debugger {
    constructor() {
        this.enabled = true;
    }
    
    timestamp() {
        return new Date().toLocaleTimeString('en-US', { hour12: false });
    }
    
    format(level, module, ...args) {
        const time = `[${this.timestamp()}]`;
        const mod = module ? `[${module}]` : '';
        const msg = args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' ');
        return `${time} [${level}]${mod} ${msg}`;
    }
    
    error(module, ...args) {
        if (!this.enabled) return;
        console.error('\x1b[31m%s\x1b[0m', this.format('ERROR', module, ...args));
    }
    
    warn(module, ...args) {
        if (!this.enabled) return;
        console.warn('\x1b[33m%s\x1b[0m', this.format('WARN', module, ...args));
    }
    
    info(module, ...args) {
        if (!this.enabled) return;
        console.info('\x1b[36m%s\x1b[0m', this.format('INFO', module, ...args));
    }
    
    debug(module, ...args) {
        if (!this.enabled) return;
        console.debug('\x1b[35m%s\x1b[0m', this.format('DEBUG', module, ...args));
    }
}

module.exports = new Debugger();```
stable sun

It’s still 2 api calls iirc tho

.channels.create({ name: …, position: …, … })

ashen moat
ashen moat
stable sun Nvm, it’s a single api call

I was using


            const newChannel = await guild.channels.create({
                name: channelName,
                type: ChannelType.GuildVoice,
                parent: templateChannel.parentId,
                position: previousChannelPosition + 1
            });

But it wasn't working, it just set it to a different position, sometimes in the start of the category

ocean portal

because this probably wont work at all

rose tangle

you only shared the console.log line

which isn't that useful by itself

stable sun
ocean portal
ashen moat
stable sun

I’m talking abt the previous channel

rose tangle

you only shared a CommandLoader which stores your commands in a collection you created

not where you actually use that collection

ashen moat
stable sun No

ah, nope: let previousChannelPosition = templateChannel.position;

stable sun

Try using rawPosition

Appears create doesn’t help you with position anymore, it just sets the raw position directly

Or maybe it never did I didn’t notice

ocean portal
rose tangle not where you actually use that collection
const {
  Client,
 ---- Collection, ----------
  GatewayIntentBits,
  Partials,
  REST,
  Routes,
  ActivityType,
  PresenceUpdateStatus
} = require('discord.js');```


after this
```js
client.prefixCommands = new Collection();
client.slashCommands = new Collection();
client.aliases = new Collection();
client.cooldowns = new Collection();```

Thonk

rose tangle

yeah, that's how you create it

ashen moat
rose tangle

do you actually listen to the messageCreate event somewhere?

you're creating those collections, they're not managed by djs

if you store commands in there (or anything else) they won't do anything by themselves

you must program a listener that will actually use them

ocean portal
rose tangle do you actually listen to the messageCreate event somewhere?
client.on('messageCreate', async (message) => {
    if (message.author.bot || !message.guild) return;

    const prefix = await client.getPrefix(message.guild.id);
    if (!message.content.toLowerCase().startsWith(prefix.toLowerCase())) return;

    const args = message.content.slice(prefix.length).trim().split(/ +/);
    const commandName = args.shift().toLowerCase();

    const command = client.prefixCommands.get(commandName) ||
                   client.prefixCommands.get(client.aliases.get(commandName));

    if (!command) return;

    if (!client.cooldowns.has(command.name)) {
      client.cooldowns.set(command.name, new Collection());
    }

    const now = Date.now();
    const timestamps = client.cooldowns.get(command.name);
    const cooldownAmount = (command.cooldown || 3) * 1000;

    if (timestamps.has(message.author.id)) {
      const expirationTime = timestamps.get(message.author.id) + cooldownAmount;
      if (now < expirationTime) {
        const timeLeft = (expirationTime - now) / 1000;
        return message.reply(`Please wait ${timeLeft.toFixed(1)} more seconds before using \`${command.name}\` again`)
          .then(msg => setTimeout(() => msg.delete().catch(() => {}), 5000))
          .catch(() => {});
      }
    }

sorry for late response, the code is too large

rose tangle

no worries, and yeah that's the important part

that's where you should place your logs and see where it stops executing

ocean portal

alright, thank you

rose tangle

I assume the next line is something like command.execute(message), it'll probably stop before that, you need to find where

ocean portal

alright, thanks

woeful lark

How can I collect these badges from the user's profile using TypeScript?

topaz bluff

most badges are not available from the app api... but some of them, you can get with ⁨User#flags

sharp ginkgoBOT
woeful lark

And how can I access at least the user's boost levels even when fetching from anyone?

sharp ginkgoBOT

method GuildMember#timeout() discord.js@14.25.1
Times this guild member out.


// Time a guild member out for 5 minutes
guildMember.timeout(5 * 60 * 1000, 'They deserved it')
  .then(console.log)
  .catch(console.error);

topaz bluff

Should only be available from OAuth... and it's ⁨user#premium_type?⁩ but it doesn't show when it starts... only the tier

topaz bluff
woeful lark
bleak owl

thats not available in the API

topaz bluff

most badges are not available from the app api

ashen moat

Is it possible to access the user connections through the API?

topaz bluff

through oauth, yes

ashen moat

Oh yea, thx

bleak owl

which discord.js does not support

ashen moat
topaz bluff through oauth, yes

It isn’t possible to create a channel and ser the position in the creation right? Only afterwards? I had the feeling that was, but probably just a confusion

topaz bluff
steel trail
ashen moat
solar ocean

Every time I try to follow the official documentation my token never logs in. Youtube tutorials work but never really get my far enough along to understand the API. directly copied-and-pasted code from the docs straight up doesn't work. How is this allowed to happen?

wary coral

what does your index file look like? and are you getting an error?

unique shoal

Its a bit hard for us to answer that based on what you've told, yeah. There's many things that could prevent a successful login, but if the code is directly from our guide, it shouldn't be the issue

ashen moat
solar ocean
unique shoal Its a bit hard for us to answer that based on what you've told, yeah. There's ma...

that's why I'm so confused. my index file is (currently, for the sake of trying to get it exactly right the exact code from the starting doc. my token is correct. What other issues could be causing it to refuse to login? Like I said, it never had trouble logging in before I turned to discordjs's official guide. now it doesn't want to. I even made an entirely new project and reset my token just to try to make this work and it just won't.

// Require the necessary discord.js classes
const { Client, Events, GatewayIntentBits } = require('discord.js');
const { token } = require('./config.json');
// Create a new client instance
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
// When the client is ready, run this code (only once).
// The distinction between `client: Client<boolean>` and `readyClient: Client<true>` is important for TypeScript developers.
// It makes some properties non-nullable.
client.once(Events.ClientReady, (readyClient) => {
    console.log(`Ready! Logged in as ${readyClient.user.tag}`);
});
// Log in to Discord with your client's token
client.login(token);

my config file should be correct as well. it all exists within the same file directory

unique shoal

When you say "refuse", what happens?

solar ocean

I get the error code "TokenInvalid"

unique shoal

Well then, its invalid

That error comes from Discord

solar ocean

can't be. direct cut and paste. even reset it just to make sure. nothing

unique shoal

Its possible that its not being imported from config directly. Have you tried logging it in index.js to make sure it matches

Or pasting it directly into client.login() to skip the import step

solar ocean

you might be onto something there. runs with the token directly pasted into the js file

Appreciate the patience. thin on my own. I'll make sure my config file is made right

red coral

My bot is in around 1300 servers now, and I kinda wanna become more familiar with sharding before I have to implement it. I have a test instance which is in like a few servers, if I use the sharding manager from the guide will this still “spawn”? So I can become familiar

loud quartz

if you set up Sharding Manager as the starting point of your app, it will pretty much already work

with your guild count, unless you change the defaults, it will ask discord for the shard count, which i'm pretty sure would be 1 shard. discord goes for 1k guilds per shard

that said, rest of your bot code will need adapting if you depend on certain assumptions

like guilds or channels simply "being there" in cache

red coral

Ok so it’ll still work then, I’ll give that a go and learn from there. Thanks. And yh exactly so I wanna start learning what I need to change etc

loud quartz

ShardingManager spawns each shard as separate process, so each one has it's own client and as such own caches

red coral

As from my understanding you also can’t use like client.channels.cache.get? You’ll need to like use broadcast eval

loud quartz

you can

it's just that the channel might be in another shard, if it's from a different guild (or you're doing stuff from different entry-point than guild stuff)

red coral

Wait, if I use that in the message create event, client.channels.cache, can I just assume that that channel will live in that client.channels.cache?

loud quartz

IMO, the most foundational tip i could give is to not grab all data to process it locally, but ask the shards that have the data to do it

unique shoal

It encourages a bit more thoughtful design into the scope of what you're trying to access

red coral

Definitely, will test and improve my skills for sure lol

loud quartz

e.g.: don't grab an entire channel via bEval just to call .send() on it, or entire guild just to check its .memberCount

red coral

Ah, return the member count itself

loud quartz

just ask the shard that has that channel to send something, or to return you the .memberCount directly

red coral

Gotcha, that’s super useful thanks

loud quartz

the former will also not work for a different reason, namely that stuff gets serialized

check my pin there

red coral

If that’s still valid is it possible to pin it here or maybe #1115775988857581668 ? That’s pretty good

loud quartz

(just note that since i wrote that, bEval stopped accepting string, no difference for the example itself though)

loud quartz
red coral
loud quartz

yeah

wintry laurel

is there any fix i can add myself for the attachment builder issue?

by this i mean when you try to create a thread with files that are attachments it says there is no path variable or something like that

wary coral

what version of discord js are you on?

wintry laurel

is is fixed in a newer version?

wary coral

Try updating to latest and see if it goes away

wintry laurel

hopefully

did not unfortunately

wintry laurel
dark canyon show full error please
TypeError: Cannot read properties of undefined (reading 'path')
    at findName (/app/node_modules/discord.js/src/structures/MessagePayload.js:291:17)
    at MessagePayload.resolveFile (/app/node_modules/discord.js/src/structures/MessagePayload.js:305:31)
    at /app/node_modules/discord.js/src/structures/MessagePayload.js:273:85
    at Array.map (<anonymous>)
    at MessagePayload.resolveFiles (/app/node_modules/discord.js/src/structures/MessagePayload.js:273:56)
    at GuildForumThreadManager.create (/app/node_modules/discord.js/src/managers/GuildForumThreadManager.js:65:8)
    at Object.execute (/app/src/components/modals/bssHelp.js:98:78)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Object.execute (/app/src/events/client/interactionCreate.js:164:21)```

its a error with djs i was told by monbrey

but its really causing issues in my bot and i just want to know if theres any easy way i can fix it myself, of course i could update the module in node_modules, but my hosting service pulls from discordjs's npm page so i would have to have the whole package locally which i guess wouldnt be a problem but

wary coral

just tring to cover my bases what packages do you have installed?

sharp ginkgoBOT

discord.js includes multiple sub-packages, installing these separately can mess with internal code:

npm uninstall discord-api-types @discordjs/rest @discordjs/builders
yarn remove discord-api-types @discordjs/rest @discordjs/builders
pnpm remove discord-api-types @discordjs/rest @discordjs/builders
wintry laurel

some of them are useless i could probably get rid of them

wintry laurel

can i still import rest and routes from discord.js? because i used resst and apitypes to register commands and set my token

bleak owl

yes

wintry laurel

ok great

mmm nope error still there
guess i will just have to remove file uploads from the modals which isnt to big of a deal i guess

should i open a bug report on the github? i dont see one explaining what i have, then again i am not sure exactly what is causing this so maybe its under a different name

wary coral
wintry laurel mmm nope error still there guess i will just have to remove file uploads from th...

I just tried to replicate you bug and could not on js will try to see if it happens in ts

client.on(Events.InteractionCreate, async (interaction) => {
    if(!interaction.isChatInputCommand()) return
    if(interaction.commandName !== 'ping') return
    const modal = new ModalBuilder()
    .setCustomId('modal')
    .setTitle('Modal')
        .addLabelComponents(label => label
            .setLabel('File')
            .setDescription('must be small')
            .setFileUploadComponent(new FileUploadBuilder()
                .setCustomId('file')
                .setMaxValues(1))
        )
    await interaction.showModal(modal)

    const submit = await interaction.awaitModalSubmit({time:15_000})

    const file = submit.fields.getUploadedFiles('file', true)

    submit.reply({
        files: file.map((f) => f)
    })
})
wintry laurel
wary coral

right, retest with updated code. edit previous message to reflect the change

wintry laurel

ok, i will try and let you know

wintry laurel
wintry laurel

wait no it was a collection, but that should still work no? spread operator on a collection uses the values right

unique shoal

nope

wary coral

getUploadedFiles returns a collection not an array

unique shoal

it uses entries im pretty sure, if it works at all

wintry laurel

wow ok

i think it works on maps, i'm so use to maps so i assumed that was the same when i saw the snowflake attachment

unique shoal

Well Collection does extend map

wintry laurel

true, idk im just happy its fixed lol

thanks so much to you guys for helping, glad i was able to get it resolved. especially you @wary coral ! 💗

unique shoal

Yeah its not values, its entries

wintry laurel

oh dang ok, so it was giving the snowflake to

solar ocean

Just found out my discordjs version is out of date. Is there a way to force it to install v14? it only wants to install v13 despite me being on nodejs 18.19.1

polar karma

Completely uninstall d.js and install, it defaults to only updating within the same major version that's installed

gaunt patrol

Why my bot getting a "Missing Access" error when trying to edit a message? I've already verified that it has the required permissions

DiscordAPIError[50001]: Missing Access
    at handleErrors (/home/container/node_modules/@discordjs/rest/dist/index.js:762:13)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async SequentialHandler.runRequest (/home/container/node_modules/@discordjs/rest/dist/index.js:1163:23)
    at async SequentialHandler.queueRequest (/home/container/node_modules/@discordjs/rest/dist/index.js:994:14)
    at async _REST.request (/home/container/node_modules/@discordjs/rest/dist/index.js:1307:22)
    at async GuildMessageManager.edit (/home/container/node_modules/discord.js/src/managers/MessageManager.js:255:15)
    at async Paginator (/home/container/src/utils/helpers/Paginator.js:51:35)
    at async interactionCreate.js (/home/container/src/events/guild/interactionCreate.js:103:7)
{
  CreateInstantInvite: true,
  KickMembers: false,
  BanMembers: false,
  Administrator: false,
  ManageChannels: false,
  ManageGuild: false,
  AddReactions: true,
  ViewAuditLog: false,
  PrioritySpeaker: true,
  Stream: true,
  ViewChannel: true,
  SendMessages: true,
  SendTTSMessages: true,
  ManageMessages: false,
  EmbedLinks: true,
  AttachFiles: true,
  ReadMessageHistory: true,
  MentionEveryone: false,
  UseExternalEmojis: true,
  ViewGuildInsights: false,
  Connect: true,
  Speak: true,
  MuteMembers: true,
  DeafenMembers: false,
  MoveMembers: false,
  UseVAD: true,
  ChangeNickname: true,
  ManageNicknames: false,
  ManageRoles: false,
  ManageWebhooks: false,
  ManageEmojisAndStickers: false,
  ManageGuildExpressions: false,
  UseApplicationCommands: true,
  RequestToSpeak: true,
  ManageEvents: false,
  ManageThreads: false,
  CreatePublicThreads: false,
  CreatePrivateThreads: true,
  UseExternalStickers: true,
  SendMessagesInThreads: true,
  UseEmbeddedActivities: true,
  ModerateMembers: false,
  ViewCreatorMonetizationAnalytics: false,
  UseSoundboard: false,
  CreateGuildExpressions: false,
  CreateEvents: false,
  UseExternalSounds: true,
  SendVoiceMessages: true,
  SendPolls: false,
  UseExternalApps: true,
  PinMessages: false,
  BypassSlowmode: false
}
stable sun
gaunt patrol
stable sun

Generally, you should be using ButtonInteraction.update to edit the message the button to avoid this sort of issue

gaunt patrol
eager garnet

hey, is cv2 only for embeds ? thx

stable sun
eager garnet

i dont really get how look cv2 tbh

i've never seen it for now

stable sun

The guide has pictures

eager garnet

where is the guide pls ?

sharp ginkgoBOT

guide suggestion for @eager garnet:
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.

eager garnet

oh great, thx

I see the container look like a bit like embeds. So it ain't possible to concat embed + cv2 ig ?

stable sun

¯_(ツ)_/¯

eager garnet

yeah ok thats what i thought... Thx for you help mate

stable sun

Np

honest sandal

okay i might be stupid but i am not able to find answer to my problem
i want to get user that triggered an interaction but get if from event CreateMessage

unique shoal

But they didnt send a message

So there is no messageCreate event fired

honest sandal

but the interaction created an reply

unique shoal

From the response to an interaction?

honest sandal

yeah

sharp ginkgoBOT
honest sandal

okay thank you im trying this rn i couldnt find this

yeah this works, thank you
i just didnt see this in docs

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.

loud quartz

We have #app-commands or the ⁨hide⁩ option for personal usage

eager garnet

hi, how can i get the accessory button interaction from a message component collector ?

eager garnet
unique shoal

You can look at interaction.component if needed

eager garnet

oh ok, nothing changes

so i dont need any action row or else ?

unique shoal

Not in an accessory

eager garnet

k thx, and is there any way to set a default value for a StringSelectMenu ?

@crimson gale

@fleet ridge

savage publicity won't make people come to u

wary coral
eager garnet

couldn't ping mod role so

wary coral

Yo, sorry didn't read the spam bot message you're good

eager garnet
sharp ginkgoBOT
eager garnet

oh i meant StringSelectMenuBuilder, which is the one you put in cv2

wary coral

The select menu is the same as it has been. When creating a string select menu. You need to create options for that menu. In the options is a Boolean value to set whether or not it's a default

edgy laurel

Hey! Question about source. Is there a reason why skipLibCheck: true is missing in the tsconfig? I'm having trouble building because of this

edgy laurel
wary coral
eager garnet
wary coral

You can, but it's a Boolean value in the string select menu option

example

 const menu = new StringSelectMenuBuilder()
        .setCustomId('menu')
        .addOptions(
            new StringSelectMenuOptionBuilder()
                .setLabel('option 1')
                .setValue('option 1')
                .setDefault(true), // set option as default
            new StringSelectMenuOptionBuilder()
                .setLabel('option 1')
                .setValue('option 1')
                .setDefault(false) // set option as Not default
        )

@eager garnet this help?

eager garnet

i was trying with pure object so... thx :p

wary coral

If you're using the raw objects you can just defult: true

sharp ginkgoBOT
chrome chasm
const removeButton = new ButtonBuilder()
                        .setCustomId('disable')
                        .setLabel('Disable button')
                        .setStyle(ButtonStyle.Danger);
                    const removeDisabledButton = // Same button as above but disabled with custom id 'disabled'
const row = ActionRowBuilder().addComponents(removeButton);
                    const reply = await interaction.reply({
                        content: 'text',
                        flags: MessageFlags.Ephemeral,
                        components: [row],
                        withResponse: true,
                    });
                    const collectorFilter = (i) => {
                        i.user.id === interaction.user.id;
                    };
                    try {
                        const confirmation = await reply.resource.message.awaitMessageComponent({ filter: collectorFilter, time: 60000 });
                        if (confirmation.customId === 'disable') {
                            console.log('ok') // logs nothing when button clicked
                            const disabledRow = new ActionRowBuilder().addComponents(removeDisabledButton);
                            await confirmation.update({ content: `disabled button`, components: [disabledRow] });
                        }
                    } catch {
                        const disabledRow = new ActionRowBuilder().addComponents(removeDisabledButton);
                        await interaction.editReply({ content: 'text', components: [disabledRow] });
                    }

Any idea as to why the button click isn't even logged?

polar karma

I don't see where row is defined to show what components are in it. You could use a regular collector to get better real time information, such as the interaction data that the filter sees

chrome chasm

forgot to add it again while adding the comments in the snippet I sent

polar karma

I would still suggest using a regular component collector to get more data as you're debugging, then you could go back to await

Also, I don't see where you put a max in your current collector, that may have something to do with it

sick rover

Hey curious questions, Can you use a container builder in @discordjs/rest and send it via

body: {
  components: [component],
  flags: [MessageFlags.IsComponentsV2]
  }
)}```
normal flare

question about archived threads due to inactivity, if I give the bot Manage Threads permission, can the bot send a message normally in that thread without needing to manually unarchive it?

rose tangle
rose tangle
normal flare

okay thanks, that's what I thought as well

sick rover
rose tangle try it and see, if it doesn't work then call toJSON on it first

I tried it out, and from what i'm getting for an error, its for some reason talking about my thumbnail and components

Is this wrong formatting?

            row.addComponents(
            new ButtonBuilder()
            .setCustomId('approve')
            .setLabel('Approve')
            .setStyle(ButtonStyle.Success),
            new ButtonBuilder()
            .setCustomId(`deny`)
            .setLabel('Deny')
            .setStyle(ButtonStyle.Danger),
            new ButtonBuilder()
            .setCustomId('more_options')
            .setLabel('More Options')
            .setStyle(ButtonStyle.Secondary)
        );
        return row;
        });```

The docs are not clear at all when it comes to this, I can send the whole containerbuilder if you want
topaz bluff

please do send the whole thing... from what it sounds like, you are using a section component somewhere but youre not adding an accessory

sections are required to have an accessory... which is either a single thumbnail or a button

sick rover
const embed = (title) => { 
        const container = new ContainerBuilder()
        .addTextDisplayComponents((text) =>  
            text.setContent(`## New Appeal Submission n\**Username:** ${userData.username} (${userData.discordId})\n ${logs}`)
        )
        .addSeparatorComponents((s) => s)
        .addSectionComponents((section) => {
                section.addTextDisplayComponents(
                    (t) => t.setContent(`**What reason were you given for your ban?**\n${appealData.reason1}`),
                    (t) => t.setContent(`**What action(s) or word(s) of yours led to this ban?**\n${appealData.reason2}`),
                );
                section.setThumbnailAccessory((thumb) => { return thumb.setURL(userData.avatar)})
                return section;
        })

        .addSectionComponents((section) => {
            section.addTextDisplayComponents(
                (t) => t.setContent(`**Why do we have a rule against this type of behavior?**\n${appealData.reason3}`),
                (t) => t.setContent(`**To show why you should be unbanned, what steps have you/will you take to reform your behavior and ensure this wont happen again?**\n${appealData.reason4}`)
            );
            return section;
        })

        .addSectionComponents((s) => s)

        .addTextDisplayComponents((textt) => 
            textt.setContent(title)
        )

        .addSeparatorComponents((s) => s)

        .addActionRowComponents((row) => {
            row.addComponents(
            new ButtonBuilder()
            .setCustomId('approve')
            .setLabel('Approve')
            .setStyle(ButtonStyle.Success),
            new ButtonBuilder()
            .setCustomId(`deny`)
            .setLabel('Deny')
            .setStyle(ButtonStyle.Danger),
            new ButtonBuilder()
            .setCustomId('more_options')
            .setLabel('More Options')
            .setStyle(ButtonStyle.Secondary)
        );
        return row;
        });

        return container.toJSON();
        }```
topaz bluff

yup, there it is... a section with no accessory... pass the text display by itself without wrapping in a section

ruby bane

yeah youre missing two accessories (buttons or thumbnails), you should just use a regular textdisplay if you dont need more accessories 🐌

sick rover

So just remove the section componets for one of them and just use regular text display components?

topaz bluff

you also appear to have a typo and did a .addSectionComponents((s) => s) when you probably meant to do .addSeparatorComponents((s) => s)

ruby bane

remove whichever ones dont include accessories

sick rover

Bless, thank you two, that worked beautify now

mortal prairie

Is there any solution about this situation?

I have created a modal that contains let user fill the information and send attachment to my server. I use an AI to scan that file and send user back the result of data in that file

The problem i got is when the attachment sent to server, it took a few time (~10-15s) to process. Since the user clicked submit in the modal, after 3 seconds it responds "Somethings went wrong, try again".

I have tried the interaction.awaitModalSubmit() but seem like not work for me, so how do i can do that like make the modal wait longer until the data is processed and sent to user?

stable sun

awaitModalSubmit is for collecting a modal submission

sharp ginkgoBOT
mortal prairie
coral siren

Hello everyone, I am a bit unsure about my approach and wanted to share it.
Several users have asked me if I could make a method to remove the data of all the members who left.
So my approach is to basically fetch everyone in my list and filter those for which there is an error, and it seems to be working when I test it

const guildMembers = await ctx.bot.db.fetchPlayersFromServer(server);
const toDelete = (await Promise.all(guildMembers.map(x => ctx.getGuild().members.fetch(x.uid).then(() => null).catch(e => e.status == 404 ? x : null)))).filter(x => x);

But, uh, won't there be a problem if I try this on a larger guild ? Like a rate limit ? So is there a better approach that this one ? (I don't have the guild members intent enabled)

south sigil

Hey, is there a solution if I use commands with
const data = await restClient.put(Routes.applicationGuildCommands(client.user.id, guild.id), {body: uniqueCmdList});
The process will be completed after a few seconds.

topaz bluff
unique shoal
topaz bluff

^
calling guild.members.fetch() at/near startup will load your members cache for a guild... then the gateway will keep it updated from there... so you never need to perform another fetch again

coral siren

I'm not looking to delete any messages, just local data related to the members.
But, in order to use guild.members.fetch(), don't I need to have a special intent enabled ?

topaz bluff

youll need the GUILD_MEMBERS intent to get gateway events on member join/leave anyways

coral siren

I don't use this event, I basically keep the data until the server owner wants to purge it for all those who left
(and also because it was a pain to apply for the message content intent and I would hate to do that procedure again)

unique shoal

I don't want to call that a bad design but its certainly contradictory to the way Discord is designed

The events exists for you to automatically and efficiently manage your cache

bleak owl
unique shoal

You could still have both - receive the events for a guild member leaving, set a flag in the database that they've left, and then purge from the database on request

Without any fetching required

Thats how I'd be implementing a feature like that

coral siren

Hmm, so it's either I have the intent and I can fetch the entire guild, and easily compare it to my internal list, or I don't have the intent, and I risk hitting the rate limit ?
(Even if I had the intent, I think I would still fetch in case someone left while the bot was offline even if it doesn't happen really often)

topaz bluff

you can't fetch a member if they aren't in the server anymore

unique shoal

yeah but thats how theyre managing it

fetch throws = purge

topaz bluff

oh i see... i missed that part...

unique shoal

You also risk hitting the global errors limit lol

Thats less likely but still

topaz bluff

the guild members intent is generally also far easier to get than the message content intent... so if you got that one, you shouldnt have that hard of a time getting the members one

halcyon bison

though just putting it out there, specifying ids with <Guild>.members.fetch({ user: <id array> }) allows you to fetch multiple members in 1 call and doesn't require the GuildMembers intent
so you could just attempt to fetch the members you have data for and cross reference just those

coral siren

Hmm I see, thanks. It's actually been a while since I did that (it was in 2022), but if you say so, maybe it's worth a try. Or else I'll just keep using the current method, which is letting the mods delete data for users one by one xD

coral siren
topaz bluff
halcyon bison
coral siren

It's worth a try actually, but wait how does it behave if there's members that are not here anymore? Does the entire request fails?
(I can't test right now, in an hour I will be able to)

I'm looking at the docs, and it doesn't seem to be written

halcyon bison

it just doesn't send a member for them
cross referencing would be the same as if you had fetched all members

coral siren

Oh so in theory it would be perfect, it just maybe depends on how many I'm fetching

south sigil
bleak owl
south sigil

that's intentional

bleak owl
south sigil
bleak owl

they are referring to refreshing your discord app

reloading it

south sigil

Do I have to do that too?

bleak owl

sometimes the commands don't cache into the client, so reloading is needed for them to show up

wary coral
south sigil

Ah, okay, I thought code technically, yes, I pressed CTRL+R to reload.