#development
1 messages ยท Page 2006 of 1
data: new SlashCommandBuilder()
.setName('whois')
.setDescription('To see members information')
.addUserOption(option =>
option
.setName('user')
.setDescription("Enter who would like you to know their information")
.setRequired(true)
),
async execute(interaction, client) {
await interaction.channel.send({embeds: [embed]})
},``` just like this right
Yeah
You mean get the user object?
yap
2 secs
how to i check a people voted or not ?
use their api
howw ???
interaction.options.getUser('user')
i am toooo beginer
@bright hornet ^
dont need to do .username?
You need to await it too
assign to a variable
ohh
Hm.....
It doesn't return a promise btw*
var member = interaction.options.getUser('user)```
ok ill try this shit
await lib.topgg.get.user.voted.or.not?({
user : toast
});
quite nice XD
Alrighty
Forget var please
what
wait why
hm..nice
Long story short, var is hoisted and causes way more issues than necessary
oh
If u want the full list of reasons give it a search
const then
let = you can reassign it
const = it stays as it is
dw, I see people using var here all the time
const thing = "hi"
thing = "bye"
//error
let thing = "hi"
thing = "bye"
console.log(thing)
//"bye"
most come from very old tutorials that still used var
let is a quite new thing
Oh interesting
and a privilege devs that support IE can't afford to have
luckily for them, IE support is bound to die this year
In the old versions of JavaScript, only the var keyword existed to declare variables, and the strict equality operators (===/!==) didn't even exist
interaction.member.roles.cache.size``` this is how can i get their roles right
another difference is that let/const is block scoped, while var is function scoped```js
var x = 10;
if(something) {
var x = 20;
}
console.log(x) // 20
let y = 10;
if(something) {
let y = 20;
}
console.log(y) // 10
That's "size"
as in. You'll get the total # of roles they have (if that code is even correct I never messed with slash commands yet)
damn
.addField(`Roles [${guildUser.roles.cache.map(r => r).length}]`, guildUser.roles.cache.map(r => r).join(" "), false)
how I atleast display roles in an embed
as weird as it seems, I feel var being hoisted comes from VERY old way of programming where you declared variables on the beginning
that's the reason ye?
const member = interaction.options.getUser('user')
const member = message.mentions.members.first()``` how this is so diff
i guess it was a very early attempt at supporting some kind of static analysis
like ```js
function aFunction() {
var a, b;
a = 10;
b = 5;
console.log(a * b);
}
understandable^
I suffer that pain everyday with delphi
sucks not being able to declare a var anywhere other than the head of a function/class
delphi requires all vars to be declared beforehand at the top?
ye
yikes
These differences wouldn't even have existed mostly if Discord staff implemented slash-commands a long time ago, which they planned to implement at the very start (6 years ago) and they're being implemented now
6 years?
iirc they added support for in-code variable declaration on newer updates
but we wont be updating delphi in the foreseeable future
Yeah
why? look at how much it costs to update
yes, you also have to pay for bug fixes
yes, the IDE crashes and freezes all the time for absolutely no reason (like pressing ctrl + space)
Do people even use Delphi anymore
sad brazil reality
oh, and did I mention that you dont get database components unless you purchase the second package (there are 3 packages)?
because who would need databases anyway /s
Sounds like EA to me
Is there a link I can check out Discord.JS V14?
isn't it still nightly?
Pardon?
Those are the changes, if you want to use the v14 early, you just install the development version by running
$ npm i discord.js@dev
Would you do that?
using nigthly branches is risky
I'm afraid I don't understand what nightly means.
everything could change from one commit to another
well, how could I explain?
basically an in-dev version
Ohh. Makes sense.
still-hot bread
I don't recommend using the development/beta/alpha/nightly branches since they ship the newest code without any consideration or security checkups and breakage checks
also they almost always lack any meaningful documentation
And they're meant for testing, not production ready projects
i second this,
const user = interaction.options.getUser('user')
const embed = new MessageEmbed()
.setTitle(`Informations`)
.addField(`Member:`, `${user.username}`, true)
.addField(`Roles:`, `${interaction.user.roles.cache.size}`, true)
.addField(`Role Names:`, `${interaction.user.roles.cache.map(r => r).join(" ")}`, false)
.addField(`Joined At:`, `${moment(user.joinedAt).format('ddd, MMM Do, YYYY, h:mm a')}`, true)
.addField(`Created At:`, `${moment(user.joinedAt).format('ddd, MMM Do, YYYY, h:mm a')}`, true)
.setColor('RANDOM')
.setTimestamp()
await interaction.channel.send({embeds: [embed]})``` so after doing this, if i ping someone, it shows the role to me not in the member that i pinged
shows the role to me, what do you mean?
.map(r => r) why
it can be?
he def tried my code out 
It makes no sense.
my role is 7 roles, i pinged the other members only 2 but it shows mine
yep
need to see the codes with this slash command
It shows your roles instead of the user's roles?
ya
interaction.user refers to the user who invoke the interaction
You're getting the roles of the user who performed the interaction.
since its my code, i did that bec that's what I found on stack overflow a millions years ago and never bothered to make it better. It works
why does it make no sense?
ohhh
You pass in an array of objects, and Discord.JS, in backend, should loop through that array and handle the rest, why not keep it that way?
it does tho...
I don't see an array?
This is v13?
if i dont add the interaction gonna get the eroror
i think so, says stable on the site ๐
eroror
Since you're getting role info and all that, you should use getMember() instead, it returns the guild member instance of the user, which you can also access the user's details from the <GuildMember>.user property
I'm talking about V14. :)
oh js has varargs
when did that drop? lol
basically an open array
can u give some example?
Even if that's removed, you can just addFields(...embeds)
you don't need to declare explicitly an array, you just write whatever would go inside it
the fucntion itself can grab the values as an array normally
since interaction only define who use the command
Why not pass in an array to the argument and discord.js use the array instead of grabbing the values and putting them into an array?
how about for the members :
function aFunction(...args) {
for (a of args) {
console.log(a)
}
}
aFunction(1, "a", {}, 10)
aFunction(2, "b")
aFunction(3)
I use it all the time on java, didn't know it was a thing in js too
Yup, that's possible.
๐ really? i thought that was super common lol
The rest parameter, I believe it's called.
we call it varargs in java
Rest Parameter in JS. :)
you also dont need to declare '...args' and can access the arguments property within a function, buts its not quite the same an the array you get from using ...args
An example
// Get the guild member instance of the user.
const member = interaction.options.getMember('user');
// Username.
console.log(member.user.username);
// Roles.
console.log(member.roles.cache);
// User flags
console.log(member.user.flags);
yes, all functions have a hidden arguments variable available in its scope
You don't need to us it unless for some certain reasons.
Not sure when, though, and at what cases?
one case is checking how many params were given to the function
a(1,2,3,4,5,6) { console.log(arguments.length) }
Well args.length?
In terms to this function.
Indeed.
If you want to check the amount of arguments passed to the rest parameter, although that's not recommended if you don't want to actually use rest parameters, so that's when the arguments internal scope slot comes into play
OHH, this is the perfect example, indeed.
there are a few use cases on the mdn page
arguments and the args.length return the same value unless you have more parameters with the rest parameter, and that's when the arguements internal scope comes handy. args is for the function above from KuuHaKu.
^ another use case
ohhhh
for example ```js
function myConcat(separator) {
let args = Array.prototype.slice.call(arguments, 1);
return args.join(separator);
}
myConcat('. ', 'sage', 'basil', 'oregano', 'pepper', 'parsley');
but thats different from the actual functions arugments i guess ๐
.getMember and .getUser for slash commands
more just a destructuring example
but yes, pretty much everything you can do with arguments, you can also do with the spread operator
Exactly what I said, you don't need to use an additional rest parameter just to check for that unless you actually want to check the length of the rest parameters passed, the another thing considered with it is the function length
Rest parameters can modify the length of the function while the arguments internal scope slot doesn't, which was a fatal case in older browsers but I'm sure that was patched by someone in the team
Yup, exactly.
things get funny when u want to pass an actual array as a param
const member = interaction.options.getMember('user')``` in here, i should focus on ```js
.getMember('user')``` whatever in the `option .setName('')`?
It should be the same name as the user option's name, it just gets the guild member instance of that user instead of just returning the user
why this happened?
you didn't ack
ha?
You only have 3 seconds to respond to an interaction before it expires, if you need to respond after 3 seconds, you need to defer the response
YandereDev Simulator
interaction.deferReply()?
Yeah
you should focus on why it took 2 min tho
where should i put it? on interactionCreate event? or in the command.js?
Either their bot host is pretty shitty or they're sorting a ton of shit in that command or something
brah
Id recommend Discord time stamps for join and create dates
if you deferReply, you need to use editReply instead of reply when responding
oh i see
The reply to this interaction has already been sent or deferred.```
dunno what to tell you there 
as long as you defer once, and edit reply after that you should be fine
Aye use timestamps 
Canโt be easier to read tho 1647831025
If anyone knows how to fix this, it would be greatly appreciated.
https://cdn.ch1ll.tk/r/invalid_perms_discord.png
Found the error, it was the Start Activities perm.
I like that rgb background ๐
can anyone tell me approximately what specifications I may need to host a bot with over 200 servers (5k members on average) which will run the bot smoothly without any lags. Also Note: I'll be using flask. Thanks In advance
^
economy, leveling, moderation, integration of social media APIs
Again, that doesnโt provide too much detail on what specs youโll need
What does your bot cache? Do you run in memory databases? Do you do any intensive calculations? Etc
i mean, as long as you have around 2gb ram and not running a potato, your bot should be fine for that number of guilds unless your doing obscene things with your cache
Itโs difficult for someone to estimate specs without looking at your specific implementation
I don't need any intensive calculations. Yeah, I use databases
Be more specific on the database.
actually you don't need to be specific, just a quiet idea would be enough
start with 1gb ram 1 core and continue from there
If you're using a database known to be resource intensive, that could also need more ram.
Thereโs always the handy testing method
like mongoliadb
I use mongoDB and redis. Both are not that resource heavy.
yeah, mainly I need database for the economy but I'll also need to store social Oauth keys
well mongoliadb uses a certain % of your system's max ram by default
so it can be more resource intensive than others, depending on the configuration
hmm understood, Thanks
is there any good hosts that is cheap and accepts crypto :))
I donโt think thereโs many hosts out there that accept crypto
Never heard of one that does, but I donโt know many hosts
umm I saw some but can you tell me what's the cheapest price I can have?
so that I can compare
Iโm not sure about the cheapest hosts, especially for accepting crypto, but generally speaking you get what you pay for
most hosts that claim to be cheap also use less powerful hardware
Mainly I need a python hosting. I'll need to use flask and connect my domain to use the Oauth callbacks.
so, will also need a good bandwidth for the site
I have a shared hosting but it has gcc disabled. so, not being able to use it for hosting the bot primarily
gcc is required for python? Interesting
to install the python version of discord module
and other modules which requires that
I suppose node-gyp is a similar way, makes sense
Is there a top.gg npm module
Like when someone votes your bot it shows up in a channel
Could I get a link to it
just search on "npmjs.com/package/" ez
dunnu if it's allowed to share links, so yeah, search manually ๐โโ๏ธ
about 3 usd for 1gb ram 1 cpu
if you dont mind slow disks, yes contabo is unbeatable, nothing else comes even close
they offer nvme now which is nice ๐
i think i only have ssd, and never had any issue with read/write speeds
last time i saw someone benchmark it, they were still slow
could be yea, i remember checking the hardware when i first signed up and it was a little older than i'd have liked
its usually not a problem since most programs wont be doing lots of reading and writing from disk
easy to reduce writes as well if you cache temporarily... but i wont start that again lol
I was getting flamed the other day cause i cache my active db items for a minute before saving ๐
im running a full text search based on grep lol
ye, its used to find lines in a text file
this is for parsing your astronomy datasets? ๐
thanks
ig 1gb ram and 1 cpu is enough for early stage
sort of yes lel
i have a huge list of keywords and names that can be searched for, but i didnt find any tokenizer that was good enough
grep still gives me the best matches
this is not usable https://github.com/timotejroiko/ftset ?
i did use it a first, but since its inside the program, its also blocking and limited to 1 thread
grep can be multithreaded if searching through multiple files
ahhh ok ok, so your outsourcing it ๐
and its non blocking to the progam
ftset is faster to search in a single file
but grep is faster for multiple files
how many files are there?
about 8 or 9
ahh ok, so how much faster is it to use 'native' grepping?
well, with ftset i was getting anywhere from 10ms to 50ms per query
with grep im getting an average of 10-20ms
im caching all queries tho, so they will only actually grep once
after its cached is < 1ms
is that heavy on the rams?
the movie website? 
ahh ok, so a lightweight key->value storage
ye
can you give me the website link :)
I wonder how my cache system compares to others
lmdb is kinda like redis but embedded like sqlite
ohhh, so its a recoverable cache too? like, in between boots?
ye it has persistence
nice! thats a thing i did not bother with as I'm mostly cacheing mongodb objects ๐
my brains hit a complete dead end for what to do to improve this more ๐ญ
thanks again ๐
labels would be nice, or do you have placeholder labels instead?
Does someone know why Structures.extend return undefined on v13 ?
because it was removed in v13
yea it has placeholder type labels
and tooltips
nice
Oh so i should use prototypes or is there something else ?
I was going to stop writing it and just use the Discord RPC Maker app someone linked when I first showed it, but eh, theres no fun in that ๐
I also needed to poll an api for json data for like, players and server counts
yes, you can try using prototypes
Okay thanks :)
dope
i get this error:
ModuleNotFoundError: No module named 'discord.ext.commands.bot'```
I just ran import topgg
how do i get the random data in here? seems doing this js .then((res) => { const embed = new MessageEmbed() .setTitle(res.data[0].name) .setImage(res.data[0].image.url) .addField(`Weight:`, `${res.data[0].weight.imperial}`, true) .addField(`Height:`, `${res.data[0].height.imperial}`, true) .addField(`Bred for:`, `${res.data[0].bred_for}`, true) .addField(`Breed Group`, `${res.data[0].breed_group}`, true) .addField(`Life Span:`, `${res.data[0].life_span}`, true) .addField(`Origin:`, `${res.data[0].origin}`, true) .setColor('RANDOM') .setTimestamp() message.channel.send({embeds: [embed]}) }) only focus on the first data
nvm
fixed
In d.js v13 is there a way to get the number of voice channels the client is playing on
how can i make this emoji?
Any of your files named as discord?
Nope
okay so i want my bot to have time when the message is sent by the user in any channel in epoch format, for python
how can i do this?
< : HOUSE_BRILLIANCE : 735339675102871642 >
^ that, but no spaces
oh, that ones slightly different actually, my bad ๐ฆ
thats topggpy right?
yes but I fixed it
you use pycord?
at first yes, but I switched to discord.py
owh okay, i guess the problem occur because topggpy needs d.py 1.7.3 dependancy that may cause error for people who uses pycord since they use the same import name, thats why for pycord you must install it using --no-deps
idk what epoch is (Google says some archaeological stuff)
but anyway just use unix timestamp and let discord format it
try using message.created_at.timestamp() * 1000
im trying to run nodemon but i just geet this error here how can i fix it? nodemon : File C:\AppData\Roaming\npm\nodemon.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Pol icies at https:/go.microsoft.com/fwlink/?LinkID=135170.
Run powershell as admin
then run ```ps
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
thanks
you use index 0 to access items
you can randomize the indexies
how i can add my website as bot description? i forgot website that converts
Wdym by bot description ?
About Me ? If yes it's on the developer portal
If you're talking about Top.gg bot page's long description, you can use the iframe tags, if you're talking about the bot's about me section, all you can do is to add a link to your website to it from the Discord developer portal
yeah iframe is answer thanks
How do I get the duration of an mp3 file? Iโve tried reading the metadata, used different libraries (mp3-duration, music-metadata, etc.) but they all return different values than the actual duration. I essentially download an mp3 file using node-fetch or axios and store it locally, then read the file and stream it using Discordโs @discordjs/voice. Iโm attempting to get the duration of the file and display the total time of what is being played, but when trying to get such duration it always returns the wrong output.
Donโt quote me on this because Iโm not sure entirely, but the buffer length is probably directly related with how long the song is
ffmpeg can do that
also, where are you downloading the mp3 from?
audio files can be of bad quality and contain garbage data
Yeah, I just looked at the code for some duration packages, and they use ffmpeg internally

https://github.com/caffco/get-audio-duration/blob/main/src/index.ts seems pretty simple to do yourself if you wanted to reduce dependencies as well
This error makes no sense
Are you sure that line 40 doesnโt have spaces instead of a tab? I donโt use python, not so sure
That looks like spaces to me.

No but Iโm intending it
Iโm going to trust the python interpreter on this one
And say that youโre doing SOMETHING wrong
did you make sure to enable indents for ur bot bro
What? 
its all because of that damn phone of urs
guys I'm trying to do a function that outputs 2 results
for example
return 1,"hello"
and if I do
thatFunction[0] it would return 1
and if I did [1] it would return "hello"
would that be possible to do?
Uhh, sure.
const values = [1, "hello"];
console.log(values[0]); // 1
console.log(values[1]); // "hello"
I figured an array would do it
Indeed, that would work.
is there a way to do it without an array though?
function athing() {
return {a:1, b:2};
}
athing().a
athing().b
function otherthing() {
return [1, 2];
}
otherthing()[0]
otherthing()[1]
Can you eat an apple without eating it?
that actually works?
your just returning an object, or an array, and then using that data
Dude, why all of this. ๐
let me test
idk, why not ๐
huh that actually works
yup, but you should do the function call and store the value before referencing its properties, eg:
const mything = athing();
mything.a```
const athing = () => ({ a: 1, b: 2 });
athing().a
athing().b
const otherthing = () => [1, 2];
otherthing()[0]
otherthing()[1]
This is better. ES6 Moment
to extract the values you'd usually have to do
function().then((0, 1) => {
return 0,1;
} no?
cause if I do them separately and call the function two times
otherthing()[0]
otherthing()[1]
like so it will give two different results
I'm not sure why you would not want to use the simpler way.
why not
const athing = ()=> ({a:1, b:2});
const {a, b} = athing();
``` ?
my thing isn't a constant function
Dude, you're basically using a value of an object you defined in a function, use the simpler way.
.then is only for async function callbacks
hey, you wanted to 'es6-ify' it ๐
You can return an object
Thatโs the easiest way
it is an async function
it would only return one value
I was unaware, but even then you donโt want to fall into .then callbacks
Iโm confused
I thought you wanted multiple values
okay let me explain what I'm doing so you guys can understand
basically I have a function
If you want to return more than one value in a function you generally want to use objects for that
everything is javascript is an object. it doesnt matter if you return a value, a string, an object, an array, its all only relevant to how you handle those returned values.
if you want to return an object, do it, then handle that object
Letโs try to not be confusing about semantics right now :p
how about doing it the C way? ```js
function something(return1, return2) {
return1.value = 10;
return2.value = 20;
}
const return1 = { value: null }
const return2 = { value: null }
something(return1, return2);
console.log(return1.value) // 10
console.log(return2.value) // 20
const certainFunction = function (something, something2) {
//do stuff with something and something 2
return {result:something, result2:something2};
//return them
}
and then somewhere else in the code I call the certainFunction
certainFunction(input, input1);
I want to be able to call that function and get both of the outputs out of it, by your guys example I figured it would be like so
const {result, result2} = certainFunction(input, input1);
and I want them both because I want to use them in a switch case like so:
switch (result) {
case "modified-something-here":
//rest of the code
conssole.log(result2);
break;
@wheat mesa @neat ingot
apologies for taking so long
that was hilarious!
yep this might be alright too
omg im dying lol
so would my example above work correctly?
depends on a few things
is something and something2 a primitive? like number, string, etc? or are they objects/arrays?
both are strings
i think that looks right
ok, so they will not be accidentally modified by your function
however the something is classified and second is an object that a string is later passed onto
I'll forever do it this way from now on
lmao
The good ol mutable object reference method
is that a problem? :/
I haven't tested it yet let me see if that works
i was laughing at mistyy
scared me lol
if they are unmodified, why do you need to send them to the function to begin with?
they are, the function modifies them and returns them to be used in another function, basically
They are just not explicitly done so tim
He made a comment saying to do something with something and something2
did you await your function? its async right?
else its trying to destructure a promise
it's an async but I forgot to await it
Damn, what. ๐
I don't think await here would even matter it'd just return something anyway just probably not what they want
What's the benefit from that?
explicit behaviour ๐
nothing really, its just a way of doing things. in C/C++ its often done that way
C is al lang from old times there is no benefit to most of how things have to be done in C
but since in js you cant have references to primitives, you have to put them inside an object
Failed: FATAL ERROR HAD OCCURED
Reason: TypeError: Cannot destructure property 'result' of '(intermediate value)' as it is undefined.
that's a problem
It's the most unnecessary long code which can be shortened.
i've worked with an old C lib from the 90s that returns 3 different values, one as the actual return value, and two in referenced args
Unless there are benefits from doing it in that long way, then I take it back.
the same lib also has functions that you need to pass an array to, and the function will add all the results inside the array you gave it
instead of returning an array with the values
I'll try fixing that myself then
Wait, really?
You're talking about C from the 90s?
ye
How's that possible, where is the final value stored?
in the array
like this
const result = [];
something(result);
console.log(result)
async function athing(input1, input2) {
return {
result1: `${input1}-success`,
result2: `${input2}-success`,
}
}
const {result1, result2} = await athing('test', 'result');
console.log(result1, result2);
as long as your doing something like this, there should be no issue.
the actual return value of the function is a flag indicating if the function was successful or failed
so it works like this
OHH.. instead of returning the value from the function, it stores it in the array you passed, damn.
Same as this, like you said.
const result = [];
const status = something(result);
if(status === 1) {
console.log(result)
} else {
throw error
}
libs like that are a pain imo
Hard to understand and comprehend, and can get confusing when knowing multiple languages.
const result = [];
const error = "";
const status = something(input, result, error);
if(status === 1) {
console.log(result)
} else {
throw error
}
ofc that doesnt work in js
but thats pretty standard in many C libs
like whatever the function actually uses as an arg
Oh, fair enough.
let me show the actual c code
Go ahead.
would passing one argument and outputting 2 be problem?
i have this in djs
const options = message.guild.channels.cache.map((channel) => ({ label: channel.name, value: channel.id }));โ```
but idk how to make a select element in html and forEach select option it's label is the channel name and value is the channel id(im trying to make a discord bot dashboard and need help assigning the options of a channel select dropdown to the contents of a variable)
if flag returns ok, its safe use use xx, otherwise the error will be written in serr
Goodness. 
info is the input vars
the arguments you pass, and the values you return are near irrelevant compared to how you handle/process the data.
that's great, however somehow, somewhat it doesn't work even though I've done everything correctly
didnt we already solve this some time ago?
i dont think
What's the difference between int32, int64, double, integer and maybe there are else.
i even showed you the ejs code
we didnt solve the select tho
in short: the size that the value can be
int32 = 32 bit signed integer
uint32 = 32 bit unsigned integer
***64 same thing but 64 bits
double = double precision number (aka numbers with decimals)
do you know why it might not work then?
this ig
Cannot destructure property 'result' of '(intermediate value)' as it is undefined.
not a clue im afraid ๐ฆ
you will need to show some code
it's exactly as you typed it above
int32 is the same as int
int64 is the same as long long int
uint32 is the same as unsigned int
you will need to show some of your actual code
Ohh.. thanks!
I love how folks always hoarde their code like its golddust ๐
I'm sorta confused as to why I can't access the duration object. I have this JSON object:
{
format: {
randomStuffIdk: "asdfasdfasfasdf",
duration: 34.207800453514736
},
otherThings: {
asdfasdfasdfasdfd: "asdfasdfasdf"
}
}
But for some reason, I can't access format.duration as it returns undefined.
let meta = await mm.parseFile(`./handlers/voice/music/${title}`);
let metadata = util.inspect(meta, { showHidden: false, depth: null }); // Returns the JSON object above
console.log(metadata);
console.log(metadata.format); // Undefined
let duration = metadata.format.duration;
console.log(duration); // Undefined
const function(_input){
//code
if (result == 200) {
return {
result: "success",
input: _input;
};
}
if (result == 200) {
return "error";
}
return {
result: "failure",
input: _input;
};
}
and am calling that using
const statusResult = function(input);
statusResult.result and .input
I also tried doing the await
const {result,input} = await function(input);
but that also didn't work @quartz kindle
I shortened it as much as I could
your structure cannot be like that, as this works fine:
let metadata = {
format: {
randomStuffIdk: "asdfasdfasfasdf",
duration: 34.207800453514736
},
otherThings: {
asdfasdfasdfasdfd: "asdfasdfasdf"
}
}
console.log(metadata); // The JSON thing above.
console.log(metadata.format); // <works
let duration = metadata.format.duration;
console.log(duration); // < works
if (result == 200) {
return "error";
}```
this is not an object containing the properties you are trying to destructure
so even if that part doesn't execute it has to have the correct syntax?
you also have ; instead of , in your return objects
i didnt notice there was a duplicate if statement for that status lol
yeah sorry I was kinda hurrying with the copy pasting lol
the ; is only to finish the statement
Unfortunately the JSON data is what is returned from the library I'm using
is that a problem?
well, thats what happens when you dont want to show your actual code, we end up fixing the problems with the example code you show instead of the actual problems with your actual code
I didn't write the JSON, it's just what is returned..
I can't it's wayy to big
function functionname(_input){
//code
if (result == 200) {
return {
result: "success",
input: _input,
};
}
return {
result: "failure",
input: _input,
};
}```
const function is not valid syntax
The util.inspect() method returns a string, not an object
which also means the actual problem can be anywhere else instead of the parts you're showing
Oh whoops. My bad. Thank you
Use JSON.parse() instead
I use contant functions
const something = function() {
}
I feel like I should've stated that before
could that be the issue? 0_0
no
ok, well, please, when sharing code your 'having issues with', please show the actual code, not some half whipped up filled with errors example.
sorry to be blunt ๐
why not just put it in pastebin or something
pretty sure there are pastebin variants out there that support password protection and auto-deletion after 5min and shit like that
if you're that worried about your code
i worry about my code sometimes... then i remember i plagarized every line from some tutorial somewhere, and that makes me feel better as a human ๐
nah it's not that
let me post it all
hold on I just gotta short it to message limit
any other vital options an app might need?
const getWorkingWebStatus = function (website) {
req(website, (error, res, body) => {
if (res.statusCode == 200) {
return {
result: "success",
input: `${website}`
}
}
if (res.statusCode == 429) {
return {
result: "error",
input: `${website}`
}
}
return {
result: "failure",
input: `${website}`
}
});
};
const statusResult = await getWorkingWebStatus("http://google.com/");
switch (statusResult.result) {
case "success":
console.log(`${statusResult.input} is WORKING!`);
break;
case "error":
console.log(`ERROR occurred!`);
break;
case "failure":
console.log(`${statusResult.input} is NOT WORKING!`);
break;
}
``` @quartz kindle
tim suggesting pastebin tsk tsk
well thats the problem
basically every bunch of code that matters is here
your function returns undefined
HWAT?
you return inside the req callback
Use a promise to resolve the said value
also I'd check for status family not for exact statuses
that's an issue? I'm not returning anything related to res output?
its not returning anything period
your function is basically doing this:
new Promise((resolve) => {
req(..., (...) => {
...
resolve(...);
});
});
it's an await function I don't have to resolve it
const getWorkingWebStatus = function (website) {
req(website, (error, res, body) => {}) // initiate a requst and return undefined
}
all your function does is initiate a request
it does not wait for it
it immediately returns
oh...
You're requesting a value from a callback, if you want it, you must use a promise to resolve the value
I'm confused, then what am I exactly supposed to do? take the callback out of the promise?
const getWorkingWebStatus = function (website) {
return new Promise((resolve) => {
req(website, (error, res, body) => {
if (res.statusCode == 200) {
resolve({
result: "success",
input: `${website}`
})
}
if (res.statusCode == 429) {
resolve({
result: "error",
input: `${website}`
})
}
resolve({
result: "failure",
input: `${website}`
})
});
});
};
not to spoon feed. but that is what your function could look like
You can either return the promise and resolve the value from the callback, or additionally promisify it for later use by using the util.promisify() method
function something() {
return new Promise(resolve => {
doSomethingWIthCallBack(callback => {
resolve(callback)
})
})
}
when you return a Promise, your function automaticaly becomes an async function that returns whatever the promise resovles
i think you are misunderstanding which parts of your code are async and which arent
no, async only works if the thing is already using promises
callbacks are not promises
callbacks existed way before promises did
might have
they are the old style of asynchronous coding
let me try figure this out
promises came to improve it, but if whatever you're using doesnt use promises yet, you need to turn it into a promise yourself
// create a non async function that returns a promise (and should be awaited)
const getWorkingWebStatus = function (website) {
// returns a promise that can be awaited
return new Promise((resolve) => {
// perform a non async function call with some callback
req(website, /*the callback >*/ (error, res, body) => {
resolve({ // resolve the promise we returned with an object
result: "failure",
input: `${website}`
});
});
});
};
hope that helps somewhat ๐
thanks!
I think I might actually have fixed it
running the code has no errors let me try to test the function out
it worked
amazing
thanks @quartz kindle @neat ingot @earnest phoenixand @lyric mountain lol
const events = [
{
id: 'message',
events: [
{
name: 'Message Delete',
id: 'messageDelete',
},
/*{
name: 'Message Delete Bulk',
id: 'messageDeleteBulk',
},*/
{
name: 'Message Update',
id: 'messageUpdate',
}
]
},
{
id: 'role',
events: [
{
name: 'Role Create',
id: 'roleCreate'
},
{
name: 'Role Delete',
id: 'roleDelete'
},
{
name: 'Role Update',
id: 'roleUpdate'
}
]
},
];
How can I count the number of events?
You're welcome
both from message and from role?
yes
events.reduce((a, b) => a + b.events.length, 0)
something like this maybe?
events.reduce((result, item) => {
result += item.events.length
},0);
.reduce() is really handy at times, I keep forgetting what it does and remembering the day after.
oh tim beat me lmao
I need to keep understanding it now that I am handling sharding.
is there a way to make a temporary variable that will be removed once function is over? I know I can do that in c# pretty easily
If you've already set those to the client, which I assume you've already done so, you can just do <Client>.listenerCount(), if you haven't, then you can reduce it by using <Array>.reduce(), which was already shown
everything declared inside the function only exists while inside the function
so having a normal
var object;
and then later be used for something such:
object = "string";
won't be stored?
cause I'm running to performance issues declaring a new variable with looping
When I have this code:
require('dotenv').config();
const { ShardingManager } = require('discord.js');
const manager = new ShardingManager('./src/index.js', { token: process.env.TOKEN, totalShards: 2 });
manager.on('shardCreate', shard => {
console.log(`[SHARDS]: Launched shard ${shard.id}`)
});
manager.spawn({ delay: 10000, timeout: 60000 });
The error is Error [SHARDING_IN_PROCESS]: Shards are still being spawned..
Some people told me, don't broadvast eval or fetch client values before all shards get ready. Although, I have the ready event immediately firing up, what can I do at this case?
function something() {
let object;
// do something
object = "string";
}
console.log(object) // undefined
you should first start the client then count shards
dont use the var keyword, its obsolete and has quirks. use const for constant vairables or let for variables that can change
I have the ready event immediately firing up, what can I do at this case?
anything declared inside a function only exists inside that function and its respective subfunctions and subscopes
using var is just muscle memory at this point
var is bad
I use it both with const and practically never use let
lol, fair. i ; every language i use because of habbit
Unless you know the baggage that comes along with it, you should probably not be using var
still, should try for the sake of modern code ๐
let is block scoped, var is function scoped
since JS doesn't need the ";" I sometimes forget to add it while writing in C and I can't figure out the why my code isn't running sometimes lol
give code I doubt that's where the issues are coming from
arent var declerations also hoisted ?
nothing you can do about it, catch the error and try again later
let is block scoped, var is function scoped
var amount = 5;
for (let i = _amount; i--;) {
const variable = something;
return variable;
}
take this as an example of what I'm doing
the only thing you could do is pass a timer calculated from the number of shards multiplied by the timeout between shards
it just hurts to look at how I'm declaring a new variable each loop
You should probably show the actual code of what youโre doing instead of showing vague examples
yea, but im sure the var variables are hoisted to the top of the scope and can be accessed (with no value) before definition ~ iirc, could be wrong
Is there no promise to first check that shards all finish launching first then continue to fire up the ready event?
That would run the loop only once. Variables have little to no cost so don't think that they're making your code slow
(()=> {
console.log(testvar)
var testvar = 1;
console.log(testvar)
})();
Oh thatโs what you meant, then yeah youโre right
if you declare it inside the loop, it only exists while that iteration of the loop exists, once the iteration is done, the variable is gone automatically
I figured, I'll just let it be like that
also one last question before I go, what it's the best efficient way to check if the loop has stopped?
I've been using if (i === 0) and sometimes it doesn't work or get's called before loop is actually done
Could you provide an example?
what..?
The loop condition?
for (...) {
...
}
console.log("Loop has stopped :D");
That
for (let index = 0; /* condition > */ index < array.length; index++) {
const element = array[index];
}```
all loop types have a build in condition for if they should run
But I donโt think thatโs what you meant unless Iโm wrong
there is no such thing, unless you're doing something really weird
can you show from where do you want to check that?
something like this i guess? ShardingManager({ shardArgs: [2 * 10000] })
calculate the total delay for all shards
2 shards * 10000ms delay each
give it to the shardArgs so yuo can access it from the children
then use that as a timer before using broadcastEval
but that is not an ideal solution
the last shard will wait the full time for all shards, instead of waiting just its own time
well basically
I had a function that logs something to the consAole
then loop
and then checked if it hit o and logged it's own thing, often the 0 check console.log came first before the logging from the function finished
but that may be just cause my code is really unoptimized
The idea is great, but not an ideal solution made me not do it.
its better to just catch the error and retry later
Catch the error, where?
I fixed the above with a asynchronous delay of like 3000 ms
broadcastEval
but now that it's being resolved automatically it's fixed
if you have race conditions, that means you're not using promises correctly
once you are, there should be no race conditions
anyway i g2g
Thanks for your time, Tim. 
I asked earlier but it got immediately buried lol
Any vital options I could add to my app
Canโt think of any. What framework did you use for that? React native? Electron?
electron with bootstrap and custom styling
thankies 
@quartz kindle ty the code u gave worked tysmmm
may I ask, what this app is? :)
this
but what does the app do, is it some kind of dashboard for the bot?
Discord RPC doesn't sound like a dashboard...
No it's quite literally the message you see in the picture
RPC probably Rich Presence Creator?
rich presence
like what i have rn too
the app communicates with discord on my pc to set my 'currently playing' information on my user profile. it also polls an api for information on players and servers, but that api is offline atm ๐
mines from VisualStudio, they made an app to allow you set it to whatever you want basically
can you not use the request NPM to ping an IP by itself?
just use node-fetch
@lyric mountain can node-fetch do it though?
without the port it isn't a http request
just a plain IP
without the port it's implicit to be either 80 or 443
but that's address not request
technically anything you send to an IP endpoint can be treated as a request
so setting it's port would fix it?
in order to ping an address, that address must be able to respond somehow, so it needs to be running some kind of server on some port
yeah that
for example http://1.1.1.1:80
I think ur missing the point
no
cause before I had a invalid URI error while trying to ping an IP
in order to ping, both side send messages
maybe u passed an invalid ip
you can't ping if endpoint doesn't respond
address and port matters
you tryna ping cloudflare?
port is 80 for http, 443 for https
nope, http:// and https:// are required
just for testing
if you write http:// it will automatically set port 80 for you
it didn't, it seems
5432 for pogstress
if you write https:// it will automatically set port 443 for you
I kept getting invalid URI errors
you host on the same machine right
I host the script on my PC and I'm trying to ping 1.1.1.1
which is a host as well
yep, but it is hosting
testing for hosting returns data so it is a host
๐
okay, just give me a different IP address I'll see if it fixes the error
also another possibility is that, the host refuses connectio
alright let me check then
tim why you use odd node version
its runkit
i demand node 16
node 17 is nice
or [object Object]
best gender
ngl
"hi, are you male or female?"
"im a js object"
also any good image renderer that uses svg
what platform?
wanna do programmatically
lmao
well it worked weirdly enough
I'll try with http now
you dont need anything to make svg
no
j-j-java maybe? ๐๐
let amount = 10;
var intervalAmount = setInterval(() => {
amount -= 1;
if (amount === 0) clearInterval(intervalAmount);
}, 250);
``` can anyone tell me why this doesn't work?
you can generate svg by concatenating strings
supposed to be a counter and stop once it reaches zero but it goes infinitely for some reason
for drop shadows on a transparent surface
var
never ever use === to check loop condition WITH an increment/decrement
does not work for me
then you're doing something wrong
== / === doesn't matter
runtime issue
then how else am I supposed to check?
or ==, if type is certain
nonono
When working with integers u'll never get a floating point
you see, cosmic rays are a real thing in programming
^ thats true
yes
plus iirc the compiler does some under-the-hood optimizations when using </<=/>=/> for loops
also like
tim
btw
any platform, as long as executable
and takes svg definition as argument
alright so I'll just change it to amount < 0 then
i mean, if what you're trying to do is supported by the svg spec, you can do with by concatenating strings, otherwise idk
<=
< 1
< 2
lmao which one
render to .png tho
=<=>>=<.<0.1
or .webp in this case
= 0 if u want to include 0, else use > 0
-_-
< 1
oh wait nvm, it's an inverse check
ah so you want an image rendering to convert svg to raster, in node or in browser?
yep, it's going down
โ
and canvas didnt work?
did you try sharp?
reminded me of JAVA logo for some reason
well, try random npm modules i guess
that's the idea
tim you
me me
cli compatible?
because ima run that with 1227 consecutive images
thank
also is there any event in browser to tell if javascript code is already fetched and ready to execute
I mean... if the code is executing then it's already ready and getting executed? Like what do you mean
i mean "when do browser APIs are available"
Depends on which API
why does async delay not work in setIntervals?
document should be used in an window.onload event, or in a script which has the defer attribute
on serverside render config i tried but ended up with localStorage is not defined
when the code is rendered on servers , browser APIs are not available
callback is not async
yeah localStorage is a browser-only API and you're trying to use it server-side. Check if it exists beforehand
check if you're running on the server
if (typeof window !== "undefined") {
// ... running on the client
} else {
// running on the server
}
no, I've made a asynchronous setTimeout delay thingy that works as a delay function that javascript never gave us
that is a microtask iirc
the problem is that it doesn't wanna work for some reason it doesn't work inside setInterval parentheses
please, I'm all about right syntax and 100% clean code
i wanna know when it's available so i can use them right away
localStorage is available right away if the code is running on the client
localStorage will never be available on the server
more code
it doesn't work event though the entire function is an async function
meant to be async, so
return new Promise(resolve => setTimeout(resolve, <delay>))
that's almost what I did
just put it into a constant function as alwayas
IT WORKS btw don't say it doesn't
you also have synchronus wait
for some reason it says that my function isn't async when it is whenever I try to exec it from setInterval
const delay = ms => new Promise(res => setTimeout(res, ms));
it's evaluated on server before that
pain
I've shown you the one that causes the errors
the function that hosts this block of code is async right
let me fix it then so I can paste it
it's got too much stuff in it to fit into one screenshot
answer
yep
then it should work
then issue is _speed being too small for the await to work at all
rl.question(`question`), async (_something, _amount) => {
//more code
var interval = setInterval(() => { // here is the interval
_amount -= 1;
if (_amount <= 0) {
clearInterval(interval);
await delay(_speed + 100); //this causes the error but it shouln't
return recursiveAsyncReadLine();
}
}, _something);
});
``` this is basically the entire function
rest doesn't affect it whatsoever
var
what error
that the function is not async
protip a _ prefix means intentionally unused variable outside of classes so this is probably going to end up confusing you
shouldn't it be _speed * 100 btw?
nope, just want a slight increase
no
updated it to that whilst trying to figure out
setInterval(async () => {
then u did something else wrong
maybe this
req("http://" + _ip, async function (error) {
should I convert it to an arrow function?
Most of the time it doesn't matter if it's an arrow function or a function defined with the function keyword so that's not your issue
could be though you never know
and at this point I feel braindead so it doesn't hurt to try
I think I just did
the delay didn't even work
no error though so that's progress
I won't make you help me anymore so I'll just figure it out myself
you're definitely not doing something right if that removed ur error
yeah, but I got no clue what ๐ซ
could it maybe be an IP validation function?
it uses REGEX, and only is used once in the if statement
okay I finally fixed it lmaoooooooooooooooooooooo
congrats
aaaaand now I got a different error ... I just can't
๐คญ
imagine getting error when programming
i dont
cap
work pefrectly in 1 try
massive cap
stop the cap
what is an average r/w speed for a hdd
like couple hundred mbs per sec
for a SSD prolly like couple GB
A typical 7200 RPM HDD will deliver a read/write speed of 80-160MB/s
550 MB/s for a ssd
I don't get why the god damn thing logs AFTER THE ERRORS
can I make kind of a setTimeout that runs every x time infinitely? And I want to start the timeout every time the bot starts if it dies or I update it
this sounds me of ```js
client.setTimeout/Interval
im getting 210mbps so epic
how to meter that
your disk usage lowered?
?
You could use cron depending on your use case
cron? my usecase is that, every certain time I want to add some gems to all players added in the mongodb database
will check cronjob
answer it
Are those two IDs are actually bot IDs?
he wants to get the bots from that ids
Thank you but i do understand English as well

Canโt create a test invite on mobile meh
I wonder if both IDs are actually bot IDs
wait i'll make invite
sent
Hmm one actually is a bot




