#djs-help-v14

78874 messages · Page 65 of 79

patent epoch

well it doesn't really say where to put stuff
does it matter where in my index.js I put client.cooldowns = new Collection();
I put it here:


client.cooldowns = new Collection();
client.commands = new Collection();```
steel trail

That should not give you the error you got. Show the full error with stacktrace please

patent epoch
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```
crimson gale

that is entirely different from what you said

patent epoch

yeah I removed the code, just re-added it, got this error earlier too, then changed some things and got the other error

crimson gale

can you please show your code? you clearly don't have what the guide has and guessing around this makes little sense

patent epoch
steel trail

You don't import Collection so yes, it indeed won't be defined

patent epoch

well the guide doesn't mention anything like that - unless I missed it?

steel trail

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"

patent epoch

I haven't worked with JS in years, it's all very rusty

also I assumed discord.js would import it somewhere

steel trail

sure, it does. But if you use a class in your code you need to import that class in your code

patent epoch

const { Client, Collection, GatewayIntentBits } = require('discord.js');
is this not importing Collection?

steel trail

It is, in your index.js file. But you also use it in your command file, so need to import it there too

patent epoch

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)

subtle girder

how to check whether a voice channel exists?

velvet cipher

From what? An ID? A name?

subtle girder

VoiceBasedChannel, just prevent user delete it

so I can check using channel id?

tiny condor

Prevent a user from deleting it or checking it?

subtle girder

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

snow onyx

I assume you are creating the channel beforehand? did you wait for that request to complete?

subtle girder
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

snow onyx

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

subtle girder
ripe topaz

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

steel trail

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?

ripe topaz

how come sometimes the check passes even without the intent tho?

steel trail

Probably because your bot was the one moving them, so it has the voice state cached

subtle girder

when my bot is playing audio resources, the sound may vary in speed or be choppy.

ripe topaz

the users? nope

last ether

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

mint kettle

hello! any chance someone around familiar with recording bots? I got this #1453448220708700160 issue stuck on it with no clear path 😅

polar karma
last ether

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)

polar karma

Most restrictions like that revolve around user privacy. Might help you to understand some of their decisions

last ether

Yeah I guess so, thanks for your help 😄

vestal sun
wary coral

The intent is needed to see any details about the content of the message

polar karma
toxic moat

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 💀

topaz bluff

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

toxic moat
rose tangle

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

toxic moat

the fact you choose to argue instead of looking into the problem really shows what type of staff i just stumbled upon

toxic moat
rose tangle

because checking channel names is useful to figure out what they're for

toxic moat
rose tangle

I'm not trying to argue, just making the point that you can check beforehand what a channel is for

toxic moat

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

toxic moat
toxic moat
dense jackal

id:customize in your channel list at the top and then “All Channels”

its the same, but anyway

toxic moat

stop carrying the argument youre loading the help channel with this

dense jackal

that you don’t know how this messaging app works isn’t the problem of “whoever made this server”, you can only blame yourself

toxic moat
tardy sable
topaz bluff

Guys... Stop... Drop it

toxic moat
toxic moat

@fleet ridge @crimson gale good job at being mods 😄

fleet ridge

congratz

topaz bluff

How will we ever recover from the loss of "random dev #1476017"

crimson gale

wat

tiny condor

dudes gonna be real upset when he realises this is the best support for djs

robust haven
topaz bluff

A section component

sharp ginkgoBOT

guide 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:...

tardy sable

why is it sometimes it feels like an event gets fired twice (dupe)?

i got twice the same channeldelete event

rose tangle

how do you know you got it twice?

tardy sable
rose tangle

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

tardy sable
rose tangle

it can happen, that's why there's the nonce option

tardy sable

oh okay

what does the nonce thing do and how should i implement it

rose tangle

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

sharp ginkgoBOT
tardy sable

thanks. and then i shouldnt worry about accidental dupe events?

rose tangle

it's unrelated to events themselves, it just makes it so the same message request doesn't get "sent" twice

tardy sable

oh okay i see thanks will try out

rose tangle

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

verbal plinth

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?

ripe topaz

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 });
tardy sable
ripe topaz

with update or how

tardy sable

after deferupdate you cant update again its editReply then or use a followUp

rose tangle
verbal plinth

Shouldn't that disable the queued option?

verbal plinth
rose tangle
rose tangle
verbal plinth
rose tangle

like I said, log it to make sure you're checking the correct endpoint and method

rose tangle

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?

ripe topaz

Does GuildMember#displayAvatarURL return anything for users with the default discord icon?

verbal plinth
await guild.channels.create({}).catch(async (e) => {
  if (error.name === "RateLimitError" || error instanceof RateLimitError) {
    console.log(e)              
  }
})
tardy sable
rose tangle

like where are you logging that

verbal plinth

In the line console.log(e), that's where the log goes.

rose tangle

so you say it throws the ratelimit error, and it still creates the channel regardless after 60s?

steel trail

Also that log is not what a console.log of a RateLimitError would look like

verbal plinth

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

steel trail

So the log does not actually come from the console.log does it? Please show the actual code causing that log

verbal plinth

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)
            }
        })
steel trail

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

verbal plinth

No, we don't have any other instances running.

steel trail

How did you determine that to be the case?

verbal plinth

We only have new Client({}) once in the code, and that's where we added rejectOnRatelimit.

steel trail

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?

verbal plinth
loud quartz

Is that the only thing that extended class does?

verbal plinth
steel trail

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

verbal plinth
steel trail

And did you do what I proposed to do in the message you replied to?

verbal plinth

Yes, no message was received in the response.

steel trail

Considering that event should emit for every response to any REST call I sure would hope there were many received

sharp ginkgoBOT
ripe topaz

can you have a value be pre-set in a string select menu?

steel trail

Yes, put default in the option

sharp ginkgoBOT
steel trail

If you use builders 👆

For raw json it's simply default: true

ripe topaz

tip

ripe topaz

how do i set a custom activity? I want to set something like "Touching grass" with a grass emote

verbal plinth

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.

loud quartz

how did you listen for it

verbal plinth
loud quartz

didn't you just say that they kinda like don't come

verbal plinth

The data comes from the proxy and is the count, which shows how many connections are currently open through it.

loud quartz

not the graphs

verbal plinth
loud quartz this

That was just to check if it was running twice, which it isn't. So everything is correct.

loud quartz

did you read what Qjuh said?

verbal plinth

Yeah

And everything fits perfectly there.

wintry laurel

is there a limit to the ammount of times you can run .update on a deffered interaction?

tardy sable
wintry laurel
clear garnet

editReply()

wintry laurel

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

clear garnet

deferX() and update() are both forms of acknowlegement. You can only acknowledge an interaction once

wintry laurel
sharp ginkgoBOT

Responding to interactions:

  • #reply immediately respond with a message
  • #update immediately update the original message (buttons, select menus)
  • #showModal immediately show a modal (cannot be deferred)
  • #deferReply/Update respond later (up to 15 minutes)
  • #followUp post an additional message

The initial response has to happen within 3s of receiving the interaction!

clear garnet
wintry laurel

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?

clear garnet

Correct

wintry laurel

thank you

gusty glacier

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?

clear garnet

You'd want to first add a label to the modal, which you can then add a select menu inside of

sharp ginkgoBOT
loud quartz
subtle girder

Will using mp3 files as audio resources and having them converted by ffmpeg cause the audio playback to stutter or become inconsistent?

bleak owl

that’s not really a discord.js question

compact gorge

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)

bleak owl

that’s not really a d.js issue either

wintry laurel

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

crude mist

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

topaz bluff
wintry laurel

kinda weird why you cant defer those

i wonder why

oh i guess its probably the same as .launchActivity

clear garnet

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"

wintry laurel
wintry laurel
clear garnet 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

rose tangle

it really depends on what you're doing but the stuff that is heavy is probably inferrable

wintry laurel

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

rose tangle

eg if you were to do big calculations like the 1000000th fibonacci number, technically a sync operation but yeah

rose tangle

well db calls might need a defer if they're over a network or goes through fs, which is generally what a db does

wintry laurel
rose tangle

what is "internal communication"?

wintry laurel

like same network, so all the traffic stays inside their servers

rose tangle

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

wintry laurel

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

crude mist

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?

rose tangle

you mean deploy commands with a call?

sharp ginkgoBOT

guide suggestion for @crude mist:
guide Registering Commands
For fully functional slash commands, you need three important pieces of code:...

warm charm

💀 jst read guide bro

rose tangle

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

crude mist
rose tangle

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

wintry laurel

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

rose tangle

djs only serves to interact with the discord api

crude mist

I think they do have an api for the slash commadns then

rose tangle

yeah you can retrieve the commands that are in discord

sharp ginkgoBOT
crude mist

meh too complicated for my first day i'll deal with that later

thanks tho

odd stirrup

i think it sometimes happens to me too

rose tangle

its like impossible for me to respond to it faster
defer before unarchive?

wintry laurel
wintry laurel
odd stirrup

this particular command you mean?

wintry laurel

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?

odd stirrup

you could console.time everything up until the interaction.reply or whatever, see if it ever spikes above 3s

wintry laurel
odd stirrup
wintry laurel

maybe making changes to a thread if theres tons of active ones takes longer

odd stirrup

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

rose tangle
wintry laurel

yea true but again like this happens pretty rarly and has just started happening again more so

odd stirrup

well best u can do is probably console.time it to isolate the problem

rose tangle

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

wintry laurel

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

odd stirrup
odd stirrup

tho it could be a little annoying since you have to actually check the logs

wintry laurel

ehh thats not to bad

i want this error gone so

odd stirrup

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

wintry laurel

to much work

odd stirrup

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

wintry laurel

ok i just archvied 600 active thread and added that so hopefully that fixes it

valid rock

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?

ruby bane

instead of using the pound sign, just use 0x
#ffffff -> 0xffffff

odd stirrup

^ outside of a string

so .setAccentColor(0xffffff)

valid rock

aaa thanks guys thats really helpful

odd stirrup

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))

solar furnace
    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(`![vfmsno](https://cdn.discordapp.com/emojis/1211980350813773885.webp?size=128 "vfmsno") **@${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

odd stirrup
solar furnace

ah i used that syntax from the guide directly

but it did look unusual

ruby bane

you need to check if role.name is equal to them individually
so role.name === ... || role.name === ...

odd stirrup

your best option is to have an array of role names, and check in your .some myArray.contains(role.name)

solar furnace

alright, so for example ((role: {name: string;}) => role.name === "X" || role.name === "Y") would work?

odd stirrup

yes

solar furnace
odd stirrup
ruby bane

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

odd stirrup
valid rock

question, can you do like setImage() with the ContainerBuilder()? or is that not an option

solar furnace
odd stirrup
solar furnace

if a role changed i'd be the one changing it

odd stirrup

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

solar furnace

alright, got it
ty for the help! :D

odd stirrup
valid rock
odd stirrup

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

valid rock
odd stirrup
valid rock
odd stirrup

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)

valid rock
odd stirrup

i do still love components v2 tho

odd stirrup
solar furnace
odd stirrup well just be careful then, if you forget to update the bot in the future then th...

hi, it's me again, sorry!

 
    if (!interaction.member.roles.cache.some((role: Role) => authLevels.disciplineAndStandards.includes(role.name))) {
        await interaction.editReply(`![vfmsno](https://cdn.discordapp.com/emojis/1211980350813773885.webp?size=128 "vfmsno") **@${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

odd stirrup
solar furnace
odd stirrup

hmm

hmmm im not sure what there would be causing the problem

solar furnace

all good haha

odd stirrup

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?

solar furnace
odd stirrup

shouldnt be possible

odd stirrup

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
warm charm

its better than using role name

solar furnace

ah no that's not how it is, it's all in execute()

odd stirrup
odd stirrup
warm charm

im thinking about array, if the func return string, not array

odd stirrup

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

solar furnace

my execute() is asyc yeah

odd stirrup

everything inside will still run sync tho

solar furnace
odd stirrup

it is 1:20am i should probably sleep lmao

solar furnace

oh boy sorry lmaoo

odd stirrup
solar furnace

ty

odd stirrup
solar furnace

lool fair

i cant really talk im known to be up atthese times too lmao

steel trail
patent epoch

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],
        });
    },
};```
rose tangle

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 the join variable

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'

patent epoch

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?

rose tangle

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

patent epoch

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?

cobalt plover

why does my bot receive MESSAGE_UPDATE events for messages that have not even been updated?

rose tangle

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

patent epoch

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

rose tangle

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

cobalt plover
rose tangle for instance?

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

rose tangle

is it a regular message?

cobalt plover

it's a webhook embed

rose tangle

sent by your bot, or?

cobalt plover

no, that webhook is executed by a game and it doesnt belong to my bot

steel trail

Also if discord adds embeds to the message after it was sent (if the message contains a link for example)

patent epoch

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? 🤔

warm charm

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!`);
            }
halcyon bison
halcyon bison
patent epoch

thx 🙂

tiny blade

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

crimson gale

you have a section without an accessory

tiny blade

thanks

flint pier

editReply cant delede with timeout?

polar karma

You want to delete a message after a certain amount of time?

subtle girder

why return interaction.editReply({ embeds: [embed], flags: MessageFlags.Ephemeral });
won't reply user ephemerally?

also same as return await interaction.editReply({...})

unique shoal

Yeah edit doesn't accept ephem, the original message or defer sets the state

signal pumice
low spear

if I had a channel with say months old messages, could I fetch the last 100 even if theyre >2 weeks old?

loud quartz

You can fetch any messages

flint pier
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

tardy sable

you have to place your string select in another labelbuilder

flint pier
tardy sable
flint pier
sharp ginkgoBOT

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

flint pier
flint pier
tardy sable
flint pier
Timeout duration was set to 1.
(Use `node --trace-warnings ...` to show where the warning was created)```What kind of error is this?
tardy sable
fallow finch

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

loud quartz

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

fallow finch

Oh probably, because my local development uses node v20 and production build uses v24 so I never saw this error on local development

tribal birch

can we use dokploy for djs

velvet cipher
tribal birch
velvet cipher
tribal birch
velvet cipher
outer plume
tribal birch
outer plume

If yes, then it can run a discord bot written with djs

velvet cipher
tribal birch
outer plume
loud quartz

Can it run it forever

Not just for 5 minutes after an http request to wake it up

tribal birch
loud quartz

Yes

velvet cipher

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.

topaz bluff

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

loud quartz

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

topaz bluff

What's it, 200 allowed logins a day?

loud quartz

1000

topaz bluff

Oh I'm thinking of commands

That sounds better

outer plume
loud quartz

No

outer plume

Oh the discord limit. I thought smth else

past spear

Can I show users with a specific role in the user select menu?

polar karma

No, there's no functionality for that

lavish surge

Is it currently possible in forum channels to only allow the creator of the post to talk in their own post?

lavish surge

Thank you!

red coral

Theres a permission for fetching audit logs right? Do you need that permission to recieve the gateway event?

loud quartz

do the dapi docs for the event say anything about that?

reef wave

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?

topaz bluff

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

reef wave

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?

loud quartz

depends however your database adapter decides to handle such numbers

reef wave

Yeah okay, thanks, it should work then

velvet cipher

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

reef wave

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.

velvet cipher

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

loud quartz
red coral
odd stirrup

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

reef wave
odd stirrup

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

reef wave

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 🙂

crude mist

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

clear garnet

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

crude mist

so before it then

ruby bane

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

crude mist

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

tardy sable
formal sail

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.

clear garnet

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

formal sail

i found the culprit

sorry about that

odd stirrup

whats the difference?

stable sun
odd stirrup

how would the guild not be cached?

stable sun

Bot was added for commands only

odd stirrup

is that possible without manually customizing the caches

odd stirrup
stable sun

Both actually

odd stirrup

hmmmm i feel like i can assume both are invalid installations

stable sun

Well, I don’t think the former is a thing anymore

Pretty sure application.commands now implies bot scope

odd stirrup

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

topaz bluff
stable sun

Oh

odd stirrup

yea i recall that previously application.commands was part of bot, and they added application.commands retroactively to anything that had bot

topaz bluff

bot is required for an application to have membership in a guild... but all bots have the ability to manage commands

stable sun

Stuff that doesn’t need to be in the guild like d.js docs bot doesn’t need the bot scope

odd stirrup

like without user installation, can i safely assume that itll always be cached

topaz bluff

if you are only guild installed and only allow commands in a guild (no dms), then it should always be from a cached guild

odd stirrup

hmmmm dms might be tough

stable sun

It depends on how you want it to look in ur handler

odd stirrup

less assumptions to make

topaz bluff

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

odd stirrup

my problem is just about negotiating with typescript

topaz bluff

for guild only commands, i would just typecast it in your execute function

odd stirrup

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

odd stirrup

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

finite zealot

Can we develop discord voice agent bot?

finite zealot
proud arrow
ripe topaz

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?

halcyon bison
ripe topaz

that's very annoying but alright

patent epoch

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],
        });```
drowsy plinth

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?

stable sun
  1. You receive an interaction from interaction create (whether it’s from a button press, slash command, etc),
  2. You check its data and branch accordingly (e.g. isButton(), .isChatInputCommand(), .customId, .commandName)
  3. You reply to interaction

This should happen for every interaction that you receive

stable sun
drowsy plinth

14.25.1

stable sun

Are you redefining client fields by chance?

Specifically client.voice

drowsy plinth
patent epoch

I also don't understand how the counter is actually working - since it should be reset to 0 each time not? (It's not)

stable sun
patent epoch

Nvm, it's actually just working, hmm

stable sun

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

patent epoch

ah yeah 🙂 just experimenting a bit as I'm learning

drowsy plinth

I’ve been stuck on this since yesterday and couldn’t figure it out at all.

stable sun

Yea, that’s why I don’t recommend sticking stuff to things you didn’t make

past spear

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

sharp ginkgoBOT
past spear
const candidate = interaction.fields.getSelectedUsers('candidate_select')```

like this?
stable sun
past spear
stable sun

Select menus may have multiple users selected, if you haven’t limited it

past spear

I'm aware

stable sun

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

past spear

I called it that because there really is only one user at most

warm charm

hi, how i can check channel type

sharp ginkgoBOT
cobalt solstice

<Channel>.type

warm charm

alr ty

btw how i can check the channel is rule channel or not

sharp ginkgoBOT
crimson gale

compare its id to ^

warm charm

oh, i need to fetch the rule channel and compare it, right?

crimson gale

what are you trying to do?

warm charm
crimson gale
warm charm

alr ty

brisk lynx

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'],
                    },
                ],
            });```
tardy sable
brisk lynx

How can I set the category where those channels are created as default?

tardy sable
brisk lynx

Ok, thanks.

tardy sable

that category must have already the view channel permission tho. so that might not be ideal for your use case

past spear

how many select menus I can add to my modal?

wary coral
livid kettle

Any chance we might ever see autocomplete components in modals?

topaz bluff

Doubtfully

ripe topaz

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

sharp ginkgoBOT
fallow finch

The same property might exist on other interactions so look at the docs

ripe topaz

i am aware, yes, but that doesnt help me figure out a targeted user's locale

fallow finch

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

wary coral

you can get the locale for the guild

sharp ginkgoBOT
loud quartz

No, you cannot scan all guild members to target only spanish-using users

tardy sable

on getStringSelectValues() does it return empty array if nothing select or undefined?

loud quartz

What do the docs say it returns

dire iris

Is there a way to fetch a user tag?

like the guild tag

sharp ginkgoBOT
rose tangle

there's also other data there you can check

primary guild is how discord calls the tag feature pretty much

dire iris

alright, thank you :)

dire iris

guildMemberUpdate?

rose tangle

I think userUpdate since it's on the user

dire iris

okay ty

tiny condor
loud quartz

Because discord sends all that via gmu, and we separate it out basing on what changed

tiny condor

whats the difference between userupdate and guildmemberupdate again?

tiny condor
dire iris
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

tiny condor

the old primary guild maybe null sometimes don't use that to validate

dire iris

Thank you @tiny condor and @rose tangle, I've finally got it working :)

dire iris

Now- does anyone know how to check if a server has a tag or not? crySparkle

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.

tardy sable

you can only check if guild has the feature to set tags in guild.features

dire iris

ahh damn okay

ripe topaz

How do I edit a role's permissions?

sharp ginkgoBOT

documentation suggestion for @ripe topaz:
method 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);

ripe topaz

thanks

civic jungle

is it possible to send a new message on button interaction, without replying?

loud quartz

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

civic jungle

is it possible to make an invisible reply

loud quartz

you can respond ephemerally, yes

civic jungle

that means only user who interacted can see that message?

loud quartz

yes

civic jungle

but i dont want that

like im converting my app from eris.js to discord.js
in eris I had something like interaction.acknowlege()

loud quartz

if that does what i think it does, that has been defunct in API for years

wary coral
civic jungle but i dont want that

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

civic jungle

people just got used to it, its been 8 years since its like that

wary coral

so user press the button and a new message is sent in channel?

civic jungle

exactly, without any error

wary coral

you should use reply then
-# if async use deferReply then editReply once ready to send

civic jungle

when i do that in discord.js i got interaction failed, but message is sent though

proud arrow

That's most likely doing deferUpdate then not following up on that. Though that's bad practice to do it

civic jungle

dang it

loud quartz

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

civic jungle

so, since interactions are available only for 15 minutes, i have to manually clear components from a message?

tardy sable
bleak owl

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

civic jungle
loud quartz

pressing a button creates a new interaction

tardy sable
loud quartz

which has its own 3 second reply time, and eventual 15 minute limit

civic jungle

I think I understand now, thx

very helpful community
didn't expect that

azure forge

How to make this pingable slash command?

azure forge
rustic willow

not work select menus in embed it s out embed

@14.17.3

i want like this select menus

sharp ginkgoBOT

guide suggestion for @rustic willow:
guide Display Components
While you might be familiar with embeds in Discord, there are more ways to style and format your apps messages using display components, a comprehensive set of layout and content elements. To use the display components, you need to pass the IsComponentsV2 message flag (in docs: MessageFlags) when sending a message. You only need to use this flag when sending a message using the display components system, not when deferring interaction responses.

rustic willow

thx work <3

tardy sable

this channel is for asking help, dont just send invites here

sharp ginkgoBOT

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
loud quartz
severe pumice

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)

loud quartz

Well, presumably how you create event listeners

severe pumice

whats confusing though is that this just started happening, it has not happened before now

loud quartz

Something has had to change

Not necessarily directly in your own code

severe pumice

alrighty wasnt sure what i should look for thanks!

leaden wadi

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)

rose tangle

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

leaden wadi

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

leaden wadi
leaden wadi

you can see that this works but if there is an audio uploaded with the message it does not work @rose tangle

velvet cipher

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.

warm charm

hi, how i can fetch the discord channel comm log

Error handling component "confirm": DiscordAPIError[50074]: Cannot delete a channel required for community servers

rose tangle

do you want to fetch or delete?

you say you want to fetch, but your error says you tried to delete

warm charm
rose tangle

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?

warm charm

this one

warm charm
rose tangle

it will delete what?

warm charm

the channel

rose tangle

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?

warm charm
rose tangle

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?

warm charm

yes

rose tangle

I think it's the publicUpdatesChannel

sharp ginkgoBOT
rose tangle

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

sharp ginkgoBOT
rose tangle

that checks whether it's protected and you have enough perms

warm charm

alr imma try that, ty

serene robin

Does anyone know if it is better to use .addUserOption or .addMentionableOption?

unique shoal

What do you want it to accept?

Users, or all mentionables?

There is no "better", it depends what you want it to do

serene robin
unique shoal

So use a user option

Why would you use mentionable and include roles?

serene robin
unique shoal

You want it to only accept users - use the user option

balmy kraken

can webhooks use display components?

stable sun

Yes

They just have to enable withComponents

odd stirrup
patent epoch

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

loud quartz

Mention them

cobalt pendant
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)
patent epoch
wary coral
cobalt pendant

oh i forgot 😭 thank you

azure forge

Does codeblock in embed message (footer) works?

steel trail

No

azure forge

I can't react to messages here but thanks 👍

dire iris

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?

sharp ginkgoBOT
dire iris

ty

dire iris
  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?

fresh condor

what is guild ?

dire iris
polar karma

d.js version?

dire iris

Oh I see 😭 my d.js didnt updatee lol

fresh condor

what is your current version

dire iris

14.14.1

rose tangle

yeah you need at least 14.23, ideally latest

dire iris
rose tangle

I'd advise just updating manually

dire iris

alright thank you- it works

dire iris
steel trail

auto with no issues
And yet you talk about an issue with it meguFace

barren prawn

did discord add frame decoration url yet? like get the gif url or something for users frame

sharp ginkgoBOT
noble turtle

Is there an easy way to see who deleted or created a channel?

tardy sable
noble turtle

So I have to fetch audit log entries?

tardy sable

there is no other way i think

tardy sable
sharp ginkgoBOT

method 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);

noble turtle

Uh, none of those shows up in autocomplete after client.

(Yes, it's an instance of the Client class)

tardy sable

can you show your code

noble turtle

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, });

tardy sable

yes and then?

steel trail

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.

noble turtle

Then I try doing client.channelUpdate but it's not a member of the class

steel trail

client.on('channelUpdate', ...)

noble turtle

Oh

spice iris

or use
client.on(Events.ChannelUpdate, .....)

tiny condor

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

rose tangle

that depends on your intents and partials

tiny condor
tiny condor

Well crySparkle

proud arrow
tiny condor Well <:crySparkle:1257817748218708070>

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

tiny condor

I know, I listen to both

So there is no thing about member update events not firing sometimes

proud arrow
tiny condor

I don't use old member either

tawny roost

Hello 👋 ~~ I keep getting this error… Error and the related code is in the picture

sharp ginkgoBOT

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
tawny roost

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?

tardy sable
tawny roost
verbal plinth

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?

loud quartz

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

verbal plinth
verbal plinth
loud quartz
verbal plinth

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.

loud quartz

what did you get ratelimit on

or rather, the RateLimitError

verbal plinth

on POST /guilds/234/channels

loud quartz

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

verbal plinth
loud quartz

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

serene robin

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;
            }
        }
    }
}```
loud quartz

and what about it doesn't work

serene robin

There is no reply and my message doesn't delete. Nothing in the console also.

loud quartz

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

serene robin
loud quartz

yeah

serene robin
loud quartz

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

tardy sable

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

loud quartz

as its name and what you call it on would suggest, yes

tardy sable

ok thanks and what exactly is dispose? the doc doesnt make it clear for me

loud quartz

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

tardy sable

oh okay i see

serene robin
loud quartz

did you enable the intents?

serene robin

yes

loud quartz

is the bot in the server and does it have permissions to see messages in the channel you're sending messages in?

serene robin

yes it has administrator

loud quartz

how are you registering the events

serene robin
loud quartz

if you put a log as the first line in the event, before any ifs, does it log at all?

loud quartz

well, then log the content to see why your if doesn't work

serene robin
loud quartz

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

serene robin
sharp ginkgoBOT

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
serene robin

i dont understand

bleak owl

which part?

serene robin

would it be true or false in my situation?

loud quartz

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

serene robin
loud quartz

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

serene robin

how would i do that?

loud quartz

by using console.log() and putting inside what you want to log

did you write that code at all

serene robin

so like console.log(message.content)?

loud quartz

yes

serene robin
loud quartz

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

serene robin

ok

serene robin
tiny condor

because you don't even know how to log

loud quartz
  1. you're using if blocks without any understanding how they work. specifically, you cannot even tell what an already written if actually does
  2. you have no idea how to log
  3. you continuously ask if you should add code in blocks you already know that don't run
  4. you asked how to check permission despite doing it 3 times in the code you sent
serene robin

oh alr

loud quartz
serene robin

is my understanding not solid?

loud quartz

it's really not enough

anyway

i'm done here

i tried enough

solar furnace

hi any idea why interaction.member.username is returning undefined?

ruby bane
serene robin
jagged rock

whats the best way to auto translate replys to other languages

loud quartz

writing the code that does it

ruby bane

an external api

loud quartz

it's not related to discord.js, that's for sure

also machine translations will be shit

jagged rock
ruby bane

are you referring to the translations for commands because thats not the same thing

loud quartz

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

ruby bane

nor can you receive the translations from your bot and send them to users in other languages

jagged rock

so jsut use json fules then

loud quartz

how you store and pass the translations is up to you

ruby bane

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

serene robin
loud quartz

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

ruby bane

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)

serene robin

i see

serene robin

does anyone know how hide slash commands from people without certain permissions?

sharp ginkgoBOT
rose tangle

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

serene robin

k

proud shoal

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.

coral maple

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

novel mauve

you need to pass with_components=true to the url

coral maple
novel mauve

yes

wary coral
sharp ginkgoBOT

documentation suggestion for @coral maple:
discord 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.

gleaming radish

in the editMe method, if a bot restarted, do I need to re-run the editMe or it's persistent?

snow onyx

it persists

gleaming radish
sleek mural

Is there a way to see who removed reactions from a message? Like remove other people's not their own

sharp ginkgoBOT
wary coral

ohh I have know idea not realy a djs question. best to ask on DDevs

cobalt valley

is it possible to change bot's avatar and banner per guild not globally in discord.js?

sharp ginkgoBOT
jolly radish

TypeError: Cannot read properties of undefined (reading 'displayAvatarURL')

Why do I get such error from the GuildMember? A GuildMember no longer has displayAvatarURL?

bleak owl

can you show your code?

woeful hamlet

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?

bleak owl

correct

jolly radish
bleak owl can you show your code?
   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

bleak owl

are you sure? did you try logging them?

jolly radish

yeah I did

strange turret

quick question : /avatar <image> these commands for per guild personalization do call discord api?

bleak owl

what?

strange turret
bleak owl

i dont understand you

wary coral
strange turret
bleak owl i dont understand you

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?

jolly radish
wary coral could you share the full error stack

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)```
bleak owl
strange turret

quick question...

woeful hamlet
bleak owl
strange turret

so how i do it?

bleak owl

i can't help with your web dashboard, that's something you need to figure out

sharp ginkgoBOT
jolly radish
strange turret

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

tiny condor

You wouldn't set it through commands, your API would run a method to set the profile

strange turret

you mean we cant through discord?

halcyon bison
jolly radish ```TypeError: Cannot read properties of undefined (reading 'displayAvatarURL')``...

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)

tiny condor

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

jolly radish
halcyon bison
strange turret

if bot restart, it will read db and will set auto

tiny condor

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

strange turret

restart...?

tiny condor
jolly radish
tiny condor
halcyon bison
jolly radish

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?

strange turret
halcyon bison
woeful hamlet
tiny condor
jolly radish

So I should basically instead of the GuildMember send the url instantly

strange turret
woeful hamlet
jolly radish

oh and the user username, I will also pass that with a list for each user so the list contains the id and image

tiny condor

if all you need is the username and image and id, don't pass the entire guildmember

jolly radish

Okay! Thank you all!

strange turret
sharp ginkgoBOT
tiny condor

^^ 3 times

topaz bluff

From a website is an OAuth process...and DJS doesn't handle oauth... Just gateway routes

strange turret

what you trynna say ahm..

ivory valve

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?

tiny condor

You need to authenticate the user on your website dashboard, then send an api request to your bot's code to update the profile

tiny condor
strange turret
tiny condor

So then what is the question here?

ivory valve
tiny condor

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

proud arrow

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

ivory valve

So ideally, I would need a backend with a bot running to execute these kinds of requests?

tiny condor

Of course

ivory valve

Thanks!

strange turret

"You are changing your avatar too fast. Try again later"
How much laterr...

tiny condor

How many times did you change it? smile

strange turret

2

topaz bluff
red coral

Doesn’t that one error with the time it’ll reset?

strange turret

"[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

rose tangle

can you show your code?

strange turret

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