#djs-help-v14
78874 messages · Page 10 of 79
Is it possible to get the original ID of the user that used a command by the interaction of a button in this said message?
Like I do a command /messageWithButton the bot reply to that command with a message and a button, can I get the ID of the user who made the command?
Message#interactionMetadata discord.js@14.19.3
Partial data of the interaction that this message is a result of
It‘s in there, on the <ButtonInteraction>.message
One per ActionRow. Total components limit is 40
So absolute max would be 19
But that would not be a nice message to work with
No. 19 ActionRows, 19 menus, 1 container = 39 components
Yes
Hi, is there a way to not have to define an emoji when using StringSelectMenuOptionBuilder ?
Wdym by not have to define emoji? It's optional, you don't need to provide it
ig but I'm getting TypeError: Cannot destructure property 'emoji' of 'selectMenuOption' as it is undefined.
I'm probably doing something wrong then
const selectMenu = new StringSelectMenuBuilder()
.setCustomId('selectSquad')
.setOptions(squads.slice(0, 25).map(squad => {
new StringSelectMenuOptionBuilder()
.setLabel(`${squad.id}`)
.setValue(squad.name);
}));
Can you show the full error please?
Am I also right by saying since you don’t return anything from the .map it’ll result in an empty array?
yep just saw that
Ah, that is true as well
it's always when you ask that you find your stupid error
If you didn’t ask you’d have found it later
im sure this question has been asked millions of times but
// if i have a message thats stored in a variable like this
const sent = await message.reply("hi")
// and then significantly later i try to access it
setTimeout(() => {
await sent.edit("bye")
}, 60 * 60 * 1000)
// how do i ensure at this point sent hasn't been deleted?
// if someone manually deletes it before now then it throws an api error for `Unknown Message`
Catch the rejection when editing
is there not any other method than catching it
No
Hi, what can cause an error like this?
TypeError: Cannot read properties of null (reading 'byteLength')
at Object.pull (C:\...\node_modules\undici\lib\web\fetch\body.js:63:20)
at ensureIsPromise (node:internal/webstreams/util:185:19)
at readableByteStreamControllerCallPullIfNeeded (node:internal/webstreams/readablestream:3099:5)
at readableByteStreamControllerPullSteps (node:internal/webstreams/readablestream:3207:3)
at [kPull] (node:internal/webstreams/readablestream:1197:5)
at readableStreamDefaultReaderRead (node:internal/webstreams/readablestream:2243:39)
at nextSteps (node:internal/webstreams/readablestream:507:7)
at async writeIterable (C:\...\node_modules\undici\lib\dispatcher\client-h1.js:1437:22)```
sounds like a problem while fetching, probably when trying to send an attachment based on its url?
could try fetching yourself and sending the buffer instead
I just updated to D.js 14.19.3, updated my Gatewayintentbits, and now messages don't seem to have a "channel" property (in a server)
They have the channelId, but not the actual channel property, has something changed? I have:
GatewayIntentBits.Guilds
GatewayIntentBits.GuildMessages
GatewayIntentBits.MessageContent
Is there something I'm missing?
don't seem to have, or it's null?
and where are you checking that?
It's undefined, I have a ton of things that reference message.channel.send() but they all don't work anymore since channel is undefined
I printed Message to the console as well but it's not there
<ref *1> Message { channelId: '547950347814174720', guildId: '135207762299715584', id: '1370808735542280323', createdTimestamp: 1746896670948, type: 0, system: false, content: '!eval main.syncCalendar()', author: User { id: '151030795753095168', bot: false, system: false, flags: UserFlagsBitField { bitfield: 4195072 }, username: 'kiwiz0', globalName: 'Kiwi', discriminator: '0', avatar: '4f3d4d34be7d494787a0d407bfeb98d1', banner: undefined, accentColor: undefined, avatarDecoration: null, avatarDecorationData: null }, pinned: false, tts: false, nonce: '1370808739124215808', embeds: [], components: [], attachments: Collection(0) [Map] {}, stickers: Collection(0) [Map] {}, position: null, roleSubscriptionData: null, resolved: null, editedTimestamp: null, reactions: ReactionManager { message: [Circular *1] }, mentions: MessageMentions { everyone: false, users: Collection(0) [Map] {}, roles: Collection(0) [Map] {}, _members: null, _channels: null, _parsedUsers: null, crosspostedChannels: Collection(0) [Map] {}, repliedUser: null }, webhookId: null, groupActivityApplication: null, applicationId: null, activity: null, flags: MessageFlagsBitField { bitfield: 0 }, reference: null, interactionMetadata: null, interaction: null, poll: null, messageSnapshots: Collection(0) [Map] {}, call: null }
Just because it doesn’t print here doesn’t mean it’s undefined
It‘s a getter from cache, not an enumerable property
Is there some special magic I need to use, to add a StringSelectMenuBuilder on a ContainerBuilder?
export class BeginQuestSelector extends StringSelectMenuBuilder {
public customId: string;
constructor(gameNames: string[]) {
super();
const selectorId = `selector:beginQuest:${randomUUID()}`;
this.customId = selectorId;
if (gameNames.length === 0 || gameNames.some(gameName => gameName.length === 0)) {
throw new Error('Join Quest is improperly configured. Check the configuration.');
}
this.setCustomId(selectorId)
.setPlaceholder('Select a quest to begin...')
.setMinValues(1)
.setOptions(gameNames.map(gameName => ({ label: gameName, value: gameName })));
}
}
I'm attempting to put that into a container, (Works just fine for an embed)
if (quests.length > 1) {
const beginQuestSelector = new BeginQuestSelector(quests);
container.addActionRowComponents(
new ActionRowBuilder<BeginQuestSelector>()
.addComponents(beginQuestSelector)
)
} else {
container.addActionRowComponents(
new ActionRowBuilder<ButtonBuilder>()
.addComponents(
new ButtonBuilder()
.setCustomId(decodedId.customId)
.setLabel(`Begin Quest: ${quests[0]}`)
.setStyle(ButtonStyle.Success)
)
)
await interaction.reply({
components: [container],
flags: MessageFlags.IsComponentsV2
});
};
it needs to be added to an action row first nv you did that
Uhhh it is being added... right there after the quest length conditional check xD
You‘d need StringSelectMenuBuilder as generic. Because your extended class is not something the ActionRowBuilder can check against
I even tried using a plain ole "StringSelectMenuBuilder" without my implementation, and statically defined values, even that didn't work
Not work in what way? What happens
That's the weird part, just times out, no errors, nothing.
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
Yep done all that too. Stops here. Everything appears valid.
Is this another case of #djs-help-v14 message ?
Your debugger causing you to not actually find the bugs
No that was the first thing I checked lmao
Run your code regularly, add the logs the tag mentions, show what logs and what doesn’t. And make sure you don’t have any uncaughtException or catch blocks interfering with you getting the actual errors
So it's probably because the channel is not in the bot's cache?
I'm stupid asf.. I found the problem
what was it?
it should be null in that case, but what does message.channel actually log
and where is the message coming from
how big is the difference of the Large and Small size of the SeparatorSpacingSize? i feel like it's basically none
message.channel is undefined, I get TypeError: Cannot read properties of undefined (reading 'send') when my code runs like normal. It didn't use to do that
Message is coming from the command's message (legacy message content commands)
so messageCreate?
Yeah
can you npm ls discord.js
and show your full client constructor
wg-bot@4.4.0 /mnt/c/Code/Javascript/WG-Bot └── discord.js@14.19.3
export const bot = new Client({
autoReconnect: true,
messageEditHistoryMaxSize: 2,
messageCacheMaxSize: 250,
fetchAllMembers: true,
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildExpressions,
GatewayIntentBits.GuildWebhooks, GatewayIntentBits.GuildInvites, GatewayIntentBits.GuildVoiceStates, GatewayIntentBits.GuildScheduledEvents, GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildInvites]
});```
Only intents are actual properties that djs client accepts. All the rest doesn’t exist
Unless your Client class there is not imported from discord.js
Can you show the code where this error gets thrown? And the full error including stacktrace
I'll remove them, I think they're all leftover from a very old version
Is message by any chance the result of an <Interaction>.reply()? nvm, you already said it isn’t
Hey, is there any ETA on when the builders will be updated to support the new expanded component limits, or has that already been done?
Already done
Weird, I've still got the 10 component limit for some reason. I'll try updating again and see what happens.
Need builders 1.11.2
Which 14.19.3 depends on
okay, weird, i was certain i had already updated to 14.19.3 but after double checking it looks like it decided to go back to 14.19.2 (or i just never updated it properly)
oh well, fixed, thank you!
//Developer_Commands.js
export function evalFunc(message)
{
console.log(message);
try
{
let args = message.content.slice(1).trim().split(/ +/g);
const code = args.slice(1).join(" ");
let evaled = evalFunc(code);
if (typeof evaled !== "string")
evaled = require("util").inspect(evaled);
//message.channel.send(evaled, {code:"xl"});
}
catch (err)
{
message.channel.send(`\`ERROR\` \`\`\`xl\n${err}\n\`\`\``);
console.log(err);
}
}
// ...
//Command_Check.js
case 'eval':
if(permLevel>=6)
{
developerCommands.evalFunc(message);
}
else
{
message.channel.send('Insufficient permLevel');
// This works, but after being passed to evalFunc, it no longer has channel
}
// ...
//bot.js
bot.on('messageCreate', async message => {
// ... message is not overwritten anywhere
checkCmd(messageArray, message, bot, args, command, channel);
// channel is message.channel
I figured it out but I'm really baffled on how it broke it. I did a rename symbol in VSCode to rename my function that was called eval. That made the eval in the try block "evalFunc()" instead of eval()
Undoing that fixed it somehow
evalFunc tries to call itself with the code string instead of message, then it can't access message.content, goes to the catch, there's no message.channel either, error
typescript would've caught that 
Damn yeah I usually do use Typescript but this code is like 5 years old at this point, just updating from d.js 12 and node 16 lol
Crazy how a function can call itself from within
it's called recursion, you've discovered it by mistake
I have to get better about going to debugging instead of console logging T.T
Thanks for the help pals!
hi i have a question maybe this is a common issue i don't know but im using
.setThumbnail(target.displayAvatarURL({ dynamic: true }))
in my embed, the image is appearing on my android phone but not on iphone
does anyone know the issue here? or why it's not appearing on iphone?
sounds like a client issue then
nothing djs can do about
#useful-servers ddevs perhaps
do you have an iphone?
no
and this is not djs related if it works on other devices
i personally don't care, cause i have an android i just wanna know if this is a common issue that images don't appear on a iphone
so i don't have to try search for solutions to fix it, so if it never works on a iphone please let me know
again, this is nothing djs can do about. ask in #useful-servers ddevs
o my bad i thought this server knows, do you know what server i need to go to?
sigh
re-read my message
no thanks ill just find the right server, fyi. the ''sigh'' makes u sound whiney
ddevs = discord developers, it's a server
because i told you twice which server to go to
it doesnt take much effort to just click
not going to lie i still don't knwo which server it is, there's a list of all kinds
ah thank you
^^
sorry i didn't know what ddevs means i was looking for it, but now i see u means = discord developers haha
Amgelo has told you what ddevs means
i know but i was looking for that word specifically, nowhere to be found
forgot to reply, there's some internal discussion on how to address it
imo it'll most likely be "fixed", though that wrapping shouldn't have been a thing in the first place
in the meantime you can use resolvePartialEmoji which is what the ButtonBuilder uses
I was capturing my reply in the "else" so it wasn't scoped properly.
hello,
so i'm making a ticket system where, when a modal is submitted, a channel is created with the name "appeal-membername"
i'm currently trying to make a system where, if a mod decides to decline the appeal, a string menu would appear with different options of why to decline to appeal
thing is, how do i send a dm to the member who submitted the modal?
do you have a db?
if yes, you should be saving the channel id and the member that created it and just query that
so the best thing i can do is set up a data base?
should i do that with sequelize?
if not, you could use the channel name to search the GuildMember, but if they change their username you're out of luck, you could save it to the description but then again if that description is changed it breaks
the most straightforward and constraint-less way would be with a db, yes
what db and orm you use depends entirely in your preferences and usage
but since it isn't djs related you should ask that in #1081585952654360687
alright, thanks
Does MediaGalleryBuilder not handle audio/audio links?
Is there something that does, or does discord not support in message audio like that
It doesn’t and no, not in components (yet?)
Thats a shame, but thank you. Guess I'll have to look into another way to handle them
Well, you can put them as File component. It will show as file/attachment. just probably not as playable in the UI directly
I was gonna try that actually, there's a fileBuilder same way there's a textDisplayBuilder and MediaGalleryBuilder, right?
yes
FileBuilder discord.js@14.19.3
they do show as files though
and it's intended that way
in the future as Qjuh said maybe they'll add some playable component
I see, thank you so much!
Is there any reason why these loading dots show at the bottom of my sent container component?
They don’t show on desktop, only on mobile.
client bug, ask discord
o ok
maybe try updating, it has been an issue for a while
kinda unexpected it's still around
just updated the app, tried again and it still shows, ill just ignore it lol
i wanted to transfer my /apod cmd from embed to component and according to the errors componentsv2 dont support such api requests rn is that true?
Huh? What „such api requests“? Show the actual error (and code)
at Object.execute (file:///C:/Users/ANON/Documents/spacecat/apod.js:59:19)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
at async Client.<anonymous> (file:///C:/Users/ANON/Documents/spacecat/apod.js:88:16)
Error Support: You won’t get those components, because they belong to Discord's internal/experimental V2 components API, which is not yet part of stable discord.js and isnt published.```
## apod.js code
```import dotenv from 'dotenv';
dotenv.config();
import pkg from 'discord.js';
import fetch from 'node-fetch';
const {
Client,
GatewayIntentBits,
Collection,
REST,
Routes,
SlashCommandBuilder,
createComponent,
Container,
TextDisplay,
MediaGallery
} = pkg;
// === SlashCommand definieren ===
const apodCommand = new SlashCommandBuilder()
.setName('apod')
.setDescription('Zeigt das Astronomy Picture of the Day der NASA mit UI-Komponenten.');
const commands = [apodCommand.toJSON()];
const rest = new REST({ version: '10' }).setToken(process.env.TOKEN);
// === SlashCommand registrieren ===
try {
console.log(':satellite: Registriere /apod Command...');
await rest.put(
Routes.applicationGuildCommands(process.env.CLIENT_ID, process.env.GUILD_ID),
{ body: commands }
);
console.log(':white_check_mark: Slash-Command registriert.');
} catch (error) {
console.error(':x: Fehler bei Registrierung:', error);
}
// === Bot starten ===
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
client.commands = new Collection();
client.commands.set('apod', {
data: apodCommand,
async execute(interaction) {
await interaction.deferReply();
const url = `${process.env.NASA_APOD_API}?api_key=${process.env.NASA_APOD_KEY}`;
try {
const res = await fetch(url);
const data = await res.json();
if (data.media_type !== 'image') {
return await interaction.editReply('Das heutige APOD ist kein Bild. :milky_way:');
}
const component = createComponent(
Container.from([
MediaGallery.from([
{
url: data.url,
title: data.title
}
]),
TextDisplay.from([
`📅 **${data.date}**\n\n**${data.title}**\n\n${data.explanation.substring(0, 4000)}`
])
])
);
await interaction.editReply({ components: [component] });
} catch (err) {
console.error('[APOD Fehler]', err);
await interaction.editReply('Fehler beim Abrufen des Bildes.');
}
}
});
client.once('ready', () => {
console.log(`🚀 Eingeloggt als ${client.user.tag}`);
});
client.on('interactionCreate', async interaction => {
if (!interaction.isChatInputCommand()) return;
const command = client.commands.get(interaction.commandName);
if (command) await command.execute(interaction);
});
client.login(process.env.TOKEN);
what is your djs version
and why are you using .from everywhere?Just use builders.
And you're missing the flag
Does the file builder not handle direct file urls same way mediaGalleryBuilder does?
const file = new FileBuilder({
spoiler: true,
file: {
url: 'file.png',
},
});```
like this
discord.js@14.19.3
it does, but you need to reference it with attachment://
There is no class Container nor does ContainerBuilder have a .from method. Don’t just guess class names, look at the docs
Is there any built-in support in Discord (Gateway or REST) or in discord.js to tell which invite code a new guild member used when joining (and therefore who invited them)?
Or must bots still implement manual invite tracking (fetching guild invites before/after a join) to determine which invite was used?
Why do bots need to know at all? Mods can see it in mod view. Bots can’t
Do you mean me?
Considering you’re the only one that said something since my last message: yes
guys is there a guide to use the container component?
not yet
currently running into an issue when attempting to edit an interaction reply with a buffer image created using napi-rs/canvas
const captcha = await buildCaptcha(correct);
const reply = await interaction.editReply({
embeds: [{
color: Colours.Primary,
description: 'To process your vote, please select the button with the right answer',
image: {
url: 'attachment://guilds-captcha.png'
}
}],
files: [new AttachmentBuilder(captcha, { name: 'guilds-captcha.png' })],
components: [{
type: ComponentType.ActionRow,
components: words.map((word, index) => ({
type: ComponentType.Button,
style: ButtonStyle.Secondary,
label: word,
custom_id: `captcha-${index}`
}))
}]
});```
This is the code which creates and sends the image. Commenting out the files property prevents the error, though of course prevents the image from being sent.
```sh
TypeError: Cannot read properties of null (reading 'byteLength')
at Object.pull (C:\...\node_modules\undici\lib\web\fetch\body.js:63:20)
at ensureIsPromise (node:internal/webstreams/util:185:19)
at readableByteStreamControllerCallPullIfNeeded (node:internal/webstreams/readablestream:3099:5)
at readableByteStreamControllerPullSteps (node:internal/webstreams/readablestream:3207:3)
at [kPull] (node:internal/webstreams/readablestream:1197:5)
at readableStreamDefaultReaderRead (node:internal/webstreams/readablestream:2243:39)
at nextSteps (node:internal/webstreams/readablestream:507:7)
at async writeIterable (C:\...\node_modules\undici\lib\dispatcher\client-h1.js:1437:22)```
I've logged `captcha` and it's definitely a buffer, and I've also stored it as a file, and it's definitely a working image
d.js version: v14.19.3
Totally get that bots can’t see invite info today, but for things like welcome messages or referral stats it’d be awesome if the API exposed who invited someone. Any chance “inviter” gets added to the GuildMemberAdd event down the road?
do you know how to edit it? or is it even possible to
- add buttons below the message + edit the container?
thats a question for discord
What kind of Buffer?
Okay thx
I doubt it, considering discord explicitly disallows offering incentives for invites
const buffer = canvas.toBuffer('image/png');
const tempDir = './tmp';
const fileName = `captcha-${randomText(5)}.png`;
const filepath = join(tempDir, fileName);
await mkdir(tempDir, { recursive: true });
await writeFile(filepath, buffer);
return buffer;
this is what's returned by the buildCaptcha function
That doesn’t sound like a regular NodeJS Buffer
I just wanted it to show users who entered with a code for identification purposes and nothing else, but thx all
well the weird thing is, im running the exact same buildCaptcha function and embed on a different version of the bot which uses tsc and it works perfectly fine. same version djs and napi-rs/canvas, only difference is the one experiencing the error is tsup
this is logging captcha
Buffer.isBuffer(obj)
Returns true if obj is a Buffer, false otherwise.
what does that log
the image works too, it's being saved onto my folder and looks as it's supposed to
i can log byte length too
console.log('Buffer.isBuffer: ', Buffer.isBuffer(captcha), captcha.byteLength);
// Buffer.isBuffer: true 418165```
moved to https://discord.com/channels/222078108977594368/1370887431846498374
guys, the container can only be sended by a interaction?
no
Client,
GatewayIntentBits,
REST,
Routes,
SlashCommandBuilder,
ContainerBuilder,
TextDisplayBuilder,
MediaGalleryBuilder,
MediaGalleryItemBuilder,
SeparatorSpacingSize,
MessageFlags,
} from 'discord.js';
import fetch from 'node-fetch';
import dotenv from 'dotenv';
dotenv.config();
const { TOKEN, CLIENT_ID, NASA_APOD_KEY, NASA_APOD_API } = process.env;
const client = new Client({
intents: [GatewayIntentBits.Guilds],
});
const rest = new REST({ version: '10' }).setToken(TOKEN);
const apodCommand = new SlashCommandBuilder()
.setName('apod')
.setDescription("Sends NASA's Astronomy Picture of the Day");
async function registerCommands() {
await rest.put(
Routes.applicationCommands(CLIENT_ID),
{ body: [apodCommand.toJSON()] }
);
console.log('/apod registered');
}
client.once('ready', () => {
console.log(`Logged in as ${client.user.tag}`);
});
client.on('interactionCreate', async interaction => {
if (!interaction.isChatInputCommand() || interaction.commandName !== 'apod') return;
await interaction.deferReply({ flags: MessageFlags.Loading });
try {
const res = await fetch(`${NASA_APOD_API}?api_key=${NASA_APOD_KEY}`);
const data = await res.json();
if (!data || !data.title || !data.explanation || (!data.url && !data.hdurl)) {
console.log('Fehlerhafte API-Rückgabe:', data);
return interaction.editReply({ content: 'Fehler beim Abrufen des APOD.' });
}
const container = new ContainerBuilder().setAccentColor(0x1d2951);
const titleBlock = new TextDisplayBuilder().setContent(`# 🌌 ${data.title}`);
container.addTextDisplayComponents(titleBlock);
const descBlock = new TextDisplayBuilder().setContent(data.explanation);
container.addTextDisplayComponents(descBlock);
if (data.media_type === 'image') {
const media = new MediaGalleryBuilder().addItems([
new MediaGalleryItemBuilder().setURL(data.hdurl || data.url),
]);
container.addMediaGalleryComponents(media);
} else {
const videoBlock = new TextDisplayBuilder().setContent(`🎬 Video statt Bild: ${data.url}`);
container.addTextDisplayComponents(videoBlock);
}
container.addSeparatorComponents(s => s.setSpacing(SeparatorSpacingSize.Small));
const footer = new TextDisplayBuilder().setContent('© NASA - Astronomy Picture of the Day');
container.addTextDisplayComponents(footer);
await interaction.editReply({
components: [container],
flags: MessageFlags.IsComponentsV2,
});
} catch (err) {
console.error('APOD Fetch Error:', err);
await interaction.editReply({ content: 'Fehler beim Abrufen der APOD-Daten.' });
}
});
await registerCommands();
client.login(TOKEN);
is there something wrong that the image never loads?
const audioAttachment = new AttachmentBuilder(Buffer.from(activeContent.url), {name: 'test.mp3'});
const fileComponent = new FileBuilder({
file: {
url: `attachment://test.mp3`,
},
});
await interaction.channel.send({
flags: 32768,
components: fileComponent,
file: audioAttachment
});```
Am I doing something wrong here?
`TypeError: this.options.components?.map is not a function at MessagePayload.resolveBody`
I'm getting this error
components is an array
oh right
remembered both components and file need to be array, but now I'm getting this error message
components[0].file.url[UNFURLED_MEDIA_ITEM_REFERENCED_ATTACHMENT_NOT_FOUND]: The referenced attachment ("attachment://test.mp3") was not found
activeContent.url is just a direct link to a .mp3 file
files (plural) needs to be an array
in your code above, you're using file (singular)
changing it to files worked, thank you.
Didn't work as file: notarray
hello
im new with bots and im having problem making the slash command to work
Home: What's new
read more
hello?
Dekes was pointing you to the guide which has a step by step tutorial on getting slash commands to work
But to help you point somewhere in particular, what issue are you having with your slash commands?
- are they not loading to the bot (nothing shows up when you press /)
- are you getting "interaction has not responded"
- are you getting some other error?
ive never had this problem before and im really confused:
Type 'MessageFlags.Ephemeral' is not assignable to type 'MessageFlags | undefined'.
return void api.interactions.reply(interaction.id, interaction.token, {
flags: MessageFlags.Ephemeral,
content: 'aa',
});
the code works properly
im able to suppress the error by using Math.trunc(MessageFlags.Ephemeral) but i dont know why it just isnt working normally
Use : flags: [MessageFlags.Ephemeral]
forgot to mention im using /core so itll be a bitfield
You prob could just cast it. Personally, I don’t think it’s the correct type that should be used as it doesn’t properly describe combined bits
ok ty
is there a way to get ws ping using /core / /ws? WebSocketManager doesnt have a ping propery afaik and Client.gateway doesnt either
i dont use /core but im guessing it's this
https://discord.js.org/docs/packages/core/2.1.0/Gateway:Interface#send
send a heartbeat payload and youll get back a GatewayHeartbeat
just read. thanks
You need to either reply or defer beforhand
const permissions = new PermissionsBitField(BigInt('36953089'));
console.log(permissions.has(PermissionsBitField.Flags.ManageGuild));
I am trying to use the permissions number from get guilds in 0auth2. This should be correct right?
/users/@me/guilds this is the get method btw
It looks fine
It’s alr been replied/updated/deferred
what's the full error? from where did you import MessageFlags?
works fine for me
Im getting interaction already replied error and don't know from where
if (interaction.isModalSubmit() && interaction.customId === 'profileCreate') {
const userId = interaction.user.id;
const name = interaction.fields.getTextInputValue('name').trim();
const specialty = interaction.fields.getTextInputValue('specialty')?.trim() || null;
const bio = interaction.fields.getTextInputValue('bio')?.trim() || null;
try {
await User.create({
userId,
detectiveName: name,
specialty,
bio,
coins: 200,
xp: 0,
level: 1,
solved: 0,
failed: 0,
activeEffects: []
});
const embed = new EmbedBuilder()
.setTitle(`✅ Profile Created: ${name}`)
.setDescription(`Welcome, detective. Your career begins now.`)
.addFields(
{ name: ':dart: Specialty', value: specialty || '_None_', inline: true },
{ name: ':coin: Starter Coins', value: '200', inline: true },
...(bio ? [{ name: ':book: Bio', value: bio }] : [])
)
.setColor(0x3498db)
.setFooter({ text: 'Use /case to begin your first mystery.' })
.setTimestamp();
await interaction.reply({ embeds: [embed], ephemeral: false });
} catch (err) {
console.error(':x: Modal failed:', err);
await interaction.reply({ content: 'Profile creation failed.', ephemeral: false });
}
return;
}
well something is replying to your interaction somewhere
Perhaps some other listener
Show the full code
interactionCreate.js = https://sourceb.in/ms39z0DrRm
profile.js = https://sourceb.in/gRxLG4AMzk
Its only the profile command with modal
what is actually happening in discord?
after updating to 14.19.3 row.components does not exists anymore how do i access the action rows?
const newRows = targetMessage.components.map(row => {
return new ActionRowBuilder<ButtonBuilder>().addComponents(
row.components
.filter((component) => component.type === ComponentType.Button)
.map((button: any) => {
return ButtonBuilder.from(button).setDisabled(true)
})
);
});
i think it has something to do with componentsv2 that you need to check for that but not sure
you were right needed to check the type
if (row.type === ComponentType.ActionRow) {
[CRASH] Something went wrong while connecting to your bot...
[CRASH] Error from Discord API:Error: self-signed certificate
whats the wrrong?
I’m building a moderation bot with Discord.js v14.19.3 and Sapphire Framework, but I'm hitting a problem where I get an "Application didn't respond" error when running commands like /ban, /kick, etc.
I’ve already tried using deferReply() for commands and deferUpdate() for buttons to prevent timeouts, but I’m still having the issue. The bot has all the necessary permissions, and commands are registered correctly.
Anyone have any ideas or suggestions on how to fix this?
what host are you using
Log to see whether you are receiving the interaction at all
how to obtain a clan tag and also change the clan tag using a bot?
and also how to create gradient roles?
its in early access, bots have no access at all to those features
hi i got this error but why it shows an error but the embed is good?
const embed = new EmbedBuilder()
.setColor(__CONFG.colors.default)
.setTitle(`User Info: ${user.tag}`)
.setThumbnail(user.displayAvatarURL({ dynamic: true, size: 512 }))
.setDescription(`**Nickname:** ${member.nickname || 'None'}\n**Status:** ${user.presence?.status}\n**Roles:** ${member.roles.cache.map(role => role.toString()).join(', ') || 'None'}`)
.addFields(
{ name: 'ID', value: user.id, inline: true },
{ name: 'Username', value: user.username, inline: true },
user.discriminator !== '#0' ? { name: 'Discriminator', value: `#${user.discriminator}`, inline: true } : null,
{ name: 'Bot', value: user.bot ? ':white_check_mark:' : ':x:', inline: true },
{ name: 'Joined Server', value: `<t:${Math.floor(member.joinedTimestamp / 1000)}:R>`, inline: true },
{ name: 'Account Created', value: `<t:${Math.floor(user.createdTimestamp / 1000)}:R>`, inline: true }
)
.setFooter({ text: `Requested by ${message.author.tag}`, iconURL: message.author.displayAvatarURL({ dynamic: true }) })
.setTimestamp();
CombinedPropertyError (1)
Received one or more errors
input[1]
| CombinedPropertyError (1)
| Received one or more errors
|
| input.value
| | ValidationError > s.string()
| | Expected a string primitive
| |
| | Received:
| | | undefined
at _ArrayValidator.handle (C:\Users\ylian\Documents\ecotune\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:1254:70)
at _ArrayValidator.parse (C:\Users\ylian\Documents\ecotune\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:972:90)
at EmbedBuilder.addFields (C:\Users\ylian\Documents\ecotune\node_modules\@discordjs\builders\dist\index.js:235:31)
at Object.execute (C:\Users\ylian\Documents\ecotune\src\commands\userinfo.js:21:14)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
at async Client.<anonymous> (C:\Users\ylian\Documents\ecotune\src\app.js:149:13)
because user.username is undefined if I am saying that right
uuuhh yea bcs im using this:
const user = (await message.guild.members.fetch(message.author.id)) || (await message.guild.members.fetch(message.mentions.users.first().id));
const member = await message.guild.members.fetch(user.id).catch(() => null);
message.member exists too
That's incredibly inefficient. There's also mentions.members
MessageMentions#members discord.js@14.19.3
Any members that were mentioned (only in Guilds) Order as received from the API, not as they appear in the message content
The data is sent with the message payload, it's always present
oh
And indeed, members don't have a username. Both your user and member variables are GuildMembers
okay
GuildMember#user discord.js@14.19.3
The user that this guild member instance represents
Anything needed from the user class is available there
ty
Is it possible to send a Automod Alert message based on a member which have the Spammer UserFlag?
is tehre a way to give a bot the server tag?
im assuming no
No
hm
you can't send automod alerts, no
is there any djs support for linked roles in apps?
linked roles are an oauth2 feature for the most part
the only thing that the library does in regards to it is allow you to figure out which app a role is linked to via role tags
Configuring App Metadata for Linked Roles
read more
How did you get this glow effect in your name?
limited rollout, gradient roles. Not djs related, #archive-offtopic for these kind of questions
ok thanks and sorry
what's the difference between dividier and divider property in separator component?
both return boolean
OH ITS TYPO XD
update to 14.19.3
it was a typo yeah, but it was fixed in that version, and also an allowedMentions bug
so you should really update
ty, didnt notice
where can I find the limitation of a new components v2 message i see 40 max components but what about the characters, and how much per message? its same like embeds?
Does it auto shard as the bot joins more servers?
( Ex it only deployed 1 shard cause the bot had 2500 servers to manage, now it have to manage Like 7500 servers , does it auto deploy? Or needs manual restarts ? )
It's 2000 chars per content component
and 40 per message?
technically ye? You should test it! But it's 2000 per content component, last time I checked
thx
regular embed descriptions are limited to 4000 characters right
Its 4000 max per message ( default )
but it's 2000 per content component, so you can send a total of 2 content component with 2000 chars in each component.
Or you can send multiple with respect to limit of both content component and message limit
is there a way i can fetch the server tag of a server using its invite link
server tags are experimental, any functionality with them is not supported
sorry, but im stuck in the command handling part
it'll be hard to help if you don't explain what you're struggling with or sharing the code you've written so far
#how-to-get-help
can i stream you? because that way be more easy for me
@upbeat saffron @humble frost I'm a bit late to the conversation, but there isn't actually a documented limit on text display component content
2000 is the default limit for normal message content
the 4000 total across all components is correct
you can have a single text display with 4000 characters or two text displays with 3000 and 1000 respectively
no thanks
if you can show your code through a screenshare, you can show your code in a pastebin
thank you so much duck im already checking it out ^^
alright
hello i have an issue with my ready.js, after a days my bot status going to online, playing activity going to none and left to voice channel i cant fix this issue
Here's the code
const { ActivityType } = require("discord.js");
const { loadCommands } = require("../../Structures/Handlers/commandHandler");
const { joinVoiceChannel } = require("@discordjs/voice");
module.exports = {
name: "ready",
once: true,
async execute(client) {
loadCommands(client);
client.user.presence.set({
activities: [
{
name: "LVBEL ❤",
type: ActivityType.Streaming,
url: "https://twitch.tv/discord",
},
],
status: "online",
});
console.log(`Hazır! Giriş yapılan bot ${client.user.tag}`);
const channel = await client.channels.fetch("1343295471988506654");
if (channel && channel.isVoiceBased()) {
joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
selfMute: false, // Mikrofon kapalı
selfDeaf: true, // Kulaklık kapalı
});
console.log(`🔊 Ses kanalına katıldı: ${channel.name}`);
} else {
console.log("❌ Ses kanalı bulunamadı veya geçersiz.");
}
},
};
here's is @halcyon bison https://pastebin.com/yEU6mhCp
how you post your code like that?
I've never actually made the connection before, and previously I had assumed it was just a feature of discord that they don't want bots alone in voice channels 24/7 wasting resources
thinking on your presence, I believe the presence is cleared if your presence isn't set in the client options and it reconnects (which can happen for various reasons)
I could also see this being the reason for your bot disconnecting from the voice channel, especially if it's at the same time
```js
[ paste your code ]
```
aww thanks
Codeblocks:
```js
const Discord = require("discord.js");
// further code
```
becomes
const Discord = require("discord.js");
// further code
Inline Code:
`console.log('inline!');` becomes console.log('inline!');
You could use setInterval to reapply it every hour or so
wdym about "client options"? i dont understand it
yes you can add to client options
This is when you initialise your client variable
const client = new Client({options})
// Require the necessary discord.js classes
const { Client, Events, GatewayIntentBits } = require('discord.js');
const { token } = require('./config.json');
// Create a new client instance
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
// When the client is ready, run this code (only once).
// The distinction between `client: Client<boolean>` and `readyClient: Client<true>` is important for TypeScript developers.
// It makes some properties non-nullable.
client.once(Events.ClientReady, readyClient => {
console.log(`Ready! Logged in as ${readyClient.user.tag}`);
});
// Log in to Discord with your client's token
client.login(token);
const fs = require('node:fs');
const path = require('node:path');
const { Client, Collection, Events, GatewayIntentBits } = require('discord.js');
const { token } = require('./config.json');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
client.commands = new Collection();
ClientOptions discord.js@14.19.3
Options for a client.
What are the options and where can i see them?
here's the index.js , it says i had to add an additional part for the command handling but gives me some errors
oke i see
this looks as though you copy pasted from the guide without really reading the guide or thinking about what the code does
I'd suggest properly rereading the guide and its explanations of each code block, but here's the cliff notes:
- you're attempting to create 2 variables named
client, both of which are separateClientinstances - I don't see any code for actually loading commands in to that collection
- it doesn't appear you've finished reading the rest of the guide for where you deploy commands and handle interactions
so which option i can use it for dont clear presence
im reading the deploy part right now
you can add intents, partials, sweepers ( like a cache clean up ) also activity such as presence
intents already added
Wait let me check my code
const client = (global.client = new Client({
allowedMentions: { parse: ["users"], repliedUser: true },
intents: Object.values(GatewayIntentBits),
partials: Object.values(Partials),
}));```
here's the client @humble frost
public client: Client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.DirectMessages
],
partials: [Partials.Channel, Partials.Message, Partials.Reaction],
presence: {
status: "online",
activities: [{
name: "bls help",
type: ActivityType.Playing,
}],
},
sweepers: {
...Options.DefaultSweeperSettings,
users: {
interval: 3600, // Sweep offline users not seen for 1 hour
filter: () => user => {
// Try not to sweep the bot it self
if (user.id === this.client.user?.id) return false;
// Check if the user is offline in ALL guilds the bot is in
const isOfflineInAllGuilds = this.client.guilds.cache.every(guild => {
const member = guild.members.cache.get(user.id);
return member?.presence?.status === "offline" || !member; // Consider not being in a guild as offline
});
return isOfflineInAllGuilds;
},
},
messages: {
// Sweeps messages older than 30 mins??
interval: 1800,
lifetime: 1800,
},
},
});
side note: we heavily recommend not adding all intents/partials like that since it's just wasting both your and discord's resources and defeats the purpose of intents in the first place
it said to add this ``` const fs = require('node:fs');
const path = require('node:path');
const { Client, Collection, Events, GatewayIntentBits } = require('discord.js');
const { token } = require('./config.json');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
client.commands = new Collection(); ``` to the index.js . sorry it's that im new on javascript
const client = (global.client = new Client({
allowedMentions: { parse: ["users"], repliedUser: true },
intents: Object.values(GatewayIntentBits),
partials: Object.values(Partials),
presence: {
presence options
}],
},
}));
should do the trick
okey thanks for help
I admit the wording "make these additions" isn't absolutely 100% clear that you shouldn't copy paste the entire code block
but you're also not expected to copy paste any of the code blocks
and furthermore if you notice, a few of the lines are highlighted
comparing this code block to the code you had prior to this section, you can notice these highlighted lines are the new ones that you should be adding
const fs = require('node:fs');
const path = require('node:path');
const { Client, Collection, Events, GatewayIntentBits, ActivityType } = require('discord.js');
const { token } = require('./config.json');
const client = new Client({
intents: [GatewayIntentBits.Guilds],
presence: {
status: "online",
activities: [
{
name: "LVBEL ❤",
type: ActivityType.Streaming,
url: "https://twitch.tv/discord",
}
]
}
});
client.commands = new Collection();
we also prefer you don't continuously spoonfeed people the corrected code, especially when they're already struggling to understand the base concepts and code itself
#how-to-give-help
oh thanks :>
oh sure, I will try to follow next time
@halcyon bison could you explain the concept of sharding in discord js?
I have a question. Let's say when I started or ran the script it deployed 1 shard, as it only had like 2000 servers. But now once it reached 4000 servers, will it redeploy another shard for 1500 servers or does it need manual restarts ?
the ones i do add em to the number of line or add em to the line already made?
it'd need a restart
you could devise a system such that it isn't manual
but guilds are divided into their shards based on the current total shard count
it doesn't create a new empty shard and start filling it up
Is there a 15 minutes limit to editing ephemeral messages?
after that the interaction webhook expires yes
It gives invalid webhook token Error, so yup makes sense, thanks
Is there a way around to this?
after 15 minutes most users will have dismissed that message eitherway
(but also the answer is no)
Well somehow a dude i made bot for manages to stare at the message for more than 15 minutes and still want them ephemeral 😭
Guess i will need to like do a follow up reply or smth with interaction
Hello guys ! Do you know if there's a way to retrieve a registered slashCommand's ID ? From the client or another source I cannot find any options to do that on the documentation... I can only get the name
if a component is used on the message i believe you can update the message
do you already have the ApplicationCommand object?
or how are you getting the name?
Nope, it is like a menu and the arrow buttons defer but no edit
I mean idk, I use a command handler that stores commands in a Collection. But it is using provided values from the command's file
well make the buttons update then
right, that's your own command type, you need the ApplicationCommand that represents the already deployed command on discord
im assuming the buttons are on the ephemeral message?
documentation suggestion for @orchid latch:
ApplicationCommandManager#fetch() discord.js@14.19.3
Obtains one or multiple application commands from Discord, or the cache if it's already available.
// Fetch a single command
client.application.commands.fetch('123456789012345678')
.then(command => console.log(`Fetched command ${command.name}`))
.catch(console.error);
or if you prefer doing it through the client, you can right click the command above the chat bar as seen at the end of #1143952258321612922
Dear god, thanks !
Yup, they get defer updated, but on the editReply, it is prob where the issue is, as message webhook no longer works, idk if im even wording these things right 😅
in this scenario you don't have the id so you'd fetch without any arguments, which return all commands, and then .find() by name
❤️
each interaction gets its own interaction token, so a new interaction should be able to update the message
Weird, console shows invalid webhook token,
Are you using editReply on specifically the button interaction, or the interaction from before?
The interaction is a reply to a slash command, stored in a variable sentmsg, and a message component collector listens to interactions on the sentmsg, and on button, the sentmsg gets edited with .edit
Buttons just get updated
use the interaction from the message component collector and use interaction.update()
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);
not even sure how that didn't error because you're not replying to the button interaction
I got a interaction.deferUpdate() for the collected button interactions, which interaction you mentioning about? Slash or button
don't defer update, replace that with update
Whats the difference?
unless you editReply the button interaction afterwards
(unless you really need to defer, eg making a db call before updating)
defer update tells discord you'll update later
Oh
interaction.update() edits the message the button is on
Oh, thanks
The update takes the message parameters? Like to edit the message the buttons are on
yes, docs are here
Lemme go docs ig that would be better, thanks for yall help
it takes what you want to edit
Ooh thanks for help yall
hello i have a question, how i can get a tag of a user ?
Ok ye this is alot better, thanks
it
@blissful abyss can i still use defer update as some stuff between the interaction update might be slow
afaik the feature isn't even fully rolled out
it's not documented, and therefore not supported in djs
Yes, use deferUpdate and then editReply later with the same parameters
like
int.deferUpdate
//Code
int.update
assuming int is the button interaction and not the original slash command, yes
Ohk, thanks
ah no, editReply
it would be editReply though, not update
^^
@uncut tangle just in case you missed it
yup, got it, tested it, thanks
okay thansk
is it possible to get the past messages the bot sent to delete it with cmd without being in the server or smth
no
oh
hmm! I don't think it's ideal for us to restart and redeploy the whole bot every day ( if it gets added to servers frequently)
Do you have any suggestions on how to improve it? Plus I don't think it would also be ideal for bots to redeploy every time as it has potential to rate limit and user dissatisfaction
first could you clarify what you're redeploying every time?
Shards?
ok just making sure you didn't mean commands
all I said was that you can devise a system
it doesn't have to be every day, but rather just when you need more shards
Does discord js not support automation? Cause it would have been great
Thing is that guilds get assigned to other shards than before if you increase the amount of shards. You‘d need to have a system in place to accommodate that. Restart is often the easier/better solution
But why do you think you‘d need to restart that often? If you feel like your bot will grow that fast just start more shards than you currently need and you‘ll be good for a longer time
just a theory for a discord bot that gets added to servers often
If you spawn the recommended amount of shards (auto mode) then your bot should be able to at least grow to twice its current size without reaching shards limits. Resource limits are another story, but that’s independent of djs
ic
how do i fetch the application emojis? using the actual api outside the module? or is there a function?
ApplicationEmojiManager#fetch() discord.js@14.19.3
Obtains one or more emojis from Discord, or the emoji cache if they're already available.
// Fetch all emojis from the application
application.emojis.fetch()
.then(emojis => console.log(`There are ${emojis.size} emojis.`))
.catch(console.error);
Client#application discord.js@14.19.3
The application of this bot
oh wait
emojis just isnt showing up in the auto complete
Can you show where?
its undefined
What's your discord.js version?
wait whats the cmd to check
npm ls discord.js
14.15.3
alr npm i discord.js latest
Yeah, their support was added in 14.16
ok its valid in auto complete now
is this still possible in componentsV2? the author thing with logo and server name
o so if i wanna now send it as a message do i have to format it myself or is there smth implemented?
ApplicationEmoji#toString() discord.js@14.19.3
When concatenated with a string, this automatically returns the text required to form a graphical emoji on Discord instead of the Emoji object.
// Send a custom emoji from a guild:
const emoji = guild.emojis.cache.first();
msg.channel.send(`Hello! ${emoji}`);
Not in that form. You can put text in any form with any markdown, but images only as thumbnail to the right or gallery
ohh
ok i was gonna do [...emojis].join(' ') but that adds the id, emoji
ill just map and join it
wait or
Hi, am i doing smth wrong ?
TypeError: (intermediate value).setDivider is not a function
return new ContainerBuilder()
.setAccentColor(colors.BLUE)
.addTextDisplayComponents(
new TextDisplayBuilder()
.setContent('# Test')
)
.addSeparatorComponents(
new SeparatorBuilder()
.setDivider(false)
.setSpacing(SeparatorSpacingSize.Large)
)
.addTextDisplayComponents(
new TextDisplayBuilder()
.setContent('test')
)
)
ok [...emojis.values()].join(' ') that will do
Show the full error with stacktrace. Because that code looks fine
ok it works
tbh what kind of fun cmds shall i do im just bored
TypeError: (intermediate value).setDivider is not a function
at buildVoiceMenu (workspace\utils\customVoiceChat\messageContainers.js:24:14)
at Object.execute (workspace\commands\textCommands\messages.js:23:45)
at Object.execute (workspace\events\messageCreate.js:54:34)
at Client.<anonymous> (workspace\app.js:132:29)
at Client.emit (node:events:519:28)
at MessageCreateAction.handle (workspace\node_modules\discord.js\src\client\actions\MessageCreate.js:32:14)
at module.exports [as MESSAGE_CREATE] (workspace\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (workspace\node_modules\discord.js\src\client\websocket\WebSocketManager.js:351:31)
at WebSocketManager.<anonymous> (workspace\node_modules\discord.js\src\client\websocket\WebSocketManager.js:235:12)
at WebSocketManager.emit (workspace\node_modules\@vladfrangu\async_event_emitter\dist\index.cjs:287:31)
And what is messageContainers.js line 24?
23- new SectionBuilder()
24- .setDivider(true)
SectionBuilder is indeed not a SeparatorBuilder
what even is that , SectionBuilder
What is what?
A builder class to make a section, aka some text displays next to a button or thumbnail
documentation suggestion for @merry quiver:
SectionBuilder discord.js@14.19.3
A builder that creates API-compatible JSON data for a section.
oh like the embed has a thumbnail banner at top and then a section splitter under it and then text as i see on google?
wait even buttons inside the embed!?
They aren’t embeds. They might look alike but they are components, made to replace the legacy distinction between content, embed, buttons, attachments… all are components in v2
ohh
videos inside embeds possible yet!?
No. But inside components: yes
o
button
i clicked on the most clickbait "how to embed videos" video ever, all he did is upload a video to chat and video ended. omg the comments
ah yea, so this is how it is supposed to be then ?
.addSectionComponents(
new SectionBuilder()
.addTextDisplayComponents(
new TextDisplayBuilder()
.setContent('text')
)
)
if yes, It gives : Received one or more errors
oh V2 Components seems sick place stuff anywhere
Is it possible to do this thingy <t:${Math.floor(reminder.remind_at.getTime() / 1000)}:R> in a container?
I keep on getting an error when I add it, it works in embeds and when i remove it but doesn't seem to work in containers.
const container = new ContainerBuilder()
.setAccentColor(0xffff)
.addSectionComponents(
new SectionBuilder()
.addTextDisplayComponents(new TextDisplayBuilder().setContent([
`# __${user.globalName} GrimKin has your reminder!__`,
`-# The time is now <t:${Math.floor(reminder.remind_at.getTime() / 1000)}:R>, that means its time for your reminder!`
` You asked GrimKin to remind you: \`${reminder.message}\`!`,
].join('\n')))
.setThumbnailAccessory(new ThumbnailBuilder().setURL("https://i.ibb.co/XxDqJp7p/Grim-Kin-SVGAnnouncement-White.png"))
)
.addTextDisplayComponents(footer);
[ERROR] Reminder execution error: Math.floor(...) is not a function
you're doing Math.floor(...)(...) somewhere, probably because of a missing semicolon
i was missing a comma 💀
im now gonna test around with Components V2 😭
uh it wont show video
oh file literally means file and not like video media?
im guessing media supports attachment url?
aa
woah this is sick
o even User Select and more wow, i think i missed a few updates..
honestly didn't know you could stack videos side-by-side like that with componentsv2. that's pretty awesome tbh
you can put upto like 4
but idk how many component limit is cuz i just put 40... rn
So, i have a memory leak on my discord bot and i'm trying to figure out on how to figure out where the leak is from. Best way to figure out?
there isn't a specific way to know tailored for bots if that's the question
It's running on a ptero container that is only containing the bot.... It's literally on 2.31`gb and it's slowly climbing
you diagnose it the same way you'd diagnose any node app is what I'm trying to say
the fact that you're using djs is irrelevant to the leak itself
unless djs itself had a memory leak, but that'd be known
seems like i can put 80 videos but then over that it errors
I didn't nor say that it's a DJS issue.
you're on the djs help channel
there's a payload limit, 80 videos is just a lot either way
yh but still wanted to test lol
just insane..
o yh no loop
could of done Array.from({length:},()=>)
With Components v2, how do you use the MediaGalleryBuilder with a file made with the AttachmentBuilder instead of just a url?
I only know of: ```js
const thumbnailImage = new MediaGalleryBuilder()
.addItems([
new MediaGalleryItemBuilder()
.setURL(preview)
]);
container.addMediaGalleryComponents(thumbnailImage);
in theory if you don't reach the limit size you should be able to send 40 components*10 videos per gallery=400 videos
in practice I don't think you can have a video that small
oops wrong tag
No worries ^^
tag suggestion for @safe wigeon:
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]
});
there you go
it's the same thing for media galleries
Oh, didn't mean that. Like how do I add it to a container with addMediaGalleryComponents?
you mean like, sending an image file, and showing that image in the gallery?
instead of an image from an online url
Like how would I add attachment to this: ```js
const thumbnailImage = new MediaGalleryBuilder()
.addItems([
new MediaGalleryItemBuilder()
// attachment here
]);
container.addMediaGalleryComponents(thumbnailImage);
Yup
like in the tag then
just MediaGalleryItemBuilder#setURL() instead of EmbedBuilder#setImage()
And setURL() will accept attachment (from AttachmentBuilder)?
ohhh
no, like the tag says, it accepts a string
you send the attachment as part of the files, and reference it through the attachment:// url
ah great params instead of funcs
Ohh so ```js
const thumbnailImage = new MediaGalleryBuilder()
.addItems([
new MediaGalleryItemBuilder()
.setURL(attachment://${attachment.name})
]);
container.addMediaGalleryComponents(thumbnailImage);
yes, and send the attachment in the files
i did mine ts way lol
Ahh gotcha
mines more raw ig?
yes
Also, will withResponse: true do the same as fetchReply: true, just different name?
Not exactly the same, no
It returns a different object, but does contain the message as a nested property
fetchReply was as workaround implemented to do that before withResponse was provided
Am I using withResponse and the object correctly? With fetchreply it was just msg.createMessageCompo....
The fetchReply option when replying to an interaction will be removed in v15.
- {..., fetchReply: true}
+ {..., withResponse: true}
```This returns an [InteractionCallbackResponse](https://discord.js.org/docs/packages/discord.js/14.17.3/InteractionCallbackResponse:Class)
Use `<InteractionCallbackResponse>.resource.message` to get the message
^^
Not sure if that's a yes or no 😅
Looks like it from the link, ty ^^
Another question... with components v2, is it possible to have more than 5 buttons in the same row / next to each other?
no
With components v2, is it possible to edit a text display? Like
- Send container
- In message component collector get the container
- Edit specific text displays in the container
- Edit the message with the edited container
Hey, is there any API for guild tags yet?
yep
nope, undocumented as far as I know
👍
This was a reply to you @safe wigeon, you can edit any component as usual
How can I achieve it? How do I get a specific text display to edit in the container?
The answer kinda depends, I use raw JSON instead of builders, so I'd just make the change and re-send it'
You can otherwise do new ContainerBuilder(message.components[0]) (assuming thats your container) and use spliceComponents to replace them
ContainerBuilder#spliceComponents() discord.js@14.19.3
Removes, replaces, or inserts components for this container.
Can we send a components v2 with emperamal flag?
I think so yes
You can combine flags with the | operator
MessageFlags.IsComponentsV2 | MessageFlags.Ephemeral
Or operator?
Bitwise OR, yes
And how do we check if the bot has access to a channel's send message permission ( not guild send message permission )
Sometimes the owners remove permission of send message in a channel, but the slash command stays visible and they can actually use it but sometimes it causes problem they need to send another or followup message
TextChannel#permissionsFor() discord.js@14.19.3
Gets the overall set of permissions for a member or role in this channel, taking into account channel overwrites.
You can use this to check a users permissions in a channel
woah i just made that... 😭 didnt know thas possible tbh
i guessed it would just accept attachments and voice flag
hm no waveform thoo
wait it shows up as audio file for mobile uhhh
.
This isnt a playground for your bot
where
Did something change?
It dont seem that its letting me send messages to a textChannel
What is the error? And what type is the gatewayChannel claiming to be?
const gatewayChannel: DMChannel | PartialDMChannel | PartialGroupDMChannel | NewsChannel | StageChannel | TextChannel | PublicThreadChannel<...> | PrivateThreadChannel | VoiceChannel
Property 'send' does not exist on type 'DMChannel | PartialDMChannel | PartialGroupDMChannel | NewsChannel | StageChannel | TextChannel | PublicThreadChannel<...> | PrivateThreadChannel | VoiceChannel'. Property 'send' does not exist on type 'PartialGroupDMChannel'.ts(2339
You can just use the isSendable() typeguard to see if it has a send() method
Fixed. Thats weird tho no?
I think it's more sensible than the old methods since just writing if (!gatewayChannel?.isSendable()) return; is both less verbose and more direct toward your use case - checking if you can send something in a channel
It is. but I dont see why it still failed
I definitely feel like I've used isTextBased instead of isSendable and got typings correct...but isSendable is probably better anyways
isTextBased() doesnt work on its own anymore since, like TS told you, partial group DM channels are text-based but not sendable
Fair enough
Does isSendable check permissions or does it just check channel type?
channel only

That's what I thought just making sure
question, will this return an error if the channel does not exist
const channel = await member.guild.channels.cache.get(channelId);
or will it only return an error if i try to send something to the channel?
caches are just maps, gets are sync
so that await is useless
and it won't throw an error, it'll return undefined
Map.prototype.get()
The get() method of Map instances returns a specified element from this map. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the Map object.
oh more than one Section isnt possible?
it is possible
this wouldnt work
sections need an accessory
oh
just wanted to have the 3 fields like embeds
you could just put all those three text displays in a single one
if you're referring to the inline option, there's no alternative for that
ohh
oh theres also text Display limit of 3 so cant either way
per section, not globally
yeah
your code there works if you add an accessory to those sections
i was going for a profile type Component with banner, pfp with name etc and then 3 fields like followerrs following etc
^^
text displays go on top of each other, not side by side
yeah unless future same with author with its icon too
i was hoping it could in section
unfortunately no
discord decided that users should control the vertical positioning of components, not the horizontal one
you can "simulate" fields with blank spaces, but it's not mobile friendly
yh lol
I thought I had said yesterday that it wasn't possible but maybe it was someone else
ig others wanted too
thanks
for role.managed, will the booster role return as true?
yes
Using ComponentsV2, with ContainerBuilder as my top-level, and then this schema for the rest of my components. Weirdly, I'm getting an error saying components[0].type must be 1, which is... ActionRow? But I didn't think TextDisplays needed to be contained with anything more than Container
Althought that could be referencing the last section which is an array of Buttons... but that doesn't make sense either since I correctly wrapped them with ActionRow
isn't a container supposed to be a component by itself? the components inside will be inside the container component, but in the screenshot it looks like the first component isn't a container
This is container.components, JSON wrapping into [...Object] was being a bitch
I think it would be helpful to see some code
private generate(options: [string, string][], page: number, closing?: true) {
const total = this.options.length;
return new ContainerBuilder()
.addTextDisplayComponents(this.text.heading, this.text.query)
.addActionRowComponents(
new ActionRowBuilder<StringSelectMenuBuilder>().setComponents(
new StringSelectMenuBuilder()
.setCustomId("ssel")
.addOptions(
options.map((o) =>
new StringSelectMenuOptionBuilder()
.setValue(o[0])
.setLabel(o[1])
)
)
.setDisabled(closing ?? false)
)
)
.addTextDisplayComponents(this.text.footer(page, total))
.addActionRowComponents(
new ActionRowBuilder<ButtonBuilder>().setComponents(
this.buttons.cancel.setDisabled(closing ?? false),
this.buttons.previous.setDisabled(closing ?? page === 1),
this.buttons.next.setDisabled(
closing ?? this.getSlice(page)[1] + count(page) > total
)
)
);
}
you aren't sending the IsComponentsV2 flag
and you're directly passing the return value of this function as a component, right? did you enable the IsComponentsV2 flag?
so it's assuming you're using v1 components, and indeed every component there is wrapped in an action row
My dumbass added that flag to the wrong message. So indeed yes I was forgetting it
Apologies and appreciations good sirs 😂
no worries, it's an understandable mistake
Where I put it [1] vs where it needed to go [2]
So, I've made pagination using buttons. The pagination works exactly how I want it to, but I get
- This interaction failed
```every time I click one of the buttons. Is there a "proper way" to handle button clicks?
The "proper" way would be updating the message through the interaction webhook (or deferring first). If you don't respond to the interaction and just edit the message otherwise, you get the error message you shared
🤔 Mhmmmm.... So, reaction.update instead of interaction.editReply?
Is reaction the button interaction and interaction some older interaction? If so yeah
Message Components: Component interactions
read more
Yup, that's indeed what did it! Apreciate it good sir
do i need intents for guildMemberAdd event?
if so which one? and in the future where can i see the list of intents and what do they do?
- Websocket intents limit events and decrease memory usage: learn more
- See what intents you need here
You need the Guilds and GuildMembers intent for that event.
As for the list, see the tag above.
ty
https://discord.com/api/v10/channels/${ChannelId}/voice-status is this available in discord js ?
is this documented?

Can't find it ,Alr nvm
how to get the user in what clan?
tag suggestion for @viral hinge:
discord.js does not support features until they are officially documented.
While there might be a way for these features to work, it can change at any time without any notice
OH OK
is there a better way to type this out?
its kinda janky
lets try for loop
mapping works
Is there a method on Client that I can use to get the add app link
Client#generateInvite() discord.js@14.19.3
Generates a link that can be used to invite the bot to a guild.
const link = client.generateInvite({
scopes: [OAuth2Scopes.ApplicationsCommands],
});
console.log(`Generated application invite link: ${link}`);
Hey guys, I was reading the docs and I have a question: in which case would you get this? (https://github.com/discordjs/guide/blob/main/code-samples/additional-features/cooldowns/index.js)
When... no command matching the command name was found
e.g., you still have it deployed, but deleted the code locally
Ok that was what I thought at first, thank you!
😮
question i am using REST And this is actually not working it throw randomly (Unknown interaction)
(Reply is sent before 3 seconds yeah)
Common causes of DiscordAPIError[10062]: Unknown interaction:
- Initial response took more than 3 seconds ➞ defer the response *.
- Wrong interaction object inside a collector.
- Two processes handling the same command (the first consumes the interaction, so it won't be valid for the other instance)
* Note: you cannot defer modal or autocomplete value responses
that's a custom code i am not using discord.js and message is passed corretly inside the function it reach message.id and message.token
Its not a message. And regardless of whether you use djs or not, same causes. Either trying to reply twice to the same interaction or it took longer than 3s to reply
oh nvm i think i found it i was sending 200 status code on the message handler after receiving the interaction for the first time
No, both are seprate action that uses seprate route
either react after the message is sent, or use buttons if it's better for the use case
are buttons possible in modals?
no
No
new here. is there any place to find examples? thanks
examples of what?
we have https://discordjs.guide
something like "create a echo bot - reply only mentioned message"
you could try searching on github for open source bots/repos. the docs and guide exist to give you the information and references to start making your own app
got it thanks !
guys i wanna make every single command called, it would be printed on console
import { Events, Listener } from "@sapphire/framework";
import { ChatInputCommandInteraction, Message } from "discord.js";
export class CommandListener extends Listener {
constructor(context: Listener.LoaderContext, options: Listener.Options) {
super(context, {
...options,
event: Events.MessageCommandRun,
});
}
run(interaction: ChatInputCommandInteraction | Message) {
// Check if it's a chat input command (slash command)
if (interaction instanceof ChatInputCommandInteraction) {
console.log(
`[Slash Command] ${interaction.commandName} used by ${interaction.user.tag}`
);
}
// Check if it's a message command
else if (interaction instanceof Message) {
console.log(
`[Message Command] ${interaction.content} used by ${interaction.author.tag}`
);
}
}
}
but i dont think this is how it gonna work tho
For slash commands, it's Events.InteractionCreate.
MessageCommandRun doesn’t seem to exist in discordjs...?
oh, @sapphire/framework
I don't think you're asking this in the right Discord server, since you're using Sapphire
does .fetchInvite() not return the uses if the invite was made by a another user?
it should, what are you seeing in use that shows otherwise?
I think I found how to use it, I've been using client instead of guild
What permission is actually needed to fetchInvites in a guild?
how do i create a collector on the interaction response?
Message#createMessageComponentCollector() discord.js@14.19.3
Creates a message component interaction collector.
// Create a message component interaction collector
const filter = (interaction) => interaction.customId === 'button' && interaction.user.id === 'someId';
const collector = message.createMessageComponentCollector({ filter, time: 15_000 });
collector.on('collect', i => console.log(`Collected ${i.customId}`));
collector.on('end', collected => console.log(`Collected ${collected.size} items`));
You also have to use interaction.reply({ fetchReply: true }) to receive a Message instead of an InteractionCallbackResponse
Read below this for the better way of doing this for compatibility with v15
tag suggestion for @topaz bluff:
The fetchReply option when replying to an interaction will be removed in v15.
- {..., fetchReply: true}
+ {..., withResponse: true}
```This returns an [InteractionCallbackResponse](https://discord.js.org/docs/packages/discord.js/14.17.3/InteractionCallbackResponse:Class)
Use `<InteractionCallbackResponse>.resource.message` to get the message
Oh thx!
documentation suggestion for @fading girder:
Guild Resource - Get Guild Invites
read more
it's best to refer to the api docs to see what permissions are required for each endpoint/method
How can i disable a button in the original interaction message after an interaction was sent from the button?
do you want to update on click or at a later time
Is it possible to edit the embed of a StringSelectMenuInteraction with interaction.update and also send a message to the user?
yes
you can do whatever you want (as long as you have perms) during/after an interaction, just make sure you reply to it (.update() is also a reply)
Does that mean I can just do interaction.update and interaction.reply? Is both possible?
no, but if you want to update and then send another message you can followUp
StringSelectMenuInteraction#followUp() discord.js@14.19.3
Send a follow-up message to this interaction.
which is kinda as if you could .update() and then .reply()
update on click
.update() sending the button as disabled
basically the same thing you originally sent, but with the disabled button
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);
so i need to make the entire container again?
its a huge container, is it possible i can do something else?
new ContainerBuilder(message.components[0].toJSON()) and you got the builder structure again. then you can access the button in it through .components[x].... (or .find or ...) and call setDisabled on it
Okay, what if I do an interaction.update, then an interaction.followUp to send a new message and then want to edit this newly sent message again?
.find?
does that new message have components?
.components is an array
Array.prototype.find()
The find() method of Array instances returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.
Ohh
that. I thought it existed on ContainerBuilder my bad
The message I sent with followUp is not there, but should be there after editing
yes, but when do you want to edit the followup?
at a provided time without user input, or does that new (followUp) message also have components, and you want to update when those are used
With the same interaction that an ephemeral message that is sent
so without user input? it'll update by "itself"?
hmm
When the user clicks Select, I first update the embed of the Select with interaction.update, then I send them a response with interaction.followup, stating that they have to wait a moment. After all the database queries, I want to process this message and say whether everything worked or something went wrong.
Argument of type 'APIContainerComponent | APITextDisplayComponent | APISectionComponent | APISeparatorComponent | APIFileComponent | APIMediaGalleryComponent | APIActionRowComponent<...>' is not assignable to parameter of type 'Partial<APIContainerComponent> | undefined'.
Type 'APITextDisplayComponent' is not assignable to type 'Partial<APIContainerComponent>' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties.
Types of property 'type' are incompatible.
Type 'ComponentType.TextDisplay' is not assignable to type 'ComponentType.Container
you can .editReply() sending the followUp message as a parameter
StringSelectMenuInteraction#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);
send it on the message property
Then I edit the message from the select menu, I want to edit the ephemeral message
no, it'll update the message you pass
if you don't pass anything it defaults to that, yes
but as I'm suggesting, you'd pass the message followUp returns
so it'd update the followUp message
InteractionEditReplyOptions#message discord.js@14.19.3
The response to edit
Default value: '@original'
you'll need to type assert that that component is APIContainerComponent, or narrow by its .type
because technically that component can be any component, hence the union
But I don't get a new interaction back with an interaction.followUp
no, you get a message
can bots use stickers in stuff like embeds (and the new component)? (stupid question i know but curious as if so then my idea can go in motion)
Ah, I overlooked that earlier, thanks
no for both
alright
though a bot can send embeds and stickers, that's always been a thing
but not stickers in an embed
you can simulate a sticker with a media gallery component though (for cv2)
how do i edit a CV2 Message? Tried ContainerBuilder.from but property does not exists
👆
how do i edit the message of an emphemeral response
interaction.editReply()
well im using a collector, and need to edit the message
.update() on the collected interaction then
its in the end event
tried using message.edit
^^
oh
im so dumb, im sorry
no worries, interactions can be tricky to understand at first
I'm trying to replace my fetchReply options with withResponse but I'm getting an unexpected type when I call CommandInteraction.followUp. Replying works as expected:
const initial = await interaction.reply({
content: "initial response",
withResponse: true,
})
console.debug(initial) // InteractionCallbackResponse
But a subsequent followUp returns a Message instead. Is this intended? Docs for InteractionReplyOptions.withResponse read to me like it should be another InteractionCallbackResponse:
const response = await interaction.followUp({
content: "follow-up response",
withResponse: true,
})
console.debug(response) // Message
`-- discord.js@14.19.3
Edit: Hit enter too quickly. One sec
followUp does return a Message yes
ButtonInteraction#followUp() discord.js@14.19.3
Send a follow-up message to this interaction.
Is withResponse not even needed then?
InteractionReplyOptions#withResponse discord.js@14.19.3
Whether to return an InteractionCallbackResponse as the response
^ That implied to me that it should have been not a Message
Reply, options
It is listed as the param type for followUp though
Hi! I'm confused with @discordjs/core^2.0.1.
How is this deprecated? What should I use instead of this?
that's an issue on our part
it doesn't actually take withResponse or fetchReply
I imagine that if you mouse-over get, it'll show you the deprecation warning which says it's just the override that's deprecated
though I see the other override's other params aside from the guildId are optional, so I suppose it'll look exactly the same if you only use the first param
Ah okay. So the fetchReply I had before wasn't actually doing anything and it just happened to work out. Thanks!
version: 14.19.3
is update() missing on the type declaration for ModalSubmitInteraction? It's there in the documentation, and during runtime, but typescript can't seem to find it for me:
Property 'update' does not exist on type 'ModalSubmitInteraction<any>'
ModalSubmitInteraction#isFromMessage() discord.js@14.19.3
Whether this is from a MessageComponentInteraction.
you need to typeguard
Tyy! Just wondering, but can deferUpdate() be possible while update() isn't, considering deferUpdate() doesn't have the typeguard?
-# As well as some other properties, like message
whats the proper way of checking a message is a CV2?
check the flag
targetMessage.flags.has("IsComponentsV2")
so this is what im currently doing
yeah, looks good
do you have an idea how do i type it corretly because the .toJSON() gives me a type error
do you want the safe variant or the "I know the type of that message" variant?
former: assign the component to a variable, check .type to be ComponentType.Container, then call toJSON() on it.
latter: cast to APIContainerComponent
i take the latter one thx
when the users authorize the App as user install. can i get the data of the users who authorize the bot in their account?
discord.js does not support oauth2
thanks.
how do i add this in my bot via djs?
discord does that automatically as soon as it has enough usage data for your commands (and your app needs to be verified)
you cannot influence that in any way
I would like my bot to be able to keep track of members who bump the server, and we’re using Disboard. The final version of my bot will be able to run a weekly leaderboard that will reset every Sunday, but that part is easy and I know how to implement that.
Is there a way to grab the username in the Disboard embed of the person who did the /bump command (in disboard?) I’ve attached a picture of the message, and it’s the bit at the top that says “XXXXXX used 💠Bump”.
CommandInteraction#user discord.js@14.19.3
The user who created this interaction
<Message>.interactionMetadata has a property for the user
MessageInteractionMetadata discord.js@14.19.3
Partial data of the interaction that a message is a result of
hello, is there any way for me to fetch all members of a role?
No, you'll have to fetch all members and then filter them by their role
Hey guys, are there any d.js docs for Components V2?
yes, every builder is in the docs page
ContainerBuilder discord.js@14.19.3
A builder that creates API-compatible JSON data for a container.
for instance
Thanks
If i deferUpdate a button interaction, and then edit the original interaction (the command interaction in which the button was sent) would it still throw an error?
it'd throw if the command interaction was sent 15+ mins ago
The button stops working after a minute
but ideally you should editReply on the button
after the deferUpdate
shouldn't error then iirc
Well Im editing the message on the end event
so I can't edit the button interaction there can i?
Or why don't i just use update with an empty object?
what are you doing with the button interaction then?
stopping the collector
but you must give the user some kind of feedback that their button click did something
a reply or an update
The message updates
and how are you updating it? (method)
originalInteraction.editReply
you should be calling .update on the button interaction
or deferUpdate and then editReply, both on the button interaction, in case you need to defer to do async/io calls
as for this, you could keep a reference to the last interaction, then you can .editReply() on that
This is what i am doing, would this result in an error?
so far i haven't recieved any error
it shouldn't, but I would move that logic to a function that takes the interaction, then on end you pass the last interaction, on button "help-end-interaction" you pass the button interaction
oh, i see
it should show a visual error to the user after a while because you didn't actually editReply on the button after the defer
but it's unlikely the user will see the message for that long
well then won't i be editting the message again in the end event
you can stop with another reason and check the reason before calling it in end
theres no guide yet for components v2 right?
No guide yet, correct
there was a preview though?
Correct. A preview of a PR
Which can change and whatnot
ah
Since that's not finalized
I got an unknown message error randomly. what could that mean?
if you are trying to fetch, edit or delete a message that doesn’t exist anymore you get that error
oh that makes sense
or when the bot doesn’t have access to that message that error also appears
lets say i deleted that message, and the bot tries to edit it
yh
always good to use a catch for such scenarios
and handle it accordingly
Hey, is it possible to get a user's tag?
documentation suggestion for @verbal iris:
User#tag discord.js@14.19.3
The tag of this user This user's username, or their legacy tag (e.g. hydrabolt#0001) if they're using the legacy username system
I meant the new tags displayed next to the username
they are not yet documented, so we do not expose them through discord.js
they are sent with the raw user payload by the api, though
can you not edit an ephemeral message or something
I'm trying to run interaction.message.edit on an ephemeral message from a button interaction event
but i keep getting unknown message
you can, if you want to update from a button press you should respond with update to the interaction, rather than trying to edit the underlying message though
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);
oh right my b, I'm way too used to the old way of doing stuff lol
Is it ok if I use the API directly or is it unrecommended?
knock yourself out! don't rely on it working or anyone providing support with undocumented endpoints or payloads
-# anything undocumented may be changed or removed by discord at any point in time without notice
Okay thanks
Client#rest discord.js@14.19.3
The REST manager of the client
for direct requests, you can use the rest interface we expose through Client instances
ComponentBuilder discord.js@14.19.3
The base component builder that contains common symbols for all sorts of components.
How can I use Components V2? Is there any documentation for it? If so, could you please share it? I’d like to use it too
Me to i need to know how to use it
how?
Yes i d’ont know how
if (interaction.targetType != "MESSAGE")
how to write this in v14?
this is for message context menus
عربي؟
I really liked the new feature, we've been using the same embed for years :]
yes
خاص
Discord API types seems to have an incorrect type
message.components is somehow optional for APIMessageComponentInteraction
which does't make sense
how can a message component interaction exist if the message has no components?
Me too i need only to know only usage
Because there isnt a special subtype of Message for one that's attached to a component interaction
seems like an oversight but ok
In theory it could be types as & { components: WhateverType }
👀 .
How to get the uyg thing
when doing channel.permissionOverwrites.set(overwrites)
with a valid user id, I get:
Unhandled promise rejection: TypeError [InvalidType]: Supplied parameter is not a cached User or Role.
why does it matter whether the user is cached on the bots end.... isnt this id just sent to discord as is anyway
app?
Nvm I thought discord made it so it's customisable
No it is not
This is because I use Discord in Turkish, it may be different for you :]
I am looking at a logging bot, and want to include some specific audit log actions as it provides a better logging system than custom crafting it for server changes etc. But I am trying to understand the difference between action and actionType and which to use to filter and select the actions I want to log. Which one do I use and how? Are they both enums?
what happens if you call message.reply() without passing any arguments in Discord.js v14?
We also need to send the type: of the overwrite (user or role), so if you don‘t explicitly set that we need to infer it from cache
Ah, makes sense
action is different for each type of AuditLog entry. actionType just refers to if it‘s create, delete, update, … and gets inferred from action
GuildAuditLogsEntry#actionType discord.js@14.19.3
The action type of this entry
So if I want to filter, you are saying use the action enum and filter from a list of the enums in an array that I want to log?
If you want to filter you should include the action to filter for in the fetch call already
Guild#fetchAuditLogs() discord.js@14.19.3
Fetches audit logs for this guild.
// Output audit log entries
guild.fetchAuditLogs()
.then(audit => console.log(audit.entries.first()))
.catch(console.error);
Its just a gateway event for GuildAuditLogEntryCreate
GuildAuditLogsFetchOptions#type discord.js@14.19.3
Only return entries for this action type
Ah, then yeah, check if your array of types includes the one from the emitted entry
Thanks. Yeah trying to make logging simple for servers. Select a level and watch as the bot logs stuff for you, simply and in a nice way.
Just didn't want to track EVERY gateway event for all the possible changes that servers would want logged.
does the GuildMemberRemovegets triggered even with a member being kicked or banned
rather than them leaving on their own
Yes
,.
MessageContextMenuCommandInteraction#isMessageContextMenuCommand() discord.js@14.19.3
Indicates whether this interaction is a MessageContextMenuCommandInteraction
I keep getting a punycode deprecation warning for @discordjs/ws package, is this meant to happen? Or am I using the wrong node version?
i forgot how to get the guild icon lol, can someone help me?
documentation suggestion for @sacred valve:
Guild#iconURL() discord.js@14.19.3
The URL to this guild's icon.
thanks
also, is there anyway to register commands for only 2 servers?
you have to register them on each server
Creating Your Bot: Registering slash commands - Guild commands
read more
sounds like way old node version indeed
im using <Client>.guilds.cache.get('...')?.toJSON() inside a broadcastEval and I sometimes get this error, is it a DJS issue?
node:internal/process/promises:391
triggerUncaughtException(err, true /* fromPromise */);
^
Error [TypeError]: Cannot read properties of undefined (reading 'replace')
at get nameAcronym [as nameAcronym] (/root/./node_modules/discord.js/src/structures/BaseGuild.js:67:8)
at flatten (/root/./node_modules/discord.js/src/util/Util.js:36:24)
at Guild.toJSON (/root/./node_modules/discord.js/src/structures/Base.js:35:12)
at Guild.toJSON (/root/./node_modules/discord.js/src/structures/Guild.js:1441:24)
at eval (eval at _eval (/root/./node_modules/discord.js/src/client/Client.js:533:12), <anonymous>:5:19)
at eval (eval at _eval (/root/./node_modules/discord.js/src/client/Client.js:533:12), <anonymous>:12:7)
at Client._eval (/root/./node_modules/discord.js/src/client/Client.js:533:12)
at ClusterClient._eval (/root/./node_modules/discord-hybrid-sharding/dist/Core/ClusterClient.js:199:38)
at ClusterClientHandler.handleMessage (/root/./node_modules/discord-hybrid-sharding/dist/Structures/IPCHandler.js:111:48)
at ClusterClient._handleMessage (/root/./node_modules/discord-hybrid-sharding/dist/Core/ClusterClient.js:180:48)
Node.js v20.17.0```
discord.js@14.19.3
can you show the warning and node version?
.0
you seem to JSONify a Guild that has no name property set... in a broadcastEval. show the code you pass to that. possibly losing a this binding or something
const changes: Array<{ key: string; new: any; old: any }> = [];
entry.changes.forEach((change) => {
changes.push({
key: change.key,
new: change.new || null,
old: change.old || null
});
});
```When i run this code, it makes the changes display as new: [ Object ]. How do I make this always show the changes, no matter the target or event type properly for nice logging in an embed sent to a channel?
display where?
Console
that's how logging works if no depth defined
And in JSON.stringify(changes) when I send the embed to the channel
but the answer to this is: you need to do it conditionally based on action 🤷♂️
im not sure which broadcastEval but they're the same for the mostpart.
manager.evalOnGuild(async (cluster, { guildId, userId }) => {
const guild = cluster.guilds.cache.get(guildId);
const user = await cluster.users.fetch(userId).catch(() => null);
return {
user: user?.toJSON() as DjsUser | null,
guild: guild?.toJSON() as DjsGuild | undefined
}
}, { guildId, context: { guildId, userId } })
evalOnGuild is from here: https://github.com/Tomato6966/Codes/blob/main/hybridUtils/customEvaluates.js (at the bottom)
I see... So a different embed based on what happened.
looks to me like you have an invalid guild object in your cache then. do you maybe accidentally have a guild.name = undefined somewhere instead of ===?
🤦♂️ Turns out i do, must of clicked guild instead of guildData too quickly. thankyou!
well, i dont do undefined, but to another value
actually, infact i do guild.name = guild.name so it shouldnt matter?
or you made the same mistake somewhere else too?
i did ctrl+shift+f name =, name= and only 2 occasions where i did guild.name = guild.name

discord.js 14.19.3, anyone know why it's happening to me?
are you sure you're on 14.19.3? does your IDE know yet? try reloading
DEfinitely on 14.19.3 yes, pnpm list and package.json report the most up to date version. I'll try restarting vsc
i hate electron
tyvm
What's the maximum textdisplaycomponents you can have with a button accessory in a single container?
i.e. I want something like a box
With a title [btn]
A description
The same below it
But how many can I stack it?
Is there no way to your knowledge to set the type of event.changes.old and event.changes.new etc based on the action type? As i cannot find any documentation about the type of changes fired by each event. So think I will struggle to format the values unless I get a way to trigger each event manually to check output.
You can have a total of 40 components in a single message. So ~9 (a container plus a section, 2 texts, and a button per item)
is there a helper function to turn an icon hash into a server icon url or should i build the link manually
I think the client.rest.cdn has some stuff
ah that's what i wanted, ty
hello! how can i add an "watching" activity to my bot?
ClientUser#setPresence() discord.js@14.19.3
Sets the full presence of the client user.
// Set the client user's presence
client.user.setPresence({ activities: [{ name: 'with discord.js' }], status: 'idle' });
with a type: in the activity (check setActivity for another example)
You cant show a modal in a deffered interaction?
Message#startThread() discord.js@14.19.3
Create a new public thread from this message
Correct. Modals can only be shown in the initial response. You'd need a new interaction
how to know if a command is being used from a user who has the bot added to his "apps"
basically all these, "only you can see this" replies from the bot
CommandInteraction#authorizingIntegrationOwners discord.js@14.19.3
Mapping of installation contexts that the interaction was authorized for the related user or guild ids
kinda confused, what does this mean?
I have a command with these, .setContexts(InteractionContextType.Guild) .setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild)
I want to make sure only users with manage guild can the command and it can't be used even if the user has the app added to his apps list and try to use the admin commands
How can I give the bot a role if someone tags put server
can somebody help me? client.user.setActivity('Ghosty.', { type: ActivityType.Watching }); ^ TypeError: Cannot read properties of null (reading 'setActivity') at Object. at Module._compile (node:internal/modules/cjs/loader:1368:14) how can i solve this?
That message was the property you can check to see if the command is added to the server. But you can also just set the command to not be available through user installs and require being added to the guild with .setIntegrationTypes
.setIntegrationTypes(ApplicationIntegrationType.GuildInstall)
like this in / command builder right?
Yep
Hello, I would like to contact you because I have my bot which is in more than 2700 servers I did not have any problem at the level of the shards and since this morning I have my bot which makes that to disconnect I tried to leave it offline during one moment but when I restart I fall on this error and that makes only reload the loading of the project: js Erreur lors de la récupération des informations de shard : Error [ShardingInProcess]: Shards are still being spawned. at ShardingManager._performOnShards (C:\Users\james\OneDrive\Bureau\Bad-Protect\node_modules\discord.js\src\sharding\ShardingManager.js:297:13) at ShardingManager.fetchClientValues (C:\Users\james\OneDrive\Bureau\Bad-Protect\node_modules\discord.js\src\sharding\ShardingManager.js:277:17) at Shard._handleMessage (C:\Users\james\OneDrive\Bureau\Bad-Protect\node_modules\discord.js\src\sharding\Shard.js:398:22) at ChildProcess.emit (node:events:518:28) at emit (node:internal/child_process:951:14) at process.processTicksAndRejections (node:internal/process/task_queues:83:21) Erreur lors de la récupération des informations de shard : Error [ShardingInProcess]: Shards are still being spawned. at ShardingManager._performOnShards (C:\Users\james\OneDrive\Bureau\Bad-Protect\node_modules\discord.js\src\sharding\ShardingManager.js:297:13) at ShardingManager.fetchClientValues (C:\Users\james\OneDrive\Bureau\Bad-Protect\node_modules\discord.js\src\sharding\ShardingManager.js:277:17) at Shard._handleMessage (C:\Users\james\OneDrive\Bureau\Bad-Protect\node_modules\discord.js\src\sharding\Shard.js:398:22) at ChildProcess.emit (node:events:518:28) at emit (node:internal/child_process:951:14) at process.processTicksAndRejections (node:internal/process/task_queues:83:21) Erreur lors de la récupération des informations de shard : Error [ShardingInProcess]: Shards are still being spawned. at ShardingManager._performOnShards (C:\Users\james\OneDrive\Bureau\Bad-Protect\node_modules\discord.js\src\sharding\ShardingManager.js:297:13) at ShardingManager.fetchClientValues (C:\Users\james\OneDrive\Bureau\Bad-Protect\node_modules\discord.js\src\sharding\ShardingManager.js:277:17) at Shard._handleMessage (C:\Users\james\OneDrive\Bureau\Bad-Protect\node_modules\discord.js\src\sharding\Shard.js:398:22) at ChildProcess.emit (node:events:518:28) at emit (node:internal/child_process:951:14) at process.processTicksAndRejections (node:internal/process/task_queues:83:21) Erreur lors de la récupération des informations de shard : Error [ShardingInProcess]: Shards are still being spawned. at ShardingManager._performOnShards (C:\Users\james\OneDrive\Bureau\Bad-Protect\node_modules\discord.js\src\sharding\ShardingManager.js:297:13) at ShardingManager.fetchClientValues (C:\Users\james\OneDrive\Bureau\Bad-Protect\node_modules\discord.js\src\sharding\ShardingManager.js:277:17) at Shard._handleMessage (C:\Users\james\OneDrive\Bureau\Bad-Protect\node_modules\discord.js\src\sharding\Shard.js:398:22) at ChildProcess.emit (node:events:518:28) at emit (node:internal/child_process:951:14) at process.processTicksAndRejections (node:internal/process/task_queues:83:21) Erreur lors de la récupération des informations de shard : Error [ShardingInProcess]: Shards are still being spawned. at ShardingManager._performOnShards (C:\Users\james\OneDrive\Bureau\Bad-Protect\node_modules\discord.js\src\sharding\ShardingManager.js:297:13) at ShardingManager.fetchClientValues (C:\Users\james\OneDrive\Bureau\Bad-Protect\node_modules\discord.js\src\sharding\ShardingManager.js:277:17) at Shard._handleMessage (C:\Users\james\OneDrive\Bureau\Bad-Protect\node_modules\discord.js\src\sharding\Shard.js:398:22) at ChildProcess.emit (node:events:518:28) at emit (node:internal/child_process:951:14) at process.processTicksAndRejections (node:internal/process/task_queues:83:21)
Make sure the bot is ready before trying to access <Client>.user, otherwise it will be null
its setting activity to client.user
<GuildMember>.roles.add or <Guild>.members.addRole are two such ways to add a role
Meaning: Where are you trying to use setActivity?
on index.js
Where in index.js? Inside an event?
Make sure the bot is ready before trying to access <Client>.user, otherwise it will be null
You're trying it before the client is ready. Put it inside an event
i putted it inside of the client.once(Events.ClientReady, rClient => {}) and it worked. Thanks
how do i take a user id and turn it into a username while inside a for loop? I can't use await client.users.fetch because of the aformentioned for loop.
you could make them into a mention via <@ID>
You can still use await inside for loops and for...of loops, so that shouldn't be a problem
However you can always use .then() instead
true but i'm trying to use it in backend and not in a message
else you could use
await Promise.all(async loop)
like this as an example
const items = normalItems.map(async (item) => {
let emote: string | ApplicationEmoji
try {
emote = await interaction.client.application.emojis.fetch(item.item.emoteName)
} catch (_e) {
emote = item.item.emoteName
}
return `${emote} **${item.item.name[`${locale === 'de' ? 'de' : 'en'}`]}**: ${item.quantity}`
})
const itemsString = await Promise.all(items)```
You can use await fetch(), @discordjs/rest or @discordjs/core to make a raw API call
Like this?
topBumpers.forEach((row, index) => {
await client.users.fetch(row.user_id).then((username) => {
console.log(`User ${index + 1}: user_id: ` + row.user_id + 'username: ' + username + 'bumps: ' + row.bumps);
})
});```
use either await or then not both
That's not a for loop
my bad i meant to type foreach
going through an array of ids
uhm for that idk but should be similar (?)
You would need to make the callback async if you do that, plus ^
also note that an async forEach() callback will not wait for all the inner loops to run before exiting the forEach() and going to the proceeding code, so take that into consideration if that matters
Using a for...of loop is the easiest method for similar syntax, as long as you dont care about the index
i see that you do use the index though now, so you can just use a normal for loop
i would guess you could make a map instead of forEach while ignoring the output - map also gives the index
<Array>.entries() exists. You can use it with for...of
Does anyone know the pixel width of a container for media? I want to put in a "Legend" for one of my features, but I need it to be an image from a URL. I need to ensure it's sized properly so I need the width. Any suggestions on that?
Depends on the user's display
I expect it should resize on their display, but is there a maximum size for it, or just send it?
Any way you can't control how Discord displays your image
where the list of events for logging
Logging what?
like message etc
Client discord.js@14.19.3
The main hub for interacting with the Discord API, and the starting point for any bot.
All client events are listed in the client
What's wrong with my code here? I am 100% certain the channel exists, and that channel?.isSendable() returns true (I recently removed console.logs that always fired) but the console.log(response) never fires..
probably because you don't receive any message. missing GuildMessages intent?
or DirectMessages if in DMChannel
Indeed I was missing DirectMessages on my intents
To receive direct message events on "messageCreate" with your bot, you will need:
- The
DirectMessagesgateway intent - The
Channelpartial setting
@steel trail Do I need to do partials if I just run interaction.user.createDM() every time?
if you never expect to receive DMs before you did that: probably not
I mean I've got two commands that can be run in DMs, and this is the only one that requires any interaction with it... I run createDM as the first line of this command
quick question:
if the ephemeral flag isn't set while using deferReply, can I set it later on followUp messages attached to that interaction?
so can I do something like this:
await interaction.deferReply();
await interaction.followUp({content: "hi", flags: MessageFlags.Ephemeral });
because the message is sent but not ephemeral, and I'm wondering if it's just not how it works or it's me who's doing something wrong
you can't even set it on deferUpdate. since the message already exists and you can't change ephemeral state
oh sorry deferReply() **
only when a new message gets made
i meant deferReply, muscle memory xd
in that case you'd need to include it in the deferReply already
yeah but on the other hand I can do interaction.removeReply() and then use followUp with the ephemeral flag 🤔
deleteReply, but yes. it won't show as response to the interaction then though but as response to the deleted message
yeah that's my problem because it looks pretty ugly this way, and I need to make a request to db and basing on the response set the flag: if success - it want the response public, if error - as an ephemeral message. I kinda don't know how to solve this. I know I could send the public message via send() method but that's not the same. Is there even a solution to that?
or just gotta use send()?
For ephemeral you have to use some variant of reply, which you have to set as ephemeral from the beginning. So I believe you would have to use interaction.channel.send to give a "non-ephemeral" message response
However, you really don't need to defer unless your DB is incredibly slow. You have 3s to respond to the interaction; if your DB can query in a reasonable amount of time, you can then check if it's valid and use reply with a normal message, otherwise reply with an ephemeral message
I'm gonna ask a probably stupid question.
Im trying to detect if reply mention was enable/disabled on a message that replied to a webhook message, message.mentions doesn't pick it up so im assuming its not possible, but i thought to ask cause maybe someone knows something I dont. Is this possible?
I think i'll just rework the order of actions so the response isn't delayed intentionally. Well i'll see, thank you though
Just letting you know it's perfectly possible to have some async code execute well before your response, allowing you to switch between ephemeral or not
once a reply (defer or reply) is sent, its ephemeral state cannot be changed. running the async code without deferring can work, but if it takes longer than 3s, you're SOL
One would hope that a DB query doesn't take 3s
There isn't actually a user to mention, so I imagine no
What exactly is the end goal here?
if my bot is listening to messageCreate events, how much can it take before it becomes overwhelming? it's doing what it's coded to do, reading every dang message. but like, i don't want to overstress it.
it's really only a bot for our own personal community server, so it won't be too many messages, but if i ever went public with it, i would have to remove/change it, right?
Question, is there a way to update an existing embed message that has an ActionRowBuilder<StringSelectMenuBuilder> to components v2? When I try to pass the new compoments v2 using await interaction.update({ components: [data], flags: MessageFlags.IsComponentsV2 }); it still throws data.embeds[MESSAGE_CANNOT_USE_LEGACY_FIELDS_WITH_COMPONENTS_V2]: The 'embeds' field cannot be used when using MessageFlags.IS_COMPONENTS_V2 even though the code is fully updated for v2 and works off a new command
That’s not entirely true, since a followUp message can be ephemeral too
When editing, discord keeps anything you don't edit
Therefore you need to explicitly remove the embeds with embeds: []
You need to set embeds: [] then, as components v2 cannot have embeds🐌
That depends entirely on your host
Ohhhhh, thank you, didn't know it kept it
... (the command line terminal on my laptop, for now at least LOL)
Then that depends entirely on how good your laptop is (and whether you're using it at the same time of course)
All it's doing is picking up on the messageCreate events emitted from the one single server
and then checking if the user id is Disboard's ID. if not, it ends. If yes, do stuff.
If all it's doing is seeing a message and then ending the function as it wasnt relevent, does this take up a lot of power?
Can't imagine so
question plz
will we ever get unlimited timeout and temporary bans?
That'd be a question you'd want to ask Discord
BotStatus: {
type: 'dnd', // Status types: 'online', 'idle', 'dnd', 'invisible'
activity: {
type: 4, // Activity types: 0 = PLAYING, 1 = STREAMING, 2 = LISTENING, 3 = WATCHING, 4 = CUSTOM, 5 = COMPETING
name: 'Over SNH Discord',
url: null // Optional: URL for streaming status
},
rotationInterval: 300000
}
bot.user.setPresence({
status: bot.config.BotStatus.type,
activities: [{
type: bot.config.BotStatus.activity.type,
name: bot.config.BotStatus.activity.name,
url: bot.config.BotStatus.activity.url
}]
});
any reason why my type wont change
How can I make my bot to check if a certain user has our server tag activated?
you tell us
const channel: GuildBasedChannel | null = await guild.channels.fetch(channelId);
if (!channel?.permissionsFor(client.user as User)?.has(PermissionFlagsBits.Connect)) {
const Embed: EmbedBuilder = new EmbedBuilder()
.setColor(parseInt(config.embeds.color, 16))
.setDescription("`❌` | Je n'ai pas la permission de me connecter à votre salon vocal.");
return void Interaction.editReply({ embeds: [Embed], components: [] });
}```
It always says that the bot doesn't have the permission but it does ?
not documented
thx
have you logged what everything is returning? the ?. chaining can be returning undefined earlier than you're expecting
Yes ! Channel is valid but permissionFor isn't
define "valid". how did you verify it has the Connect permission? did you log ...permissionsFor(...).serialize() or similar to check?
By saying valid, I wanted to say that it found the channel and for the Connect permission, the bot isn't directly in the channel permissions but it has the Connect permission on the guild
log what i asked for in the last message and show the output
undefined
then something is returning falsey earlier in the chain, since permissionsFor() cannot return undefined
what does channel log
<ref *2> VoiceChannel {
type: 2,
guild: <ref *1> Guild {
id: '716334462761435157',
name: 'DEV BOTS',
icon: 'cc1f182b999195c9d3336c806bb897f2',
features: [ 'NEWS', 'COMMUNITY' ],
commands: GuildApplicationCommandManager {
permissions: [ApplicationCommandPermissionsManager],
guild: [Circular *1]
},
members: GuildMemberManager { guild: [Circular *1] },
channels: GuildChannelManager { guild: [Circular *1] },
bans: GuildBanManager { guild: [Circular *1] },
roles: RoleManager { guild: [Circular *1] },
presences: PresenceManager {},
voiceStates: VoiceStateManager { guild: [Circular *1] },
stageInstances: StageInstanceManager { guild: [Circular *1] },
invites: GuildInviteManager { guild: [Circular *1] },
scheduledEvents: GuildScheduledEventManager { guild: [Circular *1] },
autoModerationRules: AutoModerationRuleManager { guild: [Circular *1] },
soundboardSounds: GuildSoundboardSoundManager { guild: [Circular *1] },
available: true,
shardId: 0,
splash: null,
banner: null,
description: null,
verificationLevel: 1,
vanityURLCode: null,
nsfwLevel: 0,
premiumSubscriptionCount: 0,
discoverySplash: null,
memberCount: 16,
large: false,
premiumProgressBarEnabled: false,
applicationId: null,
afkTimeout: 300,
afkChannelId: null,
systemChannelId: null,
premiumTier: 0,
widgetEnabled: null,
widgetChannelId: null,
explicitContentFilter: 2,
mfaLevel: 0,
joinedTimestamp: 1747163078343,
defaultMessageNotifications: 1,
systemChannelFlags: SystemChannelFlagsBitField { bitfield: 7 },
maximumMembers: 250000,
maximumPresences: null,
maxVideoChannelUsers: 25,
maxStageVideoChannelUsers: 50,
approximateMemberCount: null,
approximatePresenceCount: null,
vanityURLUses: null,
rulesChannelId: '1269065559950233781',
publicUpdatesChannelId: '1269065559950233784',
preferredLocale: 'en-US',
safetyAlertsChannelId: null,
ownerId: '1274808781477380112',
emojis: GuildEmojiManager { guild: [Circular *1] },
stickers: GuildStickerManager { guild: [Circular *1] },
incidentsData: null
},
guildId: '716334462761435157',
permissionOverwrites: PermissionOverwriteManager { channel: [Circular *2] },
messages: GuildMessageManager { channel: [Circular *2] },
nsfw: false,
flags: ChannelFlagsBitField { bitfield: 0 },
id: '1307142143009226774',
name: 'b',
rawPosition: 2,
parentId: '1157847937171337266',
rtcRegion: null,
bitrate: 64000,
userLimit: 0,
videoQualityMode: null,
lastMessageId: null,
rateLimitPerUser: 0
}```
uhm
go to the link in the message. if you need more help, see #1081585952654360687
alr
show the exact code that produced undefined when i asked for ...permissionsFor(...).serialize()
const member: GuildMember = Interaction.member as GuildMember;
const channelId: string | null = member.voice.channelId;
if (!channelId) {
const Embed: EmbedBuilder = new EmbedBuilder()
.setColor(parseInt(config.embeds.color, 16))
.setDescription("`❌` | Vous devez être dans un salon vocal pour utiliser cette commande.");
return void Interaction.editReply({ embeds: [Embed], components: [] });
}
const guild: Guild = Interaction.guild as Guild;
const guildId: string = guild.id;
const channel: GuildBasedChannel | undefined = await guild.channels.cache.get(channelId);
console.log(channel?.permissionsFor(client.user as User)?.serialize())
(I changed it back to channels.cache)
ditch the ? chaining and see what it outputs. ts-ignore or whatever is needed