#djs-help-v14
78874 messages · Page 19 of 79
I can't see the chat
just click the link
it's not a private channel
so .setContexts(BotDM, Guild, PrivateChannel)
Do you have the doc?: How are you learning to create this? I see a lot of people already using it, but I have difficulty
well, if you define those variables, yes
docs document individual classes, you'll have to specify which
if you meant a guide doc/entry then as I said it's still in the works
define those like
BotDM = 1, and so on..?
but there's a preview
no, the enum already does that, I already linked them to you
^^
InteractionConextType.BotDM for example
i see, so either i write that full into the parameters or i can shorten them by defining them first
what about setIntegrationTypes, could you provide what that method takes in
^^
loss for opening the topic there, I was finishing reading
anyone why i need to fetch all guild members for the guildMemberRemove event to work?
Because without partials, the event relies on cache for the old member data since Discord only provides the new member data
I was reading and was in doubt, we can only use the CV2 with class containerbuilder?
No
You can use them without a container too
Do you have a reference link? I was reading all about the topic #1365720579977511083 but I was still in doubt. It was not so clear, and then it could not solve it
I tried to send a containerbuilder, and the API rejected
It seems only is accepting the action -type action
Missing the IsComponentsV2 flag then probably
ActionRow
How do I solve it?
By passing that flag in your message payload. Showing your code helps also to help you fix it
Hello! I'm trying to use the new flexible components (CV2), specifically ContainerBuilder and TextDisplayBuilder, in an interaction reply.
However, any attempt to send a ContainerBuilder directly in the components array results in a DiscordAPIError[50035]: Invalid Form Body error, where the API expects a type: 1 (ActionRow) component.
Based on a conversation I saw (and this PR: https://github.com/discordjs/guide/pull/1620), I suspect I need to pass a specific flag to enable CV2 rendering. Someone mentioned I might be missing isComponentsV2: true in the message payload, but I couldn't find this in the official docs.
Is this correct? If so, how should I structure my reply payload? Here is the code that is failing:
import { SlashCommandBuilder, ChatInputCommandInteraction, ContainerBuilder, TextDisplayBuilder } from 'discord.js';
// ... (inside the command's execute function)
const imageText = new TextDisplayBuilder()
.setContent('');
const container = new ContainerBuilder()
.addTextDisplayComponents(imageText);
// This reply fails with error 50035
await interaction.reply({
components: [container],
ephemeral: true
});
Thank you for any guidance!
Use flags: MessageFlags.IsComponentsV2 | MessageFlags.Ephemeral instead of your ephemeral: true
is there anyway to show countdown per sec without sending api call every sec?
you could use a unix timestamp, but otherwise no
does anybody have a link to a resource presenting the limits of the api? by this i meant character limits for containers (or text displays), embeds, messages...
it's split in the docs
each resource documents its limits
Learn more about embed limits at the Discord Developer Documentation
Messages Resource
read more
text display limit is undocumented afaik but 4k characters per message
the sum of the amount of characters of each text display component must be 4000 or fewer?
Ok I have basically no clue how to get the bot to listen to the vc
discord.js doesn't have a way of doing that. you need to find your own way of doing so
Yes
Look into the voice-examples repository of discord.js, that has a recorder example
perfeito, aprendi a usar um pouco
I'm exploring the new Flexible Components (V2) and trying to build a character sheet for an RPG bot. My goal is to replicate this layout, with a small image next to the character's name:
(Attach the desired layout image here)
I've already managed to create most of the structure using ContainerBuilder, TextDisplayBuilder, and StringSelectMenuBuilder, and the result looks great.
The code that generates the text layout below is this:
import {
SlashCommandBuilder,
ChatInputCommandInteraction,
ContainerBuilder,
TextDisplayBuilder,
MessageFlags,
ActionRowBuilder,
StringSelectMenuBuilder
} from 'discord.js';
// ... (inside the command)
// 1. The Dropdown Menu
const selectMenu = new StringSelectMenuBuilder()
.setCustomId('sheet-menu')
.setPlaceholder("Hero's Nexus")
.addOptions([
{ label: 'Inventory', value: 'inventory' },
{ label: 'Skills', value: 'skills' },
]);
const menuRow = new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(selectMenu);
// 2. The Text Components
const header = new TextDisplayBuilder()
.setContent(`### Atlas Romanov's sheet\nPlayer: @user`);
const status = new TextDisplayBuilder()
.setContent('**Status**\n🎯 Proficiency bonus 1\n🛡️ Armor class 5...');
const attributes = new TextDisplayBuilder()
.setContent('**Attributes**\n```\nStrength: 7\n...```');
// 3. The Main Container
const container = new ContainerBuilder()
.addActionRowComponents(menuRow)
.addTextDisplayComponents(header, status, attributes);
// 4. The Final Reply
await interaction.reply({
components: [container],
flags: MessageFlags.IsComponentsV2 | MessageFlags.Ephemeral
});
My main challenge is positioning the image. I've already tried:
- Sending an
Embedwith.setThumbnail()alongside the V2 components. The Discord API rejects this, returning the error:Invalid Form Body: The 'embeds' field cannot be used when using MessageFlags.IS_COMPONENTS_V2. - Sending the image in the
filesfield. This works, but the image is attached to the message, completely outside the component layout.
My question is: Is there a way, using only V2 Components, to include an image from a URL so that it renders as a thumbnail next to a TextDisplayComponent, like in the example? Is there an ImageBuilder or a property that I'm missing?
SectionBuilder discord.js@14.19.3
A builder that creates API-compatible JSON data for a section.
A section is what you want: text next to an accessory, which can be a button or (in your case) a thumbnail
To use images in general Tnato at the beginning of the text or anywhere like these iamgens, follow the same standard?
non-thumbnail images would be a MediaGallery instead
MediaGalleryBuilder discord.js@14.19.3
A builder that creates API-compatible JSON data for a container.
And that JSDoc is wrong 🤦♂️
It seems a lot that you used an embed
Huh? Can you rephrase that?
I meant that it seems that the person is using a normal embeds instead of CV2, in this first image I sent
No, that's a container from components v2. Embeds can't have buttons in them
ContainerBuilder#setAccentColor() discord.js@14.19.3
Sets the accent color of this container.
You're probably confused because of the color
Yes, it really made it look like Embeds, but because of the button and other components, I realized it was a CV2
whats this field?
It's a string select menu
of predefinied text?
what exacly i can isnert there
You defined the text
damn nice, i thought only roles and members are possible
Role, Member, Channel, or String
thats awesome, but search not possible or
going to implement this to my app thanks
you can search all except string selects
I don't understand how you aren't like chairman or smth.
basicly i could create bunch of roles and "missuse" them and could have basicly the same result jsut that i can search?
Because that's not a title nor is this a business 
the only advantage would be that you could specify only the roles you want in a string select
but if you want all roles to be selectable, just use a role select
yeah i think its perfect, not ideal but could work
to bad it doesnt work with the strings
No, because you can't exclude roles from being shown in the SelectMenu. So your actual roles would show too
ah fk
StringSelectMenu is what you want
can i trigger with buttons to open slash commands ?
The search feature only exists for menus that can have more than the 25 options able to show at once
You can make a ButtonInteraction trigger the same action in your code
also for strings?
A SelectMenu also triggers an interaction, if that's what you're asking, yes
can i put a selectmenu inside a components?
Yes. A SelectMenu is a component
I thank you, I found it amazing, that thumb, it's not like the embed, where you are fixed to a place, you can for it in another line without being the superior of the message
does a function exist to auto transformate a date to discord timestamp
documentation suggestion for @harsh kernel:
time discord.js@14.19.3
Formats a date into a short date-time string.
wonderful
Are there any utility methods for resolving user ids out of UserResolveable objects?
For instance, I want to get the user id of a passed member:
function foo(user: UserResolvable) {
const id = typeof user=== 'string'
? user
: 'author' in user // message
? user.author.id
: user.id;
// ...
}
For now, I've just been manually extracting the id, but the docs promise that a UserResolveable will resolve to a user object. Is there some function in the library that does this?
documentation suggestion for @zenith perch:
UserManager#resolveId() discord.js@14.19.3
Resolves a UserResolvable to a User id.
UserManager is , client.users
Thanks, appreciate it
how can i watch this data on ws connection?
[WS => Shard 0] Shard not recoverable: 4004 (AuthenticationFailed)
is there any native event (other than debug) that triggers this data upon reconnection?
i send an ephemerael message with deferReply then i editReply but how can edit again?
by calling editReply again
oh can i use it again and again?
Tysm
up until 15 minutes after the interaction yes
So sorry to ping you but u showed me a message about components v2. Can u send this message again?
thanks again
I need GuildMembers intent to assign someone a role?
no
intents are for receiving data
you do need to have the Guilds intent
so I can not fetch a member?
a single member yes
I Can fetch a single member without the intent. right?
yes
ok thx
does GuildMember inherit User in everything like createdAt property for example?
you can access the User object from GuildMember#user to access those properties
now it makes sense for me
im so glad
inside of modals are there any options to include images
no, only text input
no
sad :(
btw you can check the docs to see what each class inherits, and what properties they have
GuildMember discord.js@14.19.3
Represents a member of a guild on Discord.
yep am doing that always
Is it a bad practice to use defer reply in all commands as they all use databases actions and it can take more then 3 seconds in a large-scale bot?
no not really
I mean, I doubt all of them use db actions
and you're also missing out on modals on commands
and you'll also have to code some way to include the ephemeral state you want in the defer
If i asked before sorry but will we get builders for components v2?
but if none of that matters then you're free to do what you feel is best
we do already
they were released at the same time cv2 was supported at all
Its actually a ticket bot so yes all the commands does use database
oh, can u send me documents for them
feel free to look on discord.js.org
I see thanks so much everyone
just XBuilder, depending on what you want, eg ContainerBuilder, SectionBuilder, etc
documentation suggestion for @pliant forge:
ContainerBuilder discord.js@14.19.3
A builder that creates API-compatible JSON data for a container.
start here
tysm @rose tangle @bleak owl and @topaz bluff

So I was checking this server (yes, I know it's a scam) but I saw that they had buttons inside an embed. I cant figure out how this person has managed to do that. Does anyone know?
that's a container, which is a part of the new componentsv2
if you want to know how, i can send the docs for that, just let me know
Please, that would really help me
^^
there's also a guide entry being made at https://discord.com/channels/222078108977594368/1365720579977511083
and an example on #announcements
Thank you! You guys really helped me
it's what we do o7
can i show a new modal on a modal submission interaction
no. a modal cannot trigger a modal
sadness why limited to only 5
no idea...but if you need more data, you can ask the user to trigger another modal with a button...or you can do something like ask your questions in a DM chain
I was wondering if someone would know if someone made a framework / module to handle interactive chat questionaire with a user?
I'm writing a medical assistance request bot for a game and was wondering if I need to manually code all the questions and their related code, or if someone had built something we can only provide our text, option and flow.
Popular Topics: Collectors
read more
maybe that?
Thanks, I'll take a look
For allowed mentions, is the default do nothing? Pass nothing? Or do you have to parse: []
By default all mentions are parsed
const { Client, GatewayIntentBits } = require("discord.js");
const {
ComponentBuilder,
ContainerBuilder,
TextDisplayBuilder,
MediaGalleryBuilder,
MediaGalleryItemBuilder,
ActionRowBuilder,
StringSelectMenuBuilder,
SelectMenuOptionBuilder,
} = require("v2componentsbuilder");
// === CONFIGURATION ===
const TOKEN = "token"; // Selfbot token (your real user token)
const CHANNEL_ID = "1179555083323707434"; // Target channel
const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages],
});
client.once("ready", async () => {
console.log(`✅ Logged in as ${client.user.tag}`);
// Build V2 Components using v2componentsbuilder
const components = new ComponentBuilder().setComponents([
new ContainerBuilder()
.setAccentColor(0xffe741)
.addTextDisplayComponents(
new TextDisplayBuilder().setContent("# **Semi-Automatic Sniper Rifle** - Legendary**")
)
.addMediaGalleryComponents(
new MediaGalleryBuilder().addItems(
new MediaGalleryItemBuilder().setURL(
"https://cdn.discordapp.com/attachments/1233225714258677781/1380441457353166909/glow.png"
)
)
)
.addActionRowComponents(
new ActionRowBuilder().addComponents(
new StringSelectMenuBuilder()
.setCustomId("rarity_menu")
.addOptions(
new SelectMenuOptionBuilder().setLabel("None").setValue("none").setEmoji({ name: "❌" }),
new SelectMenuOptionBuilder().setLabel("Common").setValue("common").setEmoji({ name: "⚪" }),
new SelectMenuOptionBuilder().setLabel("Uncommon").setValue("uncommon").setEmoji({ name: "🟢" }),
new SelectMenuOptionBuilder().setLabel("Rare").setValue("rare").setEmoji({ name: "🔵" }),
new SelectMenuOptionBuilder().setLabel("Epic").setValue("epic").setEmoji({ name: "🟣" }),
new SelectMenuOptionBuilder().setLabel("Legendary").setValue("legendary").setEmoji({ name: "🟠" }),
new SelectMenuOptionBuilder().setLabel("Mythic").setValue("mythic").setEmoji({ name: "🟡" }),
new SelectMenuOptionBuilder().setLabel("Exotic").setValue("exotic").setEmoji({ name: "🔵" })
)
)
),
]);
// Send raw component payload
const channel = await client.channels.fetch(CHANNEL_ID);
await channel.send({
content: "", // or your caption
components: components.toJSON(), // V2 components
});
console.log("✅ Message sent!");
});
client.login(TOKEN);
Why am I getting this error? I legit copied this code straight from a video so this makes no sense
just trynna figure out how discord components v2 works 😭
ContainerBuilder?
ComponentBuilder is not a thing
v2componentsbuilder is not a package made by djs
Either the video sucks or your copying does
Oh I didnt even see that
Are components v2 even supported by djs native?
yes lmao
jesus toxic mods
Thanks Mon
I mean, the video is promoting a third party package that isnt necessary, which makes it a crap video
for roughly a month and a half
ahh the video is 2 months old
and even then, if you know it's not a djs package, then it wouldn't make sense to ask for djs support 
We've supported them pretty much since release, since Discord worked with lib devs for some time prior to make sure everyone was ready
well even back then you could've used raw requests tbf
im not that advanced top g
well anyways, you'll have to adapt your code to actual djs code
// index.js
import {
Client,
GatewayIntentBits,
TextDisplayBuilder,
MediaGalleryBuilder,
MediaGalleryItemBuilder,
StringSelectMenuBuilder,
SelectMenuOptionBuilder,
ActionRowBuilder,
ContainerBuilder,
} from 'discord.js';
const TOKEN = 'token';
const CHANNEL_ID = 'id';
const client = new Client({
intents: [GatewayIntentBits.Guilds],
});
client.once('ready', async () => {
console.log(`✅ Logged in as ${client.user.tag}`);
const components = [
new ContainerBuilder()
.setAccentColor(0xFFE741)
.addTextDisplayComponents(
new TextDisplayBuilder().setContent("# **Semi-Automatic Sniper Rifle** - Legendary**")
)
.addMediaGalleryComponents(
new MediaGalleryBuilder().addItems(
new MediaGalleryItemBuilder().setURL(
'https://cdn.discordapp.com/attachments/1233225714258677781/1380441457353166909/glow.png?ex=6845de0a&is=68448c8a&hm=95eab0c2a93c5ad9dcc4da4fa6f848a5bbe8f508438272cef2a710cec004d1fe&'
)
)
)
.addActionRowComponents(
new ActionRowBuilder().addComponents(
new StringSelectMenuBuilder()
.setCustomId('ae10aeb8d2b94be6a0431b91cb67d21d')
.addOptions(
new SelectMenuOptionBuilder().setLabel('None').setValue('72b52ae0991b479abe533ae7e459eef5').setEmoji({ name: '❌' }),
new SelectMenuOptionBuilder().setLabel('Common').setValue('35f2b0e514f04660931cd352a8e3de3e').setEmoji({ name: '⚪' }),
new SelectMenuOptionBuilder().setLabel('Uncommon').setValue('e8f8d101849c4393cab6cf28484b079b').setEmoji({ name: '🟢' }),
new SelectMenuOptionBuilder().setLabel('Rare').setValue('654cc29392cb4424bbfa9478f5971772').setEmoji({ name: '🔵' }),
new SelectMenuOptionBuilder().setLabel('Epic').setValue('cc3ba9781ff843929ce9b72283fef452').setEmoji({ name: '🟣' }),
new SelectMenuOptionBuilder().setLabel('Legendary').setValue('104e9aba500d4270d6d621f41409f628').setEmoji({ name: '🟠' }),
new SelectMenuOptionBuilder().setLabel('Mythic').setValue('ea429e6cccb84f69cd384dd175a0de3b').setEmoji({ name: '🟡' }),
new SelectMenuOptionBuilder().setLabel('Exotic').setValue('e40c73f16e8c4383cafa1ce37e7666cc').setEmoji({ name: '🔵' })
)
)
)
];
const channel = await client.channels.fetch(CHANNEL_ID);
await channel.send({ components });
});
client.login(TOKEN);
not that package
All good - you should be able to import basically all of those from discord.js, but with ContainerBuilder instead of ComponentBuilder
you're missing the IsComponentsV2 flag
even with this script i tried using djs (i tried this before that other one) i got an api error
v10: MessageFlags - IsComponentsV2
read more
That send line doesnt look correct though, you'd need to set the IsComponentsV2 message flag
in general it's a better idea to ask/search here instead of using unsupported packages
and if you tried unsupported packages you should ask their support, or ask here but with your djs code
is there an example of this anywhere
in the announcement at #announcements
yeah idk im not a good discord dev im just trynna learn ty tho
The sample code in our accouncement should have it
Is SelectMenuOptionBuilder depracted
yes
should use StringSelectMenuOptionBuilder
can someone give me the doc to make your bot go invisible, idle, dnd, online etc
PresenceStatus discord.js@14.19.3
The status of this presence:* online * - user is online idle * - user is AFK offline * - user is offline or invisible *dnd * - user is in Do Not Disturb
Bro I might be an idiot but i cant find this to save my life
Is there a rate limit for bot to edit a permissions for a channel? I have a category and I want the bot to edit almost every channel (VC) (around 20 channels) permissions, my bot is verified, is there a way to check how frequent I should have my intervals as well as check if I got rate limited?
does each channel have its own different set of permissions?
if they're equal you could just use a category and sync the channels
yes each one is different
its for a temp voice thing, where you can block, hide, etc... members with a bot
const onlineMembers = guild.members.fetch({ withPresences: true }).then(fetchedMembers => {
const totalOnline = fetchedMembers.filter(member => member.presence?.status === PresenceUpdateStatus.Online, Dnd, Idle);
})```
"Dnd is not defined"
yeah that's not how === works
and even then you'll also have to actually define Dnd, Idle
yep but you then modified that code, I assume to include Dnd and Idle as well
but that's not how equality (===) works
oh alr
Foo == Bar, Baz does not check if Foo equals Bar or Baz
it's mostly invalid syntax
but it's not there because it's being passed as arguments to .filter
how would i fix it?
but you don't have a Dnd or Idle variables, hence, error
use or || to separate the conditions
Logical OR (||)
The logical OR (||) (logical disjunction) operator for a set of operands is true if and only if one or more of its operands is true. It is typically used with boolean (logical) values. When it is, it returns a Boolean value. However, the || operator actually returns the value of one of the specified operands, so if this operator is used with non-Boolean values, it will return a non-Boolean value.
near status and PresenceUpdateStatus?
that's a basic js issue, I'd recommend you brush up js essentials, there's some resources on #resources
no, you have to rework your check entirely, not just add ||
when a client fetches a guild, are members with a specific role cached by default or do we also need to fetch the role?
fetching a member and fetching a role are 2 different things
I don’t think members are included when fetching a guild
That’s only provided in the guild create event, which only runs when logging in before ready and when the bot is added to a guild
also this isn't a discord.js issue so this isn't the right place to post this
how can i edit button label after interaction..
by editing the message the button is part of
lets try
Maybe dumb question but can a bot forward a message?
Message#forward() discord.js@14.19.3
Forwards this message
💜
Is this a known issue? Or intentional? #unknown when linking channel and roles in a message (on desktop it shows as channels and roles and is clickable but on mobile it’s unknown)
It means the channel ID isn't a channel
Is there another way to get the channels and roles to be both linked on mobile and desktop without one being unknown or?
🤷 Just Discord client behavior
Oh
yuh
In case you didn't get an answer yet: the shardError event on mainlib Client or the error event on /ws if you use it directly
nope
can ephemeral messages not be edited?
they can be edited if they are linked to an interaction
via interaction.editReply
Convenience methods
All of these take a <Buffer>, <TypedArray>, <DataView>, <ArrayBuffer>, or string as the first argument, an optional second argument to supply options to the zlib classes and will call the supplied callback with callback(error, result).Every method has a *Sync counterpart, which accept the same arguments, but without a callback.
Use #app-commands for personal app usage please
is there a way to have hidden values in a message for my bot to read
not through discord but if you just use a variable you can set the message id as the key and store whatever you want as the value
every time I use a button my log spits out this whole mess of a list, does anyone know what that is? I can't seem to find any kind of console.log that would result in this anywhere in my code 
looks like a console.log(Events)
yes that was it, was berried in a file I didn't think would be executed 😅
Hello,
Am I at risk of directly calling GET https://discord.com/api/v9/users/608985661319413760 ?
And would I be at risk of spamming the API and getting banned if I call the API on guildMemberUpdate to check if the user has a specific guild tag or not to grant/remove a role on the server?
no, if the api doesnt like what you are doing you would just get ratelimited
@verbal iris
Although I would suggest using v10 of the API always
Is there a way to have per-server slash commands?
like my bot is in three servers and I want to make some unique commands for each server.
Yes, deploy them to the guild route instead of as global commands
Guild#commands discord.js@14.19.3
A manager of the application commands belonging to this guild
Even though it's just a get? mmh alr thanks
I just checked my payload and copied the link, I'll check if the v10 returns the guild tag info too
Yes. Ratelimits exist for GET too... but if you used client.rest to make the requests djs would take care of those for you
Ofc it does, v10 has everything v9 has and more
Any idea why I'm using v9? lmao
Okay thanks, will check its documentation
"You" as in your discord? Because that's the API version the app Discord still uses. v10 is only used by bots atm
Ohh ok
Yes I was talking about my user, I checked the payload to see what API I should use for my bot
Thanks
no
How can I use the bot to import my discord channels and role.
For me or her/him
one of them is a yes/no question, one is not
Oh okay.
lol
what's your mission with that?
- asks questions
- gets no immediate answer
- tries to post slurs
- annoyed that we automod that
- leaves
10/10 interaction
reply with a button to the modal submit interaction, reply with a modal to the button interaction
Hi! I have a problem with the new components v2 and I don't know why I get an error
My code:
import {
Client,
ContainerBuilder,
Message,
MessageFlags,
SectionBuilder,
SeparatorBuilder,
TextDisplayBuilder,
ThumbnailBuilder,
} from 'discord.js';
export const command: Command = {
run: async (_client: Client<true>, message: Message) => {
const characterPic = new ThumbnailBuilder().setURL(
'https://i.pinimg.com/736x/e7/92/47/e7924777722fb9cb09259fa34a5e9ff5.jpg',
);
const descripion = new TextDisplayBuilder().setContent(
`# ${'Yoichi Isagi'}\n` + `**Général: \`76\`**\n` + `**Position: \`Attaquant\`**\n`,
);
const statistics = new TextDisplayBuilder().setContent(
`\`\`\`Rythme: ${'78%'}\nDribbling: ${'78%'}\nTir: ${'78%'}\nDéfense: ${'78%'}\nPasse: ${'78%'}\nPhysique: ${'78%'}\`\`\``,
);
const upSection = new SectionBuilder();
upSection.addTextDisplayComponents(descripion);
upSection.setThumbnailAccessory(characterPic);
const midSection = new SectionBuilder();
midSection.addTextDisplayComponents(statistics);
const container = new ContainerBuilder();
container.addSectionComponents(upSection);
container.addSeparatorComponents(new SeparatorBuilder());
container.addSectionComponents(midSection);
container.addSeparatorComponents(new SeparatorBuilder());
message.reply({
components: [container],
flags: MessageFlags.IsComponentsV2,
});
return;
},
};
The error i got:
C:\Users\Matis\Documents\code\inDev\ts-project-template\node_modules\.pnpm\@sapphire+shapeshift@4.0.0\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:1965
return Result.err(new CombinedError(errors, this.validatorOptions));
^
CombinedError: Received one or more errors
at _UnionValidator.handle (C:\Users\Matis\Documents\code\inDev\ts-project-template\node_modules\.pnpm\@sapphire+shapeshift@4.0.0\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:1965:23)
at _UnionValidator.parse (C:\Users\Matis\Documents\code\inDev\ts-project-template\node_modules\.pnpm\@sapphire+shapeshift@4.0.0\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:972:90)
at SectionBuilder.toJSON (C:\Users\Matis\Documents\code\inDev\ts-project-template\node_modules\.pnpm\@discordjs+builders@1.11.2\node_modules\@discordjs\builders\dist\index.js:2169:37)
at C:\Users\Matis\Documents\code\inDev\ts-project-template\node_modules\.pnpm\@discordjs+builders@1.11.2\node_modules\@discordjs\builders\dist\index.js:1870:64
at Array.map (<anonymous>)
at ContainerBuilder.toJSON (C:\Users\Matis\Documents\code\inDev\ts-project-template\node_modules\.pnpm\@discordjs+builders@1.11.2\node_modules\@discordjs\builders\dist\index.js:1870:35)
at C:\Users\Matis\Documents\code\inDev\ts-project-template\node_modules\.pnpm\discord.js@14.19.3\node_modules\discord.js\src\structures\MessagePayload.js:151:46
at Array.map (<anonymous>)
at MessagePayload.resolveBody (C:\Users\Matis\Documents\code\inDev\ts-project-template\node_modules\.pnpm\discord.js@14.19.3\node_modules\discord.js\src\structures\MessagePayload.js:150:49)
at TextChannel.send (C:\Users\Matis\Documents\code\inDev\ts-project-template\node_modules\.pnpm\discord.js@14.19.3\node_modules\discord.js\src\structures\interfaces\TextBasedChannel.js:189:32) {
errors: [
ExpectedValidationError: Expected
...
is the ... at the bottom added by you here?
yes cause the error is very very long
because you cut off the actually useful part
your section doesn't have an accessory
ohh a section always must have an accessory?!
yes
if you don't need another thumbnail or button, simply use text display component instead of a section
oh okk I didn't knew it, thank you very much!
I'm following a tutorial and the code isn't working for me unlike in the video.
The error I'm getting is TypeError: Cannot read properties of undefined (reading 'commands')
I'm using v 14
my guess is that the guild object is undefined | Guild
so you can probably just add if (!guild) return; above where you use guild
oh right
Hi! Is there a way to reduce an image size in a mediaGalery? for exemple I want the image to fit the size of the selectMenu of the component, to make the component smaller laterally
Here is the code: https://pastebin.com/M7kWcfT7
now I see that something breaks guildID and sets three last digits to zeros
actually that might have been the issue to start with I just realised that the error you sent happened while running and not compiling
where are you getting the guild IDs from?
I don't think you can but not 100%
I right clicked on my server and clicked copy server ID, then put in config.json as int
guild IDs are strings not ints in discord.js
oh
now it works thx!
you can’t, and I don’t think changing the size of the image itself before uploading doesn’t help as Discord would try to fill in the full width of a container (not sure abt that tho)
can container have more than one action row or not
yeah I think so
As many as you can fit within the total 40 components limit
Hello, I wanted to know if it was possible to remove a specific role from many members quickly and without having to delete it and then recreate it ^^
Nope
In v14, are we able to preselect things in a channel select when the menu is created?
yeah
ChannelSelectMenuBuilder#addDefaultChannels() builders@1.11.2
Adds default channels to this auto populated select menu.
Amazing. Thank you!
with components v2 - how do u add a sticker inside of a component 
I don't believe you can as a sticker is a message of it's own
ah that makes sense
you might be able to get the image of a sticker and put that in a media gallery similar to how you can get the image of emojis
Unless the sticker is a Lottie
the stickers field is disabled on components v2 messages
i was trying to edit te response embed with response.editReply inside the collector, but it seems wrong. It say that response.editReply is not a function, any solution?
Hello, anyone has a list of free or cheap host for a little utility bot which will be used on like 2-3 servers please?
ChatInputCommandInteraction#editReply() discord.js@14.19.3
Edits a reply to this interaction.
// Edit the initial reply to this interaction
interaction.editReply('New content')
.then(console.log)
.catch(console.error);
@pearl roost assumimining your with in 15 mins ues <interaction>#editrely
or if you are using a button interaction as the triger <buttonInteraction>#update
im using button so i think yea
ButtonInteraction#update() discord.js@14.19.3
Updates the original message of the component on which the interaction was received on.
// Remove the components from the message
interaction.update({
content: "A component interaction was received",
components: []
})
.then(console.log)
.catch(console.error);
here is the button doc
great thanks!
do i need withResponse here?
if you are collecting messages yes
if user shares no servers with the bot, can the user still interact with any buttons that the bot sent in dm?
so if you were defining your collector like this then no you wouldn't
alright
wait why i still get the error?
update is not on the response but the button interaction
Message Components: Component interactions - Awaiting components
read more
see the guide for awaiting message components
No. Not if its not installed as a user app
You sure? If i use user installed app in your dm that sends a button, you should be able to press it just fine, no?
How can i add an image next to textdisplaycomponents?
i tried
const exampleContainer = new ContainerBuilder()
.setAccentColor(0x0099FF)
.addTextDisplayComponents(textDisplay => textDisplay.setContent('Bu bir test mesajıdır. Aşağıda sistemlerimizin tamamını görüyorsunuz. Onların altında bulunan menüden direkt olarak o sistemin menüsüne ulaşabilirsiniz.'))
.setThumbnailAccessory((thumbnail) => thumbnail.setDescription('alt text displaying on the image').setURL(client.user.avatarURL({ dynamic: false }))) .addActionRowComponents(actionRow => actionRow.setComponents(new UserSelectMenuBuilder().setCustomId('qweqweqw').setPlaceholder('Şimdilik üye seçim menüsü sonra değişecek')))
.addSeparatorComponents((separator) => separator,)
.addTextDisplayComponents(textDisplay => textDisplay.setContent('Bu bir test mesajıdır. Aşağıda başka bir temanın komutlarının tamamını görüyorsunuz. Onların altında bulunan menüden direkt olarak o komutun menüsüne ulaşabilirsiniz.'))
.addActionRowComponents(actionRow => actionRow.setComponents(new UserSelectMenuBuilder().setCustomId('qweqweqw123').setPlaceholder('Şimdilik üye seçim menüsü sonra değişecek')))
error: js [EVENT] Slash command error [DATA] TypeError: (intermediate value).setAccentColor(...).addTextDisplayComponents(...).setThumbnailAccessory is not a function
.setThumbnailAccessory doesn't exist
what should i use instead
nvm it does im sorry
It does, but only on SectionBuilder
for a section builder tho
you would use a mediagallery
Put a section in your container, put your textdisplay and the thumbnail in that section
oh ure right tysm
but how can i? So sorry im new for it
What part do you need help with?
.addSectionComponents(new SectionBuilder()
.addTextDisplayComponents(textDisplay => textDisplay.setContent('Bu bir test mesajıdır. Aşağıda sistemlerimizin tamamını görüyorsunuz. Onların altında bulunan menüden direkt olarak o sistemin menüsüne ulaşabilirsiniz.'))
.setThumbnailAccessory((thumbnail) => thumbnail.setDescription('alt text displaying on the image').setURL(client.user.avatarURL({ dynamic: false })))
.addActionRowComponents(actionRow => actionRow.setComponents(new UserSelectMenuBuilder().setCustomId('qweqweqw').setPlaceholder('Şimdilik üye seçim menüsü sonra değişecek')))
)```
i tried it but it says
```js
[EVENT] Slash command error [DATA] TypeError: (intermediate value).addTextDisplayComponents(...).setThumbnailAccessory(...).addActionRowComponents is not a function```
await interaction.message.edit();
Does it no longer work to leave selected menus empty?
use interaction.editReply()
Your code doesn't match your error. Did you save it?
yes but lemme try again
code: ```js
module.exports = {
data: new SlashCommandBuilder()
.setName('help')
.setNameLocalizations({ 'en-US': 'help', 'tr': 'yardım' })
.setDescription('The help menu for easiest ussage.')
.setDescriptionLocalizations({
'en-US': 'the help menu for easiest ussage.',
'tr': 'En kolay kullanım için yardım menüsü.'
}),
async execute(interaction) {
const exampleContainer = new ContainerBuilder()
.setAccentColor(0x0099FF)
.addSectionComponents(new SectionBuilder()
.addTextDisplayComponents(textDisplay => textDisplay.setContent('Bu bir test mesajıdır. Aşağıda sistemlerimizin tamamını görüyorsunuz. Onların altında bulunan menüden direkt olarak o sistemin menüsüne ulaşabilirsiniz.'))
.setThumbnailAccessory((thumbnail) => thumbnail.setURL(client.user.avatarURL({ dynamic: false })))
.addActionRowComponents(actionRow => actionRow.setComponents(new UserSelectMenuBuilder().setCustomId('qweqweqw').setPlaceholder('Şimdilik üye seçim menüsü sonra değişecek')))
)
.addSeparatorComponents((separator) => separator,)
.addTextDisplayComponents(textDisplay => textDisplay.setContent('Bu bir test mesajıdır. Aşağıda başka bir temanın komutlarının tamamını görüyorsunuz. Onların altında bulunan menüden direkt olarak o komutun menüsüne ulaşabilirsiniz.'))
.addActionRowComponents(actionRow => actionRow.setComponents(new UserSelectMenuBuilder().setCustomId('qweqweqw123').setPlaceholder('Şimdilik üye seçim menüsü sonra değişecek')))
await interaction.editReply({
components: [exampleContainer],
flags: MessageFlags.IsComponentsV2,
})
}
};```
error: js [EVENT] Slash command error [DATA] TypeError: (intermediate value).addTextDisplayComponents(...).setThumbnailAccessory(...).addActionRowComponents is not a function
the dynamic option doesn't exist anymore
What file and line is that erroring on? Because it still doesn't match your code
can i put addActionRowComponents in section?
It doesn't work, I just used it to leave the menu empty, remembering that the menu is not for interaction, but for a fixed message.
No. A section is just "text with something next to it". That something can either be a Button or a Thumbnail
oh then thats the error. We put it in the section
yeah its working now tysmm
you can check the docs instead of guessing what methods each object has
SectionBuilder discord.js@14.19.3
A builder that creates API-compatible JSON data for a section.
Hello can someone tell me what does this option do in replying message?
allowedMentions: {parse: ["roles"]}
It disables mentioning any roles or only enables mentioning roles?
Only roles would be mentioned, no users
ure right but i am dumb as doc reader 😦
in here, can i use the textdisplay like embed fields?
Like channel :blank::blank::blank::blank::blank::blank: blockedchannels
value value
Thanks! But I used parse : ["users"] but didn't ping the message author when reply
embed fields should not be recreated using cv2 as of now
you will have to wait until discord adds some sort of table or grid component first
okay thank u i hope they will add
documentation suggestion for @plush veldt:
MessageMentionOptions#repliedUser discord.js@14.19.3
Whether the author of the Message being replied to should be pinged
Default value: true
the reply mention is not a part of the parse array, it has its own property as shown above
Do you know if subcommands can have subcommands, and if so, is there any limitation?
you can have sub command groups
which can have subcommands
The max depth is of 3?
Or we can go deeper?
But since the default value of repliedUser is true, why isn't the message author pinged in this case?
message.reply({content: "<@&4728748274747289>", allowedMentions: {parse: ["users"]}})
When I removed the allowedMentions option, it ping system worked
the default value will be getting overridden, so you would have to pass it manually
Why would you want to? But no. /command group subcommand option: is already convoluted enough
Because you overwrite the default by providing a value. And the default value on API side if no repliedUser property is present is false
It's just to know the limitations, it'll impact the way I structure my project.
Thanks for the answer.
Thanks! And the parse: ["users"] means only users would be mentioned in message?
guys how can i use like this embed ?
you could read the message and look at the attached file
but if not here is the in development guide
how do i make it where if i mention a role in a embed it doesnt ping when it sends
it won’t ping regardless
That already is the case. If you're talking about components on the other hand...
You can control which entities receive notifications via the allowedMentions option. You can:
- Set a default on the client
- Set for a specific message
- Use the
repliedUserkey to disable in-line reply mentions
{ ..., allowedMentions: { parse: ["users", "roles"] } }
How can some of the big bots such as Dyno send out so many DMs in a short period of time without being rate limited?
big bots have separate ratelimits
and thats not really a djs question
const sections = await Promise.all(adminData.adminAction.map(async (action, i) => {
let memberName = 'NON';
if (action.member) {
try {
const memberUser = await client.users.fetch(action.admin);
memberName = memberUser.username || memberName;
} catch {
// Hata durumunda adminName değişmez
}
const unixTimestamp = Math.floor(Number(action.timestamp) / 1000);
return new SectionBuilder().addTextDisplayComponents(text =>
text.setContent(
`\`[Case ${i + 1}]\` ➔ **${action.action}**\n` +
`∟ Member: ${memberName}\n` +
`∟ Date: <t:${unixTimestamp}:f>\n`
)
)
}
}))
const container = new ContainerBuilder()
.setAccentColor(0x0099FF)
.addSectionComponents(sections);
await interaction.editReply({
flags: MessageFlags.IsComponentsV2,
components: [container]
});```
My data is alright but when i try call that command it keeps say Bot is thinking...
what can be wrong
sections can't have only text displays
they also need a thumbnail
and if you're not getting any errors it sounds like you're silently ignoring them
i tried it but command even can't be executed im on it
you mean 'x' is not logged?
yes
then you must be deferring somewhere before actually calling the command
start from there and see where the execution stops
yes i do and i use editReply in my every command but im watching the steps rn
shall i deploy my commands again
that's unrelated
my all other commands are working currently
oh yeah my bad i didn't put slashcommandbuilder in {} wow
you would’ve gotten a syntax error though no?
yeah but i didn't and when i put it worked idk why
probably because of how your command handling functions
is it required?_
yes
a button or a thumbnail right
otherwise the section is quite useless
just add the text displays directly if you don't want them
yes
oh thank you
in one section how many button can i use? Just one?
yes
SectionBuilder discord.js@14.19.3
A builder that creates API-compatible JSON data for a section.
hence why it's setXAccessory, unlike other addXComponents
Then how can i use them next to each other at top
i want them next to each other
just put them in the same row
right...
Sorry im eepy i need to stop trying new things. Tysm all ur patient and help
When sharding, is it okay to refresh the slash commands on every single shard, or should I find a way to only let it refresh once
there's no reason to refresh them at all
unless you changed some metadata for the commands
in that case, if they are global, well.. they are global. doesn't matter which shard did it, especially as we here recommend running that from a separate script that doesn't even login to the gateway, doing it with /rest subpackage directly
anyone have the link of that webpage that helps you build discord embeds and outputs the code (with component v2) ?
I was looking at an open source bot and noticed that when I send a link in chat, it downloads the contents of the webpage and sends them back as an attachment. This is not the intended behaviour of that bot.
I looked through the code and in my opinion it simplifies to sending this (imagine discord.com is the link i sent) using discord.js:
{
files: [ "https://discord.com" ]
}
Could I ask what exactly the behaviour is when putting a list of strings in files? Could it be by any chance downloading the webpage and sending it, or could this piece of code not be the cause of the behaviour?
where is that object located
await client.channels.cache.get(config.discord.channels.guildChatChannel).send({
files: [image]
});
this is the link to my fork of the bot
though I didn't modify any relevant behaviour
doing this does make d.js download the file from the link to attach it to that message
it's literally called "chat bridge"
you mean the project?
yeah
It's meant to take messages from a minecraft server and send them to discord and viceversa (minecraft chats don't have images)
but they have links
Downloading links i send in the bridge is not intended behaviour, especially when unrestricted, that's what i meant
that might be to images
yea but in that case the bot is just supposed to send the link and if it's an image discord will render it safely using its own servers
tbh you're fine just putting the links into the content directly
and nothing else
if it happens to be an image, discord itself will fetch it
yea I don't know why the creator of the chat bridge made it like this, thank you for the help
what do you intend it to do if not fetch the link and upload the result?
I intended none of this to happen, I host an instance of the bot for a guild playing on a minecraft server (Hypixel) and noticed this behaviour (which is extremely dangerous in my opinion).
After seeing it, I investigated the code and found this piece of code, which I thought might be the cause, but I wasn't sure if that's how discord.js handles it, so I asked here.
Thanks to you guys I now know it was indeed the culprit of this behaviour and will update my fork of the chat bridge to not have it
Sorry if I was unclear
(the bot is not coded by me, it's open source. I only have a fork with tiny changes)
ah, yeah I didn't read correctly the parts about it wasn't yours, my bad
yep, it sounds a weird design choice if that's not what they expected it to do
or maybe a not fully informed one
tbf, the code was edited 4 months ago
No worries, thanks for the help anyways
to upload to discord via d.js, instead of uploading to imgur
true, though I don't know why they would want to upload to imgur either
the code for imgur is still there, just commented out
oh nevemrind I know that, it's so people on miencraft see a link for images (and some client-side mods can display those images)
but right now it doesn't check if it's an image or not, it works for anything starting with https apparently
this is kinda where it gets tricky though
url doesn't have to end with an extension to lead to an image
(ignoring things like query params here, of course)
Yea that's true, though in general I would really rather not it fetching any link sent by random people from my private vps (images or not). Especially for a bot meant to be ran by people who don't know how to code and don't realize the potential problems (some hosting services have networking limits for example)
https://pastebin.com/tr28sFvX im trying to mimic my old biomes command with components v2, and I keep getting this error:
TypeError: Cannot read properties of undefined (reading 'Image')
at createContainer (/home/container/commands/Pets/setbiome.js:90:31)
at Object.execute (/home/container/commands/Pets/setbiome.js:104:16)
at processTicksAndRejections (node:internal/process/task_queues:95:5)
at async Client.<anonymous> (/home/container/index.js:159:5)```
Is it possible to get emoji by it is name directly on developer portal?
I kinda don’t want to reveal full emoji details in the public repo
if it's on the dev portal, it's exclusive to your bot. Sure, someone can find the emoji, but if you uploaded via dev portal, then only that bot can use them
Yeah but just using name cause copying :name: is not what i would like to do (this is what i am doing right now)
<: name : id>
why?
Can’t still people use it on webhook?
uhhh if it's for that bot no
as far as i know, MediaType does not exist
Then no problem
Okay thanks
💀 time to read docs again
TypeError: (intermediate value).addItems is not a function
at createContainer (/home/container/commands/Pets/setbiome.js:83:73)
at Object.execute (/home/container/commands/Pets/setbiome.js:92:16)
at processTicksAndRejections (node:internal/process/task_queues:95:5)
at async Client.<anonymous> (/home/container/index.js:159:5)
im tweakin
im not sure why you're passing an array
MediaGalleryItemBuilder discord.js@14.19.3
check this
MediaGalleryBuilder#addItems() discord.js@14.19.3
Adds items to this media gallery.
thank you
well okay it takes a RestOrArray, but as a spread array param so its not needed
.addMediaGalleryComponents( new Discord.MediaGalleryItemBuilder()
you want to add a media gallery, but you're creating a single item
should be MediaGalleryBuilder
btw you can also use the callback way
container.addSectionComponents((sectionBuilder) => sectionBuilder
.addTextDisplayComponents((textDisplayBuilder) => ...)
.addMediaGalleryComponents((mediaGalleryBuilder) => ...)
// etc
);
though now that I double read that, yeah that's entirely wrong
are there docs yet for the new role color styles?
you don't add a media gallery to a section
you add it to the container
sections only support text displays and a button/thumbnail accessory
Gradient roles don't have documentation at this time
alright thanks
ahh ok
Is here any way i can make this look better
The dropdown looks ugly cuz its bigger than everything
design is really up to you
can i even modify the width of that stuff tho?
Nope
Other than like, adding a label. But some components might roll over to the next row on some devices, so it's ultimately not in your control
Rip
Put it all in a container and they might look better
Won’t help with the buttons overflow, but still
a container?!
V2 components
It will reduce the size of the select menu and might all line up a little better
ty
it won’t reduce the menu size at all
it’s how discord renders it
I was more thinking it will fit it to the size of the container rather than edge of screen
it's the other way around
the container resizes to contain its components
Interesting. Either way, it will still probably look neater imo
are containers supported by djs now?
yes
how to create a poll in discord.js? cant find the builder for it, or any guides about it.
MessageCreateOptions#poll discord.js@14.19.3
The poll to send with the message
Anyone know of a simple template for a private dashboard?
MessageCreateOptions#poll discord.js@14.19.3
The poll to send with the message
Most image and video file types
Have youy checked your intents
Those events don't need any intent.
Are you sure an entitlement actually gets updated/created/deleted? Did you try fetching entitlements and comparing with what you had before? Was your bot running at the point in time you did the action causing an entitlement to change
in my command handler i realized i have execute(interaction, client) and use that client option instead of using interaction.client in the various command codes. is this a bad practice? is there any downside?
Yes, it is bad practice because it's unnecessary and prone to confusing the order of those parameters.
outside of the order, would it have any meaningful impact on performance?
not really
okay
thanks
not to my knowledge
I guess ChatInputCommandInteraction.id is the same as message.id since there is no ChatInputCommandInteraction.message.id?
[...] and video file types
media gallery does allow it
no, it's not "the same"
it is an id, but not of a message
how do u send messages to threads
try {
await thread.send(`**${message.author.username}:** ${message.content}`);
} catch(err) {
console.log(err)
}
TypeError: Cannot read properties of undefined (reading 'send')
at Client.<anonymous> (C:\Users\NotAdmin Kewl\Desktop\cODING\DiscordBot\Moderator Certification Python\index.js:90:18)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
i find the thread using
try {
const channels = await guild.channels.fetch();
thread = channels.find(
ch => ch.isThread() && ch.name === `ticket-log-${split[1]}`
);
} catch(err) {
console.log(err)
return;
}
how can I get the message id then
the thread is undefined
whenever you get channels or threads in that way you should really always check if they exist before using them just to be sure
well i know the thread exists but it says its not found. i did some debugging
as for this the code looks right are you sure there is a thread with that name
100%
Thread not found for name: ticket-log-873505666357157888
I honestly can't remember I haven't worked with threads in a long time but try fetching all the channels then on each channel do channel.threads or something
TextChannel#threads discord.js@14.19.3
A manager of the threads belonging to this channel
uhhhhhhhhhh
is that an active thread? or is it archived?
its active
either way you never should have to guild.channels.fetch(), instead use the cache
cache?
how do i use that
guild.channels.cache.find(...)
your fetch there clears the cache and replaces it with whatever you fetched... which might not include the threads you're looking fornvm, the cache doesn't get cleared, only appended to
what argument do i put in the find
split[1]?
the same as for your current find() call
Ok
i used caches and now theres no error and .send its defined but nothing sends into the thread
client.on('messageCreate', async (message) => {
if (message.channel.parentId != 1379506056610447420) return;
const guild = message.guild;
const split = message.channel.name.split("-");
let thread;
try {
thread = guild.channels.cache.find(
ch => ch.isThread() && ch.name === `ticket-log-${split[1]}`
)
if (!thread) {
console.log(`Thread not found for name: ticket-log-${split[1]}`);
return;
}
} catch (err) {
console.log("Error fetching channels:", err);
return;
}
try {
await thread.send(`**${message.author.username}:** ${message.content}`);
} catch (err) {
console.log("Error sending message to thread:", err);
}
})
your initial id check there is wrong btw, needs to be a string
- Discord ids follow the snowflake format: learn more
- Discord ids must be represented as strings as they are larger than
Number.MAX_SAFE_INTEGER, the largest integer that can be represented in JavaScript
- client.guilds.cache.get(123456789012345678)
+ client.guilds.cache.get("123456789012345678")
you meant the first line? or
second line in your codeblock
const guild = message.guild;
whats the issue, i dont see it
(could also be since im new to djs)
that's your fourth line
my second line is
space?
no, that's your third line
ohh you meant the return;?
client.on('messageCreate', async (message) => { this is your first line. not sure if trolling or counting is really that hard
if (message.channel.parentId != 1379506056610447420) { return; }
no just very confused
so you mean this
yes. you have an id there. as number. it needs to be a string. read 👆
if (message.channel.parentId != "1379506056610447420") { return; }
well still nothing
checked the thread nothing happened
not nothing. that issue is fixed. it won't affect your sending issue. it was just an additional note
oh.. well it still doesnt send anything..
wait how does cache work?
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
is it only persistant for 1 session? like is it cleared the next?
like if i turn on my bot and then turn it off and then on again
and gets filled on login/ready again, yes
it would error in your code there if the thread wasn't in cache. that's not your issue
We are in the correct category
Fetching thread
Thread got found! ticket-log-873505666357157888
Sending message to thread!
client.on('messageCreate', async (message) => {
if (message.channel.parentId != "1379506056610447420") { return; }
console.log("We are in the correct category");
const guild = message.guild;
const split = message.channel.name.split("-");
let thread;
try {
console.log("Fetching thread");
thread = guild.channels.cache.find(
ch => ch.isThread() && ch.name === `ticket-log-${split[1]}`
)
if (!thread) {
console.log(`Thread not found for name: ticket-log-${split[1]}`);
return;
}
console.log("Thread got found! " + thread.name);
} catch (err) {
console.log("Error fetching channels:", err);
return;
}
try {
console.log("Sending message to thread!");
await thread.send(`**${message.author.username}:** ${message.content}`);
} catch (err) {
console.log("Error sending message to thread:", err);
}
})
would i be correct in assuming that this error was the product of me setting the presence before the client is actually ready?
Possible AsyncEventEmitter memory leak detected. 11 ready listeners added to WebSocketShard. Use emitter.setMaxListeners() to increase the limit.
oh there is another one too but instead of ready its on error
add one after the await thread.send
yes
hey! i think i found the issue
(yes thats the issue i checked)
so not a code issue but a logic issue. having more than one thread by that name
yes!
ty for ur help anyways
This bot seems to be a discord user how they do this
report them, they violate TOS
- Do not use self-bots or user-bots. Each account must be associated with a human, not a bot. (See our Platform Manipulation Policy Explainer for more.)
how they do that btw by getting the token in inspectelement?
stop, we won't help with TOS violations
ok
what about this?
Possible AsyncEventEmitter memory leak detected. 11 error listeners added to WebSocketShard. Use emitter.setMaxListeners() to increase the limit.
Error: ```js
Error: Received one or more errors
at _UnionValidator.handle (/home/container/projects/Diva-new/node_modules/@sapphire/shapeshift/dist/cjs/index.cjs:1965:23)
at _UnionValidator.parse (/home/container/projects/Diva-new/node_modules/@sapphire/shapeshift/dist/cjs/index.cjs:972:90)
at SectionBuilder.toJSON (/home/container/projects/Diva-new/node_modules/@discordjs/builders/dist/index.js:2169:37)
at /home/container/projects/Diva-new/node_modules/@discordjs/builders/dist/index.js:1870:64
at Array.map (<anonymous>)
at ContainerBuilder.toJSON (/home/container/projects/Diva-new/node_modules/@discordjs/builders/dist/index.js:1870:35)
at /home/container/projects/Diva-new/node_modules/discord.js/src/structures/MessagePayload.js:151:46
at Array.map (<anonymous>)
at MessagePayload.resolveBody (/home/container/projects/Diva-new/node_modules/discord.js/src/structures/MessagePayload.js:150:49)
at GuildMessageManager.edit (/home/container/projects/Diva-new/node_modules/discord.js/src/managers/MessageManager.js:186:8)
Command:
import { Command, type Context, type Divamusic } from '../../structures/index';
import {
ContainerBuilder,
MessageFlags,
SectionBuilder,
SeparatorBuilder,
TextDisplayBuilder,
} from 'discord.js';
public async run(client: Divamusic, ctx: Context): Promise<any> {
const msg = await ctx.sendDeferMessage('Pinging...');
const latency = msg.createdTimestamp - ctx.createdTimestamp;
const apiLatency = Math.round(client.ws.ping);
const pingInfo = new TextDisplayBuilder().setContent(
`# Bot Latency\n` +
`**Websocket Latency:** \`${apiLatency}ms\`\n` +
`**Message Latency:** \`${latency}ms\`\n` +
`**Uptime:** <t:${Math.floor(Number(client.readyTimestamp) / 1000)}:R>`
);
const upSection = new SectionBuilder();
upSection.addTextDisplayComponents(pingInfo);
const container = new ContainerBuilder();
container.addSectionComponents(upSection);
container.addSeparatorComponents(new SeparatorBuilder());
return ctx.editMessage({
//content: ' ',
components: [container],
flags: MessageFlags.IsComponentsV2
});
}
Same
Section needs an accessory. Put the textdisplay directly into the container if you don't want an accessory
please excuse my lack of insight, could you elaborate?
As you added a section it requires an accessory (thumbnail or button). If you don’t want to add one of those, you need to remove the section and add the text display directly
i can't find the types for this in discord-api-types
https://discord.com/developers/docs/interactions/receiving-and-responding#edit-original-interaction-response
https://discord.com/developers/docs/resources/webhook#edit-webhook-message
client.on('threadUpdate', async(oldThread, newThread) => {
if (oldThread.channel.id != "1379777763421982732") { return; }
newThread.setLocked(false);
newThread.send({
content: `**Automatically opened thread since it got archived!**`
});
})
why wont this wrk
TypeError: Cannot read properties of undefined (reading 'id')
at Client.<anonymous> (C:\Users\NotAdmin Kewl\Desktop\cODING\DiscordBot\Moderator Certification Python\index.js:167:25)
at Client.emit (node:events:519:28)
at module.exports [as THREAD_UPDATE] (C:\Users\NotAdmin Kewl\Desktop\cODING\DiscordBot\Moderator Certification Python\node_modules\discord.js\src\client\websocket\handlers\THREAD_UPDATE.js:14:12)
at WebSocketManager.handlePacket (C:\Users\NotAdmin Kewl\Desktop\cODING\DiscordBot\Moderator Certification Python\node_modules\discord.js\src\client\websocket\WebSocketManager.js:351:31)
at WebSocketManager.<anonymous> (C:\Users\NotAdmin Kewl\Desktop\cODING\DiscordBot\Moderator Certification Python\node_modules\discord.js\src\client\websocket\WebSocketManager.js:235:12)
at WebSocketManager.emit (C:\Users\NotAdmin Kewl\Desktop\cODING\DiscordBot\Moderator Certification Python\node_modules@vladfrangu\async_event_emitter\dist\index.cjs:287:31)
at WebSocketShard.<anonymous> (C:\Users\NotAdmin Kewl\Desktop\cODING\DiscordBot\Moderator Certification Python\node_modules@discordjs\ws\dist\index.js:1190:51)
at WebSocketShard.emit (C:\Users\NotAdmin Kewl\Desktop\cODING\DiscordBot\Moderator Certification Python\node_modules@vladfrangu\async_event_emitter\dist\index.cjs:287:31)
at WebSocketShard.onMessage (C:\Users\NotAdmin Kewl\Desktop\cODING\DiscordBot\Moderator Certification Python\node_modules@discordjs\ws\dist\index.js:1007:14)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
use oldThread.id and not oldThread.channel.id
doesnt work also tried it rn
fixed issue
what are you even trying to archive in the first place?
fixed issue
Hello guys, it's possible to put a local image in the footer url icon on embed?
Those are also caused by you trying to setPresence before client is logged in/ready
documentation suggestion for @potent burrow:
RESTPatchAPIWebhookWithTokenMessageJSONBody discord.js@14.19.3
tag suggestion for @jagged shell:
Files in embeds should be attached via the message option object and referenced in the embed:
const attachment = new AttachmentBuilder('./image.png', { name: 'image1.png' });
const embed = new EmbedBuilder()
.setTitle('Attachments')
.setImage(`attachment://${attachment.name}`);
channel.send({
embeds: [embed],
files: [attachment]
});
Hey, not sure if this is the correct channel but I'm using components v2 for the first time (/builders but not d.js) and I'm really confused. I'm trying to execute a webhook with this body:
{
flags: MessageFlags.IsComponentsV2,
components: [
...array.map((d, i) =>
new ContainerBuilder()
.setAccentColor(colors[i % colors.length])
.addTextDisplayComponents(
new TextDisplayBuilder().setContent(
`## [${i} - Title](https://example.com)`,
),
...d.array.map((v) =>
new TextDisplayBuilder().setContent(
`### Text ${time(resolveDate(v.dt_com), TimestampStyles.ShortTime)}\n**${v.perc}%** (${v.vot_t})\n-# Text ${v.enti_p}/${v.enti_t}`,
),
),
new TextDisplayBuilder().setContent(
`-# Text: ${d.enti}`,
),
)
.toJSON(),
),
],
} satisfies RESTPatchAPIWebhookWithTokenJSONBody &
RESTPostAPIWebhookWithTokenJSONBody
However, I get a Cannot send an empty message. I tried to log the body and I get this:
{
"flags": 32768,
"components": [
{
"type": 17,
"accent_color": 7391279,
"components": [
{
"type": 10,
"content": "## [0 - Text](https://example.com)"
},
{
"type": 10,
"content": "### Text <t:1749376800:t>\n**7,41%** (3.408.482)\n-# Text 61.591/61.591"
},
// ...
]
},
// ...
]
}
Which seems correct to me. If I add a random content I get that content is not available when using components v2. What am I doing wrong?
What method do you feed that to and how? The payload looks fine, I assume you don't pass it correctly
And/or show the full error you receive
hello
Is it forbidden for me to do
const tokens = [
"...","...","..." ];
for(let bot of tokens) {
client.login(bot);
}
```?
I was sending an embed before and it worked just fine... I'm doing a POST request to ${Routes.webhook(this.env.WEBHOOK_ID, this.env.WEBHOOK_TOKEN)}?thread_id=${this.env.THREAD_ID}&wait=true. The full error is just json { "message": "Cannot send an empty message", "code": 50006 }
.
if you have a valid use case
TypeError: message.createMessageComponentCollector is not a function
at Object.execute (file:///D:/Data/Coding/Repositories/airmalpi-occ/commands/public/pianifica.js:116:39)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async Object.execute (file:///D:/Data/Coding/Repositories/airmalpi-occ/events/interactionCreate.js:12:17)
I'm gettings this. I think it's something about the latest version, I've never got this error before
Can you explain the meaning of " if you have a vaild use case "?
Do
const tokens = [ "...", "...", "..." ];
for (const token of tokens) {
const bot = new Client();
bot.login(token);
}
``` instead. As said above, only for valid use though.
May i ask why you need that?
For Premuim Bots System
Is there a better way?
If it's a webhook like that you need to add with_components=true as query parameter
Running only one bot per process would be the better way
Thank you so much, I had no idea I needed it!
It's against the TOS to get other users' tokens
Can somebody help me?
Could you show some code for context?
how about putting it into a database like mee6 or other developers does it??
do not compare yourself to other bot's that do not comply with the TOS
what is message defined as
It was general question cuz i remember seeing happen but in different ways
doesn't matter how you store the data, it's the act of requesting it that's against the TOS
Ahh that’s make sense
I have problem with interaction.reply not sending embed
it works with normal messages but not embeds
pls help
unknown integration means that your discord commands cache is out of sync with the server (most likely means that your command has been deleted)
if you restart your discord the command will probably disappear to confirm this (unless you have re-registered it)
I have
after refreshing discord it works
so it's fixed now?
Yes, but I'm confused
basically whenever you run commands discord doesn't fetch them from the server
it does it periodically and stores them in a cache to reduce load on the server
a command had been deleted on the server but your cache was outdated so when you ran the command discord couldn't find the command id on their server cuz it was deleted
ah
const message = await interaction.reply({embeds: [msg], components: [row], withResponse: true});
message is not a Message here but an InteractionCallbackResponse
InteractionCallbackResponse discord.js@14.19.3
Represents an interaction's response
but I don't understand, it always worked in my way...
It did, before you added withResponse: true, that changes the return type
so what happens if I remove that parameter?
You're asking the wrong questions: just use response.resource.message instead (naming the result of the reply() call response instead to not get confused)
Will try thanks
whats this button in the embed?
did i miss some api update
A regular button. But that's not an embed. That's a container #announcements message
is it's interaction handled the same way as a regular button?
Yes, it's the same kind of button. The container is the thing that's different
tag the docs please
its my bots
Dunno why you need multiple for the same code, but as answered earlier, they should be in separate processes
documentation suggestion for @drifting dirge:
ContainerBuilder discord.js@14.19.3
A builder that creates API-compatible JSON data for a container.
https://sourceb.in/2VvtkJbxP9
Error: Invalid Form body: ];
await interaction.editReply({
^^^
components,
flags: MessageFlags.IsComponentsV2,
});
},
what is the full error
Invalid Form Body
content[MESSAGE_CANNOT_USE_LEGACY_FIELDS_WITH_COMPONENTS_V2]: The 'content' field cannot be used when using MessageFlags.IS_COMPONENTS_V2
you're trying to enable components v2 on a message that has contnet
you need to set content to null
when using editReply
oh alr
to show text on components v2 you need to use TextDisplayBuilder
Hello, there's a way to "set" the size of the text to move the part in the "void" (where there's no image/select menu) to a new line?
there's no way to specify the text size but you can put -# at the start of the line to make it a bit smaller
-# like this
Not really responsive xd
I mean you can use \n to make a new line but that isn't very responsive either
honestly your best bet is to either split it into 2 sentences and put them on new lines or just use -#
We were used an empty image before to set the size to the select menu like that for a perfect match, trying to do that in V2 but not really possible :(
actually I mean you might be able to use a section with a thumbnail accessory of a blank image
SectionBuilder discord.js@14.19.3
A builder that creates API-compatible JSON data for a section.
I will try thanks :)
section on top?
just put the text inside of a section
with an accessory of a thumbnail
it makes a similar style to a description with thumbnail in legacy embeda
Maybe it's just not possible
yeah it's slightly better but not much
what arguments are emitted by listeners at the 'ignore' event. the argument seems to be ...* but theres no further documentation on it
(event) Collector#ignore discord.js@14.19.3
Emitted whenever an element is not collected by the collector.
What are the different ways I can create containers?
with a raw object or with the builder
or a mix of both right?
that's just gonna be pain
you can just pick one and use it
no need to alternate
How to check if i can dm a user or not?
by sending them a dm
so i can't check beffore sending the dm?
no
Thanks 
is it ok to put 2 type of component collector together ?
msg.createMessageComponentCollector({filter:filter, componentType: ComponentType.Button | ComponentType.StringSelect, time: 30000 })
cause it's only collect select menu and not collect any button
Well, 2 | 3 is indeed 3. so that's not achieving what you want. Instead don't pass componentType at all and it'll collect all components on that message
oh right ty
what are some recommended hosting services?
module.exports = {
data: new SlashCommandBuilder()
.setName('switch-category')
.setDescription('Change the service category of the current ticket')
.addStringOption(option =>
option.setName('category')
.setDescription('Select the new category for this ticket')
.setRequired(true)
.setAutocomplete(true)
),
async autocomplete(interaction) {
const focusedValue = interaction.options.getFocused();
const choices = ['Popular Topics: Threads', 'Sharding: Getting started', 'Library: Voice Connections', 'Interactions: Replying to slash commands', 'Popular Topics: Embed preview'];
const filtered = choices.filter(choice => choice.startsWith(focusedValue));
await interaction.respond(
filtered.map(choice => ({ name: choice, value: choice })),
);
},
I'm confused, why do I not get any autocomplete options with this?
did you register your command with autocomplete or add it after it was registered?
(and are you actually calling that autocomplete function)
i ran deploy-commands.js after adding the autocomplete code
ah, should I add something to my interactionCreate event
AutocompleteInteraction discord.js@14.19.3
Represents an autocomplete interaction.
Yes, an AutocompleteInteraction is another type of interaction you have to handle
ahaha yes thank you so much
have a blessed day
what does this mean??
DiscordAPIError[50001]: Missing Access
your bot doesnt have access to whatever you are trying to access
refreshing commands??
guild commands or global commands?
showing your code would be really useful instead of just guessing
im completely lost with all this bot stuff now
how do i remove a default authorisation link?
DEV portal, your bot, Installation tab
const { REST, Routes } = require('discord.js');
require('dotenv').config();
const commands = [
{
name: 'pingity',
description: 'help'
},
];
const rest = new REST().setToken(process.env.TOKEN);
(async () => {
try {
console.log(`Started refreshing application (/) commands.`);
const data = await rest.put(
Routes.applicationGuildCommands('1339327441784537098', '1327585829979422741'),
{ body: commands },
);
console.log(`Successfully reloaded application (/) commands.`);
} catch (error) {
console.error(error);
}
})();
DiscordAPIError[50001]: Missing Access
what????
Your bot doesn't seem to be in that guild
Check the ids
Both clientID and guildId as well as that the clientID matches the token
also if the IDs are correct then check if the bot was added to the guild with the applications.commands scope
else if (interaction.options.getSubcommand() === 'information' && interaction.commandName === "driver") {
When I run on replit works fine all good beautiful but when I run it on railway it doesn't detect command being run
Declared as this name: 'driver', description: 'Get the information of a NDC driver', options: [ { name: 'information', description: 'Get the information of a NDC driver', type: 1, options: [ { name: 'user', description: 'The user to get the information of', type: 6, required: false } ] },
oh hold up ima a fucking idiot
You can't add bots without that scope anymore. Even if you omit it it's implied
oh I didn't know that
cool
is it possible to set a clan tag for a bot
no
how can I use member var and edit permissions of a channel to set ViewChannel to netural state (not enabled nor disabled)?
I tried this:
await voiceChannel.permissionOverwrites.edit(member, {
allow: allow.bitfield,
deny: deny.bitfield,
});
And it didnt work
Thats not the format that edit takes
i dont know how to fix this and need help with my account manager because after 45 minutes of having accounts launched all accounts but the first 4 launched will completely close. i recorded it and can send the moment it happens if it will help.
What does this have to do with discord.js?
are you running multiple bots?
roblox account manager is git hub and i looked up github discord and this popped up and it said to ask for help in this server if needed. sorry if im in the wrong spot. where could i get help?
using multiple acounts y es.
You are in the wrong spot
This is a support server for discord.js bots
I have no idea where you can get support for Roblox account manager
ok, thanks and sorry.
No worries
uhm
who can tell me how to get discord.js
@unique shoal
npm install discord.js
where do i type that
Can you please read the server rules and not ping mods for no reason, thanks
sure
If you don't know where to type that you aren't going to be able to use it
What do you think discord.js is?
uhm i cant type npm init it does nto work
Why
look let me take a ss
Suggest you follow the guide. It has a section on getting ready to use discord.js
it says i need to use npm init
That error literally includes a link on how to fix it
let me try
I'm new to keyv, so I'll need help while I'm reading this doc. I won't require much help, just some simple answers, so I know if I'm heading in the right direction or not
Please see #1081585952654360687 or #useful-servers
not a discord.js v14 kinda question, i'm assuming 😭
how to run my command
i saw i need to put npm app.js but it does not work
@unique shoal dont get mad but can you tell me how to run cmd i have discord.js now
No
You have to write the bot, discord.js is a library, not a bot.
so how do i see if my cmds are working
Have you written the code for the commands?
uhm
i have another question
which is?
how to run scripts in my discord srver
what do you mean by "run scripts"
and how is it related to discord.js
idk but i saw some people script to get memebers and i want to know how
You can follow the guide here if you need help setting up your bot and making commands.
We can answer specific questions for issues you're having, not "how to make a bot"
I think you somehow got in the wrong server, and what you're asking doesn't sound allowed by the discord tos either way
maybe i saw people use discord.js to do that so i got in
discord.js is a library to code bots
like dyno, mee6, etc
can you tell me how to make a bot
we already did
^^
Home: Introduction - Before you begin...
read more
npm is Node Package Manager
if you want to run javascript file, please use node <filename>
and yeah
there's no defferedReply for button interaction?
ButtonInteraction#deferReply() discord.js@14.19.3
Defers the reply to this interaction.
// Defer the reply to this interaction
interaction.deferReply()
.then(console.log)
.catch(console.error)
There is. It’s just not an option of interaction.reply method
OOOOH
thx for info
eh. if i want my bot to reply to a message ephemerally
but simply message.reply({content: "hehe", ephemeral: true}) doesnt work
You can’t. It’s exclusive to interactions
have any suggestion like that got denied b4? i want that feature
Yes
It wont happen, since it would allow for endless unmoderatable spam
do collector can recieve modal submit?
either use <Interaction>#awaitModalSubmit() or use an InteractionCollector
InteractionCollector discord.js@14.19.3
Collects interactions. Will automatically stop if the message (messageDelete or messageDeleteBulk), channel (channelDelete), or guild (guildDelete) is deleted. Interaction collectors that do not specify time or idle may be prone to always running. Ensure your interaction collectors end via either of these options or manual cancellation.
const embeds = message.embeds
if (!embeds) {
await thread.send(**${message.author.username}:** ${message.content});
} else {
await thread.send({
embeds: [embeds],
content: **${message.author.username}:** ${message.content}
})
}
what did i do wrong
at handleErrors (C:\Users\NotAdmin Kewl\Desktop\cODING\DiscordBot\Moderator Certification Python\node_modules\@discordjs\rest\dist\index.js:748:13)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
at async SequentialHandler.runRequest (C:\Users\NotAdmin Kewl\Desktop\cODING\DiscordBot\Moderator Certification Python\node_modules\@discordjs\rest\dist\index.js:1149:23)
at async SequentialHandler.queueRequest (C:\Users\NotAdmin Kewl\Desktop\cODING\DiscordBot\Moderator Certification Python\node_modules\@discordjs\rest\dist\index.js:980:14)
at async _REST.request (C:\Users\NotAdmin Kewl\Desktop\cODING\DiscordBot\Moderator Certification Python\node_modules\@discordjs\rest\dist\index.js:1293:22)
at async ThreadChannel.send (C:\Users\NotAdmin Kewl\Desktop\cODING\DiscordBot\Moderator Certification Python\node_modules\discord.js\src\structures\interfaces\TextBasedChannel.js:195:15)
at async Client.<anonymous> (C:\Users\NotAdmin Kewl\Desktop\cODING\DiscordBot\Moderator Certification Python\index.js:298:7) {
message.embeds is a collection an array, which you wrap in another array
am i supposed to know what ur saying rn?
if you have any idea about what your code does, yes
correction, message.embeds is an array of embeds*
embeds: takes an array of embeds
you are now passing an array of array of embeds
what's the ModerateMembers perm? i randomly find it in autocomplete along with Kick..., Ban..., Mute...
For timing out members
the MuteMembers already exists, so ModerateMembers is basically the same?
Maybe? Idk though, I just know moderate members is for timing out people
MuteMembers is for muting voice
Ah ofc
ModerateMembers is for timing out, which prevents users from sending messages, joining voice channels etc.
ok
Allows for timing out users to prevent them from sending or reacting to messages in chat and threads, and from speaking in voice and stage channels
where u took it from? like, last time i checked discord.js.org i dont see it
discord developer documentation
im new to discord.js i got no idea how to fix it and you saying array disctionary array whatever doesnt help me
use embeds: embeds in short terms
wow instead of just saying this give a 50 hour long explaination which the receiver wont even understand
Stop it
Yes, you are expected to know what an array is if you're writing Javascript
"you are passing an array of an array, where an array is expected" - 50hr long explanation - ok buddy
Its a very basic concept and we should not be expected to handhold you through that level of knowledge
yes! 2nd day of using discord.js btw :)
so.
Great! Glad you're here, but you do need a decent understanding of the language its written in to use it
We have great tutorials and guides on Javascript in #resources
i dont need tutorials i know the basics just for not knowing this one array thing bruh
btw what's the << thing? like 1 << 3 is 0x8
Left shift (<<)
The left shift (<<) operator returns a number or BigInt whose binary representation is the first operand shifted by the specified number of bits to the left. Excess bits shifted off to the left are discarded, and zero bits are shifted in from the right.
Good to hear! I guess there wont be any more complaints about someone not just handing you the answer to very basic JS concepts then!
not ur decision. now bye
Oh but it is 
"know the basics" while "not knowing this one array thing bruh" contradicts. r u sure u know things?
yeah, you should carefully learn js before coming to discord.js because discord.js is js
-ev (0b00100 << 2).toString(2) // @clear oar maybe that makes it clear
'10000'
```• d.js `14.19.1` • Type: `string` • time taken: `0.186047ms`
0b lets you write binary literals .toString(2) displays a number as binary string
hm... ok i see
do you expect me to go through all basics top to bottom?
no
ill learn it as i go
Did it too, trust me its way harder than just doing a course
worst idea. i only "learn it as i go" when i come to new user-made contents like discord.js; the basic stuff of javascript, i learned from top to bottom
that's not very hard
Do it however you like, just dont act entitled to volunteers handing you explanations
i know its not hard
i just dont wanna spend 3 weeks on javascript basics.
learning as i go is much simpler for me
i did it for all languages i code
There are videos on youtube explaining basics in just hours
Lets move on
I dont care how people decide to learn, as long as it isn't burdening those who provide support here
i wish i had reaction perms... but i hope notadmin (not gonna ping) fixed his problem thru the upside down guy's debug
upside down guy 
how to use emitter.setMaxListeners()
how to get the author of interaction (e.g who clicked on button)
documentation suggestion for @clear oar:
ButtonInteraction#user discord.js@14.19.3
The user who created this interaction
it sets the maximum amount of listeners you can listen on an event
i know
i was wondering how to properly use it
emitter.setMaxListeners(int) iirc
this seems to be it:
client.on('interactionCreate', async (interaction) => {
if (!interaction.isCommand()) return;
const emitter = new EventEmitter();
emitter.setMaxListeners(20); // Set the limit for this specific emitter to 20.
const { commandName } = interaction;
// other code
btw im bored with slash commands and still using conventional commands. is it good to create a button with id button-id-<user id> and when interactionCreate only match <user id> can use button
depends on how you want your buttons to work
there's use cases for either behavior
oh, you mean for validation - no, see monbrey
Why not just match on interaction.user
mhm. so you thought we can set it to a float, a string, an array? [insert kekking emoji here]
i looked it up on google and thought
Why are you attempting to do this?
im using conventional commands, and idk how to make it author-only
The convention is slash commands
06-10 10:27:02 (node:44) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 12 interactionCreate listeners added to [Client]. MaxListeners is 11. Use emitter.setMaxListeners() to increase limit
"prefix commands" im using 🥀 💀
So, constructing a new event listener that has no listeners attached and changing the max of that wont help
The real issue is - why do you have 12 interactionCreate listeners
maybe merge all the stuff into one, or he thought event listeners can work in parallel so it improves performance
it does not
because i can
and i like chaos
Technically yes you can
Except now it throws warnings
Can yes, should, no
this is a bad reason; you should sacrify some pretty factors in your code, and merge all of them into one function, it's better
but i love chaotic code and errors because its fun to recode stuffffffff
i dont get it
good on you, but what are you doing here then?
btw to mention something this is not a javascript server @sudden grove, this is for a discord bot library called "discord.js"
was asking about event emitter resetting max to higher limit
but i thought i was using discord.js but ig it is 6:41 am and was tired
soooo i ruined it all-
Yeah its fine
Client is an event emitter
Its a valid question
sorry my bad
irrelated, but event emitter, api-er, represents a client, manage stuff, read messages, all in a client class is kinda impressive to me, not even speaking about how much more you can do with events
on top of all, every action will get a promise. rlly good
let button = new ButtonBuilder()
.setCustomId("ephemeral-" + m.author.id)
.setStyle("Success")
.setLabel("Click me.")
let actrow = new ActionRowBuilder().addComponents(button)
m.reply({components: [actrow], embeds: [{
title: "Click on me to show an ephemeral message. (Disappears after 30 seconds)",
color: Colors.Green
}]}).then(_ => {
setTimeout(() => {
_.delete().catch(e => {})
m.delete().catch(e => {})
}, 30000)
m.createMessageComponentCollector({
componentType: ComponentType.Button,
time: 30,
filter: (inter) => {inter.user.id == m.author.id}
}).on("collect", i => {
i.reply({content: success("Success!", "This is an emerpheral message. None except you can see it", i.user), flags: MessageFlags.Ephemeral})
}).on("ignore", i => {console.log("Ignored " + i.user.id + " 's interaction to " + i.type + " " + i.customId)}).once("end", (is) => {console.log("Collected " + is.size)})
})
expected behavior
When user clicks the "Click me" it should responds with an ephemeral. The message and collectors last 30 seconds
results
Not doing anything, simply "Interaction failed"
more info
fatal(), success() is my preset embed building utility. treat them like an embed
fatal/success(string title, string description, discord.User author)
whoops wait i think it's because im setting time for the timer to 30ms than 30 seconds
can my bot create guild invites?
sure it can
couldn't find a method for that in Guild class
documentation suggestion for @night kindle:
TextChannel#createInvite() discord.js@14.19.3
Creates an invite to this guild channel.
// Create an invite to a channel
channel.createInvite()
.then(invite => console.log(`Created an invite with a code of ${invite.code}`))
.catch(console.error);
have to do it in a channel
I see thanks
Can I add a role using the role ID?
For example:
const role = process.env.VERIFIED_ROLE_ID
await member.roles.add(role)
yes
Thank you
can i add multiple MessageFlags?
like both Ephemeral & IsComponentsV2
The ephemeral option when replying to an interaction will be removed in v15
- {..., ephemeral: true}
+ {..., flags: MessageFlags.Ephemeral}
``` Read [here](<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_OR>) on how to specify multiple flags
yes
got it, thank you!
is there a djs function to escape all formatting?
escapeMarkdown discord.js@14.19.3
Escapes any Discord-flavored markdown in a string.
ty
AttachmentFlagsBitField discord.js@14.19.3
Data structure that makes it easy to interact with an flags bitfield.
help
Use time: 30000
can ComponentsV2 can be sent through DMs
used
Also try to add the collector to _ and not m i believe.
Can’t really help much. Viewing code on phone sucks
Since m is a different message than _ the bot message
no, wont work either
Any errors that could help?
also please show your updated code
m is Message btw
componentType in the filter should be Button, not ActionRow
hm.... and?
nothing and
change it
oh it seems to ignore my interaction, but it shows type 3 while ComponentType.Button is 2
3 is select menu
you are not showing a select menu in the code
but interaction.type is also not a component type
its the type of the interaction, in this case MessageComponent
done, i removed the filter and let it do when receive interaction instead
ig it's the filter not doing its job properly
mhm. thanks
nvm
can someone help i followed the docs correctly
ModalBuilder#addComponents() builders@1.11.2
Adds components to this modal.
In TypeScript, you define the generic on an ActionRowBuilder
new ActionRowBuilder<TextInputBuilder>()
oh u put in that way i put in the modal.addComponents one thx
So in componentv2 am I able to make an image go on the left?
No
does MessageCreate event also trigger for thread messages?
yes
Yes, if the bot can see that channel/thread
Do you need the Channel partial for threads, or are they cached like normal guild channels?
Active threads the bot can see are cached. Channel partial is only needed for DMChannel
👍
That's what I thought, just couldn't remember 100%
Guys how do I log users who have a specific role? I did it but nothing came out in the array
You'd need to have all members cached for that to work. So fetch all members once in your code, the it'd be accurate for the runtime of your bot
djs is very good guys. i love it
can ComponentV2 be sent through DMs?
Yes
thanks
Hey guys, a bot cannot forward the message object it gets from listening to onMessageDelete right?
For the life of me I cant get the attachment url after sending this
embeds: [responseEmbed],
files: [attachment],
components: [row.toJSON()],
withResponse: true,
});```
wherever I find "attachments" its always emtpy collection
Can you show how you're actually trying to get the URL? You've only showed how you're sending the reply
No, because there is no message to be forwarded since it doesn't exist anymore
Oh well
So when trying to log this message (moderation purpose) I should post the snapshot 
Not sure what snapshot you'd be talking about here
The messageSnaphots
That's for if the message itself is a forward of another message
The only data you'd be getting from that event is the channel ID, message ID, and any other data that d.js already has cached about that message (taking into account Partials)
So what you see is what you get. You can't take anymore API actions on the message after the event emits because as far as Discord is aware, it's now gone
Is it possible to send components V2 via WebhookClient? While my mesage sends fine via a normal message, in a webhook it results in 'Cannot send an empty message', code: 50006. I'm using query ?with_components=true on the end of my webhook URL, for some reason however when the error comes back the query has changed to ?wait=true Am I doing something wrong or is there a known issue in discord.js atm?
i think the with_components has to be there every time
it is
it fails the very first time I send the webhook
Here is a quick example of my code, as I say, results in 'Cannot send an empty message', code: 50006:
const { WebhookClient, MessageFlags, TextDisplayBuilder } = require('discord.js');
const templatesWebhook = new WebhookClient ({ url: 'https://discord.com/api/v10/webhooks/_redacted_/_redacted_?with_components=true'});
const textComponent = new TextDisplayBuilder().setContent( 'test message webhook');
await templatesWebhook.send({flags: MessageFlags.IsComponentsV2, components: [textComponent]});```
I can only assume that for some reason the 'with_components' query is not applying
you need to pass withComponents: true in the send call
i dont know if those query params are passed on
Discord.js parses out the webhook ID and token from the URL. That query is getting discarded
right, ill try shortly what you suggest @zenith violet
perfect, many thanks, that did the trick.
if the server has access to it and unlocked, can a bot set a role gradient or not yet avaible through api?
it has not been documented by discord yet
Yeah the thing is, they are nowhere in there
const reply = await interaction.reply({
embeds: [responseEmbed],
files: [attachment],
components: [row.toJSON()],
withResponse: true,
});
console.log(reply)
const attachments = reply.resource?.message?.attachments```
is it because its a reply or something, I tried so many different ways the attachments are just never there
Hi,
Is there any easy loop-free way to apply permissions to a role in all channels of a guild ?
Thanks
No, but depending on what you're trying to do there might be a better way anyways
The objective is :
overwrites all channel-specific permissions
Why? Because if you're trying to grant a permission, do it in role permissions. If you're trying to mute, consider using timeouts. If you're granting permissions to a user, can it be done by giving them a role instead?
This snippet works on my machine with a random image. Does it actually have attachments? And how big are they?
I'm trying to grant a permission to a user via a role yes, and assigning the permissions only globally might not be enough because of pre-existing channel-specific permission overwrites.
Okay. That's still pretty vague so to go back to your original question: No, there is not a way to bulk change permission overwrites in multiple channels. So if you're insistent that's the best solution, then you would need to loop through them (which seems like a pretty spammy workflow)
That's still pretty vague
I have been asked to build a bot that temporarily gives a permission to a user.
That permission should apply server-wide.
If that permission was explicitly denied to at-everyone or any role that the user has in specific channels, then the bot must override that.
if you're insistent that's the best solution
I'm not, that's only what I was suggested to do, and I'm precisely here to ask if there's anything better.
I mean personally I'd just give them a role and assume any conflicting overwrites were intentional. If not, have the admins refactor server permissions as a one-time thing so that it can be done without mucking up overwrites every time you need to temporarily give perms. But that's not really a discord.js thing
Well, unfortunately I've been explicitly asked to deal with that this way. 😭
Thanks anyway
Unfortunate. Sometimes it is that way. Best of luck!
Thank you, have a good day !