#development
1 messages · Page 1500 of 1
super great way of having good testable code
you said that C# has DI as a forerunner
I'm saying that that's .NET core
what the fuck google
whoa
F# has decent DI due to .NET
you and i both know that the dependency injection and host builder packages were built for c# and with c#
it was built for C#, and with C#, but it's not part of C#
unfortunately
anyways the point I'm trying to make is that it's not focused on one language only; if a language has OO capabilities, you can do DI easily
turns out Maps have a max
2^24
or somewhere around there
I think its just 2^24 where js will error
discord.js
My bot doesn't answer when I try to use this command.
liveGames, liveModels, liveAvatars, brGames, brModels and brAvatars are arrays.
For example, 12345 is in the liveAvatars array, so when I run "!check abc12345def", the bot should answer with "The sent creation is in my database.", but as I said, it's not answering. Am I doing something wrong?
if (message.content.startsWith(`${prefix}check`)) { let args1 = message.content.split(" "); let creationID = args1[1]; if (creationID.includes(liveGames[i] || liveModels[i] || liveAvatars[i] || brGames[i] || brModels[i] || brAvatars[i])) { message.channel.send(`The sent creation is in my database.`); } }
No errors in the console, by the way.
what is i
that code is a mess
it'd be cleaner to have it in a command handler
now from what i'm understanding i is the creationID
that code is a mess
lol
now from what i'm understanding i is the creationID
And yes
let args1 = message.content.split(" ") // This is a terrible approach for args. You should really trim off the command and prefix before splitting off args. But, it works
let creationID = args1[1] // Why not just use args1[1], also, why use numbers in a variable name. Do you already have args defined?
if (creationID.includes(liveGames[i] || liveModels[i] || liveAvatars[i] || brGames[i] || brModels[i] || brAvatars[i])) { // What is this even supposed to do? Check if the string contains an array element using an undefined variable?
message.channel.send(`The sent creation is in my database.`); // This is the only line I don't have feedback on.
}```
the ideal way of checking an array for an element is <Array>.includes(thing) or for an object Object[key] and if that returns undefined you return an error message
Well, I just tried my best lmao, I'm not that good at programming, so I firstly need to see examples and adapt them to my needs. Thank you so much for your feedback! I've taken into account everything you mentioned and now it's working perfectly well. ^^ if (message.content.startsWith(`${prefix}check`)) { let args = message.content.split(" "); if (liveGames || liveModels || liveAvatars || brGames || brModels || brAvatars.includes(args[1])) { message.channel.send(`The sent creation is in my database.`); } } Maybe it's still a total mess, but that mess works, and that's what matters
Ah, that's looking a lot better now!
there's 1 mistake still
you should do .includes(args[1]) on each of the arrays
your indentation could be changed from js } } to ```js
}
}
Ctrl + alt + L will do that for u depending on the ide
Indentations depite being purely visual, will save u tens of hours finding erros in bigger codes
My teacher used to say "you must write codes for people to read not computers, computers will see it in binary anyway"
01010100 01110010 01110101 01100101
hmm
84 114 117 101
Anyone have experience with Lavalink clients here?
I have node: set as "1" by default. If a bot has more guilds should there be more nodes?
anyone know how to get the id of the nitro booster role on a server?
discord.js btw
Loop up the role by name and see if it’s managed is my guess
thats actually a good idea ty
Actually is the role name editable?
Then that’s no good
I’m not sure if there’s a reliable way of seeing if a role is Nitro Booster.
mmm
But you can have the bot check if the user have the Booster role! 🙂
Yeah, but you can’t check what the Nitro Booster role is
good
thx maan it finally worked
ig check the role members to see if they all have the premiumSince property? but not 100% reliable
no problem
does djs implement role tags?
role tags are the only reliable way to identify a booster role
i'm not sure about the master version of it, but pretty sure it's not on v12
i got it
@app.route("/api/profile/edit/<bio>/<uid>/")
def api_profile_edit(bio, uid):
if not current_app.discord.authorized:
return(f"401 - unauthorized | API |", 401)
else:
user = discord.fetch_user()
authid = user.id
if authid == uid:
collection5.update_one({"_id": uid}, {"$set":{"bio":bio}}, upsert=True)
return("200 - ok | API |", 200)
else:
return(f"401 - unauthorized {authid} | API |", 401)```
resp:
```401 - unauthorized 393171225838354433 | API |```
url
```/api/profile/edit/pog/393171225838354433/```, the 393171225838354433 in the resp, is the id of the logged in user
the 393171225838354433 is the id of the user i "say" i am, and its the id i am
Can anybody tell me, which database system does discord use?
oh oh i know this one
Scylla
awh, i knew it just couldnt remeber how to spell it 
today I learnt https://i.imgur.com/zA5U1HX.png
What's a better idea, giving my bot a error message saying, "Your bot needs embed links permission", or saying "Your bot needs embed links permission in this channel", grading it by overall or/channel?
first one
yo
wait wadda fuck
anyone help?
this is me btw, so not like im leaking anything
ty
np
I'm trying to make an array that is filled with random bytes or hex, then turn it into an image buffer into discord

how bout using crypto
ello
how do I collect messages in discord.js
command = s.game
bot = memorize these words - words 1 words 2. words 3 etc
if other person in the same channel talks and collector collects it, check if its the original author that said s.game, if not, ignore.
Bot.on(message
Unless of you mean a collector
yep
Which just google bcs I'm on my phone
ah kk
docs show how to use collectors.
can't seem to find it tho
I can't find how to if other person in the same channel talks and collector collects it, check if its the original author that said s.game, if not, ignore.
thats what the filter is for.
const filter = m => conditional statement here;
you should probably use the filter
yeah, should work
so like EVERY thing in my db is int/str
its not uniform
so i just left it lmfao
!message.author.bot for non bots only right
yea
alrighty
<input type="submit" class="btn btn-outline-success" style="margin-top: 25px;" value="Save" onclick="edit_bio()"> this runs the func right?
const width = 400, height = 400, buffer = new Uint8ClampedArray(width * height * 4);
for(var y = 0; y < height; y++) { for(var x = 0; x < width; x++) { var pos = (y * width + x) * 4; buffer[pos ] = 254;
buffer[pos+1] = 10; buffer[pos+2] = 1;
buffer[pos+3] = 255;}}
message.channel.send("loading", {files:[buffer]});
It isn't sending the image but no errors are shown
why are you asking
try it and see 
hey
@pale vessel py @client.command() @commands.has_permissions(kick_members=True) async def kick( ctx,member: discord.Member,*, reason=None): try: embed = discord.Embed(title=f"User Kicked!",colour=discord.Colour.green()) embed.set_thumbnail(url=member.avatar_url) embed.add_field(name="**user Kicked**",value=f"**{member}**", inline=False) embed.add_field(name="**Kicked by**" ,value=f"**{ctx.author}**", inline=False) embed.add_field(name="**Reason:**",value=f"**{reason}**", inline=False) await ctx.send(embed=embed) await member.send(embed=embed) except Exception as eror: print(err) await ctx.send("You can use that") await member.kick(reason=reason)
is his correct
Well it says the func doesn't exist
if it doesn't exist, create it
you sure
Does 2 things
send code or something idk
can anyone help?
const width = 400, height = 400, buffer = new Uint8ClampedArray(width * height * 4);
for(var y = 0; y < height; y++) { for(var x = 0; x < width; x++) { var pos = (y * width + x) * 4; buffer[pos ] = 254;
buffer[pos+1] = 10; buffer[pos+2] = 1;
buffer[pos+3] = 255;}}
message.channel.send("loading", {files:[buffer]});
It isn't sending the image but no errors are shown
- It gets the values of input boxes
- It makes a p tag be something
Does it have to be on the head or body?
Bottom of body?
Well the function does exist
Can I get help
whats the issue @solemn leaf
@drifting wedge is your script accessing objects in the dom
Yes
@earnest phoenix
Even after I put in in the bottom of the body
It still says func doesn't exist
@drifting wedge send your script
Nrn
Tmr
You define a raised exception as eror but try to use err
Other than that, I see indentation issues unless that's just mobile Discord
I don't have backticks on mobile
So here u go
====
function edit_bio() {
let bio = document.getElementById("bio").value;
let id = document.getElementById("id2").value;
let edit = await fetch(https://domain.com/api/profile/edit/${bio}/${id}/);
let resp = edit.status;
if (resp === 200) {
document.getElementById("status").innerHTML = "Worked"
}
if (resp === 401) {
document.getElementById("status").innerHTML = "Nope"
}
document.getElementById("status").innerHTML = "No1pe"
}
@earnest phoenix
The === is just so u know what's the code itself
and this
Mhm alr
Prob the func doesn't exist cuz it's not async
Do I need to call the func differently? @pale vessel
What is the reason it gives this error? When I vote, I want the command to run.
show code of your triggered.js file i think
whatever let triggered is... isnt returning a buffer
import json
def get_prefix(client, message):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
return prefixes[str(message.guild.id)]
bot = commands.Bot(
command_prefix= (get_prefix),
)
@bot.event
async def on_guild_join(guild):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
prefixes[str(guild.id)] = '?'
with open('prefixes.json', 'w') as f:
json.dump(prefixes, f, indent=4)
@bot.event
async def on_guild_remove(guild):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
prefixes.pop(str(guild.id))
with open('prefixes.json', 'w') as f:
json.dump(prefixes, f, indent=4)
@bot.command(pass_context=True)
async def changeprefix(ctx, prefix):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
prefixes[str(ctx.guild.id)] = prefix
with open('prefixes.json', 'w') as f:
json.dump(prefixes, f, indent=4)
await ctx.send(f'Prefix changed to: {prefix}') ```
ok
Firstly you might wanna use an actual database
Secondly just use r+/w+ open mode instead of opening the file twice
Possibly even add caching for prefixes
Introduction
It is an unwritten consensus that Python is one of the best starting
programming
languages [/why-beginners-should-learn-python/] to learn as a novice. It is
extremely versatile, easy to read/analyze, and quite pleasant to the eye. The
Python programming language is highly scalable and is widely considered as one
of the best toolbox...
Thanks
As for caching, the general idea is a dictionary that's attached to your bot object as a property and then used in commands to actually get the prefix
appreciation
So, instead of pulling prefix out of a file every time a command is run, you pull it from cache, which is faster and more reliable. Changing prefix still works via database, but this time you also edit it in cache
As for actual databases... eh, you'll get there if you put a bit of time into it
👍
hi
@staticmethod
def user_join(access_token, userr):
try:
url = Oauth.discord_api_url + f"/guilds/768019392596017164/members/{userr}"
headers = {
"Authorization": "Bearer {}" .format(access_token)
}
user_object = requests.get(url = url, headers = headers)
user_json = user_object.json()
return user_json
i have this function
for discord oauth2
im trying to add people to a server
but im getting a {'message': '401: Unauthorized', 'code': 0} error
plz help
idk if i should really use json there
but i tried
@staticmethod
def user_join(access_token, userr):
try:
url = Oauth.discord_api_url + f"/guilds/768019392596017164/members/{userr}"
headers = {
"Authorization": "Bearer {}" .format(access_token)
}
user_object = requests.get(url = url, headers = headers)
return user_object
as well
and that got the same error
im not rlly a py expert but i think u are supposed to just replace {} with the access_token
that does the same thing tho
and the header worked in another function
so i dont think thats causing the error
at async TextChannel.edit (E:\ON\node_modules\discord.js\src\structures\GuildChannel.js:355:2``` Text channel edit requires what permission? for channel?
Th is the reason for this?
at RequestHandler.execute (E:\ON\node_modules\discord.js\src\rest\RequestHandler.js:154:13)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async RequestHandler.push (E:\ON\node_modules\discord.js\src\rest\RequestHandler.js:39:14)
at async TextChannel.edit (E:\ON\node_modules\discord.js\src\structures\GuildChannel.js:355:21) {
method: 'patch',
path: '/channels/795936099989979146',
code: 50013,
httpStatus: 403
}```
ANY clue or suggestion?
You’re missing something in your coding I think
botPerms: ['SEND_MESSAGES', 'MANAGE_CHANNELS','MANAGE_MESSAGES', 'EMBED_LINKS', 'VIEW_CHANNEL', 'READ_MESSAGE_HISTORY'],
Is that a part of the coding or is that like the whole coding?
Its not bot issue it channel permission err
part
How to check channel perms
Oh
Hm
Oh do you have a command handler?
any clue?
what are you trying to do??
I am trying to check if channel has permission or not to run that command
how can i add an image on top of another image with sharp npm? i looked at the docs but its confusing
yeah, what is the command
i am cloning the chhanel then deleting the channel then recreating
Can someone explain what this means
SyntaxError: Cannot use import statement outside a module```
It's JS btw
it doesnt works with channel which doesnt has permisions
you bot will need the 'MANAGE_CHANNELS' permission then
Bot has Permission. I want to check if channel has perm or not
i reccomend you check out promises to catch errors like that
already used
channels dont have permissions?? you mean check if the bot has permission in that channel?
yes
at async TextChannel.edit (E:\ON\node_modules\discord.js\src\structures\GuildChannel.js:355:21) {
method: 'patch',
path: '/channels/795945752706154525',
code: 50013,
httpStatus: 403
}```
at async TextChannel.edit
I want to store a variable called "m.av" with the value "{user_avatar}" in quick.db, I want something like { guild_id: { "ar": { "m.av": "{user_avatar}"}}} but due to how quick.db works it converts it to { guild_id: {"ar": {"m": {"av": "{user_avatar}"}}}}. is there a way to prevent that?
replacing . with \. does not work
yo can someone help me
i run npm start
which compiles my typescript bot to js and runs it using node build/index.js
npm starts runs npm run build && node build/index.js
how can i create a pm2 process
with my ts code
.-.
create the pm2 process but it launches the npm start command
the site is not exist .
wdym
bots
._.
https://top.gg/bot/YOUR_BOT_ID/webhooks
just go there
replace YOUR_BOT_ID with your bot's ID
how do i get it
it only show empty box
put the is behind the your :3
@earnest phoenix click generate
generate one there
no
._.
oh then you cannot do it yet
You have to wait brb
@rustic nova it also works on the webhooks pagz
your bot needs to be approved first in order to use the api
Yeah but the docs one is better 
xD
???
rtfd
During your development you will likely run into DiscordAPIError: Missing Permissions at some point. This error can be caused by one of the following:
Your bot is missing the needed permission to execute this action in it's calculated base or final permissions (requirement changes based on the type of action you are trying to execute).
You provided an invalid permission number while trying to create overwrites. (The calculator on the apps page returns decimal values while the developer documentation lists the flags in hex. Make sure you are not mixing the two and don't use the hex prefix 0x where not applicable)
It is trying to execute an action on a guild member with a role higher than or equal to your bot's highest role.
It is trying to modify or assign a role that is higher than or equal to its highest role.
It is trying to add a managed role to a member.
It is trying to remove a managed role from a member.
It is trying to execute a forbidden action on the server owner.
It is trying to execute an action based on another unfulfilled factor (for example reserved for partnered guilds).
It is trying to execute an action on a voice channel without the VIEW_CHANNEL permission.
WARNING
The ADMINISTRATOR permission being granted does not skip any hierarchical check!```
thank you

who ? me?
yes. you
I didnt spent any time
yeah
Look someone already got helped
uhm, ok . .
Hey, I'm having tons of lag when my bot is in many servers. I've tested my bot in both a small bot in one server, and another in approx. 850 guilds. When in the smaller one, it is fast, and the lag is close to zero. However, in the large bot, the bot responds sluggishly, almost a delay of 2 seconds+. The ws ping exceeds over 2000ms (2 seconds) to 200ms. Any tips on that?
ps (if related): my bot is split into different files, and makes a request to a db on every message sent.
oes anyone have a black and white ID emoji?
does splitting into different files help?
Are the different versions hosted on the same machine? To be precise, do you consider this to be a network issue?
Do you perform any resource-intensive tasks that block the entire bot synchronously?
No. I've tested this on both a remote server and my own computer.
Why does it send a request to your database on each sent message? 
It grabs a prefix from a db (MongoDB to be precise).
Why not do that with cache?
do you have any idea how much cash that is
Thanks for the suggestion, I'll look into how to do that.
#development message
#development message
I vaguely described the general idea regarding my point here
it helps to have a db cache layer
so you don't have to do two steps each time you update
thanks
@haughty vortex god damn it it works locally
yep
if it's not the environ, it's something to do with a dependency
you really gotta tell me the error message lol
can
there is no other error
you actually not do that
not do the environ?
not hide the error
where do i hide it lol
"Couldn't load cog X" but no details about why it doesn't load
eh
exc
I use Windows too 
heretic
oh boi oh boi now we are talking
dude that's what you get when you don't touch something in half a year
i knew it
update requiremtnt
boom
requirements
lmfao
true
lesson learned
unless you are 2000% sure you aren't doing it wrong
you could do this: print(f"Couldn't load cog {filename[:-3]}: {e}")
just as effective, usually
What is the error?
WAIT
lol
if (deletecount or whatever) {
message.channel.send('no')
}
@earnest phoenix
and come on, this is basic JavaScript
imagine forgetting the () when doing if
Wha?
if (deletecount > "99"){
return message.reply(`I Can't Delete More Than 99 Message`);
}
Can this work?
nope, buddy, you should try to learn basic JavaScript before jumping to a discord bot
Not really
it's improper syntax
did it work tho?
Ye
But now it’s not...
I mistakenly deleted some of the coding then yea.. now it’s not working
Mhm, that looks about right.
Ye
Ipad* @teal egret
alr I'm done here, this is dumb
Nah, minify all your code xD
Is it possible to recursively call an anonymous function in js?
I want to return the anonymous function, within itself!
what in the heck
😱
how in ts would I efficiently check if something is in the type I included
so I have type, lets say its type x = 'a' | 'b'
how would I check if value: string is included in x
not possible, you have to give it a name
but you can give it a name even if its self-executable or in a callback
Can Anyone Help Me With 24x7 Hosting ?
read pins for 24/7 hosts
actually it may be possible
try using arguments.callee
arguments is a reserved variable that exists inside functions
oh
it contains an array of function arguments and information about the function itself
it only exists in normal functions, not in arrow functions
arguments is an Array-like object accessible inside functions that contains the values of the arguments passed to that function.
What is the best way to add more to a string if it already exists, if it doesn't set it to another value?
strings are immutable, no matter how you add/change/edit them, it will always create a new string
I would do js str = ''; str = str ? str + x : y
huh
that does what i want to but it seems inefficient
from my tests, the fastest way to add stuff to a string was to use +=
what about if the string is empty?
it works
you can still use +=
since it's still a string
but I need something different if its empty
if(!str) str += initialData
str += data
assuming str is "" and not null or undefined
no im defining it before the loop
take a look at my FTSet lib, i did a ton of micro-benchmarking on it lmao
actually?
however substr is mostly deprecated
but you'll only see difference if you loop them like 99 million times lmao
like the difference between using an object or a map
so small it basically wouldn't matter
is that because you are reassigning it?
most likely because of some internal micro optimization in v8
oh ok
also, then you add stuff to strings, they are not actually concatenated in v8
v8 creates a sort of binary tree to keep pieces of floating strings
so concatenating strings in js is super fast
but when you try to read this string, that binary tree is lazily concatenated
so the first read is much slower
damm Tim, how did you know so much from optimizing code
because im weird
xD
testing I assume
i like performance testing random stuff
like there are no Docs for these thing
there are
but hard to find
nodejs docs
Tim how much ram do you have?
how this is connected to development or this discussion?
on my pc or on my vps?
what do you test on mostly?
In .replit file
language = "go"
start = " "
What should I write in start?
i test on my windows pc mostly, 8gb ram, i5 7400hq cpu
do these test max your ram?
no
oh
oh
Thanks, can I also return arguments.callee?
yes
Hi
TIM , you're so good in js. I wonder why you have not yet got your hands dirty in typescript.
So why in the world is this not working?
let kkanal = await db.fetch(`kayıtK_${member.guild.id}`)
let kgr = await db.fetch(`kskgrol${member.guild.id}`)
moment.locale("tr");
if(!kkanal) return
if(!kgr) return
client.channels.cache.get(kkanal).send(`Hi`,
new Discord.MessageAttachment(
"https://media.giphy.com/media/3ov9k1J6jahVhiev0Q/giphy.gif"
)
);
});```When I extract the Discord attachment it works with the command but when I put it it doesn't work. Where's the error?
Log is clear
i will likely explore typescript in the future, but my problem with it is that you lose control over the final js representation, which is where i like to micro-benchmark stuff
Help?
But what is the need to control the final js representation. The ts files can look good.
the final js code usually has a ton of safeguards put there by ts, which can make the overall code slower
Help..
u need to fetch all the messages first.
For that the bultDelete takes a 2nd argument
you dont need to fetch first
2nd param is optional
and bulkDelete accepts a number
So why is this not working?
what does "not working" mean? any error?
show your command handler
Alr
maybe you have to resolve the promise
hmm
yoi
tim going to ts confirmed
I'm pretty sure ts doesn't add any type-guards to the final js code
i have a question guys, not a code
is this a good host?
anyone know?
doesnt look bad
the "festive discount" makes it not bad
looking at the vps offerings of course
i wouldnt go for "discord bot hosting"
2gb ram for less than 4 usd is very good indeed
i need help
ok
add .json
why
I assume config is a json which needs the file extention in order to be required iirc
nope
hmm
const width = 400, height = 400, buffer = new Uint8ClampedArray(width * height * 4);
for(var y = 0; y < height; y++) { for(var x = 0; x < width; x++) { var pos = (y * width + x) * 4; buffer[pos ] = 254;
buffer[pos+1] = 10; buffer[pos+2] = 1;
buffer[pos+3] = 255;}}
message.channel.send("loading", {files:[buffer]});
It isn't sending the image but no errors are shown
Help please? It’s showing no error and it’s not working and yes I have a command handler
what is it not doing?
It’s not working
My bad it’s this
Why is this not working?
It’s not showing error too
debug it then
bold to assume they know what debugging is
show your command handler, all of it, not just the part you showed before
lmao
Why if i try to use this code it says "cannot send messages to this user"?
use this to share code https://hastebin.com/ @timber fractal
still not showing everything
lol
My uh screen isn’t that bug lol. @quartz kindle
in order to dm a user two conditions have to be met
share a guild with the user
the user needs to have dms enabled
thats why you use a code sharing service
like hastebin
whats the issue?
it says "cannot send messages to this user"when it tries to send the "dmEmbed"
smh
cuz they likely have dm's closed
so the bot cant dm them
no i tested it with my alt
with dms open
But if someone else's DMs are disabled, you'll get an error
literally read my message
when you kick or ban a user there's a high chance that you won't have a shared guild anymore and you cannot message the usee
user
but his dms are open im sure
literally read my message
discord disagrees
lol
Apparently not.
thats why i setted a timeout from 100ms with banning him
Can I get help with making my buffer valid
yes they are
It's not like the error is lying to you
you're not sure that the timeout is going to execute after dming
show your privacy settings on the guild on your ALT's account
dm first, then kick/ban
aw man thats a good one
let me try it
also that
which is what ive been saying from the start
🙄
you cant chain promises like that
didnt saw that srry
your promises are being executed concurrently
It at least provides comfort that a message will maybe probably be sent.
@earnest phoenix i did this now js member.send(dmEmbed).then(message.delete()).then(member.ban({timeout: 100})) and it still says the same error
oh
let me show you an example
how than?
await/async
Give him a moment.
okay
you are doing the first option, giving the promise itself to .then(), like this: .then(Promise)
that makes the promise execute instantly
in the second example, the promise is awaited correctly, like this: .then(() => Promise)
That's actually helpful, I didn't know that tbh.
lol
@quartz kindle https://hastebin.com/woliyifojo.js
function bla(arg) { console.log(arg) }
bla(something) // pass something function to console.log
bla(something()) // execute the function and pass its result to console.log
.then(Promise) // execute the promise and pass it to the function
.then(() => Promise) // pass a callback function that when called will execute the Promise
@quartz kindle what’s the problem you see?
remove this line, its not doing anything if (message.content.startsWith("") )
add this
that will make it show in your console if the command is actually being found
Alr
are other commands working?
Hello i have a webSocket server with socket.io like this
io.on('connection', function(socket){
console.log('New user is connected, Body :', socket.request.body.token);
socket.on('disconnect', function (){
console.log('a user is disconnected');
})
socket.on('chat message', function (msg){
console.log('message recu : ' + msg);
io.emit('chat message', msg);
})
})
but i want that when a user connect to the webSocket he pass a token in his body request is it possible ? i tryed to do this in my client side but it didn't work i can't acces to the body
var socket = io('localhost:3000', {
token: 'token'
});
Ping if you can help me pleaze
Yes, and uh there’s no line called if message.content...
Hello please help me.
How to check "if (args[0]) youtube ID is invalid"?
someone understand :D?
Use query params
How ?
localhost:3000?param=something
socket.request.query.param
Ah ok
I'm guessing you want to check if the arguments given is a valid youtube link?
@cinder patio love your profile picture remind me of my childhood
I want to do a youtube subs counter. example command: !subs <youtube-channel-id>
But there is an error. if the ID is not valid, the bot is going to offline. I want to fix it
Actually I am not sure if that works on socket.io I've only used ws. I read that it's socket.handshake.query, not socket.request.query
Ok thank you i will try
@quartz kindle oh ok
@earnest phoenix do you know what type of error it gives you? You could try catching it with a try/catch statement
What language are you using?
then you did something wrong
try {} catch?
You can do something like this
try {
//Do the things you want here
} catch (err) {
await message.channel.send("Something went wrong")
}
thanks
Don't trust that code to 100% lol, I'm not good with js
I think its fine but why did you put await
because it returns a promise
It's correct.
I've never made a bot with js lol, I just assumed that the send method had to be awaited
your assumption is correct
Cool 
hm, the same error
script
if(command === 'subs'){
var request = require('request')
if(!args[0]) return message.channel.send(`${message.author}, please add a youtube channel ID`);
var id = args[0];
var key = '-------------';
var url = "https://www.googleapis.com/youtube/v3/channels?part=statistics&id=" + id + "&key=" + key;
try {
request({
method: 'GET',
url: url
}, function (err, response, text) {
if(err){
return;
}
var json = JSON.parse(text);
console.log(json)
var subc = json.items[0].statistics.subscriberCount;
message.channel.send(`Youtube ID: **${args[0]}** Subscribers : **${subc}**`)
}
)
} catch (err) {
message.channel.send(`Error: Invalid youtube channel ID`)
}
}```
@crimson vapor
ive got school, can't read through it rn
Try printing the error and see what it says with console.log(err)
Or see if it even enters the catch statement
emm
nice!
working
@dusky sundial thanks buddy for the help
@quartz kindle my whole coding is ruined now nothing is working :(.
Finally after long time new update pushed. https://top.gg/bot/783594136741609533
then you did something wrong
@quartz kindle no, when I removed it then I pasted it back nothings working :(...
that just confirms you did something wrong
i dont know what you did or how your code looks like right now, so yeah i cant see anything

if there's an error, then there's an error
computers don't lie about errors because they want to make your life hard
errors are errors regardless whether you can identify them or not
Party on a scale from 1 to 10, how well would you say you understand JavaScript?
It's usually a terrible idea to copy and paste code that you can't understand
0
ohhhhh... . something wrong again. So if i enter a valid ID, it says the error message
negative numbers are accepted too

Could you send the error message in here?
wasnt partyman called santa claus before?
Oh, I see
err variable
yes and i lost count how many times they got told to read articles on javascript lmfao
they're a help vampire
The Party guy offered me $50 to finish his bot with 67 commands in DMs lol
that's $0.74/hour, assuming every command takes an hour to finish. Which is being generous
.-.
Yeah sorry, I don't really know how to help you. I've never used the google api and I'm terrible at js lol
oh wait actually?
okay
partyman was santa clause?
wait till they find out the actual salary of a senior dev
thats even worse than an offer i got once, 200 bucks for a bot with 100+ commands
People seem to think that making an entire bot takes two hours
honestly its inexcusable if you are told multiple times to learn something, and then just come back and ask the same question
help vampirism
Programming isn't for everyone 
its worse
this
help vampirism is not as bad as what this is
If the bot has 3 commands, maybe
or if the commands are very simple such as !ping -> Pong!
const Discord = require("discord.js")
require('dotenv').config();
const axios = require('axios');
const discord = require("discord.js")
console.log("count init");
let wid = process.env.wid
let wtoken = process.env.wtoken
let GROUP_ID = a
let GOAL = 28000
let count = 1
let webhook = new discord.WebhookClient(wid, wtoken)
async function updateCount() {
let response = await axios.get(`https://groups.roblox.com/v1/groups/${GROUP_ID}/`)
let response_count = parseInt(response.data.memberCount)
//console.log("got request")
if (count < response_count) {
console.log(response_count, count)
const embed = new Discord.MessageEmbed()
.setColor("RANDOM")
.setThumbnail('cool link')
.setAuthor('Member Counter', 'link')
.addFields(
{ name: 'Current Count:', value: response_count, inline: true },
{ name: 'Members left till 28k:', value: GOAL - response_count, inline: true },
// { name: 'Goal', value: GOAL, inline: true },
)
.setFooter("Member Counter")
.setTimestamp()
webhook.send(embed).catch(async err => {
console.log(chalk.red('Issue with posting: ' + err));
});
if (count == 0) {
count = response_count
return;
}
count = response_count
}
}
setInterval(() => {
updateCount().catch(async err => {
console.log(chalk.red('Issue with posting in: ' + err));
});
}, 33000);```
how come this only sends
every like
15 mins?
like someone leaves the group and it doesnt send the embed
you 👏 cant 👏 code 👏 if 👏 you 👏 cant 👏 think 👏
i cant stress this enough, if you cannot logically think and resolve problems, then this is not for you, find another hobby like knitting
it's like forcing myself to be a surgeon but i don't like blood
there is this cool fancy keybind in vsc, SHIFT ALT F, its not that hard to do
huh?
@sterile lantern maybe there's a rate limit on the api you're using? Just a guess
it only sends if response_count is bigger than count
when a person leaves, is response_count decreased?
yep
oh that’s alright
so thats your problem
oh oof
Indents get messed up on mobile, it's terrible lol
if you want to send whenever the response_count changes, then check if response_count is not equal to count
I don’t like that it does } } tbh
instead of checking if its bigger or smaller
yeah it makes code so confusing for me when everything is
{
}
}```
not ```
{
{
}
}```
so != right
!= is never used is it?
isnt that not equal
not really
ive only ever seen it used in java for null
no
o
What do I need to do to add my bot
!= is used yes
!== or !===
!== or !===
!=== doesnt exist in js
What do I need to do to add my bot
!===============
In top. Gg
top dot gee gee
have a working bot, and fill up the top.gg form
!!=
what is != tim?
!= is the opposite of ==
oh
! is always an inverter, NOT operator
so value is not equal but doesn't care about types
your bot must be working and have at least one command that works and is ready for public use
And how much time does verification takes
idk whats the current waiting time, about a week i think?
Thanks
Yeah, like 5 days at least I'd say
im a js dev, if thats what you're asking
Why isn't working?
if(command === 'subs'){
var request = require('request')
if(!args[0]) return message.channel.send(`${message.author}, please add a youtube channel ID`);
var id = args[0];
var key = 'AIzaSyAZknfjAzmK0wsKUc2sm-DDwFPbUj18OC0';
var url = "https://www.googleapis.com/youtube/v3/channels?part=statistics&id=" + id + "&key=" + key;
try {
request({
method: 'GET',
url: url
}, function (err, response, text) {
if(console.error()){
message.channel.send(`${message.author}, Error: Invalid youtube channel ID (${args[0]})`);
message.channel.send(`https://cdn.discordapp.com/attachments/785126372515381251/796026765243056158/unknown.png`);
return;
}
var json = JSON.parse(text);
console.log(json)
var subc = json.items[0].statistics.subscriberCount;
message.channel.send(`Youtube ID: **${args[0]}** Subscribers : **${subc}**`)
}
)
} catch (err) {
message.channel.send(`${message.author}, Error: Invalid youtube channel ID (${args[0]})`).catch(err => console.log(err))
}
}```
what about it is not working
how can i fix that?
it's probably if (err) {}
how many if statements is too many?
Check yanderedev code
That's a worst-case scenario lol
game not slow just get better pc!!! 🤬🤬🤬😡
app not unresponsive, just get bigger screen!!! 🤬🤬🤬😡
but realistically how many if statements should you stay under?
I'd say 3
Pretty hard to say, I guess it depends on how much is in the actual statements. But yea, 3 sounds reasonable
but thats just preference
how many if statements do you need to actually make code slower
this is from yandere?
"blood", "insanity" seems like it yeah
who wants to make BetterYandereSimulator
It's a thing
there's a decompiled version on github, it isn't the original code because it was processed by unity but there's still some traces of his horrid code
The guy seems to spend more time arguing with people over the game rather than developing the actual game
this tbh
spends more time justifying why he cant work on the game rather than working on it
cry do you know how many if statements are too many?
I know its more personal preference
but when is it just inefficient
ironically enough every single person who tried to make a rival game to yansim turned out to be mentally retarded and dropped the project, the most recent being love letter
attention seeking furry allowing staff to sexually harass people then having a dramatic exit 👁️👄👁️
@crimson vapor it really depends on the context
how so?
lmao
for example in the above code, sure switch can be used, however you can also use a bit mask and if else that, which is arguably the most performant way
it really depends on what kind of data you need to if about
this
an else if is only the amount of if statements as the first if that was true right
if you're doing something like "if the sun is yellow, else if the moon is blue, else if the ocean has water", then use if else
if you're doing something like "if the sun is yellow, else if the sun is red, else if the sun is blue", use switch
then you can further expand it by what each of those options is supposed to do
it isn't
whats inside of it is slow
the comparisons you're doing affect performance
a comparison is one of the fastest possible operations in computing
that's why i mentioned bit masks
they're a super fast way to check for a specific flag on a bunch of properties
what you should think about is not "how to compare faster" but "how to reduce the number of comparisons needed"
for example if you have 100 if elses in a row, and you want to match the last one, you will do 100 comparisons for nothing
so you should split your code in a way, that you reduce the number of comparisons needed, by grouping options or something else
but realistically since if statements are generally very fast, as long as you are using if else and switch case when applicable, code would be fine
is that why functions are generally chained?
stuff like assembly is the fastest possible thing you can get, but nobody realistically uses it because its overly complex and complicated
in js, 500 if elses will probably be faster than array.find(), but you need 500 lines of crap when you could have 1 that does the same thing
a compiler will always optimize more than a human in asm
oh I see
so people really don't like lots of if statements because its ugly and hard to maintain
assuming it was used correctly
the rule i follow is prefer code readability and simplicity, except in places that are expected to be used multiple times, for example in loops
oh that makes sense
since a js object can be backed by different c/c++ structures depending on size, key types, data types, etc
I also assume bigger object require memory allocation which takes more time
everything requires memory allocation
yeah but an object with 1 entry takes more than an object with 2^24 entries
well by everything I mean data
Not entirely applicable here, but when I try to cd on my vps it says that the private ip of the vps is unavailable - is that firewall or something else?
I'm not sure what you mean, an object with one entry wouldn't use more memory than 2^24 entries
I guess it depends on the types of the entries - if they are other big objects then sure...
all data structures have a certain overhead, for example if your key size is 10, your data size is 100, an object containing this key and data will likely use more than 110
this overhead includes indexing, hashing and other stuff to keep information about the object
Tim is it more memory efficient to export classes or just raw objects for commands and stuff?
I assume raw objects
you won't see a difference
there is likely no difference
that kind of stuff is only relevant of you have a million commands
yea
however, classes for commands only make sense if you have a base class that all commands extend
otherwise singleton classes for commands dont make much sense
classes for commands is super unnecessary
I mean an extention of the main base command
what would you extend?
the base command class could have methods to access a database for example
oh that makes sense
to me it sounds pointless & overcomplicated
db is my least favourite but favourite thing
I don't mind db
but I really need to create good functions for the DB to have better caching
in db, working in prod is something that you don’t do
not an issue if you store nothing
aye, fair enough
it would be smarter to take a module based approach
a singleton class that contains all your command functions, that allows you to split into different categories etc
this is by far the best approach
dpy does it with cogs
dnet & dsharp with modules
when you create instances of different classes, does each class require the same amount of memory for functions, or are all of the classes using the same functions in memory?
I'm pretty sure they use the same function with a different this
so properties declared as this. are unique while functions are not?
mmm
Does the widget not work on google sites?
what is it showing?
You'll have to be a lot more precise. What widget? What site? What are you doing exactly?
Hint: no one can see your screen so we have no idea what you're talking about.
this should answer your question
so this is showing that a.get and b.get are the same in the memory?
yes
not the same instance
oh wait
panik
now im the one whos confused
anyways
✨ the magic of javascript ✨
imma head out now
not really... making a different function for each instance would be super wasteful
The code is in the class, the instance is only basically the properties that you have.
is that why Object.keys() on a class only shows the this. properties?
yes.
that makes sense
everything is in the same memory, not everything has the same pointer
i guess thats why its necessary to use this on classes
Of course if you modify one of those methods with your own then it'll remove the point and it'll no longer be equal.
so methods are the same for every instance, but they are executed with different
this context?
think of this as an function argument passed by the V8 engine that points to the instance of the class
yeah
hm aight
V8 engine is written in what language?
c++
we should all just take c++
the this keyword is easier to understand than i expected
