#djs-help-v14

78874 messages · Page 50 of 79

tardy sable

i think that depends on when you see the bot slowing down

low hamlet

iirc sharding is only really needed around 2k, so start thinking about it around 1k

kindred moon

you can't

wary coral
pine laurel

how would i go about implementing reaction roles?

wary coral
zealous marten

hmmmmm

yes onboarding is the best option

pine laurel
rose tangle

you've described what you need though? I'm not sure where you're confused

pine laurel

i dont know how to actually do it

rose tangle

you already know the steps so you know where to start

do you know how to make commands?

how to create and start a client?

pine laurel

yeah

tardy sable
rose tangle

then describe exactly where you're confused

because it sounds like you know already what to do

at the very least you know how to make the command

zealous marten

send snippets

rose tangle
sharp ginkgoBOT
pine laurel

how to assign the roles, idk what listener to use, like interactioncreate etc, and also dont know how to use partials

tardy sable
sharp ginkgoBOT

documentation suggestion for @pine laurel:
method GuildMemberRoleManager#add() discord.js@14.23.2
Adds a role (or multiple roles) to the member.Uses the idempotent PUT route for singular roles, otherwise PATCHes the underlying guild member

rose tangle

you get that manager via GuildMember#roles

sharp ginkgoBOT
rose tangle

use that to listen to reactions

sharp ginkgoBOT

guide Partials
Partial Structures were introduced to the library in version 12 and are optionally received whenever there is insufficient data to emit the client event with a fully intact discord.js structure. They are (as the name suggests) incomplete, and you cannot expect them to have any information besides...
read more

rose tangle

and there's the guide for partials

pine laurel

thank you

rose tangle

I'm not sure with what they'd be auto populated in the first place though

pine laurel

@tardy sable do you mean like this?

sharp ginkgoBOT

guide MessageSelectMenu

  • MessageSelectMenu has been renamed to StringSelectMenuBuilder - StringSelectMenuBuilder#addOption() has been removed. Use StringSelectMenuBuilder#addOptions() instead.
    read more
pine laurel

i may have misunderstood your question but im not sure @tardy sable

zealous marten

addOptions would do

native marten

Yo guyz what's going on?

tardy sable

now im just limited to one with setDefault(true) on string selects

rose tangle

you don't populate them though, that's why they're auto populated

rose tangle
zealous marten

its not possible with string select menu

native marten

.setMin(value)
.setMax(value)

tardy sable
rose tangle

it's possible to marking many options as selected by default, like I said just make sure your select menu allows multiple selected values in the first place

tardy sable

specifically i mean an .setDefaultUsers([""]) (example) equivalent for string selects

sharp ginkgoBOT
tardy sable

yh only limited to mark one. hope they add multiple like for channels and roles etc

wary coral

Then you set the option is true for multiple

rose tangle

I'm not sure why you're not reading what I'm saying though

native marten

In simple you want to show multiple roles in menu field as a default value?

rose tangle

the default selected options are stored at the option itself, not on the select menu

tardy sable
rose tangle

only in auto populated menus they're stored in the select menu, because you don't specify any option

rose tangle
native marten

That gave me an idea.

tardy sable
rose tangle

I'm not sure what that has to do with the issue

in case you haven't noticed, it's a method on the option

not on the select menu

steel trail

You define that a value is a default

rose tangle

it wouldn't make sense for it to say setDefaults, because you're in a single option

tardy sable

let me just show example thats easier to explain

native marten

yeah please

tardy sable

im allowed to set multiples values as default?

modal.addLabelComponents(
    new LabelBuilder()
    .setLabel("Select an option")
    .setStringSelectMenuComponent(
        new StringSelectMenuBuilder()
        .setCustomId("options")
        .setMaxValues(3)
        .addOptions(
        new StringSelectMenuOptionBuilder()
            .setLabel("Text").setValue("text").setDefault(true),
        new StringSelectMenuOptionBuilder()
            .setLabel("Attachments").setValue("attachments").setDefault(true),
        new StringSelectMenuOptionBuilder()
            .setLabel("Stickers").setValue("stickers").setDefault(true)
        )
    )
)
rose tangle

correct

native marten

yes

tardy sable

ok thanks for clearing my confusion

lean sail

what does djs export that is the same as MappedEvents from the core package?

rose tangle

you mean ClientEvents?

lean sail
rose tangle

ah, I missunderstood the question, thought you meant the way around (what's the core equivalent of ClientEvents) lol

well that answered it anyways kek

tardy sable

best way to check if can start a thread on a message is by checking channel perms, or is there a message.threadable ?

or can i just use deletable for that?

brittle current

Can i use deffer with componentV2?

wary coral
brittle current

Thx

thin reef

why targetId is null when I fetch audit logs
AuditLog.MemberMove event

leaden shuttle

how do i add a string select to a modal?

cunning hinge
cunning hinge
leaden shuttle
bleak owl

yes

cunning hinge

yes

leaden shuttle

whats the max options in a string select menu?

golden laurel

25

leaden shuttle

ty

cunning hinge

would be nice having autocomplete interactions on string select menus, then you could effectively have infinite options

unique shoal

It would, but that is not a Discord feature

cunning hinge

indeed

unique shoal

It would likely be far more complicated as messages dont have a "live update" framework built in the way slash command choices do

Components are inherently very static

candid grove

Did the client.once("ready, () => {}) event get deprecated? What should I be using instead?

unique shoal

Events.ClientReady

cunning hinge

use clientReady

candid grove

Ah the docs just say use ClientEvents instead, but that is the type of every event.

cobalt valley

When is v15 coming? crySparkle

bleak owl

there is no v15 yet

unique shoal

Why do you think v15 would be coming

cunning hinge

what would v15 even ensue

unique shoal
candid grove

Only reason a v15 would be needed would be if there was a complete redo of the discord api like a discord api v11...

cobalt valley

Because of this

unique shoal

Thats not the only reason, but a good example of one

Those milestones dont really mean anything tbh

cobalt valley

😭👍🏻.

unique shoal

It also answers your question: No due date

candid grove

Ah yes a milestone of v15... that could be like... 4 years off.

cobalt valley

💀

candid grove

The % annoys me because if you have 100 tasks, you can compelte 99 small ones and it say you have 1% to go but the last task be the longest most challenging one... At least from my experience with how work uses them...

unique shoal
cosmic burrow

i just created my slash command and my slash command called: annoucement didn't showed up

bleak owl

does it show when you type / ?

cosmic burrow

yeah

bleak owl

then there's no issue. don't rely on that page. it doesn't update properly

cosmic burrow

module.exports = {
  data: new SlashCommandBuilder()
    .setName('annoucement')
    .setDescription('Create an annoucement embed')
    .addStringOption(option =>
        option
            .setName('title')
            .setDescription('Adds a title for your annoucement embed')
            .setRequired(true))
    .addStringOption(option =>
        option
            .setName('description')
            .setDescription('Adds a description for your annoucement embed')
            .setRequired(true))
    .addStringOption(option =>
        option
            .setName('color')
            .setDescription('Adds a hex color for your annoucement embed')
            .setRequired(true))
    .addStringOption(option =>
        option
            .setName('footer')
            .setDescription('Adds a footer for your annoucement embed')
            .setRequired(true))
    .addChannelOption(option =>
        option
            .setName('channel')
            .setDescription('The channel where the annoucement embed would send in')
            .setRequired(true)),
  async execute(interaction) {
      const title = interaction.option.getString('title');
      const description = interaction.option.getString('description');
      const color = interaction.option.getString('color');
      const footer = interaction.option.getString('footer');
      const channel = interaction.option.getChannel('channel');

      const annoucementEmbed = new EmbedBuilder()
          .setColor(color)
          .setTitle(title)
          .setDescription(description)
          .setColor(color)
          .setFooter(footer);

  await interaction.reply({ embeds: [annoucementEmbed] });
  },
};```

i type /annoucement nothing shows the command

bleak owl

what do you mean "nothing"

cosmic burrow
bleak owl

it's hard to help without knowing what "nothing" means in this context

stable sun

You have to spell announcement correctly in the command name

Or don’t. Just be consistent however you decide to spell it

Nvm, you edited message

tardy sable

does clicking a button inside an archived thread makes the thread automatically unarchived?

stable sun

Afaik, editing a message isn’t allowed in archived threads, but sending a message is and will unarchive it

red coral

If you use the editMe too often, you get

DiscordAPIError[50035]: Invalid Form Body
banner[BANNER_RATE_LIMIT]: You are changing your profile banner too fast. Try again later.

Is this intended to error, not just like a normal rate limit? Is this the same if you use like client.user.edit or whatever it is

stable sun
red coral

Yh that doesn’t feel right

hasty fern

Hey guys, how can I avoid that? I tried using escapeMarkdown() but it makes the text be ghost\_jonas\_ instead of just ghost_jonas_

For now I'm doing it like that:

return `${formatEmoji({ id: "1411365868964806758", name: "accounts" })} ${bold("Contas:")}\n` + data.accounts.map(account => `${formatEmoji({ id: "1411360326707839016", name: "steam" })} ${hyperlink(inlineCode(account.username), `https://steamcommunity.com/profiles/${account.id}`, `Acesse a página de perfil de ${account.username} na Steam`)}`).join("\n");

If you guys know a better way instead of using inlineCode() please ping me here

pearl roost

How do I receive the choosen Channel from ModalBuilder?

sharp ginkgoBOT

documentation suggestion for @hasty fern:
function escapeMarkdown discord.js@14.23.2
Escapes any Discord-flavored markdown in a string.

pearl roost

Nevermind, I found it getSelectedChannels

wary coral

Sorry I don't have any other answers. Right now

hasty fern

Ok, I'll keep it with inlineCode() for now then

wary coral
hasty fern <@287765319311687682> Read my message

just tested it and it worked on plain text will test with URL shortly

await interaction.reply({
      content: `${escapeMarkdown("ghost_jonas_")} instead of just ghost_jonas_\n${codeBlock(`${escapeMarkdown("ghost_jonas_")} instead of just ghost_jonas_`)}`,
});
orchid radish

can i use the same custom id for multiple buttons on the same message? i am facing a situation where i am going to have a list of minecraft names as buttons and i am unsure what the best way to approach it is.

i was thinking of temporarily storing the names and appending them to the data for one button file but im not sure yet

something like this?

wary coral
wary coral
orchid radish
wary coral

Fair enough, but it is not best practice to use the buttons label as stored information.

orchid radish
wary coral

Include the information in the custom ID and use a character such as - or _ to separate the data from your action for example
buttonid-buttondata

You can then use the string function split to separate the two strings

hasty fern
loud quartz

cc @wary coral

bitter glade

Are embeds smaller than component v2 containers by default? I have the same text, image, etc., but the container is noticeably larger.

loud quartz

Might have bit more padding here and there

zenith folio

Hi,
can .addFields be uset inside containers to have multiple texts inline?

steel trail

No. Containers aren't embeds and don't have a notion of fields

zenith folio

is there any other way to do this inside container?

loud quartz

if you want fields, use an embed

container doesn't have an equivalent of inline fields

zenith folio

ok thanks

ember nacelle

hello

where can i find the source from github i can't find it ?

crimson gale
ember nacelle

i want the final project source

crimson gale

the guide aims to explain concepts to you that you can freely apply to whatever code base you are working with
so if you read and understand it, it should be easy to apply
if you are struggling with something specific, you can always ask here

ember nacelle

ohhhhh ok thx

tough island

does djs support text display for modals?

loud quartz
zealous marten
red coral
zealous marten

oh kek

ig im outdated

heavy crow

in the new modal component, how could i get the value of channel select menu?

like somewhat similar to interaction.fields.getStringSelectValues()

sharp ginkgoBOT
steel trail

The docs have all your answers

lean sail

if im adding/removing a role from a member, will it check to see if the person already has/doesn't have the role before sending the request?

pure ridge

is there a way to get ActionRow from interaction.message.component or can I just get this with the index

[
  ContainerComponent {
    data: { type: 17, spoiler: false, id: 1, accent_color: 54008 },
    components: [
      [TextDisplayComponent],
      [SeparatorComponent],
      [TextDisplayComponent]
    ]
  },
  ActionRow {
    data: { type: 1, id: 5 },
    components: [ [ButtonComponent], [ButtonComponent], [ButtonComponent] ]
  }
]
steel trail
steel trail
pure ridge

yes .. found a way - thx for your response

simple glen

Hi everyone!
I’m a software developer with 8+ years in Next.js, Vue, Rust, Django, and AWS. I enjoy building scalable systems and collaborating with technical teams.
Looking forward to contributing here!

loud quartz
wooden carbon

Is there server only avatar for discord bots?

wooden carbon

The profile is trivial, but why look for collaboration in a random Discord server with a stranger?

wooden carbon
frosty dagger
simple glen

I am freelancer

wooden carbon

no way, a 8 exp guy go and beg for free lance, you sound like really immature.

wooden carbon

Is there server only avatar for discord bots?

Again, this is not a place, and you sound like chatgpt

and, don't expand this conversation anymore.

sharp ginkgoBOT
robust flame

why does RPC disappear after 24 hours?

limpid moss

how can i have more than one og the same options

        .addUserOption((option) =>
            option.setName('fighter1').setDescription('Fighter Number 1').setRequired(true),
        ),
        .addUserOption((option) =>
            option.setName('fighter2').setDescription('Fighter Number 2').setRequired(true),
        ),
loud quartz

if you mean presence status, then that's just due to how discord handles long running connections on their end

you can avoid that by setting the presence in the Client options

primal edge

why does my bot just randomly turn off?
it doesnt print any errors or anything. I am very confused.

loud quartz

turn off how?

primal edge

it just shuts off after a hour or so.
but, its still running in the console, no errors, anything.

loud quartz

by "shuts off" you mean it goes from statusOnline to statusOffline ?

primal edge

yes

and commands dont work, but, console still running

loud quartz

out of curiosity, is that cmd or powershell?

primal edge

git bash

looks good imo lol.

loud quartz

okay but, by default cmd/powershell pause execution when you start selecting text

primal edge

ye, this dont do that.

cosmic burrow

i registered 2 commands then why /announcement command didn't showed up?

loud quartz
sharp ginkgoBOT

Please add the following code to your code base outside of any other event listeners and provide the full log output relevant to your issue.

client
    .on("debug", console.log)
    .on("warn", console.log)
  • Note: if you initialize your Client as bot or other identifiers you need to use these instead of client
  • If the output is too long to post consider using a bin instead: gist | sourceb.in | hastebin
loud quartz
cosmic burrow
loud quartz

and what does that do

cosmic burrow

it registers commands

loud quartz

i thought it cooks food

how does it registers them

cosmic burrow
const { clientId, guildId, token } = require('./config.json');
const fs = require('node:fs');
const path = require('node:path');

const commands = [];
// Grab all the command folders from the commands directory you created earlier
const foldersPath = path.join(__dirname, 'commands');
const commandFolders = fs.readdirSync(foldersPath);

for (const folder of commandFolders) {
    // Grab all the command files from the commands directory you created earlier
    const commandsPath = path.join(foldersPath, folder);
    const commandFiles = fs.readdirSync(commandsPath).filter((file) => file.endsWith('.js'));
    // Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment
    for (const file of commandFiles) {
        const filePath = path.join(commandsPath, file);
        const command = require(filePath);
        if ('data' in command && 'execute' in command) {
            commands.push(command.data.toJSON());
        } else {
            console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
        }
    }
}

// Construct and prepare an instance of the REST module
const rest = new REST().setToken(token);

// and deploy your commands!
(async () => {
    try {
        console.log(`Started refreshing ${commands.length} application (/) commands.`);

        // The put method is used to fully refresh all commands in the guild with the current set
        const data = await rest.put(Routes.applicationCommands(clientId, guildId), { body: commands });

        rest.put(Routes.applicationCommands(clientId, guildId), { body: [] })

        console.log(`Successfully reloaded ${data.length} application (/) commands.`);
    } catch (error) {
        // And of course, make sure you catch and log any errors!
        console.error(error);
    }
})();```

using node deploy-commands.js

loud quartz

You're deploying the commands to a guild, right?

Is it this guild?

cosmic burrow
loud quartz

Could you log the commands in that script right before the rest.put() call to see what is actually being sent to discord?

cosmic burrow

ok

primal edge
primal edge

ah
didnt see that LMAO.

my bad lmao.

rustic seal

Hello, I have a quick question to ask you when I choose option 1 on the select menu, I have to choose option 2 to click on option 1 again. Is there a way to be able to click on the option without having to choose another one each time to select it?

loud quartz

Did you set your select to require at least one option?

rustic seal
tardy sable

if i do allowedMentions: { replied_user: true } it will only mention the replied user and nothing else right?

steel yacht

Hi,
What's the event for when a user is being timed out (isCommunicationsDisabled toggles from false to true) ?
Thanks

bleak owl

that would be the guildMemberUpdate event iirc

tardy sable
steel yacht

So, I've been trying, but it seems I can't find out how to trigger this event, I even tried changing nicknames too, without success... 🤔

bleak owl

you need the GuildMembers intent

steel yacht

Ah, intents.
I'm just gonna enable them all cause I always forget about them and I don't see the point of loosing time on a toggle 😂

It works, thanks !

There's no event when the time out ends though ?

snow onyx

correct

steel yacht

Well, I need to log messages when someone gets timed out and when the time out ends, how can I do the second one ?

I did notice there's an event when the time out is manually stopped before the scheduled end though, but that's not the majority situation

snow onyx

set a cron job on the duration and then log it, thats your only way

pure ridge

I may have overseen something, but how do I create input fields for modals now?

pure ridge
wary coral

Set label has moved to the label builder. It still exists on text input but is deprecated

pure ridge

thank you .. I will no change that

steel yacht
halcyon zephyr

Is it possible after initializing a WebhookClient to somehow check if this webhook URL is still valid?
const webhookClient = new WebhookClient({ url: 'https://discord.com/api/webhooks/id/token' });
trying to make sure it wasn't manually deleted by a user etc

bleak owl

you could use a regex, but i’m pretty sure an error will throw if the webhook is invalid

red coral
pure ridge

Is there now an option to get the user who has created a channel

tardy sable

for threads channels use ownerId

pure ridge

thx

tardy sable

does getTextInputValue auto trim()?

unique shoal

The function internal to discord.js does not - Discord might in what it sends you though.

steel yacht

Is there a better way for a bot to hyperlink a message than using https://discord.com/channels/${guildId}/${channelId}/${id} ?
Especially since this template string, for example, doesn't support threads, forums, and who-knows-what-else-they'll-create-next ?
Thanks

sharp ginkgoBOT
bleak owl

or

sharp ginkgoBOT
steel yacht
halcyon zephyr
wary coral
loud quartz
silent mirage

hey question is it possible to see who invited the bot to server

wary coral
unique shoal

Yeah, there is a BOT_ADD audit log type

wary coral
// Apps added in the last 45 days
const integrationCreateLogs = await guild?.fetchAuditLogs({type:AuditLogEvent.IntegrationCreate})
polar karma

Promise<...>

silent mirage
stable sun

Requires the read audit logs permission, of course

wary coral

How long does Discord store audit logs? bc I think the events "fall off"

wary coral
stable sun

It’s either 60 or 90 days. Can’t remember for too long

stable sun
wary coral

good to know thanks

zealous marten

how are the components inside the embedthinkLul

rose tangle

because that's not an embed, it's a container

zealous marten

oh nice thanks

sharp ginkgoBOT
rose tangle

dafuq

okay the link is correct, it just doesn't display any preview like before

primal edge
primal edge my bad lmao.

it was probably this.
i dont know.
i only got 1 shard lmao, so, ye.
might just remove this. no point in it rn.

topaz shoal

Hi guys, i want to implement a feature in my bot that gives users a role when they use my guild tag, the bot should auto update the role (add/remove) depending if they use it or not. Is that possible yet?

sharp ginkgoBOT
clear garnet

Yes

topaz shoal
old onyx

you can only set one child component per label right?

proud arrow

Correct

zealous marten

oh no

vivid iris

Are you able to make it so only select roles show up in role select menus?

golden laurel

No

dense latch
golden laurel
dense latch
golden laurel

There's no guide on how to use them, @discordjs/core is pretty easy (see the README.md). That's all you need to know.

For HTTP interactions, you'd need a way to respond to ping interactions validate security headers, which discord.js doesn't provide though. There's example code on Discord's documentation or discord-interactions (if you're not comfortable setting things up yourself, might recommend that)

dense latch

thanks for the help btw @golden laurel

echo anvil

Any of you writing tests for your bot ? If so, how do you do that ?

golden laurel
dense latch
dense latch

claude just told me I should stick with websockets cause the webhooks are too limited 😂

crimson gale

whelp, guess you cannot use webhooks then

red coral

Depends what you need, ofc you can’t get any events using the webhooks. If you only care about interactions then sure

A few of my util bots can be interaction only so I just stick them on a cf worker

thin reef

if the member wasn't cached, and GuildMemberUpdate has been fired
is it possible that the OldMember will not be accurate? answer is yes

chrome chasm

how do I get a user's bio? (or does discord api not read it?)

novel mauve

bios aren't exposed to bots

cloud nacelle

Did StringSelectMenu is supporter in Modal ?

little pebble
cloud nacelle
sharp ginkgoBOT
pearl roost

No embed preview? 😔

robust flame

how to disable context menu after inactivity?

rose tangle

what do you mean by "disable context menu"?

dense jackal
robust flame

I was wrong, not context, select menu

steel trail

Edit the message to not contain the menu anymore

rose tangle

or disable it

sharp ginkgoBOT
feral sierra

How to add status text on my bot’s profile (not presence)?

I saw some bots like Appy have a small text under their name on their profile (status like how discord accounts can set status that “+ Add Status” thingy).
I’m using Discord.js v14 and I know how to set presence/activity (Playing, Listening, etc.), but that’s not it, that im looking for.

How can I set that profile status text for my bot?
I checked docs and StackOverflow but couldn’t find anything, i asked chatgpt but it said bots cannot set custom status only activities, custom status only for user account not discord bot

steel yacht

Hi,
Regarding the guildUpdate event :

Emitted whenever a guild is updated - e.g. name change.
Is there an exhaustive list of situations ?
Thanks

winter oar

Is it correct that you can add Select Menus to modals now?
Can someone point me towards the updated documentation for it? I haven't found anything . Thanks

sharp ginkgoBOT
proud arrow

And so on...

tough island

slash commands support attachments right?

proud arrow

Yes

If you mean attachment option that is

tough island

yes

not available in modals yet afaik

sharp ginkgoBOT
wary coral
tough island

ty

steel yacht

In the emojiUpdate event, how to know whether the emoji image was updated ?
Thanks

polar karma

compare the old and new emoji objects for the imageURL()

steel yacht

emoji.imageURL() changes systematically ?

loud quartz

you can't change emote image

steel yacht

Oh, okay, what can be changed then ?

loud quartz

name

and roles that can use it

steel yacht
client.on(
    'channelUpdate',
    async (oldChannel, newChannel) => {
        if(!newChannel.inGuild()) return;
```Shouldn't `inGuild` be a thing here ?
hallow mesa

There's the inverse in isDMBased() or you can check whether it has a guildId

loud quartz

better question is if DM channels can even be updated

dense jackal
hallow mesa

While true, those can't have bots, right?

loud quartz

that can never have a bot in it

dense jackal

i thought bots could make gDM’s my bad

loud quartz

they might (which itself is also very annoying to do)

but still won't really be a part of it

it's wonky af

loud quartz

why what?

why do we have one property and not the other?

steel yacht

Yes

hallow mesa

Because it would be redundant

loud quartz

because the coin flip made us use this one and not the other

you can perfectly fine achieve the same thing with it

steel yacht
hallow mesa

🤷 doesn't seem like it really matters

steel yacht

Also funny how one is prefixed is and the other one isn't

loud quartz

the second one isn't on a channel, is it

interaction would never be a guild

steel yacht
loud quartz

so wouldn't make sense to be interaction.isGuild()

and a direct DM check on a channel makes more sense because it's DMs that have less stuff in it

also

steel yacht
loud quartz

i believe there's a reason to this

if you look at this:

the ises are checking what it actually is

while the inses check where it is

steel yacht

ises should remain unchanged and ins should be renamed isIn.

loud quartz

channel has only the thing checks

steel yacht

Clean code.

loud quartz

that has like, nothing to do with it whatsoever

i explained why

your reasoning is not really relevant

steel yacht

Yes, this is totally valid :

the ises are checking what it actually is
while the inses check where it is
But the latter should still be isIn rather than is.
is = what it is, isIn = where it is.
In all cases, is because it's a boolean.

loud quartz

we're not going to break this for the sake of semantics

bronze dew

Is there a limit for .addStringOption inside the SlashCommandBuilder?

bleak owl

what type of limit are you referring to?

bronze dew

Of options to add to an CommandBuilder like string, user, bool etc. but it seems to be 25

lone eagle

what are the d.js methods for new modify current member endpoint

sharp ginkgoBOT
lone eagle
sharp ginkgoBOT

discord Guild Resource - Modify Current Member
read more

wary coral

you will need CHANGE_NICKNAME Permission

zealous bison

what is the best way to send messages on a channel if i only have the id, possibly not in the cache, and without having to make a request just to paste an instance of BaseChannel?

red coral

If you have the id of the channel?

zealous bison

yes, i'm using this right now: ```js
return clients.discord.rest.post(
/channels/${channel_id}/messages,
{ body: payload /* RESTPostAPIChannelMessageJSONBody */ }
);

but i don't know how to parse `files` from `MessageCreateOptions`
zealous bison

yes, but the MessageCreateOptions.files can be ```js
readonly (
| BufferResolvable
| Stream
| JSONEncodable<APIAttachment>
| Attachment
| AttachmentBuilder
| AttachmentPayload
)[]

Is there any tool within discord.js that makes all of this automatic parse for RawFile?
red coral

djs doesn’t seem to have a like client.channels.send

zealous bison

yes, i miss this 😦

zealous bison
zealous bison
clear garnet

Yea, I think what you have now is the best method if you aren't fond of making a fetch request prior to sending it

wary coral

Out of curiosity are you validating that the channel is text when you get the id?

zealous bison
zealous bison
clear garnet

Scratch that, the target needs to be some d.js class, so I don't think that'd work for your use case after some quick thinking

zealous bison

yes, i tried this before sending message here

happily i ever use AttachmentBuilder for files, i'm trying to parse AttachmentBuilder => RawFile

clear garnet

You might still be able to use the static resolveFile() method on it though

zealous bison

i tried this, this is basically what <MessagePayload>.resolveFiles() do, but it seems that AttachmentBuilder is not compatible with fileLike, my typescript complained

red coral

Could .toJSON the builder

zealous bison

toJSON returns unknown 🥶

clear garnet

I'd just cast it. Based on how d.js uses it, passing an AttachmentBuilder instance should still work just fine

zealous bison

i believe that resolveFile really should receive an instance of AttachmentBuilder pepe_think

clear garnet

Yea, seems to just be missing in the typings is all

red coral

What does it mean for a select menu to be required? Oh nvm only for modals

crisp roost
crisp roost

i cant find it 😭

sharp ginkgoBOT
crisp roost

perfect, ty!

gleaming badger

is it possible to have select menus be able to let the user select multiple options instead of just one

unique shoal

yes, just set the min/max values

gleaming badger

oh ty

robust flame

why doesn't this work?

also emojicreate and delete doesn't work

sharp ginkgoBOT

To share long code snippets, use a service like gist, sourcebin, pastebin, or similar instead of posting them as large code blocks or files.

robust flame

ok sry

rose tangle

define "doesn't work"

does it error? does the event not emit?

plucky wind

are components in modals now supported?

vital raven

Yes

plucky wind

are there some examples available?

proud arrow
sharp ginkgoBOT

class LabelBuilder discord.js@14.23.2
A builder that creates API-compatible JSON data for labels.

plucky wind

thank you

rare verge

guys

thorny glen

I don't know how to do bot 😂😂

rare verge
thorny glen
rare verge

How to use Select Menu in Embed ?

stable sun

You can’t

You can put it in a Container tho

rare verge
thorny glen
stable sun
thorny glen
rare verge
sharp ginkgoBOT
rare verge
thorny glen
stable sun
thorny glen

ممكن تعلمني كيف أعمل بوت عشان أصير برمج محترف 🙂🥲 @rare verge

thorny glen
rare verge

Nice
Container Builder
It's new right?
@stable sun

thorny glen

Am I transparent and not see? @rare verge @stable sun

stable sun

Yea

thorny glen
stable sun

Display components are the new stuff Discord made

Well, before they released new modal components

thorny glen
rare verge
stable sun
stable sun
thorny glen
stable sun

Prob not

rare verge
stable sun

Every d.js video made becomes outdated by a year

rare verge

with s
+5

rare verge
stable sun

Maybe your friend that read the guide earlier can teach you

tough island

can you pause dms through the api?

tough island
wary coral
tough island
wary coral

Oh you want to edit the guild not the user settings. One sec I will see if I can find it

tough island

yes correct sorry if my wording was confusing

polar karma

I didn't see it in the guild feature, figured it'd be there if it was documented because that's where the pause invites is

tough island

wonder how that bot managed to do it

wary coral

undocumented does not mean inaccessible. But it does mean that DJs will not support it. You would need to do the work to find it and edit it with raw rest requests

tough island

hmm i guess i’ll just add that bot then thank you for the help

novel mauve
sharp ginkgoBOT
proud arrow

It does yeah

tardy sable

can i use cache for getting all active threads instead of using fetchActiveThreads()?

steel yacht

Hi,
Does (CommandInteraction | MessageComponentInteraction).deleteReply() throw Unknown message when an ephemeral message is deleted by the user before the bot deletes it ?
Thanks

proud arrow

Yes

steel yacht

Is there a way to check whether the message is deleted before trying to delete it ?

proud arrow

No, you'll have to catch the rejection

balmy kraken

does current djs fully support components v2?

hallow mesa
silent mirage
tough island
bleak owl
dapper cave

you can now upload files in modals??

topaz bluff

SoonTM

the endpoints are still locked down to staff/testers

dapper cave
sharp ginkgoBOT

class ContainerBuilder discord.js@14.23.2
A builder that creates API-compatible JSON data for a container.

topaz bluff

@rare verge can you please use hide:true or #app-commands for personal usage of the bot?

topaz bluff

np just heads up

rare verge
dapper cave
honest lavaBOT
bleak owl

there's already a PR

dapper cave

bru

time to check if what he did is the same as me

loud quartz

prob not

dapper cave

almost the same

drifting crown

hi, how can i add this to my bot's description?

elfin scroll
shut musk

Modals can only be sent to a user from a click of a button right? not via any link or so

unique shoal

Or slash command, but yes

Interaction responses only

shut musk

Gotcha

celest coral

Bots cannot read messages in a Group DM can they? Would be useful for Guild Application Interview Archiving

halcyon bison
wary coral
halcyon bison

I was under the impression they couldn't be added to a gdm

celest coral
unique shoal
halcyon bison
wary coral

never mind then. I must be mis rembering the command context as adding the bot to the gdm

celest coral
unique shoal

That doesnt mean theyre going to document it, if its not a feature they intend to make available to applications

Also unsure how Apply to Join related to group DMs?

halcyon bison

and beyond that I also believe they don't do ETAs anyways

celest coral

ETA as in, from your experience

halcyon bison

it varies
some things take years
some things take weeks

unique shoal

Yeah its essentially impossible to tell.

loud quartz

(which is wonky af, but that's besides)

celest coral
unique shoal

Some stuff is just surprise documentation we didnt know about. Some stuff is documented after the fact within weeks to months. Some stuff is never documented

We havent heard that Discord have any intention to give applications access to this feature, so it might be a "never"

celest coral

Ohh alright, thanks!

I wasnt too sure, only just recently got back to discord applications

unique shoal

Yeah fair enough

We're very much at the whims of what Discord decides to do on any given day lol

celest coral

Maybe going back to letting everyone in and handling applications in the server is the most safe approach

unique shoal

Given the recent enhancements to Modals you could probably build a pretty mature workflow on your own now

celest coral

Yes I saw, especially the Text Display and Containers are very interesting

Last time i really put in work into discord apps was well before interactions and similar things were a thing
Thanks for the info everyone

visual tusk

I'm having an odd issue deploying commands...for some reason, deploying guild commands simply hangs:

await rest
        .put(Routes.applicationGuildCommands(clientId, guild), {
          body: pcommands,
        })
        .then(() => {
          console.info(`Synced commands to ${guild} successfully.`);
        })
        .catch((err) => console.error(err));

I tried setting the timeout on the rest client lower, but it never completes or catches. Never had trouble before...

if it's a bad command definition I usually get an error back lol

polar karma

if you're doing it too often, you're rate limited

visual tusk

Ah...I see it now. I broke on debugging and it's indeed in discordjs's sleep(), with the stacktrace pointing twoards the ratelimit handler.

signal gulch

I doubt its a djs thing specifically but i wanna make sure, is ther eanything that happens almost EXACTLY after a bot has been up for 8 hours that DJS does? Asking since after i updated my DJS to newest version, its been crashing every 8 hours from startup, consistantly

unique shoal

no, nothing specific

signal gulch

Damn, okay thanks

radiant epoch

Does Label builder support attachments too?

bleak owl

the modal attachments have not been added to d.js yet at this time

radiant epoch

Alright, thanks Jö.

pearl roost

We cannot select forum channel from ChannelSelectMenuBuilder?

stable sun
pearl roost
stable sun

Discord api calls it a thread

You will not find PostChannel in Discord api docs (and thus neither d.js docs)

Never tried it tbh

pearl roost

Well somehow... The channel appear if I test it on my test server

Idk whats wrong

Is it because my main server had too many channel?

stable sun

Try copy pasting the thread channel id

pearl roost

Nope, it's not working

stable sun

Better off asking in ddevs tbh

Can’t be helped on d.js end

eternal drift

When using a role-select menu, am I able to only display specific roles, instead of all of them?

unique shoal

no

eternal drift

Shame. ty

balmy kraken

can i have emojis in components selector dropdown menus?

sharp ginkgoBOT
balmy kraken

how exactly do i use it?

<:emoji_name:emoji_id:> stringg format?

rose tangle

yeah that should work

visual copper

any guide to use the new modal?

sharp ginkgoBOT

class LabelBuilder discord.js@14.23.2
A builder that creates API-compatible JSON data for labels.

rose tangle

basically you can now add a label component, which can wrap a select menu with a label text and a description

see the LabelBuilder for all the label component methods

and you can also add a text display

sharp ginkgoBOT
balmy kraken

can i collect buttons and selection menus with one collector or must i make multiple?

steel trail

You can, assuming they are on the same message or at least in the same channel

grizzled notch

How can I do this? I don't see anywhere on guide where I can use attachments and options in a modal?

rose tangle

attachments were just released in the api roughly 12h ago

modal select menus were added in djs a while ago, but the guide doesn't have it yet

just see a few messages above for a quick answer

grizzled notch
balmy kraken
steel trail

No. Don't pass componentType if you don't want just one type

tacit nacelle

in the TextInputBuilder, why can't we set the value to an empty string?
it's throwing this error:
✖ Too small: expected string to have >=1 characters → at component.value
but using an empty space seems to work fine if you do something like this: .setValue(someValueThatCanBeUndefined || ' ')

brave moth

Maybe just don't set the value at all? :o

red coral

I mean that’s not empty that’s a space

tacit nacelle
brave moth

If you use setValue, you have to set a value. If you don't want to set a value, don't use setValue.

tacit nacelle

but I want to set a value... it's just not always present

red coral

A space is a character, so I can’t see why it wouldn’t work

brave moth
tacit nacelle

that would mean i need to split my code and use variables rather than just retuning a new modalbuilder nyaDed

red coral

Ternary operators also exist, however a space is a character

tacit nacelle

Something like this worked perfectly fine before

return new ModalBuilder()
    .setCustomId('')
    .setTitle('')
    .addLabelComponents(
      new LabelBuilder().setLabel('').setTextInputComponent(
        new TextInputBuilder()
          .setCustomId('')
          .setPlaceholder('')
          .setValue(code || '')
          .setStyle(TextInputStyle.Paragraph)
          .setRequired(true)
          .setMaxLength(1900),
      ),
    )

now you need to add an extra space in there or split the code up

red coral

Using an empty string for customId works on the builders or for discord? For discord it’s within the api that you need to have a custom id above string length of 0. Which is intuitive. Djs just follows the spec

copper kelp
tacit nacelle

it was just an example, i do have my custom ids and titles set properly

red coral

The only time you can’t have a customid is when you have a url button

Then it’s not really an example, since that won’t work regardless

copper kelp

like, if you don't want to do that, I'd actually recommend you just use json objects instead

red coral

You can’t have empty strings in places that require you to have a non-empty string however

tacit nacelle

Just adding the empty space works for me, i just don't get why there needs to be a check if the length of the value is greather than one

copper kelp

because the API doesn't allow an empty string, or at least we think it doesn't

tacit nacelle

It worked fine before the update

copper kelp

¯_(ツ)_/¯

red coral

djs builders are for building and validating, which makes sense. You don’t wanna build something for it to not work

copper kelp

open an issue on github if you think the behavior is inconsistent with the API

but, as I said just earlier

just because this "works for you" doesn't mean we recommend it, I think you're going totally wrong if you're setting values to empty strings

builders, are, by design, to create concise and readable complex conditional code. if your task is as trivial as setting a single property conditionally and you don't want to use the builder pattern, you should just use plain objects

tacit nacelle

I build the modal based on previous interactions and the value may be present or may not be

red coral

Cool but they need to be there in the api, hence djs checks it

copper kelp

yes, I understand that. this is what builders are for, but if you insist on a single return with the whole thing, then you're throwing all of that away

what we want you to do is

const builder = new WhateverBuilder();

if (conditional) {
  builder.setSomething(someValue);
}

return builder;
red coral

Am I saying something wrong?

copper kelp

but again, if you don't like that and if your logic is simple, you're better off just writing

return {
  field: conditonal ? 'value' : undefined
};```
copper kelp
brave moth

I never used discord.js before, how long will it uusually take until the File Upload modal component that released yesterday is supported?

copper kelp

should be pretty soon, but we don't give ETAs

red coral

So I’m not wrong then, sorry I’m coming across like that it’s not my intention

brave moth
red coral

Djs doesn’t provide etas. It was also released yesterday

tacit nacelle

I'll just solve my issue by doing this and it works just fine nyaShrug

return new ModalBuilder()
    .setCustomId('customid')
    .setTitle('title')
    .addLabelComponents(
      new LabelBuilder().setLabel('label').setTextInputComponent(
        new TextInputBuilder({
          custom_id: 'customid',
          placeholder: 'placeholder',
          style: TextInputStyle.Paragraph,
          required: true,
          max_length: 1900,
          value: someValueThatCanBeUndefined,
        }),
      )
    );
copper kelp

shruge you do you, I gave you my stance as someone that's actively working on builders

brave moth
tacit nacelle

yeah, it just seems silly to me that there's a check if it's not a requirement
like a value does not need to be provided here at all

red coral

It’s just not something djs provides

brave moth

Okay, how long did the Label modal component take?

tacit nacelle
brave moth

Alright, thank you!

copper kelp
tacit nacelle

I can't be bothered

though the API does also say that it is not a required field
value? string Pre-filled value for this component; max 4000 characters

brave moth

Of course the value is not required, but if you use setValue in your code, that can't be empty.

tacit nacelle

yeah but you used to be able to just give it an empty string, now discordjs expects the string to be at least one character long

rose tangle

does the api allow an empty string in the first place?

I don't think it'd make sense for that context

it can either be something (non empty string) or nothing (not set)

tacit nacelle

I don't know, it might have just been handled by discordjs before and they didnt send off the value at all if it was an empty string

brave moth
tacit nacelle
rose tangle

I'd say it should validate it's something

red coral

apart from builders I don’t believe djs validates much else, since everything required by the api is checked in a builder

halcyon bison

just tested, the api does accept an empty string
please just make an issue

rose tangle

because you'd be inputting something and it'd actually set a different thing

red coral

Oh cool

tacit nacelle

Okay, thank you duck, i will make an issue

versed current

Guys I might've found a bug but I'm not sure.
On the new modal components, the ModalSubmitFields property is an array, that is OK. (1st pic)

However the LabelModalData has a property of component which suggests that there is only one component - but the type says it's an array (2nd pic). When I log out ctx.fields.components out though, I get this:

[{
  type: 18,
  id: 2,
  component: {
    type: 4,
    id: 3,
    customId: "text-display-1",
    value: "asd",
  },
}]

This suggests that LabelModalData is supposed to be singular instead of an array.
Is this intended or what am I doing wrong? I want to iterate over all label components because I need to collect all data with custom ids (I can't predict which custom ids to expect)

brave moth
versed current

yeah but the type suggests an array

I'm drafting an issue for the repo right now. Update: Done.
-# Hi btw

brave moth

Mhm Yeah that's probably a good idea
-# Hi lol

muted aspen

Is it possible to use container layout in modals?

wary coral
muted aspen

Alright, ty

tired kindle

The discord-rpc package is deprecated or merged into the main repo?

unique shoal

deprecated

tired kindle
unique shoal

Should still work

What djs package for RPC?

tired kindle
steel trail

That has nothing to do with RPC

grizzled notch

Isn't there supposed to be an attachment component?

topaz bluff

Not in DJS yet

grizzled notch
topaz bluff

It was just officially announced yesterday...it takes some time for libraries to update to the new features

grizzled notch

I can wait :p

frosty epoch

anybody having oauth url problems recently?

loud quartz

We wouldn't know, we don't handle that

chrome chasm

TypeError: channel.isTextBased is not a function

            const channel = await guild.channels.fetch(channelId);
            if(!channel) return;
            if (!channel.isTextBased()) {
                return;
            }

but why?

polar karma

npm ls discord.js and what is the output of channelId and channel

little pebble
chrome chasm

I only can't get the value of the channel's isTextBased() function

little pebble
chrome chasm

would using client.channels.fetch() make any difference?

loud quartz

Finding out why your variables are wrong is a better fix than using different functions

robust flame
const audit = (await guild.fetchAuditLogs()).entries.first();
                                   ^
TypeError: guild.fetchAuditLogs is not a function```
```ts
const audit = (await guild.fetchAuditLogs()).entries.first();

??

steel trail

What is guild defined as?

toxic moat

I get this error:

[17:02:41] [Command ] [Slash] Command "help" executed by mihivx (1427480488511279124) in Mein Test Bot server (1428234467272687641)
[17:02:43] [Error   ] Command Error qmxqgj3t4a:
[17:02:43] [Error   ] Error Details:
[17:02:53] [Database] Backup settings changed: Interval=24h, Retention=7d

And this is my code: https://srcb.in/yeyJUD4uh2

robust flame
toxic moat
chrome chasm
tardy sable
tardy sable

is that your full error log?

toxic moat

yes

tardy sable

the error log doesnt say anything useful

try to console log the full error

toxic moat
toxic moat
tardy sable the error log doesnt say anything useful
[17:11:35] [Command ] [Slash] Command "help" executed by mihivx (1427480488511279124) in Mein Test Bot server (1428234467272687641)
Error sending help message: 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 (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:1965:23)
    at _UnionValidator.parse (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:972:90)
    at SectionBuilder.toJSON (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\builders\dist\index.js:2404:37)
    at C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\builders\dist\index.js:2105:64
    at Array.map (<anonymous>)
    at ContainerBuilder.toJSON (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\builders\dist\index.js:2105:35)
    at C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\discord.js\src\structures\MessagePayload.js:151:46
    at Array.map (<anonymous>)
    at MessagePayload.resolveBody (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\discord.js\src\structures\MessagePayload.js:150:49)
    at ChatInputCommandInteraction.reply (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:191:56)```
tardy sable
grizzled notch
zealous marten

wait what

grizzled notch
robust flame where?

Wherever your main event handler is it doesn't look like you're defining your event name parameter properly.

robust flame
toxic moat
grizzled notch
robust flame
const files = (await glob(`src/events/**/*.ts`)).map(filePath => path.resolve(filePath));

        files.map(async (file: string) => {
            const event: Event = new (await import(file)).default(this.bot);

            if (!event.name)
                return delete require.cache[require.resolve(file)] && console.log(`${file.split("/").pop()} does not have name.`);

            const execute = context.provider((...args) => {event.exec(...args)}, lang);

            if (event.once) this.bot.once(event.name as keyof ClientEvents, execute);
            else this.bot.on(event.name as keyof ClientEvents, execute);

            return delete require.cache[require.resolve(file)];```
my event handler
loud quartz

GuildBan is indeed not a Guild

sharp ginkgoBOT
loud quartz

Check what it actually gets emitted with

robust flame

i removed user: User, and changed guild: Guild to guildban: GuildBan, and it works

how can i fetch removed ban in guildBanRemove event?

loud quartz

Fetch?

What do you need that for

robust flame
grizzled notch
loud quartz

Well, the ban no longer exists so there's nothing to fetch

grizzled notch
loud quartz

You're sent the GuildBan in the event

grizzled notch
loud quartz

Get what

grizzled notch
loud quartz

I didn't say Guild, i said GuildBan

sharp ginkgoBOT
grizzled notch
loud quartz

What are you trying to get from audit log

And are you sure you don't just receive it in the event already

grizzled notch
loud quartz

They asked about fetching it after it's gone

Don't blindly fix the "can't fetch", ask what data they are trying to fetch instead

grizzled notch
toxic moat

Hie guys i got this error:

Error sending help message: 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 (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:1965:23)
    at _UnionValidator.parse (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@sapphire\shapeshift\dist\cjs\index.cjs:972:90)
    at SectionBuilder.toJSON (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\builders\dist\index.js:2404:37)
    at C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\builders\dist\index.js:2105:64
    at Array.map (<anonymous>)
    at ContainerBuilder.toJSON (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\builders\dist\index.js:2105:35)
    at C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\discord.js\src\structures\MessagePayload.js:151:46
    at Array.map (<anonymous>)
    at MessagePayload.resolveBody (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\discord.js\src\structures\MessagePayload.js:150:49)
    at ChatInputCommandInteraction.reply (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:191:56)
(node:2228) Warning: Supplying "ephemeral" for interaction response options is deprecated. Utilize flags instead.
WARNING: Warning : Supplying "ephemeral" for interaction response options is deprecated. Utilize flags instead.

code:

sudden totem

any doc for new modal components?

robust flame

what is the replacement for guildKickAdd?

sudden totem

I am getting Error: Expected a string primitive so wanna know what's wrong with my code

robust flame
grizzled notch
toxic moat

Im asking for help 3 times now

grizzled notch
polar olive

How annoying, I don't know how to use the new selection menu in modals! Can anyone help?

loud quartz

if you don't need that, dont' use a section

use the text display directly

toxic moat
wary coral
toxic moat

Alright thx

polar olive
robust flame

why messageDelete not receiving content

polar karma

if you have partials enabled and the message wasn't cached, or you lack the message content intent

robust flame
wanton seal

I have a file that is a bit long but I still can't understand the problem. Can anyone help me?

sharp ginkgoBOT

To share long code snippets, use a service like gist, sourcebin, pastebin, or similar instead of posting them as large code blocks or files.

north mango

guys

where can i find codes to copy paste for discord js in python it was pretty easy

bleak owl

what do you mean

example codes are on our guide and on github

north mango

but it seems like discord.js has lots of changes??

bleak owl

changes like what?

north mango
bleak owl

i dont really understand what you mean by that. can you be more specific?

north mango

i tried to use chatgpt but it works with older versions of discord.js only

topaz bluff
bleak owl

thats because you asked ai to give you code that doesn't work

north mango

oh ok

vocal garnet

is it possible to get someones bio/description with discord.js?

bleak owl

nope

the api doesn't allow it

vocal garnet
loud quartz

then they do that by breaking ToS

no bot-accessible endpoint exposes that information

vocal garnet

ohhh i see, thank you!

thats probably why the command of that bot is so much slower than others 😭

loud quartz

would make sense. i'd report that for breaking ToS

anyway, nothing you can obtain via discord.js

vocal garnet
vocal garnet
robust flame

can someone do filter and collector for 2 buttons "show" and "go back"? i dont understand and gpt doing errors

bleak owl

well, don't use chatgpt for discord.js

sharp ginkgoBOT

guide Component collectors
For situations where you want to collect multiple interactions, the Collector approach is better suited than awaiting singular interactions. Following on from the select menus guide, you're going to extend that example to use an InteractionCollector to listen for multiple Begin by adding to the...
read more

celest coral

Can I read other bot's responses on interactions? so if a user uses a foreign interaction, i should be able to read the response message right?

robust flame

i wanna sleep

unique shoal

Unless it was ephemeral

celest coral

Using Sapphire:

I set a breakpoint on the first if statement and it wont trigger when using the interaction

rose tangle

interactions are webhooks

celest coral

ohhhh

Thanks!

toxic moat

Code:

const container = new ContainerBuilder()
            .addSectionComponents((section) =>
                section
                    .addTextDisplayComponents((textDisplay) =>
                        textDisplay.setContent(
                            `Welcome to the server, ${member.user.username}!`
                        ),
                    )
                    .addTextDisplayComponents((textDisplay) =>
                        textDisplay.setContent(
                            'We are thrilled to have you here. Please take a moment to read through our server rules and guidelines to ensure a positive experience for everyone.'
                        ),
                    )
                    .addTextDisplayComponents((textDisplay) =>
                        textDisplay.setContent(
                            '-# Make sure to check out the various channels and introduce yourself to the community!'
                        ),
                    )
                    .setThumbnailAccessory(
                        (thumbnail) => thumbnail.setDescription('Welcome').setUrl(member.user.displayAvatarURL({ size: 1024, extension: 'png', dynamic: true })),
                    ),
            );

Error:

CLIENT ERROR: TypeError: thumbnail.setDescription(...).setUrl is not a function
    at C:\Users\user\Documents\VSCode\random bot\Synapse-Base\events\AUTO\welcome.js:37:76
    at resolveBuilder (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\builders\dist\index.js:2461:12)
    at SectionBuilder.setThumbnailAccessory (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\builders\dist\index.js:2359:61)
    at C:\Users\user\Documents\VSCode\random bot\Synapse-Base\events\AUTO\welcome.js:36:22
    at resolveBuilder (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\builders\dist\index.js:2461:12)
    at C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\builders\dist\index.js:2050:75
    at Array.map (<anonymous>)
    at ContainerBuilder.addSectionComponents (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\builders\dist\index.js:2050:56)
    at Object.execute (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\events\AUTO\welcome.js:19:14)
    at Client.<anonymous> (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\utils\Loaders\EventLoader.js:41:76)
Attempting to reconnect... (Attempt 1/5)
Client error: thumbnail.setDescription(...).setUrl is not a function
[22:58:53] [Warning ] Shutting down dashboard server due to error...
bleak owl

setURL()

also, the dynamic option has been removed

forceStatic is the opposite. dynamic is enabled by default

toxic moat

Ohh okay

coral fractal

When using the following reply, I get the warning, that ephemeral is deprecated.

interaction.reply({
    content: `You don't have permission to use this command${
        interaction.options.getSubcommand().toUpperCase() === "ENABLE" ? "" : " in DMs"
    }.`,
    ephemeral: interaction.inGuild(),
});

Does anyone have a solution using flags that doesn't look too bad? Best I could think of was this:

interaction.reply({
    content: `You don't have permission to use this command${
        interaction.options.getSubcommand().toUpperCase() === "ENABLE" ? "" : " in DMs"
    }.`,
    flags: interaction.inGuild() ? MessageFlags.Ephemeral : undefined,
});

I guess it works fine as long as MessageFlags.Ephemeral is the only flag...

sharp ginkgoBOT

The ephemeral option when replying to an interaction will be removed in v15

- {..., ephemeral: true}
+ {..., flags: MessageFlags.Ephemeral}
``` Read [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_OR) on how to specify multiple flags
coral fractal

I don't see how using bitwise operators could make the code look better. I'd still have to check, if the message was sent on a server. Or do you want me to shift the boolean value? Could you please give me an example of what you think works best?

bleak owl

that is what works best

coral fractal

Shifting the boolean?

bleak owl

no? i think what you have is fine

unique shoal

"looks bad" is subjective, while using enums is objectively better than magic numbers or other such things

coral fractal

Okay, thx then. I really liked the ephemeral option, but i guess I'll have to live with flags now...

sharp ginkgoBOT
bleak owl
grizzled bison
stable sun
grizzled bison
thorny ridge

how does wordle send these when i havent run the command

unique shoal

it says you did though

loud quartz

might be the cool case of it just following up in next 24 hours

unique shoal

The 15 minute expiry doesn't apply?

thorny ridge
rose tangle

it says it was sent yesterday though?

thorny ridge

it was

rose tangle

then?

thorny ridge

it was way after i did /wordle

rose tangle

weird it says there you ran it and then it replied immediately

thorny ridge

also follow ups reply to the original interaction rpely

thorny ridge
rose tangle

I remember it simply sends a reminder like any message

though wordle is a special bot anyways

it's in every server without being invited

thorny ridge

true

rose tangle

so it might be another special thing if it's like you said

thorny ridge

yeah your probably right🥀

loud quartz
mental silo

im surely doing everything right simply asserting interaction.guild everywhere

outside of global commands

unique shoal

If your bot is private, and cant be used in DMs, sure

loud quartz

there is no like, "global interaction" and "guild interaction", they all trigger the same event

unless you mean in the command code itself

then if you know that it would never happen in a DM, sure

but you could also just typeguard your interaction and not have to assert it everywhere

mental silo

Yeah my handler seperates them, that command practically (hopefully) cant run outside of a guild

sharp ginkgoBOT
loud quartz

or

sharp ginkgoBOT
mental silo

Perfect, thank you!

acoustic grotto
wary coral
hexed willow

I followed documentation of creating handlers and such. It has started to create tech debt as my project has grown, with my "interactionCreate.js" and being touched by 10 other files or "guildMemberAdd.js". For example...

  • GuildMemberAdd.js handles checking for muting, onboarding,
  • Interactions Create, handles welcoming, onboarding, role menus.
  • All these files have their own OTHER files as command.js files as shown in image figure.

Pretty much my code is bouncing all around the place. If "guildMemberAdd.js" has issue it takes out several functions at once and has grown to like 1000 lines of code.

TLDR: Is it advised/possible to just put all function feature's in separate/single files so each thing is its own comparntalized bit so I don't have these monolithic "interactionCreate.js" files for a "command handler" structure?

unique shoal

Im curious just how "monolithic" they are, but yes, you can absolutely modularise further

You can also just separate things out into separate functions within the one file

hexed willow

Would it become a API problem if I rewrite and declare below several times across my code? Currently everything that requires "InteractionCreate" ends up in this single file module export which is my main concern and what I want to escape from

    name: Events.InteractionCreate,
    async execute(interaction) {```
unique shoal

The downside of having multiple event listeners is that it will fire ALL of them at once, and you then need to ensure you kill off the functions that shouldnt be handling a particular aspect of the event ASAP

There's a balance between multi-handling and single-triage

What exactly is failing that "takes out several functions" that you cant architect around without multiple event handlers?

hexed willow

Nothing is failing, but I just don't want one file with 10 totally different and unrelated functions. I am use to everything to do with "something" should just be in "something.js". Now I have to check if interaction is fine, then check command file itself, then check guildMemberAdd.js event and so fourth etc...

unique shoal

How are you handling it now, if/else or switch cases or something based on details of the event?

hexed willow

pretty much, why its such a PIA.

unique shoal

Yeah fair enough, you could modularise a bit via something like

switch(interaction.type) {
  case InteractionType.ApplicationCommand:
    switch(interaction.commandType) {
      case ApplicationCommandType.ChatInput:
        return handleChatInputCommand(interaction)
      default:
        console.log("Unhandled");
    }
  }
}```

And that way each interaction type is split out

And then those component functions like handleChatInputCommand can be separate functions, in other files if you want

There isnt a significant benefit to having multiple event listeners over this triage

hexed willow

Is there any good open source projects that are "beautifully designed" that could be helpful for me to reference?

I only ever seem to find half baked iffy bot templates on github sadblob

unique shoal

No idea sorry haha

Good design changes depending on scale

Modularising to the degree you're looking to do would be terrible for a smaller bot

These are the two options basically, I'm inclined to prefer the first one

hexed willow

I would like to keep idea open of scaling the bot up and sharding it etc... I rather invest now in making it strong than fix up holes later with 10x the codebase. I am only at 331,800 characters total code base but I am only like 30% done.

unique shoal

But feel free to experiment with what suits you better

hexed willow
unique shoal

Really depends on how you write it, like using maps or switch cases, things with efficient lookups

toxic moat

How can i use dropdown menus in models?

stable sun

You just put them in a LabelBuilder and inside of ModalBuilder

sharp ginkgoBOT
toxic moat
stable sun

No

You add the Label to the Modal

toxic moat

This is my code now:

const { ModalBuilder, TextInputBuilder, TextInputStyle, ActionRowBuilder,  } = require('discord.js');

module.exports = {
    customId: 'open-case',
    
    async execute(interaction, args, client) {
        const modal = new ModalBuilder().setCustomId('open-case-modal').setTitle('Open Moderation Case');

        const caseReasonInput = new TextInputBuilder()
            .setCustomId('case-reason')
            .setLabel("Reason for the case")
            .setStyle(TextInputStyle.Paragraph)
            .setPlaceholder("Describe the reason for opening this case...")
            .setRequired(true)
            .setMaxLength(400);
            
        const caseReasonRow = new ActionRowBuilder().addComponents(caseReasonInput);

        const categoryInput = new 
    }
};
sharp ginkgoBOT
toxic moat

can you give me a example please

No needent

unique shoal

Youve been given the documentation now though

stable sun
.addLabelComponent((labelBuilder) => {
  return label
    .setCustomId(…)
    .addStringSelectMenuComponent((menuBuilder) => {
      return menuBuilder
        .setCustomId(…)
        // … select menu stuff
      })
      // … label stuff
    });
})
// … modal stuff
kindred moon

why does the ActionRowBuilder take a generic for the components it contains while almost every other one has specific methods for adding specific components?

stable sun

Prob bc it was legacy behavior

I guess technically not all components are allowed in every context

Can’t use buttons in modals

toxic moat
stable sun Prob bc it was legacy behavior

Like this?

modal.addLabelComponent((labelBuilder) => {
            return labelBuilder
            .setCustomId('case-category')
            .addStringSelectMenuComponent((menuBuilder) => {
                return menuBuilder
                .setCustomId('case-category')
                .setPlaceholder('Select a category')
                .addOptions(
                    new StringSelectMenuOptionBuilder()
                        .setLabel('Warning')
                        .setValue('warning')
                        .setDescription('Issue a warning to a user')
                        .setEmoji('⚠️'),
                    new StringSelectMenuOptionBuilder()
                        .setLabel('Mute')
                        .setValue('mute')
                        .setDescription('Mute a user')
                        .setEmoji('🔇'),
                );
            })```
stable sun

That looks fine

toxic moat

Alright i will try it

stable sun

You could use callbacks in addOptions instead of making the classes

.addOptions((optionBuilder) => …, (optionBuilder) => …, …)

topaz bluff

just out of curiosity...there's no functional difference between using a callback and instantiating a new class correct?

stable sun

That’s correct

toxic moat

Alright

stable sun

Callbacks just reduces the imports you need to do

toxic moat

I will try first if it works

toxic moat
stable sun

Indeed

toxic moat

This is my cmd code:

const { SlashCommandBuilder, } = require('discord.js');
const { modal } = require('../../components/modals/open-case.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('open-case')
        .setDescription('Opens a moderation case'),
        
    async execute(interaction, client) {

        // Show the modal to the user
        await interaction.showModal(modal);
        
    }
};
stable sun

Can you log modal in the command before you show it?

toxic moat

And this the modal:

const { ModalBuilder, LabelBuilder,  ContainerBuilder, ButtonStyle, ButtonBuilder, TextDisplayBuilder, MessageFlags, StringSelectMenuBuilder, StringSelectMenuOptionBuilder  } = require('discord.js');
const { model } = require('mongoose');

module.exports = {
    customId: 'open-case',
    
    async execute(interaction, args, client) {
       const modal = new ModalBuilder().setCustomId('open-case').setTitle('Open a Moderation Case');


        modal.addLabelComponent((labelBuilder) => {
            return labelBuilder
            .setCustomId('case-category')
            .addStringSelectMenuComponent((menuBuilder) => {
                return menuBuilder
                .setCustomId('case-category')
                .setPlaceholder('Select a category')
                .addOptions(
                    new StringSelectMenuOptionBuilder()
                        .setLabel('Warning')
                        .setValue('warning')
                        .setDescription('Issue a warning to a user')
                        .setEmoji('⚠️'),
                    new StringSelectMenuOptionBuilder()
                        .setLabel('Mute')
                        .setValue('mute')
                        .setDescription('Mute a user')
                        .setEmoji('🔇'),
                );
            })

        });```
stable sun

Oh, it’s clearly not exported then

toxic moat
stable sun
toxic moat

module.exports = { modal }; right?

stable sun

You only export a customId and execute function

Well, need to be careful on the specifics of implementing that

Callbacks also allow you to keep it as a single expression

toxic moat
stable sun

.addX(X()) vs .addX(() => x.…)

I guess technically that’s an expression too

toxic moat

Can you help me because idk what i should do now.

stable sun
topaz bluff

just how youre exporting the custom-id

toxic moat
stable sun

Same way you did with customId

Add a key: value pair

toxic moat

ahh

toxic moat
stable sun

If you capitalize the key, you have to change it in the other file too

toxic moat

Alright+

stable sun

Also no, you can’t access modal variable from here

You have to make the model before you do exports

toxic moat
stable sun You have to make the model before you do exports

I got this error:

[04:09:03] [Command ] [Slash] Command "open-case" executed by mihivx (1427480488511279124) in Mein Test Bot server (1428234467272687641)
Error showing modal: DiscordAPIError[50035]: Invalid Form Body
data[BASE_TYPE_REQUIRED]: This field is required
    at handleErrors (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\rest\dist\index.js:762:13)
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
    at async BurstHandler.runRequest (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\rest\dist\index.js:866:23)
    at async _REST.request (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\@discordjs\rest\dist\index.js:1307:22)
    at async ChatInputCommandInteraction.showModal (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:399:22)
    at async Object.execute (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\commands\Moderation\open-case.js:12:13)
    at async validateAndExecute (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\utils\Handlers\InteractionHandler.js:377:17)
    at async Client.handleInteraction (C:\Users\user\Documents\VSCode\random bot\Synapse-Base\utils\Handlers\InteractionHandler.js:428:21) {
  requestBody: { files: undefined, json: { type: 9, data: undefined } },
  rawError: {
    message: 'Invalid Form Body',
    code: 50035,
    errors: { data: [Object] }
  },
  code: 50035,
  status: 400,
  method: 'POST',
  url: 'https://discord.com/api/v10/interactions/1428565452833161226/aW50ZXJhY3Rpb246MTQyODU2NTQ1MjgzMzE2MTIyNjpWTFlNVllwV1VaeHU0REFLaWthQmVWenZacXBHWUtueGVROElYMjExejFtQUVLSmY2V2E0b3AzM1pjeGJYQklHN05BaDlidHZXTEs1SlZ4R3ZBVGxUbDV2ck8xSDFFSDhLWWFqaWJlUWExTVRmTWt2bWN3czlzZ0o5b1h4aTVoZA/callback?with_response=false'
}
stable sun

Prob still an import/export issue

toxic moat
stable sun console.log modal in the command

The base has this temp:

const { ModalBuilder, TextInputBuilder, TextInputStyle, ActionRowBuilder } = require('discord.js');

module.exports = {
    customId: 'test',
    
    async execute(interaction, args, client) {
        const modal = new ModalBuilder()
            .setCustomId('test_modal')
            .setTitle('test Modal');

        const input = new TextInputBuilder()
            .setCustomId('test_input')
            .setLabel('Enter some text')
            .setStyle(TextInputStyle.Short)
            .setRequired(true);

        modal.addComponents(new ActionRowBuilder().addComponents(input));
        await interaction.showModal(modal);
    }
};```
toxic moat
stable sun

You never learned to print variables?

Oh, you replied to the other message

toxic moat

its undefined

stable sun

Show that other file that’s making the modal

toxic moat
const { ModalBuilder, LabelBuilder,  ContainerBuilder, ButtonStyle, ButtonBuilder, TextDisplayBuilder, MessageFlags, StringSelectMenuBuilder, StringSelectMenuOptionBuilder  } = require('discord.js');
const { model } = require('mongoose');

module.exports = {
    customId: 'open-case',
    
    async execute(interaction, args, client) {

       const modal = new ModalBuilder().setCustomId('open-case').setTitle('Open a Moderation Case');


        const category = modal.addLabelComponent((labelBuilder) => {
            return labelBuilder
            .setCustomId('case-category')
            .addStringSelectMenuComponent((menuBuilder) => {
                return menuBuilder
                .setCustomId('case-category')
                .setPlaceholder('Select a category')
                .addOptions((optionBuilder) =>
                    optionBuilder.setLabel('Warning').setValue('warning').setDescription('Issue a warning to a user').setEmoji('⚠️'),
                );
            })

        });



    }
};
topaz bluff

You're not exporting a modal there

toxic moat

I know i did idk

toxic moat

@stable sun should i talk with the owner of the base?

toxic moat
stable sun
stable sun

You can’t have it inside of execute