#djs-help-v14
78874 messages · Page 70 of 79
LabelBuilder replace ActionRowBuilder (in modals)
so confused
so remove all the ActionRowBuilder
which i done?
module.exports.run = async function (b, c, cfg, i, a, d) {
var arg = a.split('-'), id = i.message.embeds[0]?.footer?.text || '0', row = null;
switch (arg[0]) {
case 'Add':
return i.showModal(
new b.djs.ModalBuilder()
.setCustomId('-Add')
.setTitle('Add Permission Configuration')
.addLabelComponents(
new b.djs.LabelBuilder().setLabel("Select the permission type").setStringSelectMenuComponent(
new b.djs.StringSelectMenuBuilder()
.setCustomId('Type')
.setPlaceholder('Select the permission type...')
.addOptions([
{ label: 'Permissions', value: 'Perms' },
{ label: 'Settings', value: 'Settings' },
{ label: 'Logging', value: 'Logging' }
])
),
new b.djs.LabelBuilder().setLabel('Select a role for the permission').setRoleSelectMenuComponent(
new b.djs.RoleSelectMenuBuilder()
.setCustomId('Role')
.setPlaceholder('Select a role')
)
)
)
}
};
so this
how would i get the data ? i.fields.?
What is up with your function def
nothing? if its b, c, cfg, i, a, d? its fix on prod one
Are you passing the packages as function argument
yes
Why
tidyer
That just raises more questions. Why are you adding the packages as properties of your client?
cause not wanting in every file just stupid
You can import from a package in multiple files
?
I think you should read the guide and a js tutorial for multi-file projects.
To answer your question, you previously asked about the modal and receiving data from it. I would refer you to the modal guide
guide suggestion for @neat nimbus:
Receiving modal submissions
?
Sorry to clarify and provide more help than just saying go learn js. In javascript.
You can import/require a library in multiple files
yes by doing example
var { Client, Collection } = require("discord.js"), express = require("express"), a = express();
var mysql = require("mysql2"), cfg = require("../config");```
in each file yes ik that
Then why make them properties of your client?
everything goes off mymain init file
where con bot express etc is
here exmaple
var { Client, GatewayIntentBits, Collection } = require("discord.js"), express = require("express"), a = express();
var mysql = require("mysql2"), cfg = require("../config");
Logger = function (m, o = {}) {
var out = [];
if (o.bold) out.push(`\x1b[1m`);
if (o.color) out.push(`\x1b[${o.color}m`);
if (o.title) out.push(`[${o.title}]: \x1b[0m`);
console.log(`${out.join("")}${m}\x1b[0m`);
}
c = mysql.createPool({
host: cfg.SQLInformation.Host,
user: cfg.SQLInformation.Username,
password: cfg.SQLInformation.Password || null,
database: cfg.SQLInformation.Database,
charset: cfg.SQLInformation.Charset || "utf8mb4",
port: cfg.SQLInformation.Port || 3306
});
b = new class extends Client {
constructor() {
super({
intents: [GatewayIntentBits.Guilds]
});
this.cfg = cfg;
this.pkg = require('../package.json');
this.djs = require("discord.js");
this.ms = require("ms");
this.fs = require("fs");
this.path = require("path");
this.figlet = require("figlet");
this.Commands = new Collection();
this.Events = new Collection();
this.Buttons = new Collection();
this.Modals = new Collection();
this.Menus = new Collection();
}
}();
a.listen(cfg.SiteInformation.ProcessPort, function (e) {
if (e) return Logger(e, { title: "EXPRESS", color: 31 });
require("./backend")(a, b, c, cfg);
});
process.on("uncaughtException", function (e) {
Logger(e.stack, { title: "ERROR", color: 31 });
});
process.on("unhandledRejection", function (e) {
Logger(e.stack, { title: "ERROR", color: 31 });
});
module.exports = { a, b, c, cfg };```
Dont really see the diffrence in if there or in the file them self
Alright, so I am going to move past this and try to help with your questions. I don't want to get bogged down on this
i all ready fixed it
So I think I dont need to explain what the problem yis, it is obvious. Modlog and modules cmds, they are not getting highlighted
related part: https://sourceb.in/m9qB3Gg6c8
I dont use guildcommands*
is there a way to have your bot respond to a button press on a discord embed not owned by your bot?
thats not possible as ik due to api arch
Buttons only send an interaction to the specific bot it was made by
They are getting highlighted
But there's a pretty random use of inline codeblocks there
As if you never end them
ye thanks
is there a way to set defult info from the db into it?
for the select?
new b.djs.StringSelectMenuBuilder()
.setCustomId('Language')
.setPlaceholder('Select a language...')
.addOptions([
{ label: 'English', value: 'English' },
{ label: 'Spanish', value: 'Spanish' },
{ label: 'French', value: 'French' },
{ label: 'German', value: 'German' }
])
.setDefaultOptions({ label: d.language, value: d.language })
)```
[Buttons]: TypeError: (intermediate value).setCustomId(...).setPlaceholder(...).addOptions(...).setDefaultOptions is not a function
default exists inside options not a standalone function in StringSelect, you can use StringSelectMenuOptionBuilder for better readability
new StringSelectMenuBuilder().setCustomId("config:misc:language").addOptions(
new StringSelectMenuOptionBuilder()
.setLabel(localeFlags["en-GB"])
.setValue("en-GB")
.setEmoji("🇬🇧")
.setDefault(this.guildData.language === "en-GB"),
new StringSelectMenuOptionBuilder()
.setLabel(localeFlags["tr-TR"])
.setValue("tr-TR")
.setEmoji("🇹🇷")
.setDefault(this.guildData.language === "tr-TR"),
),
``` for example
how can i do that for mine?
it's basically default: boolean in the object property, so you would have to figure out which one is the default one
got one how would i do role select
new b.djs.RoleSelectMenuBuilder()
.setCustomId('VerRole')
.setPlaceholder('Select verification role...')
.setDefault({ id: d.verRole })
),```
documentation suggestion for @neat nimbus:
RoleSelectMenuBuilder#addDefaultRoles() builders@1.13.0
Adds default roles to this auto populated select menu.
see this docs are bit confusing for me in what way that works
You would need an array of role id(s) to put inside and they will show up as defaults
is there away to select the one in the db on there? and still show the rest?
as there info in db for the channel but still want them to select new one
Putting up a default will show up a default, you can keep selecting or removing regardless
so this
that won’t work
why confused on docs dont explain stuff
you can’t specify what roles are shown by default
so what trying todo wont work then
simple what ever in the db is in there it show on that menu and then they can select new one if they want if not it keep the same
If you wrap it in an array it should show up as the default, and you should be able to just submit it which would return that default one
? yeah no clue
new b.djs.LabelBuilder()
.setLabel("Verify Role")
.setRoleSelectMenuComponent(
new b.djs.RoleSelectMenuBuilder()
.setCustomId('VerRole')
.setPlaceholder('Select verification role...')
.addDefaultRoles(d.verRole ? [d.verRole] : []) // Ensure it's wrapped in an array
);
```so that
Yeah
didnt work
If you log the value of verRole does it return a string
thats why null i thought i set one ffs
Bit off topic but can I have that symbol please
It's in your code nevermind thanks
Hi I'm having a fun issue with my code, got multiple errors being thrown...
const accountSelectionModal = new ModalBuilder().setTitle(
"Account Selection",
).setCustomId("withdraw_acc");
const accountSelectionMenu = new StringSelectMenuBuilder().setCustomId(
"acc_select",
).setPlaceholder("Select Account").setRequired(true);
const accountSelectionList: StringSelectMenuOptionBuilder[] = [];
accountSelectionList.push(
new StringSelectMenuOptionBuilder().setLabel("locutus").setDescription(
"locutus",
).setValue("loco_withdraw"),
);
for (const account of Accounts) {
const strOpt = new StringSelectMenuOptionBuilder().setLabel(
`${account.AccountName}`,
).setDescription(`${account.AccountId.toString()}`).setValue(//Looks like 1fe51e6fb9c81aeb
`w_${account.AccountId.toString().toLowerCase()}`, //Looks like w_1fe51e6fb9c81aeb
);
accountSelectionList.push(strOpt);
}
accountSelectionMenu.addOptions(accountSelectionList);
const accSelectionLabel = new LabelBuilder().setLabel(
'Select your Account or select "locutus" to build text block',
)
.setStringSelectMenuComponent(accountSelectionMenu);
accountSelectionModal.addLabelComponents(accSelectionLabel);
await interaction.showModal(accountSelectionModal);
anybody got any ideas?
for your information, whoever helps: the selection menu is dynamic, we have different accounts for users to choose from
anyone made a npm packge for a embed builder
EmbedBuilder already exists in discord.js
EmbedBuilder discord.js@14.25.1
Represents an embed builder.
yeah seen my this file from my old dev
there’s no reason to use a package when EmbedBuilder exists in discord.js directly
https://pastebin.com/hFmJ9Vif Buttons
https://pastebin.com/ZJw3bS7B Modals
https://pastebin.com/YZWNB2JL Menus
is what i have atm well to long for what it is
whats your error?
there none trying to compact as make code better from previoes bot from 13 best i have did atm
here's my full stacktrace + printout of some data
{"type":3,"custom_id":"acc_select","placeholder":"Select Account","required":true,"options":[{"label":"locutus","description":"locutus","value":"loco_withdraw"},{"label":"hell","description":"1fe51e6fb9c81aeb","value":"w_1fe51e6fb9c81aeb"},{"label":"world","description":"2021a606bade7dc4","value":"w_2021a606bade7dc4"}]}
error: Uncaught Error: Received one or more errors
return errors.length === 0 ? Result.ok(finalObject) : Result.err(new CombinedPropertyError(errors, this.validatorOptions));
^
at _ObjectValidator.handleIgnoreStrategy (file:///home/monarchalia/WebstormProjects/Shadow/node_modules/.deno/@sapphire+shapeshift@4.0.0/node_modules/@sapphire/shapeshift/dist/cjs/index.cjs:2119:72)
at _ObjectValidator.handleStrategy (file:///home/monarchalia/WebstormProjects/Shadow/node_modules/.deno/@sapphire+shapeshift@4.0.0/node_modules/@sapphire/shapeshift/dist/cjs/index.cjs:1983:47)
at _ObjectValidator.handle (file:///home/monarchalia/WebstormProjects/Shadow/node_modules/.deno/@sapphire+shapeshift@4.0.0/node_modules/@sapphire/shapeshift/dist/cjs/index.cjs:2089:17)
at _ObjectValidator.parse (file:///home/monarchalia/WebstormProjects/Shadow/node_modules/.deno/@sapphire+shapeshift@4.0.0/node_modules/@sapphire/shapeshift/dist/cjs/index.cjs:972:90)
at LabelBuilder.toJSON (file:///home/monarchalia/WebstormProjects/Shadow/node_modules/.deno/@discordjs+builders@1.13.1/node_modules/@discordjs/builders/dist/index.js:1769:20)
at file:///home/monarchalia/WebstormProjects/Shadow/node_modules/.deno/@discordjs+builders@1.13.1/node_modules/@discordjs/builders/dist/index.js:2868:64
at Array.map (<anonymous>)
at ModalBuilder.toJSON (file:///home/monarchalia/WebstormProjects/Shadow/node_modules/.deno/@discordjs+builders@1.13.1/node_modules/@discordjs/builders/dist/index.js:2868:35)
at ButtonInteraction.showModal (file:///home/monarchalia/WebstormProjects/Shadow/node_modules/.deno/discord.js@14.25.1/node_modules/discord.js/src/structures/interfaces/InteractionResponses.js:402:46)
at Object.execute (file:///home/monarchalia/WebstormProjects/Shadow/events/ButtonEvents/BuildWithdraw.ts:70:23)
Watcher Process failed. Restarting on file change...
OH GOD THATS A TEXT WALL SORRY
oh shit am i using builder again.
(no, just checked)
?
I'm running into a very very fun issue, multiple issues with the formatting of my modal's data, but I have no idea where the issues are
code?
up here.
better how exactly?
like so many line for one one embed
yeah ngl you're not gonna be able to cut that down easily unless you shove it all to a one-liner
which is not good for readability and definitely not if you ever need to refactor
unless i put into a db which might do
wait can you put numbers in a modal value 
? wym
try this
"Account Selection",
).setCustomId("withdraw_acc");
const accountSelectionMenu = new StringSelectMenuBuilder().setCustomId(
"acc_select",
).setPlaceholder("Select Account").setRequired(true);
const accountSelectionList: StringSelectMenuOptionBuilder[] = [];
accountSelectionList.push(
new StringSelectMenuOptionBuilder().setLabel("locutus").setDescription(
"locutus",
).setValue("loco_withdraw"),
);
for (const account of Accounts) {
const strOpt = new StringSelectMenuOptionBuilder().setLabel(
`${account.AccountName}`,
).setDescription(`${account.AccountId.toString()}`).setValue(
`w_${account.AccountId.toString().toLowerCase()}`,
);
accountSelectionList.push(strOpt);
}
accountSelectionMenu.addOptions(accountSelectionList);
const accSelectionLabel = new LabelBuilder().setLabel(
'Select your Account or select "locutus" to build text block',
)
.setStringSelectMenuComponent(accountSelectionMenu); // Fixed: lowercase a
accountSelectionModal.addLabelComponents(accSelectionLabel);
await interaction.showModal(accountSelectionModal);
oh well that wasn't the problem as an fyi
that was me making it easier to digest for others, I uppercase the start of every variable in my code
The key fix was changing AccountSelectionMenu to accountSelectionMenu on line 26 to match the variable name defined on line 4.🤣
that's... not the error
works for me
here's what it actually looks like internally.
I would never get an error like that if it had to do with a typo
The name for that is Pascal Case. If you didn't
yeah my brain wasn't cooperating with me on naming it 😂
last few times i came in here folks didn't like me using pascal case vs camel case
could you potentially take a look at it?
I'm at a loss and i ran into a similar situation previously, not sure what's going wrong this time tho
Which file do you need looked at
up here
Also what is the problem we are trying to solve
this huge block of problems
provided is a lot of the data in the modal, i don't know if i gave the topmost level of that data, tho, and then the huge asf error
I am on mobile so it may take me a sec
my thought is maybe values can't have numbers in them?
but, the discord API docs say specifically characters, of which numbers are...
basically I'm just at a loss, my last issue last time was i was importing from builders, made sure that wasn't the case this time
I can't really tell better at the moment but it is failing to validate the label builder. Here are the limits for the string select menu option object. My only other thought is that it is a deno related issue. discordjs is only tested against node
LabelBuilder#setId() discord.js@14.25.1
Sets the id (not the custom id) for this component.
that seems important yeah? ^
No? Id is an optional field
oh i misread oops
hmmm I got an ideaaaa
what exactly you trying todo?
They are trying to send a modal, but it is failing the validation
like trying todo a modal with select modal with the accounts on it?
It is a string select menu
just one
Looks like it
#djs-help-v14 message
wait does discord.js filter curse words? (lmao) this ain't api lmao im stupid
It’s not any different than typing it yourself and sending in the app
ok good
wtf is this codes issue then 
Does your code work on Node
I ain't tested it for that
is this what your trying todo
nor is it built for that, I'm using the same exact format to build this modal as i did my last one
the difference is, this one is a stringselectmenu
sort of yes
what else ?
that's the thing, that's what I'm doing
so this what you want
here send it to me and let's see if it works
I'll load it into a sample command
let Accounts = [
{ label: 'Account 1', value: 'account1' },
{ label: 'Account 2', value: 'account2' }
]
interaction.showModal(
new ModalBuilder()
.setCustomId('Logs-Add')
.setTitle('Add Log Configuration')
.addLabelComponents(
new LabelBuilder().setLabel("Select the account").setStringSelectMenuComponent(
new StringSelectMenuBuilder()
.setCustomId('Type')
.setPlaceholder('Select the account...')
.addOptions(Accounts)
)
)
)```
that works... let me try that way you have the options setup...
let List = []
for (var a of Accounts) {
List.push(
new StringSelectMenuOptionBuilder()
.setLabel(`${a.AccountName}`)
.setDescription(`${a.AccountId.toString()}`)
.setValue(`w_${a.AccountId.toString().toLowerCase()}`)
);
}
i.showModal(
new ModalBuilder()
.setCustomId('Logs-Add')
.setTitle('Add Log Configuration')
.addLabelComponents(
new LabelBuilder().setLabel("Select the account").setStringSelectMenuComponent(
new StringSelectMenuBuilder()
.setCustomId('Type')
.setPlaceholder('Select the account...')
.addOptions(...List)
)
)
)```
if want to pull from a db like you had it before
let me know if that works
WHY TF DOES THAT WORK??
🤣 that from db
yuh
atlest it works
about to test the full implementation in a moment
wish me luck
good luck
How to make it like this?, button inside
A container with a text display and an action row with a button
Display Components
While you might be familiar with embeds in Discord, there are more ways to style and format your apps messages using display components, a comprehensive set of layout and content elements. To use the display components, you need to pass the IsComponentsV2 message flag (in docs: MessageFlags) when sending a message. You only need to use this flag when sending a message using the display components system, not when deferring interaction responses.
Hi, using the API and documentation, is it possible to obtain the amount of boost a user gives to the server? 🙂
no, best way would be to listen to the boost message type
So you only hear it if it has performed a boost and when it stops boosting the server, right?
theres no system message that says they stopped boosting. with the boost message type you can keep track how many times someone boosted
You can listen to the guild member update event to get the role update
Then you would manually have to store the timing
^ That will give you the amount of times a user boosts though for the first time, if they remove one you wouldn't know
I understand, thank you very much for the information. ❤️ 🙂
Does anyone know where I can find the JS template on github?
can you be a bit more specific on what you’re referring to?
There was a link to the Github code at the end of the discordjs guide but unfortunately the guide was revised so that it is no longer there.
That was I mean after the event handlers
do you mean this ? https://github.com/discordjs/guide/tree/main/code-samples
Are you trying to follow the guide, or do you just want a template for creating bots?
We have create-discord-bot for the latter case
Howdy all, where in the docs can I learn how to do non-slash command interactions? im basically trying to do something when someone @ mentions my bot
there is not such thing as "non-slash command interactions" it is just MeesageCreate event
ah
is there a section in the docs for handling events
No I dont believe so. You would have to parse the content. it is much eseer to just use slash command.
I see
Why do you want to uses message command over slash command?
I do need to sub to messages being sent so its abit odd the docs dont cover it but its fineig
The most basic form is just your standard JavaScript event listener on the messageCreate event. The guide however has a section on event handling via different files
I essentially want to do like "@botname, {insert question here} then the bot replies.
so that the actual chat logs look like
user pings bot
bot replies
(event) Client#messageCreate discord.js@14.25.1
Emitted whenever a message is created.
There's not much for the docs to cover, message.content is a string, and parsing that is basic js, not related to d.js
Ill have to read up on JS event subscriptions then
to check if the bot is mentioned it is in the message object from the Message create event
Message#mentions discord.js@14.25.1
All valid mentions that the message contains
why couldnt you just do this with a slash command?
/question content:string
no I want it to show as a normal messge
just listen to bot mention and then go from there. not really something a doc would cover. its not a command
yea seems shrimple enough, I just dont know if I've ever done any listening before in JS
all my searches come up with listening to DOM stuff
you ever worked with the messagecreate event? cuz thats just it
no im literally hoping into discord.js for the first time and trying to learn the basics
You should look into the runtime you're working with, which is likely Node.js - not a web environment which is what DOM is associated with
oh okay. best to read the starter docs then
I am, that was my question, how to sub to events lol
youd create your file, import your client and listen for the event such as client.on(Events.MessageCreate, async (message) => { // your code })
oh it is client.on
did you do client.once? that only emits once and never again iirc
Event Handling
Node.js uses an event-driven architecture, making it possible to execute code when a specific event occurs. The discord.js library takes full advantage of this. You can visit the Client documentation to see the full list of events. This page assumes you've followed the guide up to this point, and created your index.js and individual slash commands according to those pages. At this point, your index.js file has listeners for two events: ClientReady and InteractionCreate.
no I think I just did my logic wrong
thanks guys, appreciate it
np, Take a read though the guide take a swing at it then come back and we can help you work thought the issue
last question, not something im implementing/learning tonight, but what features would you guys use to design the following:
user uses command
this creates an interactable object of some kind
users can "vote" on this (yes or no vote)
after 2 mins, logic runs based on the vote
I was thinking of using reactions somehow, but there migh be cleaner way of doing it?
discord has native polls
Poll discord.js@14.25.1
Represents a Poll
you can do buttons or reactions but yh discord has the poll feature now
you could force end the poll after 2 min
and you can run logic off it?
yes polls emit events too
so:
bot starts a poll, stores the id or something
2 mins later, force close (need to figure out how to do "2 minutes later" logic, I imagine its a node thing)
sub to poll close event, if ID matches run some logic
see setTimeout
is a node thing?
Window: setTimeout() method
The setTimeout() method of the Window interface sets a timer which executes a function or specified piece of code once the timer expires.
yes not djs
sweet thankyou all
excited to start my bot journey
MessageCreateOptions#poll discord.js@14.25.1
The poll to send with the message
duration only supports min 1h. so im not entirely sure theres a way to force end a poll
oh
if the 2min is important you go with buttons/reactions
theres an end method on a poll object
yay
Poll#end() discord.js@14.25.1
Ends this poll.
Hi, running v14.25.1, I was under the impression when ClientReady fires that caches are populated. However, this code shows that only the bot user exists in it. Am I doing something wrong?
discord.on(Events.ClientReady, () => {
const { members } = aParticularGuild();
for (const [id] of members.cache) {
logger.info(`Refreshing ${id}`);
refreshTimeout(id);
}
});
I do have the GuildMembers intent:
const discord = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
],
});
member cache is not populated guild and channels are
Oh
So I guess the option is to use fetch(), then
is this depreciated?
just following docs here
no, why would that be deprecated?
it’s not something that exists on Client, but a property you created
oh
yea I shouldve read the docs closer it clearly says that sorry
Yes ty
We highly recommend you extend the Client structure properly instead of just attaching custom properties like .commands to the regular discord.js Client instance.
- Using typescript, you might want to consider casting or augmenting the module type
Is there such a thing in the current version?
yes those are current let me get them from the monorepo
Hmmm Ionly find typescript
nv they did not get move over so those are the latest. regardless you can use the npm package create-discord-bot
rawError: { message: 'Missing Access', code: 50001 },
code: 50001,
status: 403,
method: 'PUT',
url: ''
discord is returning missing access when trying to register commands, what reason might this be?
ensure that your client ID / token are correct and for the same application.... and if you're registering guild commands, that the bot is in said guild
all of this is true I beleive
ah
found the issue, sometimes I need to trust my own debug skills instead of asking for help smh
side question, is it advisable to register commands on every boot up of the bot? It will be an entirely private bot
no... it's generally recommended to have the registerCommands.js file to only be run manually ( like with npm run register or something simiar ) as, especially during development... you can easily hit the 200/day rate limit on commands
ahhhhh gotcha
hes not using interactions
if you're refering to the non-command thing from earlier, I have not started that yet
oh well, then yes what samtino said
if you hit that limit, you have to wait 24 hours before registering again... and since the actual data on a slash command (name, description, options, etc) rarely change... deploying them every time you reload your bot is pointless... you dont need to register your commands when the actual code run on a command execution changes
thanks :)
Could anyone help me make a user install bot that works in DMs? I have it working fine, but I want it to be able to be used in DMs.
are you registering your commands globally? are you modifying the context or installation_type of your slash commands?
data: new SlashCommandBuilder()
.setName('punish')
.setDescription('Vote to punish a user')
.addUserOption(),
async execute(interaction: CommandInteraction) {
await interaction.reply(`${interaction.user} is being punished!`);
},
so how can I actually grab and mention the user from addUserOption
Global registration
Yes, I currently have
.setContexts(InteractionContextType.BotDM, InteractionContextType.Guild)
In every command.
InteractionContextType.PrivateChannel is needed to use a command in other people's DMs and other servers
Are you sure it is IntegrationContextType? Or InteractionContextType? (I couldn't find IntegrationContextType.
addUserOption returns a callback function to construct the user option itself
.addUserOption((option) => option.setName("name").setDescription("Description")
then you get the value with const user = interaction.options.getUser("name") where "name" is the same as the option name
InteractionContextType.PrivateChannel
ok ty
yes typo on my part
As a side note since you're using TypeScript, change the type from CommandInteraction to ChatInputCommandInteraction. CommandInteraction is a base class which encompasses context menu commands as well which don't have getUser()
2 useful guide pages for building slash commands
- Advanced Command Creation - how modify your SlashCommandBuilder
- Parsing Options - how to recieve the options of a ChatInputCommandInteraction
Ah makes sense, do I need to do any specific logic for mentioning a user ?
Not really - you can just throw it in a template literal and the JS backend will stringify the User object to a user mention
amazing
how do I actually add a message create option to a reply?
I have interaction files like so
export default {
name: Events.InteractionCreate,
async execute(interaction) {
}}
and I load events with this function
function loadInteractionFiles(dir) {
const files = fs.readdirSync(dir);
for (const file of files) {
const filePath = path.join(dir, file);
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
loadInteractionFiles(filePath);
return;
}
if (!file.endsWith(".js")) return;
import(pathToFileURL(filePath)).then(module => {
const handler = module.default || module;
// Must have "name" and "execute"
if (!handler?.name || !handler?.execute) {
console.log(`[WARN] Interaction file missing name/execute: ${filePath}`);
return;
}
client.on(handler.name, (...args) => handler.execute(...args));
});
}
}
is having multiple files of the same event allowed? It seems to work and doesn't spit out an error but I wonder if its equivalent of using one monolithic file for one type of event.
having several files for the same event... while is allowed, is not recommended as you're creating a WS listener for each event
it's preferred to instead, route the events depending on their status to independent files/functions
what do you mean? like, how do you actually reply to an interaction?
no like
I want to build a poll into my reply
thank you
or would I need to build a new message entirely
await interaction.reply({
poll: PollData
)}
its that simple?
yes... poll is just an optional field of a message payload... just like content, embeds, and files
aaaaah
i dont remember completely what the restrictions are (if any) on sending a poll message... but if you are restricted. you can do interaction.followUp to send a second message with the interaction if needed
as in to follow discords UX philosophy ?
:0
async execute(interaction: ChatInputCommandInteraction) {
const user: User | null = interaction.options.getUser('user');
if (!user) {
return;
}
await interaction.reply({
poll: {
question: { text: `Punish ${user}?` },
answers: [{ text: 'Yes' }, { text: 'No' }],
duration: 1,
allowMultiselect: false,
},
});
await handlePunishmentVote(user);
},
};
how can I actually pass the poll as an object here?
const poll = {
question: { text: `Punish ${user}?` },
answers: [{ text: 'Yes' }, { text: 'No' }],
duration: 1,
allowMultiselect: false,
}
await interaction.reply({ poll })
is this what you mean by passing as an object?
yes and no, I want to pass teh object to an external function so I can call .end() at a later time
so the literal object of the poll, if thats obtainable
how in messageCreate do i check if a guild has my guild subscription entitlement?
additionally, I need to know how to server mute someone (as in the can't talk in voice chats at all)
I think you can go to Client -> ClientApplication#subscriptions
ClientApplication#subscriptions discord.js@14.25.1
The subscription manager for this application
There's disableCommunicationUntil, or if you want to just do it for voice channels GuildMemberEdit has mute: boolean, so you just edit the member to be voice muted
Perf thanks
You wouldn't happen to know about poll stuff ?
You could use withResponse: boolean inside the reply function, that can give you Message which you can pass it down to the function, I think. You gotta be a little more specific
I'm literally just trying to reference a poll im creating in a reply at a different point in my code
So that I can look at the results and do .end()
then what ispik said is what you want
Would the poll object be updated though, sure you can get a Message pointing to the poll but if like pollUserAdd or remove happens does the poll in that Message get updated as well? Ig one way to find out
if you got GuildMessagePolls intent: yes
Neat
So basically if I can pass the message, I can access the hypothetical poll?
hi i realized that there was an option to "Mute Soundboard" for Discord Bots. I'm wondering whether there is an option to make a bot play Soundboards from the server itself in VC.
How to detect someone's 2nd boost or more
Like I can detect a single boost done by a user how can I detect their second boost ?
There's technically Soundboard#url so you would be able to use that url to play a sound, how to accomplish that might be a @discordjs/voice thing
I think you would have to listen for MessageCreate event, since system events also fires MessageCreate, but probably store how many times they boosted? I think it stops being a djs question once you figure out how to use message event to see who boosted the server (won't work if the system messages are disabled though)
documentation suggestion for @last eagle:
VoiceChannel#sendSoundboardSound() discord.js@14.25.1
Send a soundboard sound to a voice channel the user is connected to.
ty
@fleet spire no, and please don't ghostping
sorry! I solved my problem, wont do next time
0|Bot | [14:11:16] ERROR: Interaction Error [cfg_welcome_modal_step1]: Guild validation failed: welcome.embed: Cast to Object failed for value "undefined" (type undefined) at path "welcome.embed"
if (type === "text") {
const currentWelcome = guildData.welcome || {};
const currentEmbed = currentWelcome.embed || {};
//
guildData.welcome = {
enabled: true,
channelID: session.data.channelID,
type: "text",
text: { card: session.data.text.card },
embed: currentEmbed, //obj
};
await guildData.save();
await interaction.reply({
content: "✅ Text Welcome Message Setup Complete!",
flags: MessageFlags.Ephemeral,
});
}
why does it return undefined? My welcome schema part;
embed: {
color: { type: String, default: "#000000" },
author: { type: String, default: null },
title: { type: String, default: "Welcome!" },
description: { type: String, default: "Welcome {user} to {server}!" },
image: { type: String, default: null },
footer: { type: String, default: null },
fields: [
{
name: { type: String },
value: { type: String },
},
],
},
Please use #1081585952654360687 for questions like these, since this is not related to djs at all and instead is a question about your database wrapper
function sendInteraction(i, options) {
return i.reply(options)
}
if (i.user.id !== requestUserId) return sendInteraction(i, { content: 'Nút này không dành cho bạn!', flags: 64 });```
Why is this showing an error : The reply to this interaction has not been sent or deferred.
what does the full error say?
process.nextTick(() => { throw err; });
^
Error [InteractionNotReplied]: The reply to this interaction has not been sent or deferred.
at ButtonInteraction.editReply (/root/LunariTest/node_modules/discord.js/src/structures/interfaces/InteractionResponses.js:246:48)
at sendInteraction (/root/LunariTest/src/utils/functions.js:54:14)
at InteractionCollector.<anonymous> (/root/LunariTest/src/events/buttons/buttons/avatarButton.js:64:50)
at InteractionCollector.emit (node:events:520:35)
at InteractionCollector.handleCollect (/root/LunariTest/node_modules/discord.js/src/structures/interfaces/Collector.js:133:14)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5) {
code: 'InteractionNotReplied'
}
Node.js v24.11.0```
The error happens at a ButtonInteraction.editReply. were the interaction has not been deferred or replied to. This can happen if the defer was not awaited
It works with i.reply directly.
It only gives an error when i.reply is passed through the function.
I dont know about your fuction but the error is occuring when your app recivces a Button interaction and your app trys to uses editReply before having replyied or deferred the interaction
So, is it possible to delete ephemeral messages after 5 seconds?
documentation suggestion for @flint pier:
MessageComponentInteraction#deleteReply() discord.js@14.25.1
Deletes a reply to this interaction.
// Delete the initial reply to this interaction
interaction.deleteReply()
.then(console.log)
.catch(console.error);
yes, but why do you what to do that? that does not seem like good UX
I want it to automatically delete after 5 seconds instead of staying on indefinitely.
The user can dismiss it and if the reopen the client it goes away
what is this "overview build" called which yggdrasil use? not modal, not anything elsy I ever seen thou
looks like a modal? with two Text Inputs
nah it is not a modal
will createAudioResource method in @discordjs/voice lock the file or make the file be busy?
that's just a channel topic
i assume the bot finds the channel(s) that have !welcome! in their topic when someone enters the server and posts the welcome message there
oh ya that is just the channel settings
any hind where theissue can be? :/
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
found my mistake ty
i'm pretty certain it is not subscriptions, the docs specifically say that api is just for generally checking the lifecycle of a subscription but should not be treated as a source of truth for whether someone has an entitlement
documentation suggestion for @odd stirrup:
ClientApplication#entitlements discord.js@14.25.1
The entitlement manager for this application
I know some one has asked this before an I cant remember if there is a way to get entitlements of a individual guild
wait nv I am dumb it is in the fetchoptions
FetchEntitlementsOptions#guild discord.js@14.25.1
The guild to fetch entitlements for
ah that sounds right
client.application.entitlements.fetch({guild:guild})
hi, how we can obtain the custom username of an user in a server ?
GuildMember#nickname discord.js@14.25.1
The nickname of this member, if they have one
oh ty
when a user invite my bot to a guild, how i can check the permission the user give for bot?
check the permissions on the bot's guildMember after it joined
GuildMemberManager#fetchMe() discord.js@14.25.1
Fetches the client user as a GuildMember of the guild.
Thanks
Somehow when doing this in my code, it does not errors....
try {
const newTopic = topic.replace(/Strikes:\s*\[\d+\]/, `Strikes: [${strikeNumber}]`);
await interaction.channel.setTopic(newTopic);
} catch {
await interaction.followUp({
content:
'⚠️ Failed to update the channel topic. Please update the strike count manually.',
flags: MessageFlags.Ephemeral
});
}
It should error when it hits the ratelimit...
no. it should queue the request and do the change when the ratelimit passes. unless you provided a rejectOnRatelimit in ClientOptions#rest
How do I do that?
I am missing something here....
rest: { rejectOnRateLimit }
RESTOptions#rejectOnRateLimit discord.js@14.25.1
Determines how rate limiting and pre-emptive throttling should be handled. When an array of strings, each element is treated as a prefix for the request route (e.g. /channels to match any route starting with /channels such as /channels/:id/messages) for which to throw RateLimitErrors. All other request routes will be queued normally
Default value: null
you can check the docs of everything to figure out what it should be
Alright
How to detect someone's 2nd boost or more
Like I can detect a single boost done by a user how can I detect their second boost ?
What do you suggest is the best way to implement the system
you could listen by the boost system message type. track how many times its sent
Can u elaborate a Lil?
I'm using const wasBooster = !!oldMember.premiumSince;
const isBooster = !!newMember.premiumSince;
when you boost a server and you set up a channel for discord system messages it sends a message. that message contains the user and by how many times that message is sent you can keep track how many times someone boosted
that works for first boost. extra boosts dont triggers it
Yeah exactly so u mean I should track the system channels msgs and trigger every time user boosted this server msgs comes ?
yh thats kinda the only way
So I shall use messageCreate event ?
yes and listen for the messagetype
can i have a message and component collector in one?
interaction create and message create are two different events, collectors are just temporary event collectors
if you really wanted to (though i really don't think that's the right approach) you could collect the raw gateway event and filter based on type, i suppose
yeah just use two collectors, there shouldn't be an issue
at most if I really wanted to I'd write a single handler function that accepts both and then just call it on each collector
ty
pengu
Are embedded images / image URL always accessible via message.embed[n].thumbnail?
I wrote an image filter which scans attachments, then realized people can just send image URL instead
Figured however, those messages will have embed objects with type image. However I am unsure if discord will always put the image into thumbnail, or also into image
thumbnail and image are two different things. the image is the larger image at the bottom of the embed
Yeah I am aware, but I talk about normal messages.
When Discord embeds an image URL it will put an embed object into the message
By that definition it should be a thumbnail yeah, I just got confused, because if you check a message object on your client it will be within message.embed.image for some reason
Discord barely documents this anywhere its kinda annoying
All they say is that there is an embed type image. But nowhere documentate how one would look
https://discord.com/developers/docs/resources/message#embed-object-embed-types
maybe this is a question for DDevs
if just image url it will the thumbnail embed. best to check for both embed thumbnail and image
Alright will do both of those. Thank you guys!
if i do deferReply i dont have to use withResponse to get the message?
yes you do
Unless theres more context to that question
why this error...
idk why but i kinda dug through djs repo to check.. : [i was high lol]
Property 'voice' does not exist on type 'APIInteractionGuildMember'.
if (!(interaction.member instanceof GuildMember)) {
return;
}
const memberVoice = interaction.member.voice;
Need to check inCachedGuild
ok. ty
How do you access emojis from the developer portal? client.emojis.cache.map(e => e.name) shows only a list of the emojis in the server I'm in
probably
client.application.emojis.fetch()```
ahh thank you!
mh i have a feeling it doesnt. if i use withResponse and then get the resource message it doesnt exist with deferReplies, i can just directly use the message
example
await interaction.deferReply();
const message = await interaction.followUp({ components: [container], flags: MessageFlags.IsComponentsV2 });
const collector = message.createMessageComponentCollector(options);
When I am adding a channel, it is not syncing the permissions with the category...
const channel = await interaction.guild.channels.create({
name: channelName,
topic: `Alliance Channel for: ${allianceName}`,
parent: Config.Settings.Channels.AlliancesCategoryID,
permissionOverwrites: [
{
id: allianceRole.id,
allow: [PermissionFlagsBits.ViewChannel]
}
]
});
Or am I doing something wrong?
documentation suggestion for @torpid marsh:
BaseGuildTextChannel#lockPermissions() discord.js@14.25.1
Locks in the permission overwrites from the parent channel.
Isn't it that when you create a channel in a category it will copy the permissions automatically?
CategoryChannelChildManager#create() discord.js@14.25.1
Creates a new channel within this category. You cannot create a channel of type ChannelType.GuildCategory inside a CategoryChannel.
think you gotta create channel through this then
Alright. So that is more like <category>.create()
Or how do I make it work properly? Never used that before.
<CategoryChannel>.children is the manager, so it would be .children.create()
Ah alright
It creates the channel... But why it still not synces...
const category = await interaction.guild.channels.fetch(Config.Settings.Channels.AlliancesCategoryID)
if(category?.type == ChannelType.GuildCategory){
category.children.create({
name: channelName,
topic: `Alliance Channel for: ${allianceName}`,
type: 0,
permissionOverwrites: [
{
id: allianceRole.id,
allow: [PermissionFlagsBits.ViewChannel]
}
]
})
Setting overwrites disables sync
Ah.
That's why Monbrey mentioned context. followUp returns the message. That has nothing to do with your question being about deferReply
well doesnt deferreply always expects you to respond?
- deferReply is a response. But it is expected to later edit that response, yes
- what does that have to do with your initial question or your use of followUp?
ok nvm just trying to understand withResponse better, why would i need it for interaction.reply but for this i didnt need it?
You would need it if you wanted deferReply to return the message.
Because that is doing the initial response. followUp is not sending a response though, it is sending a message with the webhook and always returns that message
I did everything correct, and the commands aren't loading, why? (No Errors seen)
const slashDirs = [
path.join(__dirname, 'commands/slash'),
path.join(__dirname, 'commands/slash/misc'),
path.join(__dirname, 'commands/slash/stats')
];```
Where's the rest? Where are you using those paths to load the slash command file?
To organize the files, so I can easily find them
client.slashCommands = new Collection();
(async () => {
const slashDirs = [
path.join(__dirname, 'commands/slash'),
path.join(__dirname, 'commands/slash/misc'),
path.join(__dirname, 'commands/slash/stats')
];
const body = [];
for (const file of fs.readdirSync(slashDir).filter(f => f.endsWith('.js'))) {
const cmd = require(path.join(slashDir, file));
if (cmd.data && cmd.execute) {
client.slashCommands.set(cmd.data.name, cmd);
body.push(cmd.data.toJSON());
}
}
client.once('ready', async () => {
console.log(`Logged in ${client.user.tag}`);
const rest = new REST({ version: '10' }).setToken(process.env.TOKEN);
try {
await rest.put(Routes.applicationCommands(client.user.id), { body });
console.log('slash commands registered.');
} catch (err) {
console.error('err);
}
});
})();```
For debugging, you should add a log when a command is added to body
You could also add an else for the if (cmd.data && cmd.execute) to say that there was an error with the cmd data
Also 2 other things
-
It's better to get your
client.onlisteners outside of other functions/methods as you want those to happen every single time. Unrelated to your command registration -
You should NOT be registering your commands every single time your bot starts. That's a great way to get rate limited for 24 hours
so I have to manually register after some time?
you should only be registering when you add, edit or delete command data
there's no need to be doing that every single time your bot starts
Alright, Thank you :)
help
[ERRO] Cliente Discord: TypeError: (intermediate value).addImageDisplayComponents is not a function
at buildPrincipalContainer (file:///F:/map-descompiler/discord-bot/index.js:746:6)
at Client.<anonymous> (file:///F:/map-descompiler/discord-bot/index.js:963:17)
at Client.emit (node:events:519:28)
at InteractionCreateAction.handle (F:\map-descompiler\discord-bot\node_modules\discord.js\src\client\actions\InteractionCreate.js:101:12)
at module.exports [as INTERACTION_CREATE] (F:\map-descompiler\discord-bot\node_modules\discord.js\src\client\websocket\handlers\INTERACTION_CREATE.js:4:36)
at WebSocketManager.handlePacket (F:\map-descompiler\discord-bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:352:31)
at WebSocketManager.<anonymous> (F:\map-descompiler\discord-bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:236:12)
at WebSocketManager.emit (F:\map-descompiler\discord-bot\node_modules@vladfrangu\async_event_emitter\dist\index.cjs:2504:31)
at WebSocketShard.<anonymous> (F:\map-descompiler\discord-bot\node_modules@discordjs\ws\dist\index.js:1190:51)
at WebSocketShard.emit (F:\map-descompiler\discord-bot\node_modules@vladfrangu\async_event_emitter\dist\index.cjs:2504:31)
code?
addImageDisplayComponents is in fact not a function
that function doesnt exist anyway
The error is completely correct
const s1 = new SectionBuilder()
.addTextDisplayComponents(
t => t.setContent('# test'),
t => t.setContent('test.')
)
.setButtonAccessory(btn =>
btn
.setLabel('Creator')
.setStyle(ButtonStyle.Primary)
.setCustomId('create_room')
)
const c = new ContainerBuilder()
.setAccentColor(5793266)
.addSectionComponents(s1)
return c
}```
thats a very nice block of code
i dont know what you're asking
I want to put a banner on it above the messages.
I am going to try
Media Gallery
A Media Gallery is a display component that can display a grid of up to 10 media attachments. Each media item can have an optional alt text (description) and can be marked as spoiler. You can use the MediaGalleryBuilder and MediaGalleryItemBuilder classes to easily create a Media Gallery component and its items:...
const s1 = new SectionBuilder()
.addTextDisplayComponents(
t => t.setContent('# test'),
t => t.setContent('test.')
)
.setButtonAccessory(btn =>
btn
.setLabel('Creator')
.setStyle(ButtonStyle.Primary)
.setCustomId('create_room')
);
const mediaGallery = new MediaGalleryBuilder()
.addItem(
new MediaGalleryItemBuilder()
.setUrl(config.bannerImage)
.setAltText('Imagem 1')
)
// Container principal
const c = new ContainerBuilder()
.setAccentColor(5793266)
.addSectionComponents(s1)
.addDisplayComponents(mediaGallery);
return c;
}```
@bleak owl Is that correct now?
you can try it out
does it error or does it send and display correctly
[ERRO] Cliente Discord: ReferenceError: MediaGalleryBuilder is not defined
at buildPrincipalContainer (file:///F:/map-descompiler/discord-bot/index.js:756:24)
at Client.<anonymous> (file:///F:/map-descompiler/discord-bot/index.js:969:17)
at Client.emit (node:events:519:28)
at InteractionCreateAction.handle (F:\map-descompiler\discord-bot\node_modules\discord.js\src\client\actions\InteractionCreate.js:101:12)
at module.exports [as INTERACTION_CREATE] (F:\map-descompiler\discord-bot\node_modules\discord.js\src\client\websocket\handlers\INTERACTION_CREATE.js:4:36)
at WebSocketManager.handlePacket (F:\map-descompiler\discord-bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:352:31)
at WebSocketManager.<anonymous> (F:\map-descompiler\discord-bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:236:12)
at WebSocketManager.emit (F:\map-descompiler\discord-bot\node_modules@vladfrangu\async_event_emitter\dist\index.cjs:2504:31)
at WebSocketShard.<anonymous> (F:\map-descompiler\discord-bot\node_modules@discordjs\ws\dist\index.js:1190:51)
at WebSocketShard.emit (F:\map-descompiler\discord-bot\node_modules@vladfrangu\async_event_emitter\dist\index.cjs:2504:31)
You need to import it
Sorry, my knowledge of Node.js was outdated.
its really basic javascript
Node.js was outdated....
that will not resolve your issue
the issue is that you need to define MediaGalleryBuilder, which is done by importing it from the discord.js library
Inside node_modules, MediaGalleryBuilder doesn’t appear. I ran npm install discord.js and have already uninstalled discord.js.
MediaGalleryBuilder is not a package from npm, so it will not be in node_modules/
it's a thing that discord.js exports
similarly to how you can import fs or path without installing anything, as those are provided by node itself
| [20:21:30] ERROR: UNCAUGHT_EXCEPTION: Opening handshake has timed out
what is that
Now I understand, thank you very much.
an error
🥺 ✌️
nothing we can do about it, it's not related to discord.js
it's either your host, or the network connection between it and discord
well I thought it is since Ive never seen it before and was curious so thats why im here r
well, unfortunately this is d.js support, not "ive never seen this in my code before"
ur so tuff
how to check if bot is verified
check if it has that flag
Does anyone know how I can get this in discord.js embeds?
The line things I believe called line 14 in some Json embed version and separator 1 in discohook
it’s a separator component, it’s only available with cv2 not embeds
Ahh ok thx
Hi everyone, Bots can record voice channels?
yes, bots can do that
i would be very careful with persisting voice recordings, in many countries that's quite heavily protected by law
especially if they're not explicitly made aware of it
You are honest with this point, most of the followers of Server are Arabs like Jordan, Saudi Arabia, Oman, and Kuwait, all of whom are prohibited from registering without the person's knowledge.
Thanks for help
I keep getting a deprecation warning for the ready event. I've already migrated to the clientReady event but it's still popping up. Anyone know why?
Somewhere is still using ready
Node has a trace wranings flag that might help
Yeah I tried using that, it didn't show where it was originating from.
I only have 1 ready event and it uses the clientReady event
I'm not so good at doing discord.js how can I learn?
getting better at stuff usually involves doing more of said stuff
if you are struggling with one thing in particular, describing that thing in particular is useful for anyone to be able and help
Try reading https://discordjs.guide, it's a pretty helpful resource.
How about if we are like just starting
Then the guide is still the go to resource. And if you want to learn JavaScript, #resources has some helpful resources for that.
KK thx
are you using a framework or anything like that?
if im using the member partial, am i better off listening to GuildAuditLogEntryCreate for role changes, nickname changes etc instead of GuildMemberUpdate?
For logging? I personally prefer the audit log event for all of that. Regardless on if you're using the partial or not. It shows more information
Note that is a user changes multiple roles guid audit log create may only fire once
Why am I geting:
(Use `node --trace-deprecation ...` to show where the warning was created)```
I am clearly using clientReady and nowhere ready.
did you try doing what the last line suggests to find out where the warning originates? and are you using any third party libraries apart from discord.js?
Its in ts so --trace-deprecation did nothing
I am using discord-hybrid-sharding and cross hosting
are you sure you didn’t just have a file named ready that you renamed to clientReady
then that's what's listening to ready
Use the newListener event and console.trace to track it down
I dont seem to find newListener event you told me
It’s a native EventEmitter event
'newListener'
The EventEmitter instance will emit its own 'newListener' event before a listener is added to its internal array of listeners.Listeners registered for the 'newListener' event are passed the event name and a reference to the listener being added.The fact that the event is triggered before adding the listener has a subtle but important side effect: any additional listeners registered to the same name within the 'newListener' callback are inserted before the listener that is in the process of being added.
yeah so its the client of the discord-cross-hosting which causes the ready error.
not an error, merely a warning
You can ignore it
They will have to fix it in the next major version (v15) when it actually gets removed
great! thank you!
No.
FOR messageUpdate event whats the log type
wdym with log type?
djs.AuditLogEvent
there isnt one
since message update is always by the same author
ah i leave that part blank
it doesnt have an audit log, yeah
ok
client.on("clientReady", async () => {
try {
try {
await client.guilds.fetch();
await client.users.fetch();
console.log(`✅ Fetched ${client.guilds.cache.size} guilds`);
} catch (err) {
console.error("Failed to fetch guilds:", err);
}
const commandsArray = [...client.commands.values()].map((cmd) => ({
name: cmd.name,
description: cmd.description || "No description",
category: cmd.category,
aliases: cmd.aliases,
usage: cmd.usage,
}));
const slashCommandsArray = [...client.slashCommands.values()].map(
(cmd) => ({
name: cmd.name,
description: cmd.description || "No description",
category: cmd.category,
usage: cmd.usage,
}),
);
const guildsArray = client.guilds.cache.map((g) => ({
id: g.id,
name: g.name,
icon: g.icon,
}));
const guildCount = client.guilds.cache.size;
const userCount = client.users.cache.size;
console.log(`📊 Bot Stats - Guilds: ${guildCount}, Users: ${userCount}`);
await bot.findOneAndUpdate(
{ id: client.user.id },
{
id: client.user.id,
username: client.user.username,
avatar: client.user.displayAvatarURL(),
guildCount: guildCount,
commands: commandsArray,
slashCommands: slashCommandsArray,
guilds: guildsArray,
userCount: userCount,
shardCount: client.shard ? client.shard.count : 1,
},
{ upsert: true },
);
console.log("✅ Bot data saved to the database!");
} catch (err) {
console.error("❌ Failed to save bot data:", err);
}
});
``` the users cache is so low only in the on ready
whats your error/issue?
client.users.cache.size is so lower then the actual one
client.users.fetch() requires you to pass a user as a param. you can't fetch every single user on discord. thats not possible. guilds are cached by default with the Guilds intent so you don't need to fetch them
is there a Users intent too?
no
Getting your bot's member count
client.users.cache.sizeis unreliable because it will only return cached users- The preferred method is using
collection.reduce()onclient.guilds.cache
client.guilds.cache.reduce((acc, guild) => acc + guild.memberCount, 0)
let me try
@bleak owl "NaN"
pass a param here named c and use that as your Client instance inside the clientReady event
alr 1s
the code u gave me returns userCount as NaN still
did you replace client.guilds... with c.guilds... ?
yes
every single client inside the event is replaced with c
lets see your current code
client.on("clientReady", async (c) => {
try {
const commandsArray = [...c.commands.values()].map((cmd) => ({
name: cmd.name,
description: cmd.description || "No description",
category: cmd.category,
aliases: cmd.aliases,
usage: cmd.usage,
}));
const slashCommandsArray = [...c.slashCommands.values()].map(
(cmd) => ({
name: cmd.name,
description: cmd.description || "No description",
category: cmd.category,
usage: cmd.usage,
}),
);
const guildsArray = c.guilds.cache.map((g) => ({
id: g.id,
name: g.name,
icon: g.icon,
}));
const guildCount = c.guilds.cache.size;
const userCount = c.guilds.cache.reduce((acc, guild) => acc + guild.memberCount, 0)
console.log(`📊 Bot Stats - Guilds: ${guildCount}, Users: ${userCount}`);
await bot.findOneAndUpdate(
{ id: c.user.id },
{
id: c.user.id,
username: c.user.username,
avatar: c.user.displayAvatarURL(),
guildCount: guildCount,
commands: commandsArray,
slashCommands: slashCommandsArray,
guilds: guildsArray,
userCount: userCount,
shardCount: c.shard ? c.shard.count : 1,
},
{ upsert: true },
);
console.log("✅ Bot data saved to the database!");
} catch (err) {
console.error("❌ Failed to save bot data:", err);
}
});```
did you remove the Guilds intent?
no, and guildCount is correct
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.GuildVoiceStates,
GatewayIntentBits.DirectMessages,
GatewayIntentBits.DirectMessageReactions,
GatewayIntentBits.GuildPresences,
GatewayIntentBits.GuildWebhooks,
GatewayIntentBits.GuildModeration,
GatewayIntentBits.GuildExpressions,
GatewayIntentBits.GuildIntegrations,
GatewayIntentBits.GuildInvites,
GatewayIntentBits.GuildMessagePolls,
GatewayIntentBits.GuildScheduledEvents,
],
allowedMentions: {
parse: ["users", "roles", "everyone"],
repliedUser: false,
},
partials: [
Partials.Message,
Partials.Channel,
Partials.Reaction,
Partials.User,
Partials.GuildMember,
],
shards: "auto",
restRequestTimeout: 1500000,
});```
what's your d.js version? npm ls discord.js
npm ls discord.js
tryhard@0.0.1 C:\Users\...\Documents\Projects\tryhard\main\tryhard-main
└── discord.js@14.25.1
what if I use Partials to fetch the users?
you cannot fetch users
oh yh...
i honestly don't quite know why you're getting NaN since that line of code works perfectly for me
¯_(ツ)_/¯

same line works perfectly fine in my eval command too
the only Partial i can see being used here is Channel, otherwise i dont know if you really need all those others
Probably unavailable guild in cache
reactions and messages for reaction roles
For that guild.memberCount would be null and thus that reduce becomes NaN
so what do I do now?
filter unavailable guilds from that cache before reduce
even doing that code on clientReady it worked once and I got 12k members, original users count is 25k
Guild#available discord.js@14.25.1
Whether the guild is available to access. If it is not available, it indicates a server outage
How did you determine the "original users count" you compare against here?
ran client.users.cache.size in my eval command on the bot's host(so it's been on for a while meaning all users are cached)
"all users" are almost never cached unless its a small server
No, not all users will be cached. Just all users that interacted with something on a guild causing an event to emit to your bot
ah, I see. so just keep spam updating the bot data in my api I guess after clientReady...
No
under a check if the count in db is not equal to current count
This is the right way. Just might need to add an extra .filter(guild => guild.available) in between
Why would you save the user count to a db? Since it's constantly changing anyway
never knew it was constantly changing
It changes when a user joins or leaves the guild. Which will happen quite often on bigger servers. Considering you said 25k I'd say that is the case here
I just added a check in the api everytime the bot data is fetched, if one of the counts is not equal to current client count then set and save
but why save the count is the question
i personally don't see the point in saving the user count
to use in the frontend, now that I think of it yeah no need...
if discord takes the nitro booster role off of a member, does this emit a guild audit log entry create event? just wondering because theres an GuildAuditLogsEntry.executor.discord property
where are you seeing it has a .discord property? i only see user
and that doesnt emit an audit log
You can use guild member update event for that
actually, i must be appending it myself but i dont know where i do that...
yh discord doesnt exist on user, it would be user.system
the only time i use ".discord" is in strings so i dont know how it's being appended
I know but I'm using guild member partial and so the old members roles wont consist of the boost role so I can't see if its been removed
Last boost since exists
I guess you still need the old member to know it was removed and not smth else that changed
why would you use .discord on strings? that's not a property on strings either
I think they meant literally in a string like "foo.discord"
Can bots determine who moves the channels?
nope
Audit logs (if one is generated)
i dont think reorder ever makes an audit log
sadly
it doesn't because one channel move could potentially update all the channels in the category
I'm getting error about module not found something like zlibsync (name is inaccurate as I forget the actual name), imported by index.ts of discord.js
Posting the actual error will be needed to help with your issue
btw i am using it on nextjs so that's on Turbopack
so it's just module not found
zlib-sync
imported by discord.js index file
and npm install zlib-sync doesn't work, even it doesn't install anything
ping me with reply btw
not really something djs related then. where are you hosting this on?
discord.js isnt web compatible
locolhost for now as I'm developing it and it's not needed in my code anywhere it's just imported by discord.js which is not found
it's just functions
no it isnt???
I dont know what you mean by that
then how people make dashboard with djs?
by connecting to a node.js backend via APIs
or querying a shared database
this module is imported in djs zlib-sync which isn't found
using djs . I mean
yeah because it doesnt exist in web environments, its a node native module requiring node-gyp
discord.js runs on the node.js backend server side
so there's no option except using discord api directly?
Thats not what I said at all
But that is an option
then what are you saying?
That discord.js does not work in a web browser environment
nodejs is broken already
then what to do except direct discord api?
- build your own API layer for a server-side application that runs discord.js
- have your server-side bot appication write necessary data to a database that can be accessed by the front end
yes, it's broken on most latest version on the local machine as mongo is not even getting connected on it easily.
Yeah no, no idea what youve done
I'm calling discord.js via api route already
Also not what I said
it's just verifies if userid exists in serverid and which roleids it have ,
there's only this use of djs there
just use @discordjs/rest then
discord.js is a full websocket client library, it makes no sense to use it for what youre doing
I just thought it's better than direct api usage
not at all
mostly because its you know... incompatible
will it fix the issue?
I didn't know that
so what do you recommend,
direct discord api or what ?
i mean it should, you dont need the entire package
just call direct routes with the rest package
I would try that then ig
I have a dashboard that uses an API to communicate with the bot, don't know if sharing the repo would be fine though, if it is to you could see an horrible example at least
You can DM it to them if they want
is there any way to await for a modal submission like Message#awaitMessageComponent?
other than handling it through intereaction create event
Modals are interactions so no they dont exist on anything other than interactions
documentation suggestion for @boreal olive:
ButtonInteraction#awaitModalSubmit() discord.js@14.25.1
Collects a single modal submit interaction that passes the filter. The Promise will reject if the time expires.
// Collect a modal submit interaction
const filter = (interaction) => interaction.customId === 'modal';
interaction.awaitModalSubmit({ filter, time: 15_000 })
.then(interaction => console.log(`${interaction.customId} was submitted!`))
.catch(console.error);
Almost all interaction types should have it btw not just buttons, refer to docs
Hello, I need help with something. I'm trying to fetch the members from a pretty large server, and I keep on getting the Error [GuildMembersTimeout]: Members didn't arrive in time. error. I already included the intents in my Client constructor and the Server Member Intent is also enabled in the Developer Portal. Can somebody help me? What am I doing wrong?
const { Events } = require("discord.js");
module.exports = {
name: Events.ClientReady,
once: true,
async execute(client) {
console.log(`${client.user.tag} is now online.`);
const guild = client.guilds.cache.get(process.env.GUILD_ID);
await guild.members.fetch().then(console.log).catch(console.error);
},
};
Discord introduced a rate limit on requesting all guild members (once per 30s per guild).
- You will have to update your code accordingly to make sure this doesn't affect your app.
- Look for instances of
guild.members.fetch()with no user ids. - Starting in version 14.25.0, discord.js rejects the returned Promise and exposes details in
error.data.
-# If you confirmed this cannot be the reason, you can find other caveats in our guide
.
Does anyone know why the messageDelete event only sends logs if the user who deleted the file is the same user who sent the message?
Because that's how discord implemented it
probably to avoid too many unnecessary audit logs
Can we add selectmenu to modal
yes
Modals
Modals are pop-up forms that allow you to prompt users for additional input. This form-like interaction response blocks the user from interacting with Discord until the modal is submitted or dismissed. In this section, we will cover how to create, show, and receive modals using discord.js! This page is a follow-up to the interactions (slash commands) page. Reading that page first will help you understand the concepts introduced in this page.
I have a v2 container with text components and accessory buttons. Is there any way, even a hacky one, to make the widths of the buttons equal?
as far as I understand the limitations, there's only one button accessory per text component, that's why I split the title and the note/timestamp into two text components
nope, the size depends on the text of the button
There's no way of using some sort of non-breaking space or hacky invisible character to pad the width?
you can try
i know discord trims the display text to remove padding spaces... but some unicode invisible characters might solve this
Thanks. I was leaning toward that idea but wondered if there was an established workaround more experienced bot devs knew of here.
unfortunately, no... there's very little visual customization you can perform to any of the rendering of data from your bot... it's generally recommended to add as little "hacky" fixes as possible to avoid mismatched rendering between desktop and mobile
makes sense. I'll want to test it on mobile as well of course. I've noticed even normal discord.js features render differently between the platforms
The best approach would probably be to try and use the same (or close to the same) amount of characters in the labels.
Thanks again for the feedback.
Settling for that approach. I didn't like how the note text could go under the "Add Completion" button originally. This is good enough.
that correct?
Run your code before asking if it can work. (errors are often very useful in pin-pointing the issue! )

At least put some thought into the UI instead of straight-up copying others
Please keep off-topic remarks like these out of support channels
is it a good idea to have massive command files where you do all logic? or do people split them up as command builders + handle logic elsewhere
when I have many sub commands the file gets pretty long handling each case
it's completely up to you
it doesn't particualrly matter if the function is in the same file or is imported from other file
it's still the same function
you can make a "main" command file that gets called by the command handler, and then taht "main" command file then imports all its subcommands from a directory or something
it doesn't need to be something command handler is explicitly aware of (as in, it only calls the command. what the command imports and requires and where from in order to respond isn't really what that handler is concerned with, allowing each command to do it in any way it wants to)
yeah I get that but is there a standard or best practice for doing it instead of having command files that are hundreds of lines long, for example
"hundred of lines long" is not a valid measure
if your command has this much logic, then it has this much logic, and you can't avoid that
fair enough
if you have 400 lines of logic for one command in one file, or needlessly split it into 4 100 lines files doesnt' change that it's still 400 lines of logic
except now you have parts of it spread around
if your command has a subcommand that can fit its logic in 3 lines, you dont' really have to split it out either, cause you will spend more lines to export and import it back
but then that's really a question of if you want to be super strict about consistency
i was more concerned about the maintainability of files that get this long, but you would say splitting it up isnt worth it?
400 lines is not long in the slightest
and if you find it long to scroll during development you can always collapse blocks in your IDE
as for splitting - depends. if it's a single command with no subcommands, i would not split at all.
if a command would have subcommands, and each of those could easily reach 400 lines, then i would probably split out, but only after i remove common parts out of each into some reusable function
at the end it's up to you as the maintainer
alright yeah I get you
cheers
Yo
can we not send buttons using webhook?
only if the webhook was made by your bot
unless you want to send link buttons
well I tried both
it was made by me through discord itself
then no
it needs to be made by an app so that discord knows who to send the interactions to
how can I only create one webhook and not a new one each time
checking if the channel has one alr and if not make a new one?
that's one way
or just create one, grab its id and token (or the url, since it has both of those) and store that
then just reuse that
but that's what I did..
but you made the webhook
not the app
all webhooks have ids and tokens
oh.. can I make one using the bot's eval command and save it?
it's about who created it
sure
let me try(this 15s cooldown kills me)
how can I create a webhook using the app? new WebhookClient without passing an object?
no, that's just a local object that allows you to control an already existing hook
you have to create it on the channel
BaseGuildTextChannel#createWebhook() discord.js@14.25.1
Creates a webhook for the channel.
// Create a webhook for the current channel
channel.createWebhook({
name: 'Snek',
avatar: 'https://i.imgur.com/mI8XcpG.jpg',
reason: 'Needed a cool new Webhook'
})
.then(console.log)
.catch(console.error)
thanks! are the name and avatar and reason required?
no
look at the docs, i just sent them
perfect, thanks!
name is required
yup just saw it in the docs, thanks again
I can't seem to copy the url manually and in the eval command I only see the webhook's id, no url option
?
nvm I got it, thanks
is there a middleware pattern for discordjs that I can use? or do I have to implement my own.
I have multiple classes i want to integrate as "modules" for my bot, and if the event listeners on those class calls return true i want it to stop execution from going to the next event listener
or, not calling next in a way
Not really no, event listeners are not sequential
You'll have to build your own.
How i can set the custom status here?
Thanks mate
Any way to set a custom avatar for the bot on x server?
documentation suggestion for @fathom python:
GuildMemberManager#editMe() discord.js@14.25.1
Edits the current application's guild member in a guild.
guild.members.editMe()
Thanks!
i can set max 1 activities right
You can set more than one status yeah
oh it rotated my status ty, but can i change it for faster?
the lowest you can set it is to 5s without hitting ratelimits.
yeah ik but i dont know how to change it
you will have the use the setInterval(() => {}, ms) function for it.
oh okay ty
no worries. 🙂
Hello, is there a way to know if the event has already been loaded and if so, to delete it?
Do you want an event to run once?
Actually, I'm using client.once and client.on, and I'd like to know which ones are online. If, for example, messageCreate is online, I want to be able to complete it and stop receiving events.
you can remove events via EventEmitter.off() (alias for .removeListener()), passing in the event name and the function that it runs.
if you're doing anonymous functions in the listeners, or any other way that doesn't let you access the actual function in the listener, you can always get to them via EventEmitter.listeners() passing in the event, then you can pass directly from that to the off()
that will remove the listener, but has no way to actually stop an already running one
Thank you, I'm trying to do that.
is there a way to access a users game collection
not via the bot api, maybe with oauth2, but that's outside the scope of the library
thanks
why does the bot sometimes not get the user's banner? rather is sometimes get it most of the time no
you need to force fetch the user to get the banner, as the docs state
I'm using cache, I guess I gotta fetch now. Thanks!
is it possible to get a user's theme color profile?
User#accentColor discord.js@14.25.1
The base 10 accent color of the user's banner The user must be force fetched for this property to be present or be updated
Maybe this is it not sure
that's not it
"user's banner"
also why does the User#flags only return one enum?
flags are a bit field
ah I see, thanks
is the discord nitro ones not included in them?
no
but in the api I see "premium_type": 1, "public_flags": 64 how come they r not in djs?
they are, they're just not sent with the public user data
so can I get them?
oauth should have them
in djs?
discord deliberately doesn't send that info to apps via the regular user payload
pretty sure there's also a column in that table that says the oauth scope you need to get each field, including premium_type and whatnot
yeah I see what you mean now
yh all identify
except verified and email
discord api is just the best right?
user privacy is a thing
a nitro badge is public.. just like the others that are public in the user no?
what's public to users is not always the same as what's public to bots because of the possibility of automating the access and collection of that data. same reason user profiles are not accessible to bots
similar reasoning to why the message content and presence intents are privileged, for user privacy and to help prevent abuse
but like what's the difference if they add the nitro badges inside the flags bitfield?
yeah first thing that comes to mind is a bot that automates sending phishing links only to nitro users, since that's more "valuable" than a non nitro account
well when you put it like that..
ye sadly you have to think the worst possible ways someone could abuse the info you give, since that'll probably be an actual thing someone will do
ofc the most secure thing would be to not give any data but that's not useful to anyone, so they probably choose to give what's required and maybe some cosmetic stuff that's not really important
huh, its not even same things and cant i make something similar to it
anyways ur choice to choose nonsense over basic sense
Yea do whatever you like
I just informed you, that’s all It’s not a big deal
Yea you can't but I know what kind of person you are so do whatever it pleases you
you were already told this is not the correct channel to discuss this, please do not continue
Sorry for the commotion
I have a discord bot that sends messages whenever someone finishes a map, the problem is I'm doing something like
const name = [${name}](${playerUrl});
for the name, but this sometimes breaks with an object such as:
{ "timestamp": 1769704328, "map": "Houll", "name": "[D] 末一", "time": 2522.34008789063, "server": "CHN" }
I'm guessing because the name has md characters in it, and I'm not sure if the lib has something to sanitize strings specifically for this kind of usecase or if I should make a function that escapes any special md chars in strings
This is the end result of my current code :/
d.js doesn't sanitize input, so there's no function for it. you'd want to check if there's something built into js natively or another package that does it. #1081585952654360687 if you need more help
I asked cuz I thought discord has a slightly different markdown syntax, and d.js might have a helper to escape those, or at least a list of chars that discord uses for markdown
Im having trouble finding what is the most current version of discordJS can someone point me in the right direction?
npm install discord.js@latest
Ya that too
how can i make this its a selectmenu in a poll
@wary coral
Not a poll. That's a modal
Also don't ping random people. Just ask a question and wait
Select menu
Select menus allow you to limit user input to a preselected list of values. Discord also offers select menus linked directly to native Discord entities like users, roles, and channels. Since they behave very similarly to how they do in messages, please refer to the corresponding guide page for more information on configuring select menus. Here again, you wrap the select menu with a label component to add context to the selection and add the label to the modal:...
oh ye solry
thanks
is the new permissions in djs yet > BypassSlowmode
Yes
why would message.content be null for an uncached message despite having message partial enabled?
(messageDelete event)
you already mentioned why
its uncached
and its a deleted message, so why would there be content
ah i may be mistaking myself with message update
could i send 2 interactions in 1 response to a command?
The command is the interaction
You can send two responses to one interaction, if thats what you mean?
i mean i run a command and it returns some data in an embed and then i want the next message to reply to the embed with the data so i can copy it easier on mobile
ChatInputCommandInteraction#followUp() discord.js@14.25.1
Send a follow-up message to this interaction.
thanks!
Why do I get the error DiscordAPIError[10008] when I try to edit an ephemeral message?
could you show your code please?
{
customId: `edit_room_name`,
guildOnly: true,
async execute(interaction, args) {
const msg = await interaction.message.fetch();
},
},
ephemeral messages don't technically exist as regular messages, so they don't return any message data. you'll want to use .editReply to edit that ephemeral message
This is supposed to be the answer to the button here, but the error pops up even when I do a fetch.
you can't fetch an ephemeral message because it doesn't actually exist
So, will interaction.editReply work here?
it should, yes
Thanks, I didn't understand this for a long time.
Hi. I'm trying to deploy my bot and it doesn't get online. I tried to reset token and got the same. I deployed the last week without any issues, but now I can't. I tried to deploy with a version of the last week which works and I doesn't deploy too... I added this code to debug it:
console.log("🚀 Iniciando Bot...");
this.on('debug', (info) => {
if (!info.includes('Heartbeat')) console.log(`[DEBUG] ${info}`);
});
try {
await this.login(process.env.DISCORD_TOKEN);
console.log(`✅ ¡Bot loggeado exitosamente como ${this.user?.tag}!`);
this.user?.setPresence({ status: 'online' });
} catch (error) {
console.error('❌ Error FATAL en login:', error);
}
And I got this error:
❌ ERROR DE RED: No se puede alcanzar discord.com: SyntaxError: Unexpected token '<', "<!doctype "... is not valid JSON
at JSON.parse (<anonymous>)
at parseJSONFromBytes (node:internal/deps/undici/undici:4259:19)
at successSteps (node:internal/deps/undici/undici:6882:27)
at readAllBytes (node:internal/deps/undici/undici:5807:13)
at process.processTicksAndRejections (node:internal/process/task_queues:103:5).
Does anyone know what can I do?
I'm pretty sure the correct login code in your case is:
js client.login(process.env.DISCORD_TOKEN);
Not await this.login(process.env.DISCORD_TOKEN);
I extended the Client class to implement my own one
That code is from that extended class
if you're getting a "cannot reach discord.com" error, then that would likely mean an issue with your local network, not discord's
is this from your local machine or some kind of hosting provider?
Is a provider. We're using Render
We already tried to "force" the change of the IP. But the error persists
doesn't render use shared IPs? youre likely getting cloudflare banned
Yes. The free plan is shared. But it was working during the whole month and we could deployed without any issue, but we got the error now.
that's how shared IPs work... someone else on that IP has spammed the discord API so much so that cloudflare has temporarily blocked the entire IP (and possibly other IPs from the provider... depending how they do DDoS prevention)
We would need to change to another provider then?
or wait for the ip ban to expire
Ok. Thanks
hey guys, not a coding question but more related to deployment. I want to host a bot on my local server.
basically the pipeline im looking for is ->
I have a "prod" branch in my github repo
whenever a change is made to the prod branch is pushed, the instance on my server updates to it
If you already know how to use workflows then it's just ssh'ing into your server and updating it
I do not know workflows lol
or are you literally refering to just sshing in and pulling down the latest v?
Not really djs so I'll keep it simple and you should go to a more appropriate place for more questions,
You use GitHub actions to run a workflow when changes happen to the prod branch and ssh into your server to do the changes
That doesn’t sound safe tbh
I’d prob just use cron to poll gh changes or use gh webhooks to listen for changes and pull it
Unless you are referring to the self-hosted runners, which seems ok according to Google
yea i mean ultimately it might be easiest just to dockerize the app and manually deploy it since I wont be updating that often
hi umm just to be clear ChatInputCommandInteraction extends BaseInteraction right? because instanceof is telling me otherwise
It does. Are you importing those two classes from the same place?
oh wait do i fr have 2 versions
yep i think thats the issue, i did pnpm link
Why images with URL ending in “empty.png” are not displayed in the setURL of a MediaGalleryBuilder? Is that a bug?
setURL doesn't display anything
could you be more specific?
MediaGalleryItemBuilder#setURL() discord.js@14.25.1
Sets the media URL of this media gallery item.
This should indeed cause the item to display something. But is the URL actually an image containing something? Considering the name sounds like it might actually be empty
Using that, I have an image URL that ends in empty.png and it doesn't display in the Components, but if I change the name of that same image to something else, it works.
how are you changing the name
Did you check that the URL actually is a valid image URL and not containing a typo? Did you log the actual payload being sent to discord to find out? Alternatively log the message after it got sent
can i send external urls here?
Yes
If it's for support purposes like in your case
Well, I just tried the same image on a different domain with the URL ending in “empty.png” and it works. So I guess it must be a problem with the domain where I upload the files.
Not a DJS issue
is there a inviteJoin.js?
What are you trying to track? Your bot joining a server or a user joining a server?
user joining a server or using a invite
No you can't see what invite they used if that's what you're looking for
hello, i am using shard, and i want to DM a user, how can i make sure that only 1 bot will send the message even if the user exist in many shard
When you run the user.send it should originate from the shard that started the interaction/event. But received dm events should only go to shard 0
there's no event, lets say i have ID 1117220717935734814, and i just want to send a msg.
because using broadcastEval might send using more than 1 shard
but when does that trigger? code doesn't run by itself
is it some kind of schedule or interval?
yes, based on some conditions
and each shard has an instance of the same schedule?
no, i think to run the interval in the shard manager file (index.js)
AI says:
Try DM from the manager process directly via client.users.fetch(userId).then(u => u.send(...)).
This usually works regardless of guilds and avoids shard duplication entirely.
but idk the code looks weird
I need help with choosing what intents I need for my bot, is anyone able to help me?
what part of it looks weird? looks fine to me
ok thanks
check the intents each event you want to listen to requires
- Websocket intents limit events and decrease memory usage: learn more
- See what intents you need here
hi
hello
if you're just here to say hi, please take it to #archive-offtopic
if you have a question or issue, please state it
#how-to-get-help
Does guildCreate event show added by who?
no. generally, "who did this action" is available via audit logs
Does anyone know how to properly do a modal?
Modals
Modals are pop-up forms that allow you to prompt users for additional input. This form-like interaction response blocks the user from interacting with Discord until the modal is submitted or dismissed. In this section, we will cover how to create, show, and receive modals using discord.js! This page is a follow-up to the interactions (slash commands) page. Reading that page first will help you understand the concepts introduced in this page.
If you mean, just how to get them to work... Then the guide above should help
❌ Failed to register commands: DiscordAPIError[50035]: Invalid Form Body 0[BASE_TYPE_MAX_LENGTH]: Must be 110 or fewer in length.what causes this error?
I figured, thanks!
You have exceeded the command limit
Utilize sub command groups and sub commands to combine similar commands into a single object
fuckkkkk, what's the limit?
100 slash commands, 5 user context menu, 5 message context menu
alr, thanks!
You can double it by using both global and guild commands
no need, I use a lot of commands like rradd, rrlist, rrremove, which can all go under one command ect...
But you can also use sub commands to combine several into 1
/example add and /example remove can become 1 Application Command and appear as 2 slash commands
yup, that's what I need. I can also do like disable commands all under one and enable also all under one
@topaz bluff is there a limit to how many sub commands a slash command can have?
25
25? But I would have to double check
more then enough, thanks jo and samtino
Ofc
I have no reactions perms🥲
Does Events.ClientReady event pass a client to you?
Yes
thank you 🙂
maybe this should go in #1081585952654360687 but it's a very small question
Is there a cleaner way to import fields from a JSON in an ESM module? Here's the code for CommonJS as the guidebook uses:
const { productionGuildId, minimumCooldownTimeMs } = require('../../config.json');
Here's my ESM code that does the same thing, but is less ergonomic:
import config from '../../config.json' with { type: 'json' };
const productionGuildId = config.productionGuildId;
const minimumCooldownTimeMs = config.minimumCooldownTimeMs;
personally, i like having a config.js file that loads the values from the config and handles required, optional, or default values for specific config entries... then you can export the config from your config.js
If you dont mind me asking whats the value of wrapping the config.json in a config.js if the JS file could have done it all on its own anyway
i mean i also dont use .json, i use environment variables (which also need their types changed sometimes)
Is it necessary to fix every little problem that TS tells you about?
ts await channel.send({ components: [container], flags: MessageFlags.IsComponentsV2, })
Problem is:
'channel' is possibly 'null'.
this makes sense, thanks. i might also change to using environment variables
it's not necessary, but if you don't want to solve type problems, why use ts at all?
i mean, i would do at least basic null checking, yes, wouldnt want to attempt to send to a channel that doesnt exist in the api, even if you may think it exists with 100% certainty
okay
hey guys.
my app runs fine locally, how ever when deployed to my server via docker compose, it somehow fails to find my commands:
Ready! Logged in as Grok#5724
No command matching banish was found.
I dont really know where to start with de bugging this
```Dockerfile
version: "3.9"
services:
grokbot:
image: grokbot:latest
container_name: grokbot
restart: unless-stopped
# Environment variables
env_file:
- .env
# Optional: keep logs sane
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"
```Dockerfile
# ---- Build stage ----
FROM node:20-alpine AS builder
WORKDIR /app
# Copy package files first (better Docker caching)
COPY package*.json ./
# Install deps (including dev deps for TypeScript build)
RUN npm ci
# Copy source code
COPY . .
# Compile TypeScript -> dist/
RUN npm run build
# (expects "build": "tsc" in package.json)
# ---- Runtime stage ----
FROM node:20-alpine
WORKDIR /app
# Copy only what we need from builder
COPY --from=builder /app/package*.json ./
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/dist ./dist
# Discord bots don't need ports exposed
# Start the bot
CMD ["node", "dist/index.js"]
```
alright so I worked it out, if anyone has any similar issues in future here was my fix:
since I was writing in TS and docker cant natrually read that, I had to compile to JS.
then since my deploy commands and main script were searching for command files that ended in .ts, it didnt find any cause they had been turned into js.
Aren’t you supposed to use .js or no extension for imports?
sorry I dont understand the question
You shouldn’t be importing nor looking for ts files like import("file.ts") bc ur supposed to transpile to js
yea correct that was basically what my issue was
Just strange that it works locally
It might’ve worked if you used bun or ts-node or similar locally
Idk why else it would only work locally
cause I was running the TS script
i wasnt running the compiled code, so everything was still in TS and thus it could scan and find the command files
With latest node versions you can also run the .ts directly, so in the future transpiling won't be needed at all
oh dope
[Unhandled Rejection] TypeError: Cannot read properties of undefined (reading 'handle') at module.exports [as INTERACTION_CREATE] (C:\Users\zeinf\Documents\Projects\tryhard\main\tryhard-main\node_modules\discord.js\src\client\websocket\handlers\INTERACTION_CREATE.js:4:36) at WebSocketManager.handlePacket (C:\Users\zeinf\Documents\Projects\tryhard\main\tryhard-main\node_modules\discord.js\src\client\websocket\WebSocketManager.js:352:31) at WebSocketManager.<anonymous> (C:\Users\zeinf\Documents\Projects\tryhard\main\tryhard-main\node_modules\discord.js\src\client\websocket\WebSocketManager.js:236:12) at WebSocketManager.emit (C:\Users\zeinf\Documents\Projects\tryhard\main\tryhard-main\node_modules\@vladfrangu\async_event_emitter\dist\index.cjs:2504:31) at WebSocketShard.<anonymous> (C:\Users\zeinf\Documents\Projects\tryhard\main\tryhard-main\node_modules\@discordjs\ws\dist\index.js:1190:51) at WebSocketShard.emit (C:\Users\zeinf\Documents\Projects\tryhard\main\tryhard-main\node_modules\@vladfrangu\async_event_emitter\dist\index.cjs:2504:31) at WebSocketShard.onMessage (C:\Users\zeinf\Documents\Projects\tryhard\main\tryhard-main\node_modules\@discordjs\ws\dist\index.js:1007:14) at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
I get this error when running any slash commands and it doesn't show where the error is
Maybe it can't find handle function (just guessing)
lads, when I do this:
currentChannel.permissionsFor(guild.members.me!).has(PermissionFlagsBits.CreatePrivateThreads)
Does this check for guild-wide permissions as well?
alr but I don't need "guessing" so please read #how-to-give-help
rule no 2
inside ()
wdym rule no 2?
- Please keep chat and questions in English, I did ask in english...
no, #how-to-give-help rule no 2
"You don't need to respond to everything. Don't make answers up if you are not sure (or at least specify that you are guessing)"
(or at least specify that you are guessing)
yh I don't need guessing
Is this the full error? What's the code in your interactionCreate event?
it is the full error, I already fixed it thanks
share interactionCreate event code
This is a volunteer service. You need to be patient, as people are trying their best
true, but I don't need guessing. Would've been better if they didn't even anwser
Well, ok
I know plenty of stuff and have given lots of answers, but even the best of us guess at times. I didn't even have an idea on your error except that it seemed to somehow be an internal error unless you had a handle function somewhere
it was me adding my own actions inside the client so it overrides the main client.actions
I had to go inside the actual djs files to find that one out
```js
'use strict';
module.exports = (client, packet) => {
client.actions.InteractionCreate.handle(packet.d);
};```
Yeah don't overwrite lib internals
this is why it's recommended to extend the client or use functions and pass the client instead
It wasn't intended to, in my index I had ```js
client.actions = actions(my own actions files)
Yeah, that's one of the dangers of adding stuff to the library structures and why the recommendation was changed some years ago
We highly recommend you extend the Client structure properly instead of just attaching custom properties like .commands to the regular discord.js Client instance.
- Using typescript, you might want to consider casting or augmenting the module type
I just changed it to all caps
Is it possible to get a discord user via username?
Only if they're cached. Fetching is id only
If they're cached then you iterate through the cache and search for the username like that I suppose?
Isn't there some guild members search by query thing?
Yes, but you asked about a user, that's not the same as a member
Oh yeah aware but the latter does exist right?
RoutesDeclarations#guildMembersSearch discord.js@14.25.1
Route for: - GET /guilds/{guild.id}/members/search
Ok hmmm that wasn't what I wanted
Looks correct no?
GuildMemberManager#search() discord.js@14.25.1
Searches for members in the guild based on a query.
That's the API route nvm
That's the library method. The first one is the rest route
That looks about right tysm
Can someone help me figure out what permissions I’m missing here? I’m using client.channels.cache.get(id).permissionsFor(client.user).serialize() (will send the embed when I’m off cooldown)
Since I’m using reply I already check for
return channel.permissionsFor(me)
.has([
PermissionFlagsBits.SendMessages,
PermissionFlagsBits.ViewChannel,
PermissionFlagsBits.ReadMessageHistory,
PermissionFlagsBits.EmbedLinks
])
I can’t see what else I need
what is the behavers that you are getting?
Which is pretty confusing since I feel like I’m checking all possible permissions I need
what does your permissions check return?
Returns true 💀, but I thought it took an array? Sorry it took so long
Well it has all the ones I specified I believe
I dont know
lads, when I do this:
currentChannel.permissionsFor(guild.members.me!).has(PermissionFlagsBits.CreatePrivateThreads)
Does this check for guild-wide permissions as well?
I think is is only the channel
it def can take an array
is it possible to get a parent message from the interaction on a reply?
Message#fetchReference() discord.js@14.25.1
Fetches the Message this crosspost/reply/pin-add references, if available to the client
If the parent message is an ephemeral reply, you’ll have to then get it through interaction webhook
CommandInteraction#fetchReply() discord.js@14.25.1
Fetches a reply to this interaction.
// Fetch the initial reply to this interaction
interaction.fetchReply()
.then(reply => console.log(`Replied with ${reply.content}`))
.catch(console.error);
this one did the a trick, thx
Weird question, if I receive an interaction for a slash command that doesnt have any subcommands or groups (ie: /ban), and I run getSubcommand() on the interaction, what string is returned? I assume its just the command's name?
If you don't specify the sub command as being required, it errors. If you specify it as not being required, it returns null
CommandInteractionOptionResolver#getSubcommand() discord.js@14.25.1
Gets the selected subcommand.
What's the type of the channel? Can you log that?
It’s GuildText, but if you want a log I can give you that too
I was thinking if it was voice channel, then the error would make sense without Connect perm
This is strange, type 0 is guild text right
Yup
{
"type": 0,
"guild": "905194979650052208",
"guildId": "905194979650052208",
"permissionOverwrites": [
"905194979650052208",
"1380936713639166082",
"1390416128983040120",
"1239582062844055592",
"1314089193340665937",
"1424421417394507876",
"646937666251915264"
],
"messages": [
"1467232437670121676",
"1467251805468754004",
"1467251813899047176",
"1467251903430660339"
],
"threads": [],
"nsfw": false,
"flags": 0,
"id": "1338629243814416445",
"name": "",
"rawPosition": 91,
"parentId": "1338603952773791836",
"topic": null,
"lastMessageId": "1467251903430660339",
"defaultThreadRateLimitPerUser": null,
"rateLimitPerUser": 0,
"createdTimestamp": 1739224482254
}
Using
c!e const chan = client.channels.cache.get('1338629243814416445');
const data = JSON.stringify(chan, null, 2);
await message.channel.send({
files: [
{
attachment: Buffer.from(data),
name: 'data.json'
}
]
});
I have this in my cache? 💀
have what?
Oh nvm it’s because I use json stringify
util inspect instead
I did and it’s a text channel, I’m gonna guess you want it?
For reference my djs version is root@grapes:/home/CardCompanion# npm ls discord.js
cardcompanion@1.0.0 /home/CardCompanion
└── discord.js@14.23.2
root@grapes:/home/CardCompanion#
did you restart your bot? curious if getting everything fresh will give same results and same data
We are planning a restart soon so I can try and check the permissions again but I can’t see how that’ll change anything
i'm just curious if it's mismatched state on your end