#djs-help-v14
78874 messages · Page 65 of 79
That should not give you the error you got. Show the full error with stacktrace please
node:events:486
throw er; // Unhandled 'error' event
^
ReferenceError: Collection is not defined
at Object.execute (C:\DiscordProjects\LandofGods\events\interactionCreate.js:17:41)
at Client.<anonymous> (C:\DiscordProjects\LandofGods\index.js:37:44)
at Client.emit (node:events:508:28)
at InteractionCreateAction.handle (C:\DiscordProjects\LandofGods\node_modules\discord.js\src\client\actions\InteractionCreate.js:101:12)
at module.exports [as INTERACTION_CREATE] (C:\DiscordProjects\LandofGods\node_modules\discord.js\src\client\websocket\handlers\INTERACTION_CREATE.js:4:36)
at WebSocketManager.handlePacket (C:\DiscordProjects\LandofGods\node_modules\discord.js\src\client\websocket\WebSocketManager.js:352:31)
at WebSocketManager.<anonymous> (C:\DiscordProjects\LandofGods\node_modules\discord.js\src\client\websocket\WebSocketManager.js:236:12)
at WebSocketManager.emit (C:\DiscordProjects\LandofGods\node_modules\@vladfrangu\async_event_emitter\dist\index.cjs:2504:31)
at WebSocketShard.<anonymous> (C:\DiscordProjects\LandofGods\node_modules\@discordjs\ws\dist\index.js:1190:51)
at WebSocketShard.emit (C:\DiscordProjects\LandofGods\node_modules\@vladfrangu\async_event_emitter\dist\index.cjs:2504:31)
Emitted 'error' event on Client instance at:
at emitUnhandledRejectionOrErr (node:events:391:10)
at process.processTicksAndRejections (node:internal/process/task_queues:91:21)
Node.js v24.12.0```
that is entirely different from what you said
yeah I removed the code, just re-added it, got this error earlier too, then changed some things and got the other error
can you please show your code? you clearly don't have what the guide has and guessing around this makes little sense
You don't import Collection so yes, it indeed won't be defined
well the guide doesn't mention anything like that - unless I missed it?
The guide is a guide. You should know the language and how to import stuff yourself
It's not a "turn off your brain and do copy&paste"
I haven't worked with JS in years, it's all very rusty
also I assumed discord.js would import it somewhere
sure, it does. But if you use a class in your code you need to import that class in your code
const { Client, Collection, GatewayIntentBits } = require('discord.js');
is this not importing Collection?
It is, in your index.js file. But you also use it in your command file, so need to import it there too
ah okaj
so simple 🙂
I thought if it was imported in the main file it would also import in other files - like I said, my JS is very rusty
Thx for the help! Really appreciate it! (day 2 of learning how discord bots work)
jst read guide 💀
how to check whether a voice channel exists?
From what? An ID? A name?
VoiceBasedChannel, just prevent user delete it
so I can check using channel id?
Prevent a user from deleting it or checking it?
ah I mean, check it to know does the channel is deleted
I'm creating a "dynamic voice" feature
when member joins a specific voice channel, the bot creates a new voice channel and move the member to the channel.
However, I got Unknown Channel error when running await newState.setChannel(channel);
so I think data.channel(VoiceBasedChannel) is deleted
show the code around that setChannel and show how channel is defined
I assume you are creating the channel beforehand? did you wait for that request to complete?
const data = client.dvoice.find(d => d.owner === member.id);
if (data) {
channel = data.channel || newChannel;
} else {
channel = await guild.channels.create({
name: format.replace("{user}", member.user.username),
type: ChannelType.GuildVoice,
parent: newChannel.parent,
permissionOverwrites: [
{
id: member.id,
allow: [PermissionFlagsBits.Connect, PermissionFlagsBits.Speak, PermissionFlagsBits.ViewChannel, PermissionFlagsBits.ManageChannels],
},
{
id: client.user.id,
allow: [PermissionFlagsBits.Connect, PermissionFlagsBits.Speak, PermissionFlagsBits.ViewChannel, PermissionFlagsBits.ManageChannels],
},
],
});
};
await newState.setChannel(channel);
if (!data) client.dvoice.set(channel.id, {
owner: member.id,
channel: channel
});
the original code should be this
I'm also trying to fix
So which case should it be in now?
use an existing channel or a new one
if you do channel.fetch() it should throw an error if the channel was deleted
only existing channel may not a voice channel, but weird
I have a weird bug with this code
if (!member.voice.channelId) {
const noVc = new EmbedBuilder().setColor(client.options.embedColor).setDescription(`Trebuie să fi într-un canal de voce pentru a utiliza această comandă.`);
return await interaction.reply({ embeds: [noVc], ephemeral: true });
}
This is a check for a command that requires members to be in a vc to use, but sometimes the check fails even if the user is in a vc
Do you have GuildVoiceStates Intent and don't limit the voice state cache?
And do you have a bot user in the guild the command is ran in?
I don't have voice states intent, and idk what's the voice state cache
and yes the bot user is in the guild
how come sometimes the check passes even without the intent tho?
Probably because your bot was the one moving them, so it has the voice state cached
when my bot is playing audio resources, the sound may vary in speed or be choppy.
wdym moving them
the users? nope
How can I detect when a message is a poll?
The message type is 0 (default), poll property is null, and flags bitfield is 0
hello! any chance someone around familiar with recording bots? I got this #1453448220708700160 issue stuck on it with no clear path 😅
Do you have the message content intent enabled?
No, just saw I need it to get the poll property 😅
That's a shame we can't know if a message is a poll (even without seeing the poll content)
Most restrictions like that revolve around user privacy. Might help you to understand some of their decisions
Yeah I guess so, thanks for your help 😄
i assume message length is also behind the intent or is it accessible ?
The intent is needed to see any details about the content of the message
Without the intent, I believe message.content is an empty string ""
I just made a discord music bot that downloads the music locally then streams to my server
i couldnt get native ffmpeg url streaming to play through discord for the life of me
using opus yes
When you clean all your old code bases 💀
Hey. This channel is for asking for help with the Discord.js package... Let's keep it clear of general conversation and use #1081585952654360687 or #archive-offtopic to talk about your projects
Ahh wasnt on my channel list blame that on whoever made the server
the channel name should be self explanatory
it isn't about djs, it isn't about getting help, and isn't about the v14 version
Umm its very much about Discord JS my first message was about seting up a music bot, Second of all Your general rooms are not available to users upon joining
the fact you choose to argue instead of looking into the problem really shows what type of staff i just stumbled upon
Never mind youre not even staff remind me why you replied
because checking channel names is useful to figure out what they're for
Once again general is not open upon joing the server. Your point is invalid
I'm not trying to argue, just making the point that you can check beforehand what a channel is for
I read very clearly and searched for the General room
i figured support would be best because people would see i know what im doing and then maybe ask me for help
I really am not going to take your point especially when youre most likely 12 arguin an invalid point
its in id:browse
Yea no one uses those dawg
infact i cant even see that naturally i had to click your tag
id:customize in your channel list at the top and then “All Channels”
its the same, but anyway
stop carrying the argument youre loading the help channel with this
that you don’t know how this messaging app works isn’t the problem of “whoever made this server”, you can only blame yourself
Except user experience is apart of development you did a whole lot there buddy
youre making a discord music bot and you dont even know how discord works. stop being disrespectful to others
Guys... Stop... Drop it
I have yet to be disrespectful I started making conversation pointed out the general room is not avalible to users and you guys keep responding.... It speaks for itself yall
One hell of a community you got here just lost a 5 year dev
@fleet ridge @crimson gale good job at being mods 😄
congratz
How will we ever recover from the loss of "random dev #1476017"
wat
dudes gonna be real upset when he realises this is the best support for djs
How can i do the Button up right
A section component
SectionBuilder#setButtonAccessory() discord.js@14.25.1
Sets the accessory of this section to a button.
Section
Sections represent text (one to three Text Display components) with an accessory. The accessory can either be an image (thumbnail) or button. If you do not want to send an accessory, use a Text Display component instead. You can use the SectionBuilder class to easily create a Section component:...
why is it sometimes it feels like an event gets fired twice (dupe)?
i got twice the same channeldelete event
how do you know you got it twice?
because i have a channel delete log and it got logged twice
couldn't it be possible that the message was sent twice by mistake?
or is there any other non message-related logic that also got executed twice
that wouldnt make sense. its just a very simple
client.on(Events.ChannelDelete, async (channel) => { });
it can happen, that's why there's the nonce option
oh okay
what does the nonce thing do and how should i implement it
I'm not sure what's the specifics of why it happens but I've seen it so it's something worth considering
discord lets you set a nonce, so if you send two message send requests with the same nonce, only one of them goes through
in djs you can provide the enforceNonce option and let it handle it for you
ClientOptions#enforceNonce discord.js@14.25.1
The default value for enforceNonce
Default value: false
thanks. and then i shouldnt worry about accidental dupe events?
it's unrelated to events themselves, it just makes it so the same message request doesn't get "sent" twice
oh okay i see thanks will try out
if you have any other logic not related to messages that did get executed twice as well then it's worth considering a duplicate listener or something
but since it's just a duplicated message, it could be the nonce thing
When I get a RateLimitError, what do limit, sublimitTimeout, and hash mean? Also, what does it mean when the limit is set to infinity?
Also, if you want to create a channel right now, it takes about 60 seconds for it to happen. Is Discord.js doing something there that causes a timeout?
After i deferUpdate a modal submit interaction, how can I send the user an error message if need be?
const modalData = await interaction.awaitModalSubmit({ time: 3 * 60 * 1000, filter: i => i.customId === 'lfg-modal' }).catch(err => `${err}`);
if (typeof modalData === 'string') return handleErr(new Error('Modal submit timed out or errored: ' + modalData));
await modalData.deferUpdate();
const modalCountInput = modalData.fields.getTextInputValue('lfg-modal-count');
const count = parseInt(modalCountInput);
const invalidCount = new EmbedBuilder().setColor(client.options.embedColor).setDescription(`${modalCountInput} nu este un număr! Te rugăm să încerci din nou.`);
if (isNaN(count) || count < 1) return await modalData.reply({ embeds: [invalidCount], ephemeral: true });
just as youd do with any other message
with update or how
after deferupdate you cant update again its editReply then or use a followUp
that sounds like you're ratelimited and the request is being queued
Shouldn't that disable the queued option?
What can I do about it, since it's really stupid that everything is now happening 60 seconds late?
you can log it to make sure it's the correct endpoint, looks right though but still worth confirming
if you're ratelimited there's not much you can do
But why are the channels created after 60 seconds if the request to put them in the queue is actually disabled?
like I said, log it to make sure you're checking the correct endpoint and method
that is the right one
though even then, if you're ratelimited then making it not throw doesn't mean the channel will be created
can you show what it logged?
Does GuildMember#displayAvatarURL return anything for users with the default discord icon?
await guild.channels.create({}).catch(async (e) => {
if (error.name === "RateLimitError" || error instanceof RateLimitError) {
console.log(e)
}
})
yes displayAvatarURL always fallback
In the line console.log(e), that's where the log goes.
so you say it throws the ratelimit error, and it still creates the channel regardless after 60s?
yeah
This whole line makes no sense. e is not error, that uses some completely unrelated variable for the condition
Also that log is not what a console.log of a RateLimitError would look like
He just wanted to know where the error came from. It comes from this line. I also know that the error is a different one.
const message = Rate limit error on creating channel\n\n- GuildID: ${guild.id}\n- HostID: ${galaxyClient.config.bot.hostID}\n- ClusterID: ${galaxyClient.clusterID}\n- RetryAfter: ${error.retryAfter / 1000}s\n- Limit: ${error.limit}\n-Reset in: ${error.timeToReset / 1000}s
So the log does not actually come from the console.log does it? Please show the actual code causing that log
The log from the screenshot is exactly the message.
so
await guild.channels.create({}).catch(async (error) => {
if (error.name === "RateLimitError" || error instanceof RateLimitError) {
const message = `Rate limit error on creating channel\n\n- GuildID: ${guild.id}\n- HostID: ${galaxyClient.config.bot.hostID}\n- ClusterID: ${galaxyClient.clusterID}\n- RetryAfter: ${error.retryAfter / 1000}s\n- Limit: ${error.limit}\n-Reset in: ${error.timeToReset / 1000}s`
logError(message)
}
})
Sounds to me like you might have another instance running somewhere that doesn't have that rejectOnRatelimit setting yet
So one is aborted while the other queues the request
No, we don't have any other instances running.
How did you determine that to be the case?
We only have new Client({}) once in the code, and that's where we added rejectOnRatelimit.
Other instance could mean several things here:
- a full second process running same/similar code with full cluster and sharding
- a second cluster running the same shard
- a single shard still running which lost its parent process
- a second event listener registered to the same event
- another function being called upon the event that also does channels.create(...)
Especially the first one would explain your issue (old process running an older version of your code)
Also do you use an extended Client class or is it barebones discord.js?
I use extends Client and specify the ClientOptions in the constructor.
Is that the only thing that extended class does?
How can I check and exclude all shard/cluster cases?
Stop your instance you are running, do the thing that should create a channel, check if channel gets created => another process running somewhere
If you do have a command or event that doesn't lead to something affected by strict ratelimits do that and check it you get two responses
listen to the response event of REST and find out if and when you receive the response for the channel creation
It's not running twice. We've also completely restarted, and the problem still persists.
And did you do what I proposed to do in the message you replied to?
Yes, no message was received in the response.
Considering that event should emit for every response to any REST call I sure would hope there were many received
can you have a value be pre-set in a string select menu?
Yes, put default in the option
StringSelectMenuOptionBuilder#setDefault() builders@1.13.0
Sets whether this option is selected by default.
If you use builders 👆
For raw json it's simply default: true

how do i set a custom activity? I want to set something like "Touching grass" with a grass emote
#1142187561729658942 message you can’t do emojis though
Yes, but not in my test.
The route with the sharp increase is channel create. We didn't change anything today, meaning it increased randomly and resolved itself. During this peak period, channel creations typically took over 60 seconds. Perhaps this information is helpful.
how did you listen for it
They come from the proxy.
didn't you just say that they kinda like don't come
The data comes from the proxy and is the count, which shows how many connections are currently open through it.
That was just to check if it was running twice, which it isn't. So everything is correct.
did you read what Qjuh said?
Yeah
And everything fits perfectly there.
is there a limit to the ammount of times you can run .update on a deffered interaction?
you can edit a message as many times as you want, just not .update again after .update in same interaction
is there any way to update twice? or without another interaction or do i have to editReply that instead
editReply()
essentially what i have is a long list of ephemeral embeds that have different triggers to change them and stuff, the first button file gets disconnected from the whole system right away and then its up to my interaction handler
deferX() and update() are both forms of acknowlegement. You can only acknowledge an interaction once
ok so i would update and then edit the reply
Responding to interactions:
#replyimmediately respond with a message#updateimmediately update the original message (buttons, select menus)#showModalimmediately show a modal (cannot be deferred)#deferReply/Updaterespond later (up to 15 minutes)#followUppost an additional message
The initial response has to happen within 3s of receiving the interaction!
Correct
ok thank you, and if theres a new set of buttons on the same ephemeral message (updated with new row) and then the user clicks a new button, that is a whole new interaction so i would need to update it again?
Correct
thank you
Hello! I saw that one of the servers I am in put a dropdown menu inside of a modal and I cant figure the heck out. Any suggiestions?
You'd want to first add a label to the modal, which you can then add a select menu inside of
ModalBuilder#addLabelComponents() builders@1.13.0
Adds label components to this modal.
LabelBuilder#setStringSelectMenuComponent() discord.js@14.25.1
Sets a string select menu component to this label.
pretty sure that qjuh said that it should emit for every response. was your bot entirely dead and unused during your testing?
Will using mp3 files as audio resources and having them converted by ffmpeg cause the audio playback to stutter or become inconsistent?
that’s not really a discord.js question
i'm not sure on the issue here. im sure its device specific.
I have command tht goes thorugh series of phases, in the first 3 phases the user can see the buttons.
but in the finall phase he can't see the set of buttons. He's turned on and off his device, hes resetarted the client, closed and re-opened.
if logs into a browser on his mobile he can see the buttons. but not in the app. Any ideas how to fix for him?
(the buttons load for every one else)
that’s not really a d.js issue either
just making sure, you can defer a showModal interaction just not the response? or other way around
my code picks a random selection of things to reply from a button, one of them is a modal and i want to make sure that i can defer at the start of the buttoninteraction in the case that the modal option gets chosen
how do we import the token from the .env file? I used to use
require('dotenv').config();
but its saying this method doesnt work anymore
you dont need dotenv anymore... it's officially supported by node... --env-file=.env
then, just use process.env.TOKEN or whatever you named it
Other way around
ok so i should check the modal show case first and then defer it i guess
kinda weird why you cant defer those
i wonder why
oh i guess its probably the same as .launchActivity
UX I presume - "please wait for some random amount of time before a window pops up in the middle of your Discord client"
Versus "please wait for some random amount of time before the message is edited with new content"
yea makes sense i guess
better question accually, is there really any more than a few ms waisted on lines that arnt making requests? i asume node is pretty fast so things like getting from maps, random numbers, and what not shouldnt take any time right
oh I see
I did it I think :D
Microsecond range I'd say
ok great, and would anything depend on user ping? im still trying to figure out why im getting unknown interaction, i assume its because it hasnt been defered/took more than 3 seconds, but 99 precent of the time it works and theres very little code before the defer so
it really depends on what you're doing but the stuff that is heavy is probably inferrable
i mean the only 2 things that make request is a message edit (own bot message), and then some interanl db calls which should take miliseconds at best
eg if you were to do big calculations like the 1000000th fibonacci number, technically a sync operation but yeah
lol no nothing like that
well db calls might need a defer if they're over a network or goes through fs, which is generally what a db does
bothh my db and bot are hosted on the same service, and they use internal communication
usually dont take long at all most cases, but might be weird sometimes
what is "internal communication"?
like same network, so all the traffic stays inside their servers
yeah it could be fast enough then ig
you can debug by logging the now - createdTimestamp difference when you receive the interaction and when you're about to reply
to see if it's you taking too long to reply, or you getting the interaction too late
oh good idea
might just end up being a situation where its essentially unavoidable for a few req to not be dropped/not responded to but we will see
with python you can do like
synced = await bot.tree.sync()
print(f"Synced {len(synced)} command(s)")
for s in synced:
print(f":white_check_mark: {s}")
Is there a way to do something similiar in discord.js?
you mean deploy commands with a call?
guide suggestion for @crude mist:
Registering Commands
For fully functional slash commands, you need three important pieces of code:...
💀 jst read guide bro
I don't know much about dpy to see what's going on there, but if you mean to deploy commands then yeah, what notyuna linked
no its getting the array of slash commands and printing them out so I can see which commands actually registered
the array of commands that are currently registered on Discord?
because djs has no registry for unregistered commands, that's just not how it works
it's like trying to get out of youtube, the list of videos that aren't on youtube but are on your machine
heres another example. there is no reason why this button defer should sometimes be giving unknown interaction. its like impossible for me to respond to it faster, and any of the other 2 reasons for this error are obsolete
djs only serves to interact with the discord api
I think they do have an api for the slash commadns then
yeah you can retrieve the commands that are in discord
Client#application discord.js@14.25.1
The application of this bot
ClientApplication#commands discord.js@14.25.1
The application command manager for this application
meh too complicated for my first day i'll deal with that later
thanks tho
my guess is just occasional spikes in network latency
i think it sometimes happens to me too
its like impossible for me to respond to it faster
defer before unarchive?
no but this one is weird it happens like way more frequently than other unknown interactions
like almost impossiaBLE
yea but then you cant defer because the thread is archvied
i guess i could check if it is archived first, but still unarchiving a thread shouldnt take more than 3 seconds
this particular command you mean?
although, now that im thinking about it, it might
our server has been stuck at 1000 active threads (or very close) so maybe thats part of the issue?
you could console.time everything up until the interaction.reply or whatever, see if it ever spikes above 3s
yea ill probably end up doing that just to see
i know very little about threads myself, no clue if that could cause issues
maybe making changes to a thread if theres tons of active ones takes longer
but i'd assume anything that interacts with external apis could technically get a big delay
i prob should defer for more things myself but i haven't noticed it being much of a problem so idk
I think you should be able to since you have perms to reopen it, and moderators can talk in archived threads
yea true but again like this happens pretty rarly and has just started happening again more so
well best u can do is probably console.time it to isolate the problem
but still unarchiving a thread shouldnt take more than 3 seconds
about this, like faceboy mentioned there can be network spikes, so it isn't technically impossible
well ive tried and it just says thread archived so
my bot is a mod but idk
accually ill check again to make sure there wanst a perm change i am unaware about
manage threads and posts should be enough right? thats what it has + all mod perms and stuff so
and if you have multiple async operations, you could add a console.timeLog to each of them to further help isolate the issue
ill do that rn
tho it could be a little annoying since you have to actually check the logs
ehh thats not to bad
i want this error gone so
might be worth either finding a package or making your own that just gives you a function to store timestamps and log only if something is substantially longer than expected
to much work
fair enough
for less frequent things id say its probably worth it, but if this is not too hard to reproduce the issue then sure
ok i just archvied 600 active thread and added that so hopefully that fixes it
where abouts in the docs might i find how to put buttons inside of emebds? found it
question, in the ContainerBuilder() the setAccentColor does not take hex? is there any alterative or easy ways of turning hex to accent?
instead of using the pound sign, just use 0x
#ffffff -> 0xffffff
^ outside of a string
so .setAccentColor(0xffffff)
aaa thanks guys thats really helpful
the 0x at the beginning specifies that its a hex number, so this is a number value, and if you need to convert a string hex code to a number, you can use parseInt with the radix argument (like parseInt("ffffff", 16))
if (!interaction.member.roles.cache.some((role: { name: string; }) => role.name === 'Strategy & Development' || 'Operations Manager' || 'Advisor' || 'Oversight' || 'Robots' || 'Operations Coordinator' || 'Operations Director')){
await interaction.editReply(` **@${interaction.member.username}**, you do not have the required permissions to run this command.`);
return;
}
hi there, does anyone know why this may not be working? i am certain i do not have any of the associated roles. it is not working as in it is still running the command even though i do not have any of those roles
because thats not how you check if a string is equal to one of a set of values, unfortunately
ah i used that syntax from the guide directly
but it did look unusual
you need to check if role.name is equal to them individually
so role.name === ... || role.name === ...
your best option is to have an array of role names, and check in your .some myArray.contains(role.name)
alright, so for example ((role: {name: string;}) => role.name === "X" || role.name === "Y") would work?
yes
ahh this works best thank you! would this look like ((role: {name: string;}) => myArray.contains(role.name)?
the cleanest for more than maybe two role names is to do it this way
yes but i would take faceboys suggestion into consideration, also comparing by role id would likely be better, since they wouldn't change, but in the future, the names may
yes, and btw you shouldnt have to add types to role, the djs types should be enough on their own
question, can you do like setImage() with the ContainerBuilder()? or is that not an option
ahhhh thank you! appreciate it
this too, its best to use role ids, but im assuming you are doing this for just your own server so foolproofing it might not be as important
this is a cross-server solution (two servers for two seperate group of people with the exact same role structure) hence the name
this is for a grand total of 2 guilds
if a role changed i'd be the one changing it
fair
well just be careful then, if you forget to update the bot in the future then thats on you but it shouldnt be hard to fix
alright, got it
ty for the help! :D
.
first of all, to be clear, a container is not an embed, other than the accent color and spoiler, you dont set something about it, instead it contains other components and does not act like an embed with those predefined fields
in this case, you want to add a MediaGallery component, with one media item or whatever its called
looked like an embed to me properly shouldnt have assumed that :)
if you want to add a thumbnail image, you have to add a Section, which (must) contain 1-3 TextDisplayComponents and either a Thumbnail image or a Button that gets rendered to the right of those text displays
gotcha i think i'll mess around with it and then ask more questions
its a very common assumption, which is fair enough since they are visually similar, but you should treat it as its own whole separate thing
noted for now lol thanks though
oh and before you potentially ask, no you cannot create inline fields or author pfp or footer icon
embeds do have some things like that that containers cant do
(also very common questions lol)
bummer i'd see what i can do 🙏
i do still love components v2 tho
embeds are more about displaying info while components v2 are about interactivity
hi, it's me again, sorry!
if (!interaction.member.roles.cache.some((role: Role) => authLevels.disciplineAndStandards.includes(role.name))) {
await interaction.editReply(` **@${interaction.member.username}**, you do not have the required permissions to run this command.`);
return;
}
trying out this method now.
this is my authLevels definition:
let authLevels: {
strategyAndDevelopment: string[];
staffTeam: string[];
leadershipTeam: string[];
seniorStaffTeam: string[];
disciplineAndStandards: string[];
} = {
strategyAndDevelopment: ['Strategy & Development', 'Operations Manager', 'Advisor', 'Oversight', 'Robots', 'Operations Coordinator', 'Operations Director'],
disciplineAndStandards: ['Discipline & Standards', 'Operations Manager', 'Advisor', 'Oversight', 'Robots', 'Operations Coordinator', 'Operations Director'],
staffTeam: ['Supervisor', 'Team Leader', 'Operations Manager', 'Advisor', 'Oversight', 'Robots', 'Operations Coordinator', 'Operations Director'],
leadershipTeam: ['Operations Manager', 'Advisor', 'Oversight', 'Robots', 'Operations Coordinator', 'Operations Director'],
seniorStaffTeam: ['Team Leader', 'Operations Manager', 'Advisor', 'Oversight', 'Robots', 'Operations Coordinator', 'Operations Director']
};
you can see the roles i ahve when i am running this in the image below. these roles i have do grant me admin permissions but nothing else
what exactly is the issue? that it doesnt give permission to run the command?
ah, sorry i didn't clarify. the issue is that i can still run the commands even though i don't have the role
hmm
hmmm im not sure what there would be causing the problem
all good haha
you are sure that that if statement is run before anything else, and that it is not within a sub function that only that returns while other parts of the command can still run?
hmm, good thing to consider.
my structure is
- defer the reply
- if statement
- the code that the command intends to run
is there a chance that the command is running concurrently with the if statement? if so, how do I stop that?
shouldnt be possible
just use roleid
my thing about the structure is that if you have something like
function checkPerms(interaction) {
// your if statement
}
function executeCommand(interaction) {
checkPerms(interaction);
// the rest of the command here
}
``` then it wouldnt work
its better than using role name
ah no that's not how it is, it's all in execute()
you probably dont have anything like that but sanity check
using role id vs name isnt really relevant to this particular issue i dont think
im thinking about array, if the func return string, not array
unless you put the if statement in an async function, which presumably isnt the case, no. outside of async, code runs consistently one line after the other
try console.log ing interaction.member.roles.cache, and maybe also turn the callback for .some(...) into a code block and add some console.log stuff in there
there is rarely a problem that cant be diagnosed with enough console.logs
my execute() is asyc yeah
everything inside will still run sync tho
got it, thanks
ill eat dinner and let you sleep if ur in a timezone where ur sleeping rn
ty for the help
it is 1:20am i should probably sleep lmao
oh boy sorry lmaoo
but the only time something should run non-blocking like that is when you call an async function, that function call will be non-blocking (unless you await it)
everything inside an async function, except for other non-awaited function calls, will still run synchronously inside the function, even if the function as a whole is async
ty
im awake anyways, its winter break i dont need to have a decent sleep schedule
lool fair
i cant really talk im known to be up atthese times too lmao
Sounds like they need to update their discord app
Anyone wanna help me figure this out? I understand the code, but not where to put everything and how to put it all together to make it work - this is straight from the collectors page: https://discordjs.guide/legacy/popular-topics/collectors
const collector = message.createMessageComponentCollector({ componentType: ComponentType.Button, time: 15_000 });
collector.on('collect', (i) => {
if (i.user.id === interaction.user.id) {
i.reply(`${i.user.id} clicked on the ${i.customId} button.`);
} else {
i.reply({ content: `These buttons aren't for you!`, flags: MessageFlags.Ephemeral });
}
});
collector.on('end', (collected) => {
console.log(`Collected ${collected.size} interactions.`);
});```
First question would be how and where to define the button - I also want the button to have an id, because multiple of these will exist at the same time. Here's my current slash command:
```const { ActionRowBuilder, ButtonBuilder, ButtonStyle, SlashCommandBuilder } = require('discord.js');
module.exports = {
cooldown: 10,
data: new SlashCommandBuilder().setName('hunt').setDescription('Starts a party to hunt nearby monsters.'),
async execute(interaction) {
const join = new ButtonBuilder().setCustomId('join').setLabel('Join Hunt').setStyle(ButtonStyle.Success);
const row = new ActionRowBuilder().addComponents(join);
await interaction.reply({
content: `Do you want to join the hunt?`,
components: [row],
});
},
};```
you'd put it right there below the reply
First question would be how and where to define the button
your button is already defined, it's thejoinvariable
I also want the button to have an id, because multiple of these will exist at the same time.
it also already has an id, which is the customId you set with setCustomId:'join'
yeah the issue with that id is that multiple ppl might run the /hunt command and there would be several buttons with the same id
maybe I can add the user id to the button id?
yeah that's one option if it doesn't matter whether the same user calls the command many times and uses the button from different executions
yup, a user would only be allowed to call it once (on a cd) and the btn would disappear before they can call it again
could also just work with a counter or something?
why does my bot receive MESSAGE_UPDATE events for messages that have not even been updated?
yeah you can keep track of current executions
or you could append the interaction id instead which is unique per interaction
that way it doesn't matter whether they executed it multiple times, each one is independent
for instance?
in which file should the collector.on('collect') ... functions go?
do they go in the file where I define my command?
not sure I understand what the interactionCreate file is for then
^^
you're free to use collectors or a "manual" interactionCreate listener (collectors are just interactionCreate listeners that dispose themselves)
it depends on your style and preferences, sometimes it might be easier to use one or the other
say if you had some state in your command it might be harder to "share" it if it's in an independent listener
// on your command
execute(interaction) {
const state = somethingThatUsesTheInteraction(interaction);
// send the 'myButton' button
}
// on your event
execute(client, interaction) {
if (interaction.customId === 'myButton') {
// how do you get 'state' now?
}
}
it's not impossible, but it's not as straightforward
cant really provide an example rn, but i log the urls to old message and new message in my messageUpdate and once it gets triggered, i open either of those urls (since they're identical) and it leads me to an unedited message
is it a regular message?
it's a webhook embed
sent by your bot, or?
no, that webhook is executed by a game and it doesnt belong to my bot
How do you determine that the message is unedited? Just because there's no (edited) below it doesn't mean anything. Could be flags that changed (suppress embeds for example) or something else that doesn't show the (edited) tag
Also if discord adds embeds to the message after it was sent (if the message contains a link for example)
module.exports = {
cooldown: 10,
data: new SlashCommandBuilder().setName('hunt').setDescription('Starts a party to hunt nearby monsters.'),
async execute(interaction) {
const joinHuntBtn = new ButtonBuilder()
.setCustomId('join-hunt')
.setLabel('Join Hunt')
.setStyle(ButtonStyle.Success);
const leaveHuntBtn = new ButtonBuilder()
.setCustomId('leave-hunt')
.setLabel('Leave Hunt')
.setStyle(ButtonStyle.Danger)
const buttonRow = new ActionRowBuilder().addComponents(joinHuntBtn, leaveHuntBtn);
const reply = await interaction.reply({
content: `A new hunt has been started!`,
components: [buttonRow],
});
// Just for testing - remove!
const filter = (i) => i.user.id === interaction.user.id;
const collector = reply.createMessageComponentCollector({
componentType: ComponentType.Button,
time: 15_000,
filter,
});
collector.on('collect', (interaction) => {
if (interaction.customId === 'join-hunt') {
interaction.reply(`${interaction.user.username} has joined the hunt!`);
}
else if (interaction.customId === 'leave-hunt') {
interaction.reply(`${interaction.user.username} has left the hunt!`);
}
});
},
};```
This is giving an error when I click the buttons: rawError: { message: 'Unknown interaction', code: 10062 },
https://codeshare.io/2prlqV
it's showing me the interaction in the interactionCreate file 😒
ok so removing the code in the other file fixed it - can someone explain this?
I had:
return interaction.reply({
content: `Button clicked!`
});```
in the interactionCreate file from the tutorial
it returns the interaction, so the interaction is gone? 🤔
here, try
collector.on('collect', async (interaction) => {
if (interaction.customId === 'join-hunt') {
interaction.update(`${interaction.user.username} has joined the hunt!`);
}
else if (interaction.customId === 'leave-hunt') {
interaction.update(`${interaction.user.username} has left the hunt!`);
}
tldr: you can only respond to an interaction once, so if you attempt to respond to the same interaction twice at the same time, one succeeds and the other receives "Unknown interaction"
I'm not totally sure what you mean by this, so I'm not totally sure how to answer this
if you're asking whether returning an object from an event listener callback in some way interacts with the api, that would never be the case
thx 🙂
CombinedError (2)
Received one or more errors
1 ExpectedValidationError > s.instance(V)
| Expected
|
| Expected:
| | [Function: ButtonBuilder]
|
| Received:
| | undefined
2 ExpectedValidationError > s.instance(V)
| Expected
|
| Expected:
| | [Function: ThumbnailBuilder]
|
| Received:
| | undefined
at _UnionValidator.handle (/home/container/node_modules/@sapphire/shapeshift/dist/cjs/index.cjs:1965:23)
at _UnionValidator.parse (/home/container/node_modules/@sapphire/shapeshift/dist/cjs/index.cjs:972:90)
at SectionBuilder.toJSON (/home/container/node_modules/@discordjs/builders/dist/index.js:2536:37)
at /home/container/node_modules/@discordjs/builders/dist/index.js:2237:64
at Array.map (<anonymous>)
at ContainerBuilder.toJSON (/home/container/node_modules/@discordjs/builders/dist/index.js:2237:35)
at /home/container/node_modules/discord.js/src/structures/MessagePayload.js:151:46
at Array.map (<anonymous>)
at MessagePayload.resolveBody (/home/container/node_modules/discord.js/src/structures/MessagePayload.js:150:49)
at TextChannel.send (/home/container/node_modules/discord.js/src/structures/interfaces/TextBasedChannel.js:191:61)
can anyone guide to fix
you have a section without an accessory
thanks
editReply cant delede with timeout?
You want to delete a message after a certain amount of time?
why return interaction.editReply({ embeds: [embed], flags: MessageFlags.Ephemeral });
won't reply user ephemerally?
also same as return await interaction.editReply({...})
if the og msg ephemeral
Yeah edit doesn't accept ephem, the original message or defer sets the state
use deleteReply()
if I had a channel with say months old messages, could I fetch the last 100 even if theyre >2 weeks old?
You can fetch any messages
const modal = new ModalBuilder()
.setCustomId('autoresponder_create_modal')
.setTitle('Tạo Autoresponder Mới');
const mode = new LabelBuilder()
.setLabel('Tạo một autoresponder mới')
.setTextInputComponent(
new TextInputBuilder()
.setCustomId('autoresponder_trigger_input')
.setStyle(TextInputStyle.Short)
.setPlaceholder('Nhập từ khóa để kích hoạt autoresponder')
)
.setStringSelectMenuComponent(
new StringSelectMenuBuilder()
.setCustomId('autoresponder_mode_select')
.setPlaceholder('Chọn chế độ để tạo autoresponder')
.addOptions(
new StringSelectMenuOptionBuilder()
.setLabel('Chứa')
.setValue('contain'),
new StringSelectMenuOptionBuilder()
.setLabel('Khớp')
.setValue('match'),
)
)```
Why isn't my modal working with those two at the same time?
It only shows setTextInputComponent
each component goes into a separate labelbuilder
you have to place your string select in another labelbuilder
Both of those are in LabelBuilder.
yes but you can only have one in a labelbuilder
So how can I display both string and text input in a modal?
documentation suggestion for @flint pier:
ModalBuilder#addLabelComponents() builders@1.13.0
Adds label components to this 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.
oh thankyou, i did it
Does modal have any limitations?
what limitations are you thinking of? it supports up to 5 labels
ohh okay
Timeout duration was set to 1.
(Use `node --trace-warnings ...` to show where the warning was created)```What kind of error is this?
not djs related, but looks like thats not a valid integer
I see an increase in this error, not sure if it's djs related, but lately there have been some people posting an error like this
That's because they happened to update node. This could have been happening for ages, but previous node versions simply did this silently
If you're getting it, you can use the node option it mentions to pinpoint where it's coming from
Oh probably, because my local development uses node v20 and production build uses v24 so I never saw this error on local development
can we use dokploy for djs
Is there something that makes you think it won't be possible? Djs doesn't do anything special, it's just NodeJS
vercel wont work for discord bots example
Then that's a Vercel issue, not a djs issue. You'll have to ask/look into the specific provider.
okay so dokploy works with discord.js ?
I don't know, you'll have to ask dokploy
Can dokploy run a vm or a container?
please dont give support if you dont know
If yes, then it can run a discord bot written with djs
I'm giving you support by saying that this question isn't for djs, it's for dokploy
yeah as much as i can see, im new to it also
it should be possible then. djs runs as a node process. If dokploy can run node, it can run djs
Can it run it forever
Not just for 5 minutes after an http request to wake it up
wdym is that a question
Yes
Dokploy just looks like a server management platform, you still need to provide a server outside of it on your own, so if the server you provide can run Nodejs I don't see that there would be any issues.
Vercel is a serverless hosting provider. Meaning it doesn't keep an instance of your code running 24/7, rather dynamically starts and stops your application based on the location of users and current load on the system
Websocket applications CANNOT function in a serverless provider. Which is why DJS bots don't work on Vercel
Websocket can work in serverless just fine
What doesn't work is long lived connections
Each start is going to be a separate log in, which is a highway to get your token reset continuously
What's it, 200 allowed logins a day?
1000
Oh I'm thinking of commands
That sounds better
Would depend on the traffic no?
No
Oh the discord limit. I thought smth else
Can I show users with a specific role in the user select menu?
No, there's no functionality for that
Is it currently possible in forum channels to only allow the creator of the post to talk in their own post?
no
Thank you!
Theres a permission for fetching audit logs right? Do you need that permission to recieve the gateway event?
do the dapi docs for the event say anything about that?
This probably isnt djs related enough, so ignore me otherwise. But what type would u save an id (user, channel, guild) as in a database? A bigint?
String is the easiest as you don't need to convert it back and forth...but a Snowflake is a uint64 transmitter as a string
Yeah so in node I obv keep it as a string for precision, but in a database I would save a lot of space, and it wont cause precision issues right?
depends however your database adapter decides to handle such numbers
Yeah okay, thanks, it should work then
You would only realistically save "a lot" of space if you store millions of records, otherwise it's going to be a few bytes in difference
yeah it's not a lot, I think its like 20 mil rows, but I want to optimize what I can ig
^ this is a wrong answer bc not every row includes an id ofc, but still.
It's just a complexity trade-off, since you'll need to convert back and forth, but if you feel like it's worth it then go for it
is that a yes or a no
That’s a, I found it thanks
if my math doesn't suck, an average 19-character ascii/utf-8 encoded snowflake (discord/twitter-style id) is 152 bits, while a uint64 is obv 64 bits, so with this awful math and 20mil snowflakes you'd save maybe 1.8gb
i know nothing about how exactly a database stores these things so if a pointer is used to store a string then that would add extra bits, but that might be somewhat canceled out by not every row having an id as you said
nope my math is wrong
divide that by 8, so like 220MB
Oh thanks! Seems a lot more then I thought actually
(my pc crahsed while writing this message lmao)
^ So I saw ur edit in time xD
i'd assume that 220mb wouldn't be much compared to the overall size of a 20mil row database, but a string is a pretty wasteful (although convenient) way to store numbers
if i were you id stick with strings for convenience (maybe im lazy), but up to you ofc
Im gonna change it, its not a huge migration. The only thing Ill need to is check if the rows are compatible (well values), but thanks 🙂
when handling if (interaction.commandName === 'ping') {} do you put it before or after embed builders/components
client.on(Events.InteractionCreate, async interaction => {
if (interaction.commandName === 'ping') {
const rules_embed = new EmbedBuilder()
.setAuthor({name: interaction.user.displayName, iconURL: interaction.user.displayAvatarURL()})
.setDescription('Test')
.setColor("Blue");
const button = new ButtonBuilder()
.setCustomId("Hello")
.setLabel("THis is a button")
.setStyle(ButtonStyle.Primary);
const row = new ActionRowBuilder().addComponents(button);
await interaction.deferReply();
interaction.channel.send({embeds: [rules_embed], components:[row]});
}
});
ignore the weird names im just testing everythinh
Well, I wouldn't spend the - albeit very minute - resources instantiating a builder and populating it if you aren't yet sure if it'll be used
so before it then
where you define the builders/message data doesnt really matter so long as its in scope, im not really sure what this question is asking
it was really just a format question how its done, i've gotten yelled at for doing it in weird ways and committing to actions when it was supposed to be done some other way
with anything you would just normally define your stuff in the scope where youre gonna use it 🤷 dont see what you could do wrong
is there any reason why it would respond to a button with this? "You need Administrator permission to use this." It doesn't say that anywhere in my code and I have 0 clue why it's happening. I get it from a "DiscordAPIError[40060]: Interaction has already been acknowledged." error.
Sounds like you have some other process that's also trying to respond to button interactions with that message
That message is indeed not part of the Discord API nor d.js, so it must be some user-written code
i found the culprit
sorry about that
whats the difference?
Whether the guild the interaction came from is cached or raw
how would the guild not be cached?
Bot was added for commands only
is that possible without manually customizing the caches
do you mean added to a guild with just the application.commands scope without bot, or user install?
Both actually
hmmmm i feel like i can assume both are invalid installations
Well, I don’t think the former is a thing anymore
Pretty sure application.commands now implies bot scope
i want to add a type guard in my interactionCreate.ts and then type all my command files so i dont have to deal with things like interaction.member not having all the fields
i think it's the other way around
Oh
yea i recall that previously application.commands was part of bot, and they added application.commands retroactively to anything that had bot
bot is required for an application to have membership in a guild... but all bots have the ability to manage commands
Stuff that doesn’t need to be in the guild like d.js docs bot doesn’t need the bot scope
point is i wanna make sure theres not some edge case where this wouldnt work
like without user installation, can i safely assume that itll always be cached
if you are only guild installed and only allow commands in a guild (no dms), then it should always be from a cached guild
hmmmm dms might be tough
It depends on how you want it to look in ur handler
ok maybe ill just save this type guard for individual command files
less assumptions to make
BaseInteraction#inGuild is probably all you'll need... any command that needs to perform actions in a guild can have this guard or else it won't be allowed to do whatever it's doing
that or just manage the context of the command
my problem is just about negotiating with typescript
for guild only commands, i would just typecast it in your execute function
yea most stuff is guild only, cant guarantee it all will be so ill just type guard when i need it (usually when i need to mess with interaction.member)
anyways with that sorted out, back to redesigning my /rank command yet again because i hate it
aight theres my /rank command
-# it also technically supports ranks having custom images, its just not currently possible to actually configure ranks with images, i need to re enable that at some point
Can we develop discord voice agent bot?
STT -> LLM -> TTS
There maybe tools that may help you do that, but that specifically wouldn't be d.js related. If you want to know how you can recieve voice it'd be better to post in #998942774994927646 otherwise try #1081585952654360687
With a file upload field in a modal, i can get the file url and store in a db, and im doing that except now the url doesnt work anymore, is there a way to fix that?
much like with attachment options for slash commands, file upload attachments are ephemeral
and even putting that aside, attachment urls expire due to #discord-dev-news message
in general you will want to download/reupload the file somewhere else rather than using discord as a file host
that's very annoying but alright
I have a slash command that sends a reply and stores it.
How do I change this so it only stores the 1st reply? It has buttons and each button click sends a new ephemeral reply, but the reply variable is overwritten each time now.
Do I just do this with JS logic, something like if reply is empty then store reply? Or does discord.js have a proper way to handle this?
content: `A new hunt is starting soon!`,
components: [buttonRow],
});```
I’m facing an issue in discord.js and I’m not sure what I’m doing wrong.
The crash happens specifically on GUILD_DELETE.
I suspect something related to cache or an invalid reference, but I’m not sure.
This happens in two cases:
• When the bot is removed from a guild
• When a server is joined → immediately left → then joined again
Is this a known issue?
You might be thinking about the interaction flow wrong.
- You receive an interaction from interaction create (whether it’s from a button press, slash command, etc),
- You check its data and branch accordingly (e.g. isButton(), .isChatInputCommand(), .customId, .commandName)
- You reply to interaction
This should happen for every interaction that you receive
What’s ur d.js version? npm ls discord.js
Are you redefining client fields by chance?
Specifically client.voice
No, I’m not redefining client.voice.
I need some more help with this - I understand what you're saying, but I'm having a hard time applying it to my actual code.
Here's what I have so far: https://codeshare.io/G70pVL
The reply when executing the slash command is saved, but then later is overwritten each time a button is clicked.
I also don't understand how the counter is actually working - since it should be reset to 0 each time not? (It's not)
Can you add this code right after you instantiate the Client and show what logs in console?
Object.defineProperty(client, "voice", { writable: false });
console.log(client.voice)```
Nvm, it's actually just working, hmm
ok
Omitting L11 could cause ur described issue
Actually nvm, it wouldn’t even count properly
You’d get NaN when incrementing/decrementing undefined
Unless it’s not undefined, ofc
You don’t need to call setDisabled on the buttons btw. You are alr removing them from the message
ah yeah 🙂 just experimenting a bit as I'm learning
Thanks a lot for the help!
The issue was on my side — I was overwriting discord.js’ internal client.voice
by assigning my SQLite DB to it.
Renamed it and everything’s working fine now.
I’ve been stuck on this since yesterday and couldn’t figure it out at all.
Yea, that’s why I don’t recommend sticking stuff to things you didn’t make
How do I get a user ID from a user select menu in a modal? I'm not quite sure how to get it from the object map
ModalSubmitFields#getSelectedUsers() discord.js@14.25.1
Gets users component
const candidate = interaction.fields.getSelectedUsers('candidate_select')```
like this?
It would be a Collection of Users, but yes
I need to get one user so I can then assign him roles and change his nickname
Select menus may have multiple users selected, if you haven’t limited it
I'm aware
You can always use the helper methods like .first() or .last() to grab the first or last user
I only mention it because you named the variable singular, which would be misleading
I called it that because there really is only one user at most
thx!
hi, how i can check channel type
<Channel>.type
alr ty
btw how i can check the channel is rule channel or not
Guild#rulesChannelId discord.js@14.25.1
The rules channel's id for the guild
compare its id to ^
oh, i need to fetch the rule channel and compare it, right?
what are you trying to do?
im checking if type on channel is rulechannel, return
it's not a type (rules channels are text channels, so type 0), compare the channel id to <reply> on the Guild instance
alr ty
Hi friends, do you know if there's any way I can make it so that when a channel is created for a user, it's focused on that user?
With this new "View channels" option, some channels are hidden.
Basically, when a user joins my server, I create a unique channel for them, but for most people the channel doesn't appear unless they go to the option and enable it. Is there anything I can do?
// Create onboarding channel
const onboardingChannel = await guild.channels.create({
name: `👋・welcome-${member.user.username}`,
type: 0, // Text channel
parent: onboardingCategory,
permissionOverwrites: [
{
id: guild.id,
deny: ['ViewChannel'],
},
{
id: member.id,
allow: ['ViewChannel', 'SendMessages', 'ReadMessageHistory'],
},
{
id: member.client.user.id,
allow: ['ViewChannel', 'SendMessages', 'ManageChannels'],
},
],
});```
making a channel everytime someones joins your guild isnt really a good idea (do threads instead). But that depends on how your onboarding is setup. set the category where those channels are created as default followed. if that still doesnt work ping them in the channel so it appears in their list
Perfect, I'll try that. Thank you!
How can I set the category where those channels are created as default?
in the onboarding menu > default channels > select the category
Ok, thanks.
that category must have already the view channel permission tho. so that might not be ideal for your use case
how many select menus I can add to my modal?
You can have a maximum of five top level modal components. If your modal was to only include select menus, you can have five select menus
k, thx
Any chance we might ever see autocomplete components in modals?
Doubtfully
is it possible to know the locale of a guild member/user?
For example I have a faction system, and one of the subcommands is an invite command which sends a dm with an embed and 2 buttons to the targeted user, but the person that invites has their locale set to us english and the target might use spanish, so i want to send the invite in spanish to their dm
documentation suggestion for @ripe topaz:
ChatInputCommandInteraction#locale discord.js@14.25.1
The locale of the user who invoked this interaction
The same property might exist on other interactions so look at the docs
i am aware, yes, but that doesnt help me figure out a targeted user's locale
If the one who invokes the command isn't the target then your only way to know is if they set their language explicitly on a database for example
you can get the locale for the guild
BaseInteraction#guildLocale discord.js@14.25.1
The preferred locale from the guild this interaction was sent in
No, you cannot scan all guild members to target only spanish-using users
on getStringSelectValues() does it return empty array if nothing select or undefined?
What do the docs say it returns
Is there a way to fetch a user tag?
like the guild tag
User#primaryGuild discord.js@14.25.1
The primary guild of the user
UserPrimaryGuild#tag discord.js@14.25.1
The user's guild tag. Limited to 4 characters
there's also other data there you can check
primary guild is how discord calls the tag feature pretty much
alright, thank you :)
What event would I be able to detect changes of the tag changed on?
guildMemberUpdate?
I think userUpdate since it's on the user
okay ty
Both depending on the cache state
One or the other
Because discord sends all that via gmu, and we separate it out basing on what changed
whats the difference between userupdate and guildmemberupdate again?
this is much clearer now thanks
module.exports = {
name: 'userUpdate',
async execute(oldMember: GuildMember, newMember: GuildMember, client: Client) {
try {
if (newMember.guild.id !== config.yourGuildId) {
return;
}
const oldUser = await oldMember.user.fetch(true);
const newUser = await newMember.user.fetch(true);
const oldPrimaryGuild = oldUser.primaryGuild;
const newPrimaryGuild = newUser.primaryGuild;
const oldHasThisGuild = oldPrimaryGuild?.identityEnabled === true &&
oldPrimaryGuild?.identityGuildId === config.yourGuildId;
const newHasThisGuild = newPrimaryGuild?.identityEnabled === true &&
newPrimaryGuild?.identityGuildId === config.yourGuildId;
} catch (error) {
console.error('Error handling primary guild update:', error);
}
}
};
any questions on why this isnt working?
I used many things n still not working
the old primary guild maybe null sometimes don't use that to validate
okayy
Thank you @tiny condor and @rose tangle, I've finally got it working :)
Now- does anyone know how to check if a server has a tag or not? 
Im just wondering as Im making a whole system sooo- yk
and this is the last part n dont know how to check if the server has a tag or not.
no for some reason discord made guild tag only on user
you can only check if guild has the feature to set tags in guild.features
ahh damn okay
How do I edit a role's permissions?
documentation suggestion for @ripe topaz:
Role#setPermissions() discord.js@14.25.1
Sets the permissions of the role.
// Set the permissions of the role
role.setPermissions([PermissionFlagsBits.KickMembers, PermissionFlagsBits.BanMembers])
.then(updated => console.log(`Updated permissions to ${updated.permissions.bitfield}`))
.catch(console.error);
thanks
is it possible to send a new message on button interaction, without replying?
if your app that receives the interaction has a bot in the server that has permissions to send messages into the channel, yes
but that's going to leave an error on the user side
because you never responded to the interaction
is it possible to make an invisible reply
you can respond ephemerally, yes
that means only user who interacted can see that message?
yes
but i dont want that
like im converting my app from eris.js to discord.js
in eris I had something like interaction.acknowlege()
if that does what i think it does, that has been defunct in API for years
An interaction must have a response.
reply
deferReply
showmodal
[for messages]
update
deferUpdate
Why do you want to not respond to the user? it is bad practice to not tell the user the action was completed
people just got used to it, its been 8 years since its like that
so user press the button and a new message is sent in channel?
exactly, without any error
you should use reply then
-# if async use deferReply then editReply once ready to send
when i do that in discord.js i got interaction failed, but message is sent though
That's most likely doing deferUpdate then not following up on that. Though that's bad practice to do it
dang it
if it does that (and it has to do that like that), then it's lying to you with it's name. it doesn't acknowledge, but lies to discord that you need more time to produce data to update the message with, and then you simply never do that
so, since interactions are available only for 15 minutes, i have to manually clear components from a message?
no. you only have 15 minutes to reply to the interaction
well, you have to reply within 3 seconds, but can extend the reply to 15 minutes with a deferReply. you can also edit up to 15 minutes after the interaction has been sent
so user can click on a button at any point in time, and bot will receive an event?
pressing a button creates a new interaction
yes, but i assume you have your buttons in a collector? move them to a client event if you want to use them for ever
which has its own 3 second reply time, and eventual 15 minute limit
I think I understand now, thx
very helpful community
didn't expect that
How to make this pingable slash command?
its been there since 2023..... 😭 I feel stupid, this one seems so convienent for the users-
not work select menus in embed it s out embed
@14.17.3
i want like this select menus
guide suggestion for @rustic willow:
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.
documentation suggestion for @rustic willow:
ContainerBuilder#addActionRowComponents() discord.js@14.25.1
Adds action row components to this container.
thx work <3
this channel is for asking help, dont just send invites here
The fetchReply option when replying to an interaction will be removed in v15.
- {..., fetchReply: true}
+ {..., withResponse: true}
```This returns an [InteractionCallbackResponse](https://discord.js.org/docs/packages/discord.js/stable/InteractionCallbackResponse:Class)
Use `<InteractionCallbackResponse>.resource.message` to get the message
there's #app-commands for personal use, or the hide option
so uhm I’m having an issue one minute I’ll send over the error, if ya want code let me know what code ya want and I’ll send it over lol
and it is down (just stays down didn’t retry again)
Well, presumably how you create event listeners
whats confusing though is that this just started happening, it has not happened before now
Something has had to change
Not necessarily directly in your own code
alrighty wasnt sure what i should look for thanks!
So I am running into an issue where if a server member uploads an audio file along with with some cover art with their song my bot can not detect if the image they uploaded is within the range we allow for that channel (100 pixels or less tall).
Here is the code that manages that little bit.
Can someone please tell me how I can fix this issue (the audio files being uploaded not breaking detection for an image larger then 100px) ?
const { cleanContent, channel, attachments } = message
console.log(attachments.map(attachment => attachment.contentType))
console.log(cleanContent)
const urls = cleanContent.match(hasUrl)
if (!urls) {
tracer.log("No link = bad!")
await reply(message, "Where's the link?! > _< (Make sure it starts with https://)")
return true
}
const redirections = await Promise.all(urls?.map(async (url): Promise<string> => (await request(url)).headers.location as unknown as string ?? url))
tracer.info(cleanContent)
tracer.info(redirections)
const sauce = redirections.some(redirection => redirection.match(hasSauce))
console.log(sauce)
const linebreaks = cleanContent.match(/\n/gm)
const channelIsRecycledBeeps = channel.id === channels["recycled-beeps"]
const longLink = urls?.some(url => url.length > 100)
attachments.forEach(attachment => tracer.info(attachment.height))
// checks if submission has one image or less, and if that image is 100px tall or less
const twoAttachmentOrLess = attachments.size <= 2
const oneImageOrLess = attachments.filter(attachment => attachment.contentType.match(/image\/.+/g)).size <= 1
const oneAudioOrLess = attachments.filter(attachment => attachment.contentType.match(/audio\/.+/g)).size <= 1
const attachmentReqs = attachments.size === 0 ? true : oneImageOrLess && oneAudioOrLess && attachments.some(attachment => attachment.height <= 100)
const tooLong = cleanContent.length > 450
const headerFormatting = cleanContent.match(hasHeaders)
filter returns an array, and an array is always truthy
regardless of size
you might want to use oneImageOrLess.length && oneAudioOrLess.length instead
ah nvm I misread the code
I think that should work then, place some logs to see where it fails
this is the log I get when uploading a song with an audio and an image that is too tall
this is the issue bit
you can see it still sees the image and also sees that it is taller then 100 pixels, however it treats it as if everything is ok and continues
here is when there is just a link and an image that is too tall
you can see that this works but if there is an audio uploaded with the message it does not work @rose tangle
Won't attachments.some(attachment => attachment.height <= 100) always be true for audio uploads? Which means even if the image attachment fails the check, the result will be true since .some only needs one return to be true.
hi, how i can fetch the discord channel comm log
Error handling component "confirm": DiscordAPIError[50074]: Cannot delete a channel required for community servers
do you want to fetch or delete?
you say you want to fetch, but your error says you tried to delete
yes i want to fetch, if channel required ill throw error
which channel do you want to get? there's many community-related channels
also what's the error you shared, like I said it says you tried to delete a channel
is it completely unrelated to your question?
this one
yes im trying to fetch the channel, if not then it will delete
it will delete what?
the channel
but you say you're trying to fetch it
and if you can't fetch it (there isn't one), it will delete it
what will you delete given in that scenario there's no channel?
no i mean
first, ill fetch the channel i want, if the channel is required for community server, it will return a error (ill handle that), else ill delete it
ah, yeah that makes more sense
and you want to get the community channel to see if the one you have is that one so you don't delete it, right?
yes
I think it's the publicUpdatesChannel
Guild#publicUpdatesChannel discord.js@14.25.1
Public updates channel for this guild
check first just in case, unless someone else can confirm it
though consider that's not the only "protected" channel
I'd just check for #deletable
GuildChannel#deletable discord.js@14.25.1
Whether the channel is deletable by the client user
that checks whether it's protected and you have enough perms
alr imma try that, ty
Does anyone know if it is better to use .addUserOption or .addMentionableOption?
What do you want it to accept?
Users, or all mentionables?
There is no "better", it depends what you want it to do
It want it to accept a user for my warn command.
So use a user option
Why would you use mentionable and include roles?
I don't know I would just wondering which I should use.
You want it to only accept users - use the user option
can webhooks use display components?
Yes
They just have to enable withComponents
mentionable means it includes users and roles as options, and presumably you don't want the option to warn an entire role
is there a way to add multiple users to a thread at once?
I have a command that shows a button, everyone has a few seconds to click the button
then everyone who clicked the button needs to be added to a new thread
Mention them
const modal = new ModalBuilder() .setCustomId("giveaway_modal_channel")
.setTitle("Set Giveaway Channel");
const inp = new LabelBuilder({
label: "Channel",
description: "channel where this giveaway will be sent"
});
inp.setChannelSelectMenuComponent(
new ChannelSelectMenuBuilder()
.addChannelTypes(ChannelType.GuildText)
)
modal.addLabelComponents(inp);
await interaction.showModal(modal);
why's this triggering sapphire's checking?
2610 | }
2611 | phone(options = this.validatorOptions) {
2612 | return this.addConstraint(stringPhone(options));
2613 | }
2614 | handle(value) {
2615 | return typeof value === "string" ? Result.ok(value) : Result.err(new ValidationError("s.string()", this.validatorOptions.message ?? "Expected a string primitive", value));
^
error: Expected a string primitive
validator: "s.string()",
given: undefined,
at handle (C:\Users\sky\Desktop\KnightRider22's Invites bot\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:2615:70)
at parse (C:\Users\sky\Desktop\KnightRider22's Invites bot\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:972:90)
at toJSON (C:\Users\sky\Desktop\KnightRider22's Invites bot\node_modules\@discordjs\builders\dist\index.js:959:23)
at toJSON (C:\Users\sky\Desktop\KnightRider22's Invites bot\node_modules\@discordjs\builders\dist\index.js:1636:29)
at map (1:11)
at toJSON (C:\Users\sky\Desktop\KnightRider22's Invites bot\node_modules\@discordjs\builders\dist\index.js:2734:35)
at showModal (C:\Users\sky\Desktop\KnightRider22's Invites bot\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:402:46)
at showModal (C:\Users\sky\Desktop\KnightRider22's Invites bot\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:397:19)
at execute (C:\Users\sky\Desktop\KnightRider22's Invites bot\src\events\giveawayInteraction.ts:135:35)
at execute (C:\Users\sky\Desktop\KnightRider22's Invites bot\src\events\giveawayInteraction.ts:92:19)
oh so I just have my bot post a msg with all the users tagged in it then?
you need a customId on the select menu
oh i forgot 😭 thank you
Does codeblock in embed message (footer) works?
No
I can't react to messages here but thanks 👍
that would be it, yes.
Just a question, how do I change the bot's avatar, bio and banner in my discord server with the new stuff discord brought out?
documentation suggestion for @dire iris:
GuildMemberManager#editMe() discord.js@14.25.1
Edits the current application's guild member in a guild.
ty
ty it works 
await guild.members.editMe({
avatar: imageUrl || null,
reason: `Customization by ${interaction.user.tag}`
});```
TypeError: guild.members.editMe is not a function
at handleAvatar (/home/container/commands/Slash/Utility/customise.ts:205:23)```
what could be the issue or do i have to make it by the api endpoint with the bot auth token?
what is guild ?
that would be const guild = interaction.guild
d.js version?
Oh I see 😭 my d.js didnt updatee lol
what is your current version
14.14.1
yeah you need at least 14.23, ideally latest
yea- for some reason i need to improve my package updater lol. Normally it does it automatically but it didnt
I'd advise just updating manually
alright thank you- it works
I know but it does it auto with no issues and for some reason it didnt detect any lol
auto with no issues
And yet you talk about an issue with it
did discord add frame decoration url yet? like get the gif url or something for users frame
documentation suggestion for @barren prawn:
User#avatarDecorationURL() discord.js@14.25.1
A link to the user's avatar decoration.
Awesome, thanks
Is there an easy way to see who deleted or created a channel?
th easiest way is through the audit log
So I have to fetch audit log entries?
there is no other way i think
yes or by the client event
Guild#fetchAuditLogs() discord.js@14.25.1
Fetches audit logs for this guild.
// Output audit log entries
guild.fetchAuditLogs()
.then(audit => console.log(audit.entries.first()))
.catch(console.error);
(event) Client#guildAuditLogEntryCreate discord.js@14.25.1
Emitted whenever a guild audit log entry is created.
Uh, none of those shows up in autocomplete after client.
(Yes, it's an instance of the Client class)
can you show your code
I define the client like this: ts const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildMessageReactions, GatewayIntentBits.GuildMembers, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildVoiceStates, GatewayIntentBits.GuildPresences ], makeCache: Options.cacheEverything(), sweepers: Options.DefaultSweeperSettings, });
yes and then?
One of them is a method on Guild, not client. The other is an event emitted by Client, not a property or method. So ofc neither shows in client.
Then I try doing client.channelUpdate but it's not a member of the class
client.on('channelUpdate', ...)
Oh
or use
client.on(Events.ChannelUpdate, .....)
Are member and user updates 100% or are there times they won't fire? I know they are eventual, I mean like firing at all
that depends on your intents and partials
This is what I have;
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
],
partials: [Partials.User, Partials.GuildMember],
});
I am trying to listen to tag changes
Well 
Guild member update should fire, though user update depends on if the user was cached as that is used to compare if anything changed in user object recieved from various events since discord only sends user update for the connected client and not anyone else's
I know, I listen to both
So there is no thing about member update events not firing sometimes
Guild member update will fire but you'll have to account for oldMember being partial
I don't use old member either
Hello 👋 ~~ I keep getting this error… Error and the related code is in the picture
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
Thanks for replying. I deferred the interaction and that seemed to fix that issue, now it seems like i’m getting a “Request entity too large” 40005 Error
Is there a way i can look up errors returned by the discord API? Maybe the file i’m trying to send is too large?
yes the file youre sending is too large
Oh yeah, already fixed it, changed it to an image.
Sorry forgot to send a follow up.
I have a general question about rate limits. Taking the route POST /guilds/123/channels as an example, can you apply a rate limit only to the guild, only to the route, or globally to the entire bot? How do you differentiate between these, and what is the best way to handle them?
Also, if I get a RateLimitError, should I stop requesting the entire route or only for this guild?
discord.js already handles the ratelimits, and all the info you need on how or why is in the data emitted along with the ratelimit event
alternatively, take a look through dapi docs
where?
Nevertheless, I would like to know how it works.
type rate into dapi docs search bar
But how can it be that I get an infinity when using .limit on a RateLimitError?
If I have an infinite number of requests, then I can never reach them.
what did you get ratelimit on
or rather, the RateLimitError
on POST /guilds/234/channels
then that would never have an Infinity as a limit
everything in discord has ratelimit
with one exception, namely the initial response to an interaction. that doesn't have a ratelimit but you can only ever do it once anyway
clearly it's not Infinity
if it's not you messing with the data, try asking in ddevs
it's not data d.js produces
and if you're wondering about the event itself
d.js fires the ratelimited event if a request you make gets queued by d.js in order to not get hit by a 429 from the API
doing one bulk delete should emit it as you can do it once per x time
doing second one would be queued based on the ratelimit data returned from the first request
Hello, I need help with one of my events not working properly. The code will be below.
const { log } = require('../utility/logger.js')
const {
EmbedBuilder,
WebhookClient,
PermissionsBitField,
MessageFlags
} = require('discord.js')
const config = require('../config.json')
const gfx = new WebhookClient({ url: config.webhooks.gfx })
const custom = new WebhookClient({ url: config.webhooks.custom })
const premade = new WebhookClient({ url: config.webhooks.premade })
module.exports = {
name: 'messageCreate',
async execute(message) {
if (message.content === "=gfx") {
await message.delete().catch(() => {})
if (!message.member.permissions.has(PermissionsBitField.Flags.Administrator)) {
return;
}
const embed = new EmbedBuilder()
.setTitle('GFX')
.setDescription('GFX')
.setColor(config.colorHex)
return await gfx.send({
username: 'GFX',
avatarURL: config.avatarURL,
embeds: [embed]
})
}
if (message.content === "=custom") {
await message.delete().catch(() => {})
if (!message.member.permissions.has(PermissionsBitField.Flags.Administrator)) {
return;
}
}
if (message.content === "=premade") {
await message.delete().catch(() => {})
if (!message.member.permissions.has(PermissionsBitField.Flags.Administrator)) {
return;
}
}
}
}```
and what about it doesn't work
There is no reply and my message doesn't delete. Nothing in the console also.
do you have the message and message content intents?
also, it's not surprising nothing logs if you intentionally swallow errors with the empty blocks in catch()
instead of swallowing errors, check if your bot has permission to delete the message
GatewayIntentBits.MessageContent & GatewayIntentBits.GuildMessages?
yeah
could u give an example on how to do that?
literally like you're already checking if the message sender has a permission
just check on different member and with different permission
you can access your bot's member via guild.members.me
kinda new to collectors but if i do createMessageComponentCollector on a message. the collector only applies to that message right? not that im gonna have dupe interactions with another collector
as its name and what you call it on would suggest, yes
ok thanks and what exactly is dispose? the doc doesnt make it clear for me
afaia it doesn't do anything for components/interactions, but it's a base collector option for listening and emitting removals
message and reaction collectors can use that
in case someone reacts and unreacts
oh okay i see
i did this but it still dont work i added a console.log before deleting and it didnt log anything
did you enable the intents?
yes
is the bot in the server and does it have permissions to see messages in the channel you're sending messages in?
yes it has administrator
how are you registering the events
like the code?
for (const file of fs.readdirSync("./events")) {
const event = require(`./events/${file}`);
client.on(event.name, (...args) => event.execute(client, ...args));
}```
if you put a log as the first line in the event, before any ifs, does it log at all?
yes
well, then log the content to see why your if doesn't work
i put a hey before any ifs and a here after the if and the here didnt log
you just said it logs
if it doesn't log, are you running the code? are you using correct token?
okay, sorry i misread
if the here didn't log it means that the if is working as designed - the condition wasn't true
so you need to check why is the condition not true while you think it should be
log what it's trying to check
so you see why it doesn't work
is it supposed to be === or =?
In JavaScript, = is used for assignment, == for loose equality, and === for strict equality checks.
x = 1; // assigning a value to x
'1' == 1 // true
'1' === 1 // false
- Equality and sameness in JavaScript: learn more
i dont understand
which part?
would it be true or false in my situation?
this is just example
but for if to work the condition has to be true
this is very basic stuff, not even really javascript specific
huh
what does your if do
it checks if message content is something
since the if doesn't run
the message content is not that something
check what it actually is
how would i do that?
by using console.log() and putting inside what you want to log
did you write that code at all
so like console.log(message.content)?
yes
before or inside the if?
this is genuinely basic programming at the moment
you have already established the if doesn't enter
i'm giving you extreme amounts of handholding for this code you hadn't written yourself
ok
how do u think i didnt write it myself?
because you don't even know how to log
- you're using if blocks without any understanding how they work. specifically, you cannot even tell what an already written if actually does
- you have no idea how to log
- you continuously ask if you should add code in blocks you already know that don't run
- you asked how to check permission despite doing it 3 times in the code you sent
oh alr
#rules 3
it's really not enough
anyway
i'm done here
i tried enough
hi any idea why interaction.member.username is returning undefined?
because interaction.member.username doesnt exist, either youre looking for GuildMember#nickname / displayName, or just use interaction.user.username
oh ok
whats the best way to auto translate replys to other languages
writing the code that does it
an external api
it's not related to discord.js, that's for sure
also machine translations will be shit
in the doc it is
are you referring to the translations for commands because thats not the same thing
d.js takes content for responding or translated strings for command names and descriptions
it has nothing to do with generating any translations
it's just strings
"yes", "tak", "asiudhsi" are all just strings, just that people give meanings to the first two
nor can you receive the translations from your bot and send them to users in other languages
thanks! :D
so jsut use json fules then
how you store and pass the translations is up to you
i mean that would likely be the easiest way apart from external ones yes
since you can both use that as the translation data sent to discord and also access it yourself
should i come back for help once i learn?
absolutely, we're here to help
but you need to actually understand what we're saying and know how to apply it on your end
no ones stopping you from getting help now, the issue is that theres a line drawn between "I dont understand the library" and "i dont understand programming at all" and youve gotta cross the latter before worrying about the former
trust me, if you search old messages here, i was also in your boat at one point, take some time to read the MDN docs, learn about how JS works and mess around (or just browse #resources) and come back stronger with basic programming topics and some more "advanced js" (async js/promises, thenables, etc)
i see
does anyone know how hide slash commands from people without certain permissions?
SlashCommandBuilder#setDefaultMemberPermissions() discord.js@14.25.1
Sets the default permissions a member should have in order to run the command.
like the name and description say, it's a default value, so a guild admin can override it (for that guild)
if you want something hardcoded you'd need a runtime check, but the member would still be able to see it
unlike the "native" feature
k
Does the following no longer work? As it worked before for me to add attachments.
async function sendLog(intr: ChatInputCommandInteraction, videoId: VideoId, history: RelayedComment[]): Promise<void> {
const start = await getStartTime(videoId)
const tlLog = await filterAndStringifyHistory(intr, history, start)
const attachment = new AttachmentBuilder().setFileData(Buffer.from(tlLog)).setFilename(`${videoId}.txt`)
await intr.editReply({
content: localeText(LOG_FOUND(videoId), intr.locale),
embeds: [],
files: [attachment],
})
}
Gives the following error in VSC:
Type 'AttachmentBuilder' is not assignable to type 'Attachment | AttachmentPayload | BufferResolvable | FileBodyEncodable<APIAttachment> | Stream'. Type 'AttachmentBuilder' is missing the following properties from type 'Buffer<ArrayBufferLike>': slice, subarray, write, equals, and 101 more.
edit: figured it out, was on V15 branch testing some newer code. got it working again.
Is Component v2 incompatible with webhooks? I’m getting the "Cannot send empty message" error when I try to use Component v2 in a webhook
you need to pass with_components=true to the url
at the end of the url?
yes
it is a Query String Param
documentation suggestion for @coral maple:
Webhook Resource - Execute Webhook POST webhooks/{webhook.id}/{webhook.token}
Refer to Uploading Files for details on attachments and multipart/form-data requests. Returns a message or 204 No Content depending on the wait query parameter.
WebhookMessageCreateOptions#withComponents discord.js@14.25.1
Whether to allow sending non-interactive components in the message. For application-owned webhooks, this property is ignored
thanks
in the editMe method, if a bot restarted, do I need to re-run the editMe or it's persistent?
it persists
alright, thanks!
Is there a way to see who removed reactions from a message? Like remove other people's not their own
Message#reactions discord.js@14.25.1
A manager of the reactions belonging to this message
documentation suggestion for @sleek mural:
ReactionManager#removeAll() discord.js@14.25.1
Removes all reactions from a message.
What about to see who did it?
ohh I have know idea not realy a djs question. best to ask on DDevs
Alright thanks
is it possible to change bot's avatar and banner per guild not globally in discord.js?
GuildMemberManager#editMe() discord.js@14.25.1
Edits the current application's guild member in a guild.
TypeError: Cannot read properties of undefined (reading 'displayAvatarURL')
Why do I get such error from the GuildMember? A GuildMember no longer has displayAvatarURL?
can you show your code?
As far as I can tell, setDefaultMemberPermissions() only applies at the top-level command and can’t be configured per subcommand.
If a command has multiple subcommands—some intended for regular members and others restricted to staff—is the only way to handle this to do permission checks at runtime? In other words, there’s no way to hide specific subcommands from users without the required permissions like setDefaultMemberPermissions() does at the command level, correct?
correct
const [challengerAvatar, opponentAvatar] = await Promise.all([
loadImage(challenger.displayAvatarURL({ extension: "png", size: 256 })),
loadImage(opponent.displayAvatarURL({ extension: "png", size: 256 })),
]);
challenger and opponent are both type GuildMember
are you sure? did you try logging them?
yeah I did
quick question : /avatar <image> these commands for per guild personalization do call discord api?
what?
and what if we want to have that option in a web dashboard?
i dont understand you
could you share the full error stack
so think of it like i want in my web dashboard of bot, guild owners set a custom name for bot, how in discord that bot name will change?
I removed .user before the displayAvatarURL and now it keeps giving:
TypeError: challenger.displayAvatarURL is not a function
at getRequestCard (C:\Users\micha\Desktop\Weky\api\src\functions\FightCards.ts:98:24)
at <anonymous> (C:\Users\micha\Desktop\Weky\api\src\routes\Fight\api.ts:37:21)
at Layer.handleRequest (C:\Users\micha\Desktop\Weky\api\node_modules\router\lib\layer.js:152:17)
at next (C:\Users\micha\Desktop\Weky\api\node_modules\router\lib\route.js:157:13)
at Route.dispatch (C:\Users\micha\Desktop\Weky\api\node_modules\router\lib\route.js:117:3)
at handle (C:\Users\micha\Desktop\Weky\api\node_modules\router\index.js:435:11)
at Layer.handleRequest (C:\Users\micha\Desktop\Weky\api\node_modules\router\lib\layer.js:152:17)
at C:\Users\micha\Desktop\Weky\api\node_modules\router\index.js:295:15
at processParams (C:\Users\micha\Desktop\Weky\api\node_modules\router\index.js:582:12)
at next (C:\Users\micha\Desktop\Weky\api\node_modules\router\index.js:291:5)```
this is in regards to discord.js ?
quick question...
Can you show the code where you’re obtaining challenger and opponent?
do you have a question about discord.js? or about your web dashboard?
both, i want like user should be able to set bot custom name from discord commands or even through web dashboard
so how i do it?
i can't help with your web dashboard, that's something you need to figure out
GuildMemberManager#editMe() discord.js@14.25.1
Edits the current application's guild member in a guild.
const opponent = msg.mentions.users.first();
if (!opponent) return;
const guildOpponent = await msg.guild?.members.fetch(opponent.id);
if (!guildOpponent) return;
const challenger = context.member;
challenger is taken from the context and opponent from the mention
i mean like im asking simple flow
Admin in Website set avatar -> direct call to api, instant pfp set
in commands -> direct call to api
is it the right flow, or..? i need to read from db after eveyr x time
You wouldn't set it through commands, your API would run a method to set the profile
you mean we cant through discord?
just to answer your original question directly
no, neither <GuildMember>.displayAvatarURL() nor <User>.displayAvatarURL() have been removed
your original error and the subsequent error suggest that challenger is not a GuildMember
you showed a log of an object that, while at first glance does appear to contain member data, I worry isn't actually a GuildMember object and could have through some means been stripped of its class (whatever system by which you're receiving this context)
You can do both, I'm just saying you don't need to run a command to set the pfp just have a method that you can run both from your command and also from your dashboard when needed through the API
You should start it and test it then ask in #1081585952654360687 for further help with it
well I updated the challenger to this: const challenger = await context.guild.members.fetch(getContextUserID(context)); which does return a GuildMember and still it gives same error
could you log challenger.constructor.name?
(to be specific, please log it directly before the erroring line)
ok just correct me if i'm wrong
Set pfp to A from webdashboard -> api does it and saves pfp A to db also
set pfp to B through discord command -> api does it and updates the db to that new pfp B
if bot restart, it will read db and will set auto
You don't need to save the pfp to your database, just pass it through the API to your method, not sure why you are involving the db
restart...?
Also again, just start it and see how far you get and ask in #1081585952654360687
it returns object because the GuildMember is passed thru an api request
? Since when does discord reset your guild profile when you restart your app
then it's not a GuildMember
so after it passed thru network request to the api its no longer GuildMember, it can access the ids and all but not functions and etc?
i assumed lol, but user in dsahbord set to pfp a, but when he refresh the website, then that pfp wont show in db, which acutally sucks, or is there a way we can fetch it also through api, the pfp of bot in that specific guild?
yes, json doesn't contain functions
functions aren't sent via http requests
correct. it becomes a plain json obj
Yes? get the bot members pfp like how you get the server's pfp
So I should basically instead of the GuildMember send the url instantly
okkkkk thank youuuu
if all you need is the image
oh and the user username, I will also pass that with a list for each user so the list contains the id and image
if all you need is the username and image and id, don't pass the entire guildmember
Okay! Thank you all!
faseeeeee, can you send the docs link, for seting custom pfp/banner/about me/ pfp for bot from website
GuildMemberManager#editMe() discord.js@14.25.1
Edits the current application's guild member in a guild.
^^ 3 times
From a website is an OAuth process...and DJS doesn't handle oauth... Just gateway routes
what you trynna say ahm..
Hey, quick question: is it okay to run a Discord bot in a web app to retrieve channels and roles from a server, for example, or would it be better to use an external backend?
You need to authenticate the user on your website dashboard, then send an api request to your bot's code to update the profile
It would be best for you to simply use oauth2
yep, like its obvious every dashboard do need users to login
So then what is the question here?
Let's say I have my 0auth2 configured, my user can log in with their account, and I have access to these servers and their permissions. Would I then need to go through the API?
Tbh you could do it with both, after they auth, you could get the channels with the bot or from the API
I think bot would be the best way to access it
You can use bot token to query the api on the server side, not sure what's the confusion is. As long as bot can access the channels
Though you need to make sure you do it on the server side and not expose your bot's token to the client side
So ideally, I would need a backend with a bot running to execute these kinds of requests?
Of course
Thanks!
"You are changing your avatar too fast. Try again later"
How much laterr...
How many times did you change it? 
2
rest.on("rateLimited", console.log)
Doesn’t that one error with the time it’ll reset?
"[Personalization] Discord API error: {"message": "Invalid Form Body", "code": 50035, "errors": {"avatar": {"_errors": [{"code": "AVATAR_RATE_LIMIT", "message": "You are changing your avatar too fast. Try again later."}]}}}\n"
stuck
can you show your code?
my mom gonna crashout, bye
const apiBase = 'https://discord.com/api/v10';
const headers: Record<string, string> = {
'Authorization': Bot ${BOT_TOKEN},
'Content-Type': 'application/json'
};
const memberPayload: any = {};
if (name) memberPayload.nick = name;
if (aboutMe) memberPayload.bio = aboutMe;
if (avatarUrl) {
const avatarData = await getImageDataUri(avatarUrl);
if (avatarData) memberPayload.avatar = avatarData;
}
if (bannerUrl) {
const bannerData = await getImageDataUri(bannerUrl);
if (bannerData) memberPayload.banner = bannerData;
}
( got some seconds )
banner/nick/about-me working fine

