#development

1 messages Ā· Page 1870 of 1

wanton axle
#

@quartz kindlei updated it,

#

i need to update some codes ?

grim aspen
#

some of the code you have may not be supported

wanton axle
#

how i can know

#

is there any tool?

#

is*

grim aspen
#

because discord.js was updated to v13, screwing everyone over with new code

boreal iron
#

The docs will help you

#

They also contain notes about the specific changes from version to version

lyric mountain
quartz kindle
#

install it again

split hazel
#

hate when i mix up updating and uninstalling

proven lantern
#

is the my_credentials_token the token in the body? const {token} = req.body

hasty lotus
#

hey, just on the djs docs i've seen that a reply to an interaction can return an empty promise (https://discord.js.org/#/docs/main/stable/class/CommandInteraction?scrollTo=reply), which is actually my case, but i'd like to get the message object of the message that the bot just sent, for further code.

What defines if the promise will return a void or a message object ?

proven lantern
#

dang

quartz kindle
#

you receive it as a query string in the redirect url

#

after the user logs in

#

well, the exchange token

#

the actual token you get when you use the exchange token

proven lantern
#

oauth stuff

quartz kindle
#

if thats what you're talking about,idk what you're doing

proven lantern
#

i just wanted to use the token in the body and not my bot token directly

quartz kindle
#

well the final access token you should get in the body yes

proven lantern
#

this is all i see in the body

quartz kindle
#

thats not an oauth2 request

proven lantern
#

nope

quartz kindle
#

then what are you doing?

proven lantern
#

receiving a normal slash command sent to the INTERACTIONS ENDPOINT URL

#

i thought there might be a way to use the token in the body to authorize my api calls

quartz kindle
#

thats an interaction token, not an oauth token

proven lantern
#

dangnabit

hollow depot
#

i'm running two screen instances on a linux vps, until yesterday everything was fine and i could reconnect to both of them without any problem, now if i execute screen -r it shows this:

There are several suitable screens on:
        1396.pts-(heres server ip)     (Detached)
        1191.pts-(heres server ip)     (Detached)
Type "screen [-d] -r [pid.]tty.host" to resume one of them.
~```
what can i do?
signal estuary
#
let channel = msg.member.voice.channel
await joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
let connection = getVoiceConnection(channel.guild.id)
const player = createAudioPlayer({
        behaviors: {
         noSubscriber: NoSubscriberBehavior.Pause,
        },
});
connection.subscribe(player)
let resource = createAudioResource(path.resolve(`./music/name.mp3`));
player.play(resource);

Why is the sound lagging when the bot is added to another voice channel on another server?

hasty lotus
#

or maybe when testing on your local machine ?

#

try to put it on an online vps or something

signal estuary
hasty lotus
#

well yeah try to put it on a server

#

maybe a ressource issue, if you have other processes running on your computer, or just your connexion

signal estuary
hasty lotus
#

i can't assure 100% this is the issue, but probably

#

:/

signal estuary
#

@hasty lotusdo you know maybe what causes this error:

Error: Cannot perform IP discovery - socket closed
#

This error appears sometimes when the bot gets kicked out of the channel

hasty lotus
#

uh, without any code like this i coudn't explain it no sorry x)

lament rock
#

The UDP connection to the voice server was closed before it could resolve the IP from the name server

#

or the name server is experiencing issues

hasty lotus
#

yeah that's basically what it means, but why does this happen, like this, idk šŸ˜…

lament rock
#

that would be cataclysmic

modest maple
lament rock
#

the opus packets are sent over udp

modest maple
#

mmm true

balmy root
#
          message.guild.channels.cache.forEach(async (channel) => {
            await channel.createOverwrite(muteRole, {
                        SEND_MESSAGES: false,
                        MANAGE_MESSAGES: false,
                        READ_MESSAGES: false,
                        ADD_REACTIONS: false
                    });
          })
```is giveing me that await can only be used in a async function
#

:<

lament rock
#

maybe somewhere got fucked when trying to udp hole punch

#

idk

lament rock
#

That is multiple screen instances running. You need to destroy one of them and then just stick to creating new windows inside of screen with control + a + C iirc

#

either c or C

balmy root
#

do ctrl + r

#

or f4

pallid jungle
#
            const botname = client.user.username;
            await Channel?.createWebhook(botname, {
                avatar: client.user.displayAvatarURL({ format: 'png', dynamic: true, size: 128 })
              })
              .then(webhook => Promise.all([webhook.send({ embeds: [ChannelDeleted] }), webhook]))
              .then(([_, webhook]) => webhook.delete())
              .catch(() => {});

How can i make it create it once it's not generated and if it already there it sends with the webhook?

hollow depot
balmy root
#

a

lament rock
#

control + a + X all of the screens in one of them and it should destroy it

balmy root
#

help

hollow depot
balmy root
#

command handler

hollow depot
#

try removing it from the loop (?) idk

hollow depot
# balmy root

maybe since you have it both in the execute() and the loop it conflicts in some manner idk

coarse topaz
#

I need helpjs if (!message.content.includes("www.link1.com"||"www.link2.com")) { let errorEmbed = new Discord.MessageEmbed() .setTitle(`**Something went wrong**`) .setDescription(`.`) .setColor("RED") .setFooter(`Command ran by: ${message.author.tag} (${message.author.id})`, message.author.displayAvatarURL()) .setTimestamp() message.channel.send(errorEmbed).catch(console.error); } else { something } It's working perfectly fine when the message doesn't include www.link1.com, however, the bot is totally ignoring the second condition (www.link2.com), when the message content includes it, the bot reads it as false and sends the errorEmbed when it actually shouldn't!
How can I solve this? I don't know what's wrong

hollow depot
#

unfortunately comparison operators do not work inside of functions like includes

coarse topaz
hollow depot
coarse topaz
#

Alright, thanks

coarse topaz
lyric mountain
#

screen -r ID

#

or screen -r -d ID to force attach

hollow depot
hollow depot
lyric mountain
#

you can rename the screen to make reconnecting easier

hollow depot
#

ye i know that

#

i didnt name the instances before but now i did lmao

lyric mountain
#

lul

wheat mesa
coarse topaz
# hollow depot could you please show the line of code?
       if (!message.content.includes("link1")||!message.content.includes("link2")) {
          let errorEmbed = new Discord.MessageEmbed()
          .setTitle(`**Something went wrong**`)
          .setDescription(`.`)
          .setColor("RED")
          .setFooter(`Command ran by: ${message.author.tag} (${message.author.id})`,  message.author.displayAvatarURL())
          .setTimestamp()
          message.channel.send(errorEmbed).catch(console.error);
} else {
        let args = message.content.split(" ");
        let gameLinksArray = args.slice(1);
      if (gameLinksArray.some(v => !v.includes("link1")||!v.includes("link2"))) {
        let errorEmbed = new Discord.MessageEmbed()
          .setTitle(`**Something went wrong**`)
          .setDescription(`.`)
          .setColor("RED")
          .setFooter(`Command ran by: ${message.author.tag} (${message.author.id})`,  message.author.displayAvatarURL())
          .setTimestamp()
          message.channel.send(errorEmbed).catch(console.error);
} else {
something
}```
lyric mountain
#

you could just use regex for that

#

probably faster than 2 includes checks

hollow depot
median raft
#

What would be a recommended amount of RAM for a VPS hosting a bot?

median raft
#

Uh ok?

lyric mountain
#

not-or checks are dumb

median raft
#

I guess my question was poorly phrased I edited it

lyric mountain
#

there's no such thing as "recommended amount of ram for a bot"

median raft
#

šŸ¤”

lyric mountain
#

answer is "as much as it needs"

median raft
#

Okok, thanks

balmy root
#

ded

lyric mountain
#

you could have a bot run both using 10kb or 10gb

quartz kindle
#

depends on the language and library you use

lyric mountain
#

depends on its function

quartz kindle
#

depends on how many guilds

#

etc

balmy root
#
message.guild.channels.cache.forEach((channel)=>{
  channel.permissionOverwrites.create(muteRole, {
      SEND_MESSAGES: false,
      MANAGE_MESSAGES: false,
      READ_MESSAGES: false,
      ADD_REACTIONS: false
  });
#

:<

median raft
#

Yeah makes sense, I know how much my bot is using right now but it's only on 2 guilds and I have no idea how to determine how much will it use in 100 guilds for example

lyric mountain
#

foreach

quartz kindle
lyric mountain
#

don't expect a big change in ram usage

balmy root
coarse topaz
median raft
#

Using discord.js

quartz kindle
#

then i would guess about 100mb ram per 1000 guilds as a baseline

thorny cargo
#
module.exports = {
    name: "mute",
    usage: "mute [@user] {time} {reason}",
    cooldown: 3,
    perms: ["MANAGE_MESSAGES"],
    run: (client, message, args, storage) => {
        const Discord = require('discord.js')
        const moment = require('moment')
        const GuildSchema = require("../models/guild.js");

        if(!args[0]) return message.channel.send('Usage: `' + client.commands.get('mute').usage + '`');



        let units = ["second", "minute", "hour", "day", "week", "month", "year"]
        for(i=0; i>units.length; i++) {
            let plural = [];
            plural = plural.push(units[i]+"s");
            console.log(plural)
        }
        let target = message.mentions.users.first() || message.guild.members.cache.get(args[0]);
        let time = args[1]
        let reason = args.slice(2).join(' ');

        if(units.includes(args[2]) || unitsPlural.includes(args[2])) {
            time = args.slice(1, 3).join(' ');
            reason = args.slice(3).join(' ');
        }

        let unit = args.slice(1, 2).join(' ')
        let value = args.slice(2, 3).join(' ')
        let unmuteAt =moment().add(unit, value)

        message.channel.send(new Discord.MessageEmbed()
        .setTitle("Data")
        .setDescription(`User "${target.username}" \n` +
                        `has been muted for "${time}" \n`+
                        `for the reason "${reason}" \n` +
                        `and would be unmuted at "${unmuteAt}" \n` +
                        `current time: ${moment()}`

      ))

         let mutedRole = message.guild.roles.cache.find((n) => n.name === "Muted")
         if(mutedRole === undefined) return message.channel.send('No role nammed "muted" has been found !mute setrole <id>')

         message.channel.send(`i found the role "${mutedRole}" Āæwould you like it to be the one i use to sanction?`).then(async (msg) => {
             await msg.react('āœ…');
             await msg.react('āŽ');

             let yesFilter = (reaction, user) =>
             reaction.emoji.name === "āœ…" && user.id === message.author.id;
           let noFilter = (reaction, user) =>
             reaction.emoji.name === "āŒ" && user.id === message.author.id;

           let yes = msg.createReactionCollector(yesFilter, { time: 20000 });
           let no = msg.createReactionCollector(noFilter, { time: 20000 });

           yes.on("collect", async(r) => {
             GuildSchema.findOneAndUpdate({
                 guildID: message.guild.id
             }, {
                 $set: {
                     mutedRole: mutedRole.id
               }
             }, {
                 new: true
             }).then(() => {
                 message.channel.send(`k, the new mutedrole is ${mutedRole}`)
             }).catch((err) => {
                 message.channel.send(storage.errorEmbed);
             });
         })
         no.on("collect", async(r) => {
             message.channel.send('ok, for set a muted role use `!mute setrole <id>`')
       })
         })

    }
}```
lyric mountain
thorny cargo
#

can somedody help me

balmy root
thorny cargo
lyric mountain
#

let's read your if clause: "if message NOT contains link1 OR message NOT contains link2"

#

see the issue?

#

the proper way of doing that would be "if NOT (message contains link1 OR message contains link2)"

#

so, basically, not contain either options

quartz kindle
#

or "if message NOT contains link1 AND message NOT contains link2"

coarse topaz
lyric mountain
#

!

quartz kindle
#

if not ()

#

if(!())

coarse topaz
#

oh

#

makes sense

#

thank you, will try it out

lyric mountain
lyric mountain
#
  • any error that appeared in ur log
balmy root
#

:< @quartz kindle

#

if (!mutedRole) {
        try {
            muteRole = message.guild.roles.create({data:{
                name:"šŸ”‡ | Muted",
                color: "#f70404",
                permissions:[]
            }});
message.guild.channels.cache.forEach((channel)=>{
  channel.permissionOverwrites.edit(muteRole, {
      SEND_MESSAGES: false,
      MANAGE_MESSAGES: false,
      READ_MESSAGES: false,
      ADD_REACTIONS: false
  });
})
        } catch(e) {
            console.log(e.stack);
        }
    }
quartz kindle
balmy root
#

v12

quartz kindle
#

there is no edit in v12

balmy root
#

brh

lyric mountain
#

hello darkness my old friend

balmy root
lyric mountain
#

tim: "there's no update in v11"

balmy root
coarse topaz
coarse topaz
# balmy root

wait what
does your bot use an illegal version of discord? (better discord)

balmy root
#

no

coarse topaz
#

then what is it lol

balmy root
#

idk

#

its just installed uwu

quartz kindle
#

channel.permissionOverwrites is a collection

balmy root
#

freak

#

how can i change a channel permission for a role then?

quartz kindle
#

its a collection

#

you loop over it

signal estuary
#

How can you make the bot listen to the next message?
Like

bot: > Please mention a channel
user: > #general
bot: > set channel

So that the user doesnt need to use a prefix for this

rose warren
#

With a message collector

azure lark
#

how do i run a .bat file

boreal iron
#

Just double click it or right click execute

#

Or via CLI
$> mybat.bat

#

(Windows exclusive)

azure lark
#

yh but i want a js file to run it

boreal iron
#

I wonder if JS even has inbuilt OS service options to work with

azure lark
#

well, i just want a way yo run all git cmds and push a commited version

quartz kindle
#

node.js has functions to run processes

#

for example spawn and exec

boreal iron
#

Oh yeah node has… well anyways no clue about GitHub and related stuff, but I’m sure you will find a way smirk

thorny flume
#

how can i get the user.presence discord.js v13?

azure lark
proven lantern
#

would a 6 character string with only numbers and letters (10+26=36) have 1947792 combinations? e7ef23

coarse topaz
#

How can I get a list of users who reacted to a message with a specific reaction?

#

message.reactions.cache.get("").users may work?

pallid jungle
#

Hey @quartz kindle Can you help me please ?

quartz kindle
azure lark
#

cd out of the folder

#

that its in

#

i have 2 folders

quartz kindle
#

no i mean, what are you expecting it to return?

#

you are executing a command, and reading the return value

azure lark
#

well its giving me an error

quartz kindle
#

thats because spawn expects a valid process to execute

pallid jungle
#

There is a way to create webhook once and the bot send with it evertime?

            const botname = client.user.username;
            await Channel?.createWebhook(botname, {
                avatar: client.user.displayAvatarURL({ format: 'png', dynamic: true, size: 128 })
              })
              .then(webhook => Promise.all([webhook.send({ embeds: [ChannelDeleted] }), webhook]))
              .then(([_, webhook]) => webhook.delete())
              .catch(() => {});
quartz kindle
#

idk, what do you want it to do?

azure lark
#

cd out of a folder, cd into a different folder, do git add, commit and push

quartz kindle
#

you dont need to cd folders

#

use relative paths

pallid jungle
quartz kindle
#

no

wheat mesa
pallid jungle
#

k

proven lantern
azure lark
quartz kindle
#

also, you have the cwd option

#

exec("git", ["add"], { cwd: "../otherfolder" })

azure lark
quartz kindle
#

no, thats an array of arguments for one command

#

each command goes in a separate exec

azure lark
#

oh ok

sage bobcat
quartz kindle
#

h

sage bobcat
#

One message removed from a suspended account.

quartz kindle
#

hug

simple stump
#

Just wondering, but there is a weird issue with my bot. When I leave it running overnight via console, I get an error that the bot can’t connect to Discord or that handshake failed (don’t have the error right now cause I’m out). Any ideas?

lyric mountain
#

does the bot stop at all?

lament rock
#

alternatively, cd ../somefolder && git add && git commit && git push

lyric mountain
#

using && is weird

proven lantern
#

false ? true : false ? true : false

#

i like doing those in big one liners

#

like 20 lined up

sudden geyser
#

would be simple to fix if switches were expressions

proven lantern
#

switches should never be used

lament rock
#

switches are ugly to look at imo

proven lantern
#

they are a code smell

sudden geyser
#

I don't know, I'd rather read:

name: option.name,
value: switch (option.type) {
  case 8: ...
  case 7: ...
}

than what you have now

lament rock
#
switch(expression, { one: () => { console.log("poggers") }, two: () => { console.log("not poggers") } });
sudden geyser
#

or Rust's match expression

proven lantern
#

if switch statements didnt have to break out it would be so much better

boreal iron
sudden geyser
#

my new favorite language

sudden geyser
#

Like Python's match

lament rock
#

hope an ecmascript revision removes that necessity

#

or a deprecation of switch (unlikely)

sudden geyser
#

It'll never be deprecated.

#

I can confirm that

boreal iron
#

$name = match(2) {
    1 => 'One',
    2 => 'Two',
};

echo $name; // "Two"
``` ā¤ļø
proven lantern
#

i have already deprecated it in my book

boreal iron
#

Rip switch

proven lantern
#

functions are great

sudden geyser
#

then write a function mimicking switch

proven lantern
#

map look ps

#

map look ups

sudden geyser
#

maybe ramda has one

proven lantern
#
const Switch = (map, value) => {
  return map[value];
}
const val = Switch({1:"ONE", 2:"TWO"}, 1);
sudden geyser
#

could call it get

proven lantern
#

and then throw switch in the garbage

#

i agree

sudden geyser
#

imagine a world without control flow

#

a paradise

simple stump
#

Just wondering, but there is a weird issue with my bot. When I leave it running overnight via console, I get an error that the bot can’t connect to Discord or that handshake failed (don’t have the error right now cause I’m out). Any ideas?
Also the bot does stop completely/crashes.

(The bot is hosted on a raspberry pi)

wheat mesa
#

Could be your internet being unreliable

#

That’s why it’s generally better to run on a VPS rather than a self hosted rpi imo

lament rock
#

Imagine a bot

jaunty ore
#

Do you know how to install cisco packet tracer?, if anyone knows can you teach me?

pallid jungle
#
]: /app/node_modules/discord.js/src/structures/Webhook.js:158
2021-09-08T01:11:11.229131+00:00 app[Worker.1]:     if (!this.token) throw new Error('WEBHOOK_TOKEN_UNAVAILABLE');
2021-09-08T01:11:11.229133+00:00 app[Worker.1]:                            ^
2021-09-08T01:11:11.229134+00:00 app[Worker.1]: 
2021-09-08T01:11:11.229135+00:00 app[Worker.1]: Error [WEBHOOK_TOKEN_UNAVAILABLE]: This action requires a webhook token, but none is available.

But it's working on ready event

#

Without token

#

Code:

        const botname = client.user.username;
        const webhooks = await Channel.fetchWebhooks();
        const webhook = webhooks.first();
        if(webhook) {
          await webhook.send({
            embeds: [DeletedLog],
            username: botname,
            avatarURL: client.user.displayAvatarURL({ format: 'png', dynamic: true, size: 128 })
          });
        } else if(!webhook) {
          await Channel?.createWebhook(botname, {
            avatar: client.user.displayAvatarURL({ format: 'png', dynamic: true, size: 128 })
          })
          .then(webhook => Promise.all([webhook.send({ embeds: [DeletedLog] }), webhook]))
        }
#

Someone help

thorny cargo
#

I just updated to v13 and I think I did the wrong decision

#

can somebody help me? because my bot is not going up

#

and my mind is blowing up i cant figure out wth is going on

sudden geyser
#

just explain your problem

thorny cargo
pallid jungle
boreal iron
#

Just because it’s midnight for most Europeans

pallid jungle
sudden geyser
#

because I can't figure it out

lyric mountain
sudden geyser
#

yeah now get rid of the break statements pls

pallid jungle
lyric mountain
#

Break statement?

sudden geyser
#
switch (5) {
  case 5:
    System.out.println("Five!!!");
    break;
    System.out.println("God damn it, break!");
}
lyric mountain
#

That switch format is long gone from java

sudden geyser
#

wait

#

what

#

you serious

lyric mountain
#

Well, java had a shitton of updates since 1.8

pallid jungle
lyric mountain
#

Plus that switch example u gave won't print

wheat mesa
#

BEFORE you use it

lyric mountain
sudden geyser
#

is the -> special syntax

wheat mesa
#

That’s just Java’s lambda equivalent

#

(Unless I’m wrong, correct me if so)

sudden geyser
#

it doesn't seem like syntax

lyric mountain
#
var anInt = switch (name) {
	case "joe" -> 1;
	case "mama" -> 2;
	case "who?" -> {
		processThat();
		yield 3;
	} 
} 
lyric mountain
lyric mountain
#

Same as fat arrow

sudden geyser
#

I know what lambda is, but I didn't think it was compatible with switch statements

#

and it doesn't seem so since it just throws an error at me

lyric mountain
#

Version?

sudden geyser
#

11.0.6

lyric mountain
#

Outdated

sudden geyser
#

what version is required

lyric mountain
#

13 iirc

sudden geyser
#

ew

#

not lts

lyric mountain
#

Or something around that

#

There's no issue keeping java updated tbf

#

Rarely something breaks suddenly like the old days

sudden geyser
#

Yeah, I just prefer LTS stuff unless I want new stuff

pastel plaza
#

Hello

sudden geyser
#

and java's good enough where I don't need that

lyric mountain
#

13 is lts

#

Also 15 iirc

#

We're at 16

sudden geyser
#

None of them are

#

Only 8, 11, and 17 are

#

and 17 is coming in a few weeks

lyric mountain
#

Ah, nope then

#

But anyway, you're missing a lot of juice

#

Like multi-line strings

#

Oh and records

sudden geyser
#

I'm interested in virtual threads

lyric mountain
#

Records are sweet

thorny cargo
sudden geyser
#

I've never really liked records in any language

lyric mountain
#

I find them nice

boreal iron
#

console.log(a);
const a = "banana"

thorny cargo
#

because it didnt work at first thats why I tried it

#

and now nothing works

boreal iron
#

This won’t be your only issue as a lot of things have changed

thorny cargo
#

why tf did I update before I do a damnresearch Ok

boreal iron
#

Even unnecessary things like a few property names have changed or aren’t existing anymore

thorny cargo
#

I saw for the embeds an example...

lyric mountain
#

Oh, switches are getting pattern match on jdk 17

boreal iron
#

Well downgrade temporarily and work on the code before updating

thorny cargo
#

.send({ embeds: [embed1, embed2] })

thorny cargo
boreal iron
#

Yeah method parameters and options in this case have changed too

thorny cargo
simple stump
#

Just wondering, but there is a weird issue with my bot. When I leave it running overnight via console, I get an error that the bot can’t connect to Discord or that handshake failed (don’t have the error right now cause I’m out). Any ideas on a fix for this?
Also the bot does stop completely/crashes.

(The bot is hosted on a raspberry pi)

simple stump
boreal iron
thorny cargo
errant flax
#

dumb question but whats react?

thorny cargo
#

that ^

sudden geyser
wheat mesa
feral aspen
#

Can my bot edit a message that the bot sent 1 year ago?

#

.. since it errors when I do so. 😭

coarse topaz
#

How can I get a list containing the IDs of the users who reacted to a message with a specific reaction?
Please ping me when replying

#

I'd like to get that data to display it later this way:

//example
message.channel.send(`People who reacted with ${reaction}: \n<@${user.id}>, <@${user.id}>, <@${user.id}>`)```
chilly sparrow
#

Can anyone tell me why my for loop within this function is not completing, and instead only enters the first available option. My goal is to once it explores the first node depth-first, it should go back and check the others. But for some reason it only checks the first and stops.

lyric mountain
#

I don't get how people can read anything when source code is THAT colored

#

Also spaces and newlines are your friend, you don't get lighter applications by not using 'em

old cliff
lyric mountain
#

If it has more than 3 colors I panic

#

That's why I love intellij theme so much

earnest phoenix
#

There is a theme on Jetbrain IDEs that make everything a rainbow iirc

lyric mountain
#

Tf

earnest phoenix
#

If I find it I will send it here

#

kekw

chilly sparrow
#

figured it out

#

it was because i didnt do for (var i=0...

chilly sparrow
old cliff
#

wtf stop using that ew

earnest phoenix
#

imagine using var

#

nerd

chilly sparrow
old cliff
#

Use let or const (const preferred - but not for beginners)

chilly sparrow
#

ty šŸ™‚

#

var is global right?

earnest phoenix
#

var is old

#

it isn't typically used anymore cause of the issues it caused

#

so let is most commonly used in its place

#

let is for when you wanna define a variable that can change values, and const is ofc for a var thats value never changes

chilly sparrow
#

ahh gotcha thanks

earnest phoenix
#

In basic terms, You can redefine the value of a variable using the let keyword, const you can't do such.

chilly sparrow
#

man everytime I use any other language I just love python more and more

earnest phoenix
#

kekw

severe dawn
#

Excuse me, I want to ask. Why if someone tags me, it doesn't show up in history mentions. In fact, all roles do not appear only a few.

earnest phoenix
#

try restarting discord

severe dawn
#

I've been in and out of Discord. I've also reinstalled discord. I've also tried logging out and logging back in.

#

Still same

earnest phoenix
#

excuse me sir

#

that's not pings that's Lord of the Pings

earnest phoenix
severe dawn
#

So, is it not logged in because of history mentions due to too many pings?

earnest phoenix
#

It's probably wayyyy down the mentions list

#

Try using the filter button

severe dawn
earnest phoenix
#

Press the three dashes on the side

#

And select only this server

severe dawn
#

Ok

#

Its empty

severe dawn
earnest phoenix
#

@severe dawn

#

Try checking now

#

It should show my message

severe dawn
#

Still same

earnest phoenix
#

weird

#

probably an issue with discord

severe dawn
#

Yes

#

This has happened about 1 month ago.

earnest phoenix
#

maybe the 6903 pings are starting a war with each other trying to be the first in your mentions list

errant flax
#

whats the best way to keep a user logged in?

#

and how do i make a "global" variable" that could be access from any file??

earnest phoenix
errant flax
#

oh

#

i thought theres a more efficient and quicker way to d that

pale vessel
#

globals.foo = "value"

errant flax
earnest phoenix
#

what is globals

pale vessel
#

foo // "value"

earnest phoenix
#

window for node?

pale vessel
#

The global object, literally

#

Anything you can use globally

earnest phoenix
#

they said every file

pale vessel
#

Yes

earnest phoenix
#

wouldn't you have to redeclare it

pale vessel
#

no

errant flax
#

lemme try

earnest phoenix
#

nice

#

so all my imports have access to the variable?

pale vessel
#

Sjsjsbsbsbs

earnest phoenix
#

frappajappajooza

pale vessel
#

It's technically not a variable

#

You just use foo

#

I think doing foo = "bar" also works, without any keyword

earnest phoenix
#

eh const const = (k, v) => window[k] = v;

errant flax
pale vessel
#

Ye

#

Like URLSearchParams

#

Or performance

earnest phoenix
#

how about i just use esbuild with auto imports

errant flax
#

globals is not defined

earnest phoenix
#

and pipe the data to npx node

pale vessel
#

try global

#

I forgor

#

Or just do a = "b"

earnest phoenix
errant flax
#

it works

#

It workS

earnest phoenix
#

i just import everything from db.js so i don't have to reconnect mongo for every file

#

not really that hard

errant flax
#

u can make add a function right?

pale vessel
errant flax
#

global

pale vessel
errant flax
#

like
global.idk = () => stinky===me

pale vessel
#

Yes, you can assign anything

#

Just like a normal object

errant flax
#

oh pog it also works without global.

#

thx!

pale vessel
#

Although it's a bad practice since it could collide with a variable with the same name

errant flax
#

tru

#
require(`./db.js`)
const chalk = require(`chalk`)
global.success = (str) => {
  console.log(chalk.green(str))
}
global.failed = (str) => {
  console.log(chalk.red(str))
}
global.warning = (str) => {
  console.log(chalk.orange(str))
}

this is what i was planning to use for the global variable

#

does that mean i cant use .fineOneAndUpdate?

proven lantern
#

is there a way to get our bots to auto accept friend requests? if the bot is friends will it be able to DM the user even if they have this disabled?

split hazel
pale vessel
#

"Bots can't have friends"

#

I think the API says when you try to use the endpoint

proven lantern
#

that's rude

split hazel
#

racist

proven lantern
#

when the bots become aware discord will be sorry

#

so i need to ask the user to enable direct messages if i want to send them a DM

#

shucks

errant flax
#

whats the best way to keep a user logged in?

near stratus
errant flax
#

whats a session?

near stratus
#

........

#

lemme get a tutorial

#

@errant flax you use express ?

errant flax
#

yos

earnest phoenix
#

Hello.

Today I'm trying to send a attachment with interaction.reply function but he send me one error and i ask if someone can help me for fix this ?

Thanks you!

Error:

/moontest/node_modules/discord.js/src/util/DataResolver.js:125
    throw new TypeError('REQ_RESOURCE_TYPE');
          ^

TypeError [REQ_RESOURCE_TYPE]: The resource must be a string, Buffer or a valid file stream.
    at Function.resolveFile (/moontest/node_modules/discord.js/src/util/DataResolver.js:125:11)
    at Function.resolveFile (/moontest/node_modules/discord.js/src/structures/MessagePayload.js:240:41)
    at /moontest/node_modules/discord.js/src/structures/MessagePayload.js:205:85
    at Array.map (<anonymous>)
    at MessagePayload.resolveFiles (/moontest/node_modules/discord.js/src/structures/MessagePayload.js:205:56)
    at CommandInteraction.reply (/moontest/node_modules/discord.js/src/structures/interfaces/InteractionResponses.js:97:64)
    at Object.exports.run (/moontest/commands/Images/avatar.js:24:22)
    at Query.onResult (/moontest/events/interactionCreate.js:28:41)
    at /node_modules/mysql2/lib/commands/query.js:72:16
    at processTicksAndRejections (node:internal/process/task_queues:78:11) {
  [Symbol(code)]: 'REQ_RESOURCE_TYPE'```

I think i don’t use correct syntax?
near stratus
errant flax
#

thx! ill look into this

near stratus
near stratus
earnest phoenix
#

line 23

near stratus
earnest phoenix
#

No, as you can see I am getting the user's avatar from the discord API? Therefore, I use the MessageAttachment () function to get it

near stratus
#
<>.send({
  files: [{
    attachment: 'entire/path/to/file.jpg',
    name: 'file.jpg'
  }]
})

This is from the docs

earnest phoenix
#

yes but i generate by discord

near stratus
#

You can just put the avatar url

earnest phoenix
#

Ok i see

#

i try

near stratus
#

If you don't
then do it like this

files: [
   attachment
]

@earnest phoenix

earnest phoenix
#

Ok

#

he send me nothing

earnest phoenix
#

void only

#

i was passing ephemeral on false and it's working šŸ™‚

#

thx u bro

chilly sparrow
#

was looking at some old code from my data structures class...holy shit this gave my eyes cancer just looking at it pepowot

earnest phoenix
#

i wish i never saw that

errant flax
#

do anybody know "Restler"?
its like a requesting app for apis for mobile

surreal hamlet
#

I actually wanted to learn database integration in discord.py, does anyone have a link to any docs I can go through?

errant flax
#

how do i delete a cookie in expressjs?

#
app.get("/test",(req,res)=>{
  console.log("hi")
  res.clearCookie("hello")
  console.log(req.cookies)
  //es.cookie("hello","hi").status(200).send("lol")
})
#

req.cookies should be an empty object {}

cinder patio
#

It is probably clearing the cookie, just not mutating the req object

errant flax
#

ah

quartz kindle
#

res is response, req is request

#

clearing cookies from res, means they will not be sent in your response

#

doesnt remove them from the received request

errant flax
errant flax
#

pog ive made a "login" system

#

time to deal with cookies

spark flint
#

Anyone know how to set buildpack on Heroku?

#

I'm installing Quart and I need to set it to Python

errant flax
#
app.get("/login",validToken,(req,res))

validToken:

async function validToken(req,res){
res.send("test")
}
quartz kindle
#

you cant set headers after they are sent

errant flax
#

wdym?

#

im not setting a header?

quartz kindle
#

somewhere you are

#

show full code

forest drift
#

How do you make it so a SLASH command that has a "@ user" field added can access all users?
Like for example, in a channel that only staff can see, you could use the dyno /avatar @ user for ppl who cant even see the channel, how do you do this?

earnest phoenix
#

so slash command for specfic channels?

forest drift
#

not really, Ive made a ticket like system where one of the commands is an adduser command, where itd then add another user to the ticket, but how do i make it so u can @ the user if they cant see the channel?

#

example:
my bot

forest drift
forest drift
hybrid cargo
#

U need to click on the user ye

#

Cuz user is a optional parameter and u need to hit tab or click on it to highlight it and use it

forest drift
# forest drift

my bot doesnt list the user if they cant see the channel, but dyno can, how do i fix this?

hybrid cargo
#

The option is not selected

forest drift
hybrid cargo
forest drift
#

ok

hybrid cargo
#

Click on this

forest drift
#

;-;

#

im dumb

crimson vapor
#

You can also press tab

hybrid cargo
#

^

forest drift
#

is there a way i can make it where if you just type smt like
/ticket create
itll create it and not require the user
and if u type
/ticket create
and add a space at the end itll then auto require the user

crimson vapor
#

You can make user optional

forest drift
#

i currently have

#

im just trying to find if theres a way i can make it optional if u just type "/ticket create" and then required if you type "/ticket create ", like as soon as u add the space to the end it then auto selects the user option

crimson vapor
#

you can make user the first option, I don’t think the pressing space thing is an option but tab would work

forest drift
#

yeah...

#

darn

feral aspen
#

Uh.

#

Why can't a bot edit a message that was sent a year ago?

#

.. and the error makes no sense.

errant flax
#

does this mean the url i provided is invalid?

#

nvm fixed it

lyric mountain
errant flax
cinder patio
#

could be a pinned message

#

or a message in an announcement channel or something like that

feral aspen
#

Edit: resolved.

earnest phoenix
#

@bright thorn you're trying to install a package from github but you don't have git installed

simple stump
#

Just wondering, but there is a weird issue with my bot. When I leave it running overnight via console, I get an error that the bot can’t connect to Discord or that handshake failed (don’t have the error right now cause I’m out). Any ideas on a fix for this?
Also the bot does stop completely/crashes.

(The bot is hosted on a raspberry pi)

earnest phoenix
#

Discord became aware of covid and rejected the handshake

boreal iron
#

lol

lament rock
#

Lol

#

TLS handshakes are banned until covid is cancelled

pallid jungle
#

Can anyone help me and tell me how to create a webhook in channel and send with it everytime?

        const botname = client.user.username;
        await Channel?.createWebhook(botname, {
            avatar: client.user.displayAvatarURL({ format: 'png', dynamic: true, size: 128 })
          })
          .then(webhook => Promise.all([webhook.send({ embeds: [DeletedLog] }), webhook]))
          .then(([_, webhook]) => webhook.delete())
          .catch(() => {});
pale vessel
#

Jaheeek!

pallid jungle
#
        const webhooks = await channel.fetchWebhooks();
        const webhook = webhooks.first();
#

How can i make the bot fetch the webhook he create ?

raw nest
#

{"client_id": ["Value \"undefined\" is not snowflake."]}
I get this error if I want to put like process.env.REACT_APP_CLIENT_ID in my React App

#

I see this error on my page not in the console

worn sonnet
#

Hi

#

There is something i have been trying to do

#

whenever a certain Exception is raised when calling functions in a class

#

i want to call another function which solves that error in python

#

lemme give you some example

#
def some_function():
  try:
    # do_something
  except Exception:
    some_other_function()
#

i want to do this globally for a class

earnest phoenix
coarse topaz
#

Hello
Is there a way to like, check if the reaction from a message has been removed by a bot or by the user itself?

inner fulcrum
#

wat library u use?

coarse topaz
#

reaction removals don't appear on audit logs

#

Yeah there's collector.on('remove' (reaction, user) event handler but I need to check if the reaction was removed by a bot or by the user itself

pale vessel
#

:skull: issue

coarse topaz
#

no worries lol

ebon pulsar
#

@opaque fern

rustic nova
#

@ebon pulsar no ads

ebon pulsar
#

🄺

ebon pulsar
rustic nova
#

Not here

ebon pulsar
#

Ok but can you help me

#

😢

outer perch
#

have you actually asked anything?

ebon pulsar
outer perch
ebon pulsar
modest maple
outer perch
#

it was a choose one question

modest maple
earnest phoenix
outer perch
#

šŸ˜‚

earnest phoenix
#

Neither

outer perch
earnest phoenix
#

Guilded > *

outer perch
#

ayy, using * as all

earnest phoenix
#

Ofc

outer perch
#

almost forgot that worked

earnest phoenix
#

Who uses all

#

weirdos

outer perch
#

speaking up to normies has to be like that

quartz kindle
#

guildead

earnest phoenix
#

guildalive

outer perch
lament rock
#

the #MakeYourOwnDiscordChallenge

outer perch
#

anyone who uses OVH?

lament rock
#

I've used them before

outer perch
#

why did you stop using?

#

I wanna make sure I am picking a decent VPS xD

lament rock
#

The CPU wasn't good enough. Only 1 vCore for the lowest tier. 2GB of ram and 200GB ssd is a good starter VPS. I had multiple OVH instances, but then I moved to 1 Contabo VPS

outer perch
#

compared to Heroku, it should be better šŸ˜‚

#

anything is better than Heroku

lament rock
#

anything is better than heroku

outer perch
#

haha knew it

#

I actually have enough in Heroku

#

the problem is the updates, have to commit shit on GitHub and a full restart takes almost 2 minutes

modest maple
#

Sip I mean, that'll be no faster with your own machine

#

not unless you know how to setup a full CI workflow

#

but that'll still probably take the same time

lament rock
#

You'll want to overspec a bit so that you have some room to grow if you intend to grow large. If you use any of the popular libs like discord.js and don't practice efficient memory management, then you'll want more ram. I still want more ram anyways despite my bot only taking 175MB at 4.6K guilds

outer perch
#

wanting better even if near perfection was already achieved šŸ‘€

modest maple
#

I have plenty to spare hahayes

#

although I really wanna change this dedi

#

but pain transferring everything over is gonna be pain

lament rock
outer perch
#

anyways, my bot isn't a big thing

lament rock
#

I've got plenty of room

outer perch
#

on my machine it starts up very fast

#

like 2 to 4 seconds after hitting ts-node index

modest maple
#

yeah but you're not having to re-clone the repo, build the container and then deploy

pale vessel
#

Ts-node on prod

outer perch
lament rock
#

not compiling and pushing to prod MaikaDisgust

outer perch
modest maple
#

yeah, but thats a real bad habbit

outer perch
#

in real time like your pc?

modest maple
#

use docker, and save yourself a bunch of pain

outer perch
quartz kindle
#

docker is for pussies

#

:^)

modest maple
#

if you say pm2 tim

outer perch
modest maple
#

you're gonna get a bonk

lament rock
#

all my homies fuck their machines raw

quartz kindle
#

real men use screen/tmux

outer perch
#

raw, on action deployment

modest maple
#

say that to yourself

#

I'll chill with my setup hahayes

outer perch
#

I actually updated my bot through GitHub file manager

#

Thrice

lament rock
#

bad deploy? Just restore the vps insert buff doge

quartz kindle
lament rock
#

time to go to work. Later

outer perch
#

my bot only weighs 114 MB (not counting node_modules)

quartz kindle
#

on disk? only?

#

thats a lot

outer perch
#

yeah

#

wot

quartz kindle
#

excluding db?

outer perch
#

db is in Firebase

quartz kindle
#

then how do you have that much only from files

#

lmao

outer perch
#

it's because of the img folder

#

it's 113 MB by itself šŸ˜‚

quartz kindle
outer perch
#

if I count everything aside from the pics and node modules it's just 1 MB

#

maybe I should start compressing the pics Thonk

modest maple
#

literally pointless doing that

outer perch
#

yeah, it'll only reduce about 10%

modest maple
#

images are already compressed, your space savings are generally very very very small

#

not even 10%

outer perch
#

some pics actually compress to 70% without losing quality

azure lark
#

when i use git pull it tells me my project is already up to date but it is not, how do i fix this?

outer perch
modest maple
#

you'd be better off just lossy encoding or a webp encoder setup to customise it

#

but in reality, 113MB isnt really much

outer perch
#

ikr

#

but some day it'll be 500 MB I'm afraid

#

unless the designer stops making content xD

#

at that moment the designer will have to be me xD

modest maple
#

then store them on some other server and just do links to the images

modest maple
#

thats what I do with Crunchy when managing hundreds of gigabytes of images

outer perch
#

but I know for sure it's faster reading just the file

modest maple
#

mmm you'd be suprised

outer perch
#

šŸ‘€

modest maple
#

for images bellow 1MB storing them on a database tends to be faster than the normal filesystem (also able to make better use of caching)

#

also, if you're using this with a bot, then it's generally slower / less scalable for you because you're uploading it every time.

outer perch
quartz kindle
#

if you're uploading the original images every time, just upload them once somewhere and link them

#

if you're using them for backgrounds and stuff on canvas, keep them loaded in memory

modest maple
#

use lust because lust is good and yes

quartz kindle
#

ads

modest maple
#

we be speed

quartz kindle
#

but yes lust is good and yes

modest maple
#

\o/

quartz kindle
#

exactly

azure lark
#

when i use git pull it tells me my project is already up to date but it is not, how do i fix this?

modest maple
#

have you actually committed the changes

#

and pushed those changes

#

to the right branch

azure lark
#

yes

earnest phoenix
#

@drowsy crag we got it here as well

#

How to embed this

#
function menuselection(menu) {
            switch(menu.values[0]) {
                case "Option 1":              menu.reply.send("Moderation Cmd -: ```$lock, $unlock, $ban, $kick, $unban```", true)
                break;
#

How to add embed command in it

#

message.channel.send({embeds[embed]}}

earnest phoenix
#

menu.reply line

#

All you have to do is change your message to embed.

humble crane
#

How to put playing
Invite Cater bot in our status?

earnest phoenix
#
function menuselection(menu) {
            switch(menu.values[0]) {
                case "Option 1":              menu.reply.send("Moderation Cmd -: ```$lock, $unlock, $ban, $kick, $unban```", true)
                break;
                case "Option 2": 
                    menu.reply.send("the reply for option 2", true)
                break;
                case "Option 3": 
                    menu.reply.send("the reply for option 3", true)
                break;
      
            }
        }
earnest phoenix
#

As i said just change to embed message you sent

#

And its better to edit message sending new one doesnt seem good

#

@earnest phoenix actually can i share replit multiplier link coz i cant identify

old cliff
#

Can anyone help me make this memory efficient?

/**
 * @param {number[]} heights
 * @return {number}
 */
const largestRectangleArea = (heights) => {
    const getChains = (arr) => {
        const toReturn = [];
        for (let i = 0; i < arr.length; i++) {
            for (let j = arr.length; j > i; j--) {
                toReturn.push(arr.slice(i, j))
            }
        }
        return toReturn;
    }

    const getSmallest = (arr) => {
        return Math.min(...arr)
    }

    const getMagic = (arr) => {
        return getSmallest(arr) * arr.length;
    }

    return getMagic(getChains(heights).sort((a, b) => getMagic(b) - getMagic(a))[0]);
}```
#

Because a very long input is making the js v8 engine go crazy

#

and crash in runtime

split hazel
#

why tho

old cliff
#

and this very specific input is a part of the program test

split hazel
#

what a weird puzzle

old cliff
#

My code is working except for these eternity long arrays

split hazel
#

js probably optimises this but I recommend moving functions outside of functions first of all

old cliff
#

ok

#

Still crashes in runtime

split hazel
#

I assume those array values are long lived hence why they aren't getting garbage collected

earnest phoenix
#

how do I get the shard ID in d.py

split hazel
#

would run the code on my own to play around with things but not on computer

earnest phoenix
#

idk why but my code returns 0

split hazel
#

any ways you could think of to reduce the array size?

cinder patio
#
const len = arr.length:
for (let i=0; i < len; ...) {
   for (let j = len; ...) {
}
old cliff
#

I see where the inefficiency is...

#

fuck me

split hazel
#

I'm not exactly a big person on those unrealistic puzzle questions lmao

#

I haven't checked out the exact puzzle details but if you're going to be storing huge amounts of things in arrays you should either increase memory usage by node (isn't ideal) but the best solution is to well not use so many elements

old cliff
#

Got a workaround... but this is the next input 😦

cinder patio
#

I wanna solve this

old cliff
#
/**
 * @param {number[]} heights
 * @return {number}
 */
const largestRectangleArea = (heights) => {
    const getChains = (arr) => {
        const toReturn = [];
        for (let i = 0; i < arr.length; i++) {
            for (let j = arr.length; j > i; j--) {
                toReturn.push(arr.slice(i, j))
            }
        }
        return toReturn;
    }

    const getSmallest = (arr) => {
        return Math.min(...arr)
    }

    const getMagic = (arr) => {
        return getSmallest(arr) * arr.length;
    }

    const checkEqual = (arr) => {
        return arr.every((item, index) => {
            return item === arr[0]
        });
    }

    if (checkEqual(heights)) {
        return heights.length * heights[0];
    }

    return getMagic(getChains(heights).sort((a, b) => getMagic(b) - getMagic(a))[0]);
}```
#

My code till now... might help you

#

Successfully crashed vsc when I pasted the array...

quartz kindle
#

where does the input come from?

#

cli?

#

or file?

old cliff
#

Got a way... not to save in array... but to process it when generated

cinder patio
#

Wait I'm so confused, why is the output of [2, 1, 2] 3

old cliff
#

1,1,1

#

Horizontal rectangle

cinder patio
#

fuck

old cliff
quartz kindle
#

is there a width limit for the rectangle?

#

otherwise isnt the largest rectangle most likely gonna be 1 height N width?

pallid jungle
#
2021-09-08T18:37:16.841144+00:00 app[Worker.1]:     var status = mentionedMember.presence.status;
2021-09-08T18:37:16.841145+00:00 app[Worker.1]:                                           ^
2021-09-08T18:37:16.841146+00:00 app[Worker.1]: 
2021-09-08T18:37:16.841147+00:00 app[Worker.1]: TypeError: Cannot read properties of null (reading 'status')

If the user is offline

dull terrace
#

Good evening,
does anyone know how I can post the total number of servers in my bot? By adding the number of servers on each shard

earnest phoenix
#

Hii

#

Is it normal for the bot to be offline every once in a while?

#

I'm hosted it in repl.it and uptimerobot

#

And i selected interval 5 minutes

grim aspen
#

i thought repl.it wasn't supported anymore

#

i'd be surprised

#

check your code too to see if there are any errors

earnest phoenix
#

Can i host it on glitch ?

grim aspen
#

glitch is banned

#

i suggest a vps

earnest phoenix
#

It's normal ?

earnest phoenix
grim aspen
earnest phoenix
#

?

#

Ahaa thank you bro

grim aspen
#

np

earnest phoenix
woeful pike
#

man this is by far the most useless restriction I've ever come across

quartz kindle
#

lol

quartz kindle
#

so you dont need to count them yourself, as long as you send the shard ids in the request

dull terrace
boreal iron
signal estuary
#

how do I delete something from a collection? For example the collection named "test

client.test.delete(key)

Does this work?

sudden geyser
eternal osprey
#

how do i get all user roles?

#

so all the roles a user has in v12

earnest phoenix
#

<Member>.roles

urban slate
#

Hey guys is it possible to host my discord bot on an old machine that runs on windows 7? If yes then how? Cause the only way i know to start my bot right now is by doing node . In vscode but is this even possible in windows 7?

sudden geyser
#

yeah

#

Install node like you would and run your bot

urban slate
#

Wait really?

sudden geyser
#

probably

urban slate
#

Will it run?

#

Oooo

#

Imma do that

#

How do i fire up my bot from node though? Rn i just do it from the terminal in vscode

sudden geyser
#

You'd open your command prompt in the bot directory then run the command

#

That's what you're doing when you're in vscode

urban slate
#

Ohhh okk

#

Thanks mate

novel jetty
#

How can i make it so my bot also works with mention as prefix. Its has prefix which is . and i want it so it also works like botMention``command

if(!message.content.toLowerCase().startsWith(dbPrefix)) return 
  const args = message.content.slice(dbPrefix.length).split(/ +/g);
  const command = args.shift()?.toLowerCase()
  if(!command) return
  // if(!command || commands.has(command) || aliases.get(command)) return
  const cmd = commands.get(command) || aliases.get(command)
  if(!cmd) return console.log(`Command not found or Disabled`)
  try {
    await cmd.run({ client, message, args })
  } catch (error) {
    console.log(error)
  }
sudden geyser
#

You can check if the message starts with a mention of your bot (<@...>)

#

And since the prefix is separated from the command by a space, you don't need to slice by the prefix length.

#

Instead just break it up by spaces (remove .slice(...)) and .shift() out the first arg (which will be the mention or prefix)

small tangle
#

@drowsy crag

quartz kindle
quartz kindle
pallid jungle
#

How can i like when if i am going to send in channel

message.channel.send({ content: 'test' })
message.channel.send({ content: 'test2' })
message.channel.send({ content: 'test3' })

How i set timeout for each message

#

And if the message is in event too

sudden geyser
#

Do you want to wait for X amount of seconds before sending another message

pallid jungle
sudden geyser
#

well you could just use setTimeout

pallid jungle
#

that will work ?

#

It will be only one message

cinder patio
sudden geyser
#

Then you could consider pushing your messages on to a queue and execute them in order

pallid jungle
sudden geyser
#

e.g.

let op = [];

on("message", (msg) => {
  op.push(() => msg.channel.send("yeah"));
})

setInterval(() => op.shift()?.(), 5000);

This is a basic example that just pushes the operation to send a message into op and calls it later.

sudden geyser
#

though I personally don't recommend it

#

because that's going to be a global queue

#

but if that's what you want go ahead

quartz kindle
pallid jungle
#

For webhook

sudden geyser
#

Your library should handle rate limits for you

pallid jungle
#

I am using webhooks to send logs so yea bot gets ratelimit

earnest phoenix
#

who here knows JS very well

#

I need help sigh

sudden geyser
#

just ask your question pls

wheat mesa
earnest phoenix
#

I need help fixing my command to deploy slash commands globally cause it didnt deploy globally I found out recently

simple stump
#

I'm trying to add a role to an user, but I get the error that .add is undefined. What's the correct code for this/what am I doing wrong?

            var role = message.member.guild.roles.cache.find(role => role.id === "885269051125932113");
            let mention = message.mentions.users.first();
            console.log(mention.member);
            if (!mention) {
                message.reply("Please mention an user!");
            } else {
                mention.roles.add(role);
                mention.roles.remove("877244655866093638");
            }

Error:
mention.roles.add(role) TypeError: Cannot read property 'add' of undefined.

wheat mesa
#

You’re getting a user object

#

User objects don’t have roles

#

Get the member object of the mentioned user instead

earnest phoenix
#
 * Required Modules
 */
const { Client, Intents, Collection } = require("discord.js"),
  client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MEMBERS] }),
  { readdirSync } = require("fs"),
  { prefix, token, color } = require("./settings.json"),
  { REST } = require('@discordjs/rest'),
  { Routes } = require('discord-api-types/v9');

/**
 * Ready event
 */
const commands = [];
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));

// Place your client and guild ids here
const clientId = '123456789012345678';
const guildId = '876543210987654321';

for (const file of commandFiles) {
    const command = require(`./commands/${file}`);
    commands.push(command.data.toJSON());
}

const rest = new REST({ version: '9' }).setToken(token);

(async () => {
    try {
        console.log('Started refreshing application (/) commands.');

        await rest.put(
    Routes.applicationCommands(clientId),
    { body: commands },
);

        console.log('Successfully reloaded application (/) commands.');
    } catch (error) {
        console.error(error);
    }
})();

client.login(token)``` where am I messing up ![sigh](https://cdn.discordapp.com/emojis/879178900272451625.webp?size=128 "sigh")
sudden geyser
#

well where are you

earnest phoenix
#

in index

#

trying to global deploy

#

where do I get clientid and guildid

#

my id?

#

nvm

#

dumb question

#

where is guild ID tho

wheat mesa
#

Guild id is the id of the guild you want to deploy your commands to

earnest phoenix
#

so do I remove that if wanna do global or?

wheat mesa
#

Global commands take about an hour to register, I’d recommend using guild commands as those are instant if you’re testing

earnest phoenix
#

no trying to do global

#

I got it working in my server

#

but trying to do global

wheat mesa
#

Not sure, I don’t use djs+I’m typing one handed on mobile rn so I can’t look into it

earnest phoenix
#

anyone?

boreal iron
#

client.application.commands

#

Use the app command manager to register/edit/delete (global) commands

#

Take a look at the methods, it’s self explaining

#

Examples are documented as well

#

And yeah keep in mind it can take up to one hour until they are deployed in any guild

earnest phoenix
#

@boreal iron

 * Required Modules
 */
const { Client, Intents, Collection } = require("discord.js"),
  client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MEMBERS] }),
  { readdirSync } = require("fs"),
  { prefix, token, color } = require("./settings.json"),
  { REST } = require('@discordjs/rest'),
  { Routes } = require('discord-api-types/v9');

/**
 * Ready event
 */
client.on("ready", () => console.log(`[ ${client.user.username} ] : Connected to Discord!`))

client.commands = new Collection()
client.color = color

/**
 * Load all the available commands
 */
for (let dir of readdirSync("./commands/")) {
  let commands = readdirSync(`./commands/${dir}/`).filter(file => file.endsWith(".js"));
  for (let file of commands) {
    const command = require(`./commands/${dir}/${file}`)
    command.category = dir
    if (!command.data) continue;
    client.commands.set(file.replace(".js", ""), command)
  }
}

/** 
 * Message Event
 */
client.on("messageCreate", async (message) => {
  if (!message.guild || message.author.bot) return;
  if (message.content.startsWith("!deploy")) {
    if (message.author.id !== "450634297871695896") return message.channel.send(`āš”ļø | This command can only be used by server owner.`)


    const rest = new REST({ version: '9' }).setToken(token);
    console.log('Started refreshing application (/) commands.');
    await rest.put(
    Routes.applicationCommands(clientId),
    { body: commands },
);

    console.log('Successfully reloaded application (/) commands.');
    return message.channel.send("āœ… |  Slash commands will be deployed soon..")
  }
})

/**
 * Interaction Event
 */

client.on("interactionCreate", async (interaction) => {
  if (!interaction.isCommand()) return;
  await interaction.deferReply().catch(err => { })

  const { commandName } = interaction;
  const command = client.commands.get(commandName)
  if (!command) return interaction.followUp("Unknown Command: Can not find this command in bot.")
    .catch(console.warn)

  if (command.category === "nsfw" && !interaction.channel.nsfw) return interaction.followUp("This command is restricted to nsfw channels.")

  try {
    if (command) await command.run(client, interaction)
  } catch (err) {
    console.log(err)
    return interaction.followUp(`Something went wrong while executing the command.`)
  }
})

client.login(token)``` is the original code used
#

what do I change in that

boreal iron
#

I’m driving…
You will have to create your own command handler being able to register commands or edit them if your local command files have changed

#

Pushing your commands over and over again is useless API spam

earnest phoenix
#

is that what its doing?

boreal iron
#

The docs I mentioned are explaining well how to use the create method to register commands or set etc

wheat mesa
#

Stop driving while on your phone fake angeryBOYE

boreal iron
#

Shh

#

It’s not like I’m driving in a city

#

With lots of traffic

earnest phoenix
boreal iron
#

Yeah expected it to be the index oldEyes

earnest phoenix
#

do I keep await rest.put( Routes.applicationCommands(clientId), { body: commands }, ); as client id or put as my bots ID?

boreal iron
#

That’s the reason I said:

Pushing your commands over and over again is useless API spam

#

Not needed as djs has inbuilt methods to push them

earnest phoenix
#
 * Required Modules
 */
const { Client, Intents, Collection } = require("discord.js"),
  client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MEMBERS] }),
  { readdirSync } = require("fs"),
  { prefix, token, color } = require("./settings.json"),
  { REST } = require('@discordjs/rest'),
  { Routes } = require('discord-api-types/v9');

/**
 * Ready event
 */
client.on("ready", () => console.log(`[ ${client.user.username} ] : Connected to Discord!`))

client.commands = new Collection()
client.color = color

/**
 * Load all the available commands
 */
guild.commands.fetch()
  .then(commands => console.log(`Fetched ${commands.size} commands`))
  .catch(console.error);

/** 
 * Message Event
 */
client.on("messageCreate", async (message) => {
  if (!message.guild || message.author.bot) return;
  if (message.content.startsWith("!deploy")) {
    if (message.author.id !== "603411112901214218") return message.channel.send(`āš”ļø | This command can only be used by server owner.`)


    const rest = new REST({ version: '9' }).setToken(token);
    console.log('Started refreshing application (/) commands.');
    await rest.put(
    Routes.applicationCommands(clientId),
    { body: commands },
);

    console.log('Successfully reloaded application (/) commands.');
    return message.channel.send(":white_check_mark: |  Slash commands will be deployed soon..")
  }
})

/**
 * Interaction Event
 */

client.on("interactionCreate", async (interaction) => {
  if (!interaction.isCommand()) return;
  await interaction.deferReply().catch(err => { })

  const { commandName } = interaction;
  const command = client.commands.get(commandName)
  if (!command) return interaction.followUp("Unknown Command: Can not find this command in bot.")
    .catch(console.warn)

  if (command.category === "nsfw" && !interaction.channel.nsfw) return interaction.followUp("This command is restricted to nsfw channels.")

  try {
    if (command) await command.run(client, interaction)
  } catch (err) {
    console.log(err)
    return interaction.followUp(`Something went wrong while executing the command.`)
  }
})

client.login(token)```
boreal iron
#

That’s the site I posted a few mins ago

earnest phoenix
#

what I have so far

earnest phoenix
boreal iron
earnest phoenix
#

I dont remember shit from my coding days

boreal iron
#

Will take a few hours and will be early in the morning anyways which means I will jump into my bed

earnest phoenix
#

so that a yes or no

boreal iron
#

Actually I can’t as I’m only available while driving lol

earnest phoenix
#

lmao

#

b r o

#

the person I paid to do it isnt replying rn sadge

boreal iron
#

I mean building a proper command handler isn’t hard

earnest phoenix
#

it is when you dont know anything thats in it

boreal iron
#

I remember I posted the required steps earlier

#

Yeah that’s true

earnest phoenix
#

yes but the fact he did it completely different means something is up

coarse topaz
#

How can I make that if check to run only after the for loop from above is over?

boreal iron
#

don’t get me wrong but you can’t expect to drive a car without knowing how to do so

earnest phoenix
boreal iron
#

Wouldn’t be an issue if I only had time to do so lol

earnest phoenix
boreal iron
#

Expecting to be back at PC at Saturday

#

Maybe Friday evening

#

Just be patient maybe someone else can help u

earnest phoenix
#
08.09 18:30:27 [PebbleHost Loader] ----------------------------------------------
08.09 18:30:27 [Bot] Startup /index.js:22
08.09 18:30:27 [Bot] Startup guild.commands.fetch()
08.09 18:30:27 [Bot] Startup ^
08.09 18:30:27 [Bot] Startup ReferenceError: guild is not defined
08.09 18:30:27 [Bot] Startup at Object.<anonymous> (/index.js:22:1)
08.09 18:30:27 [Bot] Startup at Module._compile (node:internal/modules/cjs/loader:1101:14)
08.09 18:30:27 [Bot] Startup at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
08.09 18:30:27 [Bot] Startup at Module.load (node:internal/modules/cjs/loader:981:32)
08.09 18:30:27 [Bot] Startup at Function.Module._load (node:internal/modules/cjs/loader:822:12)
08.09 18:30:27 [Bot] Startup at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)
08.09 18:30:27 [Bot] Startup at node:internal/main/run_main_module:17:47
08.09 18:30:28 [PebbleHost] Server shut down (running)
08.09 18:30:28 [PebbleHost] Server stopped```
#

after I editted

boreal iron
#

It’s also worth to search the web for some examples how to do so to get back into coding

earnest phoenix
#

I would, but my brain is slowly deteriorating from my brain damage (the memory portion)

#

frontal lobe damage

#

started to get worse after I was 17

#

had since birth

boreal iron
#

brb

earnest phoenix
#

slash commands are only working in my server sus

#

Ive already paid like 40 on this bot lmao

#

for development

wheat mesa
#

This is precisely why you don’t hire shady devs for money

coarse topaz
boreal iron
earnest phoenix
boreal iron
#

Wut?

earnest phoenix
#

add me

boreal iron
#

Huh how can I help you?

#

Trying to be more detailed… will take a while to write

#
  • create a function to load your local command files into a map for example
  • create another function to actually load the commands (register/edit/delete)

The function should do;

  • fetch the global commands registered by Discord
  • loop through thr frtched commands
  • check if your local command map HAS the registered command

If yes, then check it the name, description or options match each other, if not update the command

If no, delete the registered command as it doesn’t exist locally anymore

  • if the loops of registered commands end but thr there are still local commands missing, then register them
#

These two loops (fetched registered commands & locally loaded ones) are merched together

terse flume
#
 .addSubcommand(subcommand => 
    subcommand
        .setName("user")
        .setDescription("send you all informations off a user.")
        .addUserOption(option => option.setName("target".setDescription("lol"))))

why does i get this error? (btw first time in djs 13 i like 12 more)

boreal iron
#

Attention - English might be drunk

terse flume
quartz kindle
#

you have "target".setDescription("lol")

#

strings dont have a setDescription function

terse flume
#

i know i see the error rng

#

ty

boreal iron
quartz kindle
#

easily fixable by hacking the string prototype :^)

boreal iron
#

Or write the object by hand instead of using this ugly methods

#

Less characters to write, no need to fucking import the ugly messageembed class and no confusion

terse flume
#

where is the error? lmao

boreal iron
#

You’re passing an array as field value

#

It must be a string

terse flume
#

but----- in 12 it worked why did the dev“s removed it

#

lol

boreal iron
#

If you wanna add multiple fields then call the method multiple times

#

Or just use new lines

terse flume
#

i wanna make it look like that (my old v12 bot)

boreal iron
#

.addField()
.addField()
…

terse flume
#

not thousand field

#

s

boreal iron
#

Those are just like breaks

terse flume
#

ik

#

but in 12 it worked

boreal iron
#

\n

terse flume
#

why does it not work in 13?

boreal iron
#

Because v12 had a damn weird compatibility of supporting basically not well formatted inputs

terse flume
#

whats the cleanest way how to do it compatibil

#

in more then 1 line.

boreal iron
#

Anyway just add the line breaks and remove the brackets of the array