#development
1 messages · Page 1990 of 1
when it compiles down it compiles down to the same import statement but js wants there to be a .js at the end
In ESM you need to specify the file extention afaik
yea
but typescript compiles it down without a file extension
so it fucks imports up
Use --experimental-specifier-resolution=node flag
unknown compiler option
Whats your start script?
"start": "tsc --experimental-specifier-resolution=node && node ." assuming you mean this by start script
tsc && node --experimental-specifier-resolution=node .
Yea
Np
Guys what permission is required by the bot to change channel perms ?
probably MANAGE_CHANNELS
I gave that but it is still not changing the perms :/
does it have it for the specific channel
Yes
So like it is supposed to disable sending messges for everyone in the channel the command is used
But it does not change it
(it did work when I was lazy and gave it admin)
odd
does anyone know how to write optional chaining with array?
something like this
someArray[0]?.something
or is it impossible to do that
It should work
nope it didn't work
Js version?
how do i check
node -v
v16.10.0
Do you mean to do js someArr?.[0]?.someValue?
Then this should work
Which ide?
Uninstall js formatters and use the default code formatter
is it a good idea to make bot as a module ??
wdym bot as a a module?
sounds cool tho
yk like in a class
how you extend class in js n so on
in other langs
ofc you can use classes to make a bot
hmmm.. do you mean by this sentence a multi lang bot?
no nvm lol forget about it
You can use classes yes
It is what I do all the time
i thought both discord.py and js actualy used classes for stuff like commands?
do you use class to make the bot or like class to make submodules for it?
if you are using discord.js you can extend the Client class and add your ow nstuff to it and just make a new instance of that class and still login
so yes
you can
nope ik what you talking about but im using py
the bot is made of classes.. iirc... like.. there is a commands class you inherit and make a new command and so on
Oh as for py then idk
how to count all guilds from all shard
you never specified what language you're using
yuh its py lol forget about that can anyone help me run webserver along side the bot in py
anyone
same as len(bot.guilds) ?
in js
oh idk
from alll shards?
do you know how to run websever along side bot ?
the only webserver thingy im aware of is running flask.... like jus make a new file with a flask implemetation and start the server witht the bot
thats what im doing n it stops the bot n starts running the server
like the standard thing you do with replit keep alive lmao
a bot's code base shouldn't be a node_module
They're not really extensible like a library is
uh..... 🤔 elaborate pls
):
raise
loop = asyncio.get_event_loop()
loop.run_until_complete(bot.run())
asyncio.create_task(webserver.run(bot))
#bot.run()
if __name__ == '__main__':
main()``` this is what i basically got n yuhh it doesnt work lol
thats all i know if the bot is above the webserver then the bot works n if the webserver code is above thebot then the bot doesnt work
i thought you didnt need threads or sasync to do this.. lemme show you mine.. the keep alive thingy
jus a min
alrighh
Pretty sure trying to loop your run method will get your token reset if it tries to login a bunch of times
intresting
n does it like idk how ot word it
like if the bot is sharded multiple times does it conflict with the port
a web server should be running on a thread independent of forking. Bots don't claim ports like a webserver would
is that replit?
Noooo.. please don't attack me I jus told him an example for webserver with a bot
noone wants to attack you
Oh.. I jus had some flashbacks lmao... They would hate this method... In a server of my friend
😅
i thought replit doesnt have a dark mode
Your example seems pretty clean imo
So you were coding in replit with sunglasses? Damn 😂
i dont code in replit
Wait a min..... Run until complete bot.run.. uhhhh that wouldn't work??
Are you using replit?
whats taht 👀
The website you are using to write the code
flask
no wait its Quart
he meant where are you coding and hosting the bot.. not the module youre using
nice host
yep lol
best host
Didn't need threads
Runs the webserver on a separate thread
bestest host
oof jus realised that lol
well not even hosting it rn n yuh just tryna make it work as of now
Yeah nah chief if you run Flask and Discord.py on the same thread you're gonna have issues
ah understandable.. ig replit would be a better one cus you can share code and stor it online too.. but anyway.. but glitch oesnt support py 3 na?
it does
just make a .sh file n type
python3 main.py
n it downloads pip reqs using pip2 so you have to install pip3 reqs using terminal
wait replit got boosted plan too?
kinda.. its called hacker plan
does replit support custom domains ?
yup it does..
its way better than glitch...
@modern sable DM's
well.. yes..it also has a gr8 package manager using poetry
having a problem using env varibles on it tho lul
there is a whole new section to edit env variables
uh.. you need to bot.run(token) using env ofc
like this
i had it like that
either way imma rewrite my whole bot on this
i didnt like the way it was written
channel.guild.fetchOwner(user.tag) or channel.guild.fetchOwner.user.tag
CREATE TABLE IF NOT EXISTS Users (
id text NOT NULL PRIMARY KEY,
balance bigint DEFAULT 0,
itemsId INT FOREIGN KEY REFERENCES Items(itemId)
)
CREATE TABLE IF NOT EXISTS Items (
itemId SERIAL PRIMARY KEY,
name varchar(21) NOT NULL,
description varchar(150),
value bigint DEFAULT 10,
rarity text NOT NULL
)
I can't remember if this is correct or not, but is this is how you make a one to many relation where a user can have multiple items but an item can only belong to one user?
well I am obv doing smth wrong
error: syntax error at or near "FOREIGN"
@quartz kindle @cinder patio React performance skill issue: The setState function in hooks changes on every rerender so if a child depends on it the child would rerender on every state change
https://paste.gg/p/anonymous/fb351970794f48a69667e84b04d8b54e
Press the button and it will always log Child updated
setState={(state) => setState(state)}
actually nvm this doesn't work either
instead of passing the function directly
column "itemid" referenced in foreign key constraint does not exist I get this error for some reason even though I am creating the table before trying to make a reference to it
CREATE TABLE IF NOT EXISTS Items (
itemId SERIAL PRIMARY KEY,
name varchar(21) NOT NULL,
description varchar(150),
value bigint DEFAULT 10,
rarity text NOT NULL
);
CREATE TABLE IF NOT EXISTS Users (
id text NOT NULL PRIMARY KEY,
balance bigint DEFAULT 0,
CONSTRAINT fk_item
FOREIGN KEY(itemId)
REFERENCES Items(itemId)
);
It doesn't work because functions always return false when compared with Object.is
what if we memoize the function?
help pls
bro.. are you using discord.py only or wat
hey how do i write this json file: {"q4Bav":{"question":"test","type":[3],"good":"test2","wrong1":"test4","wrong2":"test4","emoji1":"🟢","emoji2":"🔴","emoji3":"🗑️","answer1":[],"answer2":[],"answer3":["345138133429649408"],"time1":[],"time2":[],"time3":[1646044962001],"postid":"947805981310595112"}}to an excel file using js?
you need some excel library
the most absurd question of all time since
excel.db
Can one bot read other bots' messages if it doesn't have message content intent..
it needs message content intent to read anyone's message content
😳
Why?
except your own or those that mention you
excel is formatted as csv
just transform keys into columns
the weebs are stalking you
there are so many bots out there doing this??
kpop
this is chinese
idk

The only way to do that is to change the style --chakra-ui-color-mode on root element to light or dark which you can't do without javascript
they're coming for your social credit
what are they doing exactly? being/faking chinese? using some person from some show as the avatar? i dont get it 😛
it's a vulnerability report for some dependency
although the two pages do seem to have a LOT of identical content
those are the bots that do it
except you can't really do this because most vulnerability reports are not meant to be disclosed publicly like this
it's a cool idea but can be harmful
Hey guys I have given manage channels perms to the bot but it still can't change the channel's perms.
What should I try now ?
i honestly dont get what that is supposed to do. like, i translated the description and such, but yea, totally went over my ehad lol
Yeah unfortunately you can't enforce the light/dark theme colors
you can only give perms that you have
so giving manage channels perm doesn't mean you can give any permission
No man it is my bot lol
I meant in the discord dev portal
...I keep my statement
the permissions at dev portal are only to build an invite
they don't give them to your bot everywhere
and even then, the bot can only give permissions it has
Um you did not understand what I was asking, nvm I got the right one 😓
tts is client-side, you have no control over it
tts voice is defined by your pc's language
oh okay
when i try using let membercountss = member.guild.memberCount console.log(membercountss) member.guild.channels.cache.get('856652240550625290').setName('Members:' + membercountss) nothing happens to the name of channel but the name changes if i take away the memercountss and i get the member count in the console
discord.js
nvm this fixed it `Members: ${membercountss}`
and today on "random things i found on github" we have:
can i just get confermation on the fact that none of that even does anything?
This one does.
like the ones that just go => { } dont do anything
NO YOU CAN'T JUST LEAK TOP.GG SOURCE CODE LIKE THAT
hahaha
you know whats worce? thats only half of it
theres pretty much one for every event
Hey im writing this bot https://github.com/oxy/Nest/blob/master/nest/client.py n orginally in this bot the function was in a class and im not using class to make this bot can anybody help me fix it 🙂
there is one for every event translated the comment at the top
bruh
was that to me...?
use classes
i am using em for sub modules but ion wanna use it for the main bot yk
no it was replying to a previous conversation sry
i dont know much about python sadly
is there a other fix tho...
This is a hard one but alright.
Language is JavaScript
I have a forEach
Each forEach needs to send a get request, but that would rateLimit it and break it.
So I want a interval between each get request and the response would be sent back
Kinda like this: (Green is 5 seconds after Red)
Use a recursive function instead of a for loop
Ah thanks
async function loop(index) {
await array[index].doSomething();
if (array.length === index + 1) return;
loop(index + 1);
}
await loop(0);
Had a bit different in my head but this is better yeah
eh
Not really since I already knew how to kinda
This tutorial shows you how to use the recursion technique to develop a JavaScript recursive function, which is a function that calls itself.
And google xD
Recursion is never necessary:
for (let i=0; i < arr.length; i++) {
setTimeout(() => ..., i * 5000);
}
just sayin
or even better, you could use a single set interval
let ind = 0;
const interval = setInterval(async () => {
// Check if ind == array.length, if so use clearInterval
// Do ur work
ind++
}, 5000);
recursion good

recursion is good when you dont know the exact number of loops you're gonna need
there are cases where a while doesnt cut it
for example recursion inside recursion
like for transversing objects with unknown depth
try making an object cloner with a while loop
its not impossible, but you will need some form of code reusability
I think where while is harder to use is when you need to maintain some state of what's happened
That's where recursion has a leg up since it feels a lot more natural and simpler than a while
Which is where code reuse comes in
yeah
like transversing objects
you need some sort of state to know which depth you are at or something
and if you're checking value types for properties, you wanna be able to reuse the type checking code
Recursion can always be done imperatively, not saying it's always better tho yeah
if your lang supports goto
xD
i mean
fn1 calling fn2 which calls fn1 is pretty much the same as recursion
how are you gonna reuse code without a function somewhere?
Call them procedures 
but like
with an object of unknown depth
how are you going to make just enough loops to the right depth
let child = obj;
while (child) {
child = child.something;
// do something
}
make 100 loops and break once it runs out of depth?
good option indeed
one slight issue tho
you're basically keeping a single level of state, which makes it difficult to go back to
Yes but now you can only walk top down into the thing
you could always store all parents in an array
Can't walk back down top like you can with recursion
for example an object like this {a:10, b: {c:20}, d:10}, once you set the child to object c, how will you do back to the main object to parse prop d
It probably relies on mutation so it doesn't need to get the parent
rewind stack
oh you mean without recursion?
const properties = []; // A list of all properties inside an object (and nested objects)
const parents = [obj];
while (parents.length) {
for (const prop in parents[parents.length - 1]) {
const parent = parents[parents.length - 1][prop];
// Doesn't account for arrays
if (typeof parent === "object") parents.push(parent);
properties.push(prop);
}
parents.shift();
}
Would work, I think. Obviously in this case recursion is better, but still, possible with imperative.
Looks painful
typical recursion hater
yeah that would probably work
if you want pure performance though, 100 loops inside each other would probably beat everything else
provided the object will never have a depth of over 100 lmao
I’ve never used all that much recursion until diving into parsers and interpreters, now it’s an essential piece of life for those things
Or any sort of list processor
The sum of a set of numbers?
Would prefer recursion over for/while any day of the year
I would say the same except for when it’s poorly defined recursion. Recursion that’s poorly written makes it really difficult to follow along with what the program is actually doing
Recursion is overcomplicating it for simple loops as well
@quartz kindle does Object.is return true if you compare functions that are completely same but totally different references
because maybe that's maybe what causing unnecessary rerenders in my react component
whats the point of that function
testing that its a no
setState function changes on every state change so if a child component depends on it through props it would rerender on every state change even if it doesn't depend on the actual state
i dont know too much about react i only sometimes do things in it
Can someone help me with this please?
https://cdn.discordapp.com/attachments/824411059443204127/947933786920857640/unknown.png
if options.getSubCommand isn't a function then options isn't what you think it is. Go find out by logging it
js is case sensitive, make sure to read the docs on the function names
What's the function for autocomplete: true?
new SlashCommandBuilder().setName('info').setDescription('Gets the info of an user.').setDefaultPermission(false).addSubcommand(subcommand => subcommand.setName("user").setDescription("The user to get info on.").addUserOption(option => option.setName('target').setDescription('Select an user').setRequired(true))),
I've tried:
new SlashCommandBuilder().setName('info').setDescription('...').addSubcommand(subcommand => subcommand.setName("...").setDescription("...").addUserOption(option => option ... .setAutocomplete("true"));
But that throws an error saying it isn't a function.
Attempting to implement autocomplete for slash commands.
can anyone help me with something that is completely not related to discord bots, but it's using node.js or is that not allowed?
great
if (commandArray.indexOf(answer) > -1 && customCommandArray.indexOf(answer.replace('-','')) > -1) {
require(`./customcommands/${answer.replace('-','')}.js`);
return recursiveAsyncReadLine();
}
I'm making a custom script execution for my program
and I'm trying to execute the command using the require() function
but the problem is it only executes once
https://media.discordapp.net/attachments/288498150145261568/947939448438554654/unknown.png
if it helps I search for files using
var availableCommandsArray = require('fs').readdirSync('./customcommands/');
``` then iterate though it and list everything
it's so annoying I cannot find a fix for it
nothing online either
Everything you require gets cached
you could read the file and run it with eval
I think you can only do .setAutocomplete for string option
edit: seems to work for number and integer options as well
or a Worker, but that's more resource intensive
can you give me an example?
also would eval not pose any ability to break the program?
eval runs a string of code, so if the code works, then eval will work most likely
in your case require does the same thing as eval - you don't need any exports from the file, you only want to run it
that's right, and if possible I need it to keep within the program, so any new window is not opened
eval will work
Ah I see. I'll try that.
I don't know what to put inside the eval though
I didn't use that function for a while but I doubt just putting the directory will work
const fs = require("fs");
const file = fs.readFileSync("./file.js", "utf-8");
eval(file);
Is one way to do it. Though perhaps you may want to use Workers instead, at least I would. Or maybe you could spawn the script as a child process
I tried that
require('child_process').exec(`node ./customcommands/${answer.replace('-','')}.js`);
``` didn't do anything
Unfortunately it doesn't work haha.
.addStringOption(option => option.setName('test').setDescription('test option').setAutocomplete(true))
).setAutocomplete(true),
^
TypeError: (intermediate value).setName(...).setDescription(...).setDefaultPermission(...).addSubcommand(...).setAutocomplete is not a function
perhaps workers could work, though I have no idea how to use it as I've never tried it before
nvm im dumb
i forgot i had .setAutocomplete afterwards for some reason?? anyways ty
No problem!
hello?
show one of your custom commands
How do you utilize autocomplete? I have this code:
let choices = [];
con.query(`SELECT name FROM rbridge WHERE name like CONCAT("%", ?, "%") LIMIT 10`, (err, rows) => {
if (rows.length < 1) {
return;
} else {
interaction.respond([
{
name: rows[0].name,
value: rows[0].name,
},
{
name: rows[1].name,
value: rows[1].name,
},
{
name: rows[2].name,
value: rows[2].name,
},
]).then(console.log).catch((err) => console.error(err));
}
});
But I'm not sure where to put it
my gosh... bid wars have been brutal today
Would make sense to set an accurate limit in your SQL query and to use a loop to display the autocomplete options.
I guess where I'm struggling is displaying the autocomplete options haha.
But yeah I should. I was gonna loop through but I just have it set to 3 options for testing atm.
If you just want to show 3 options then set your query limit to 3, too
Why is it 10 then?
ill have a loop that displays the 10 options. ik its super redudant not looping thru i just have it set for that for the sake of making debugging easier
Your interaction resonse just shows 3 rows ?!
Not 10
No need to have a query limit for 10 rows when you just show 3
yea ik it shows:
{
name: rows[0].name,
value: rows[0].name,
},
{
name: rows[1].name,
value: rows[1].name,
},
{
name: rows[2].name,
value: rows[2].name,
},
i just have that for testing atm
Create a loop for them
i just added those lines cause idk how to display the options for autocomplete yet
ik im doin that rn
And set the limt you wanna show using the SQL LIMIT
will do
^ idk how to display the options yet lol. ill be adding the loops and stuff cause ik its super redundant and a waste of resources to display 10 but only use 3
con.query(`SELECT name FROM rbridge WHERE name like CONCAT("%", ?, "%") LIMIT 10`, (err, rows) => {
if (rows.length < 1) {
return;
} else {
for (var i = 0; i < 10; i++) {
interaction.respond([
{
name: rows[i].name,
value: rows[i].name,
},
]).then(console.log).catch((err) => console.error(err));
}
}
});
loop
to me it looks correct, assuming rows[x].name is a number and string and that .name isn't over 100 characters
omg no
no that's wrong
that'll send the interaction response 10 times
which is not what you want to do
ah mb.
What you actually want is this:
rows.map((row) => ({
name: row.name,
value: row.name;
}));
oh i see. tysm
Or even
rows.map(({ name }) => ({
name: name,
value: name;
}));
Eww map
con.query(`SELECT name FROM rbridge WHERE name like CONCAT("%", ?, "%") LIMIT 10`, (err, rows) =>
{
if(!rows.length < 1) return;
let options = [];
for(let i = 0; i < rows.length; i++) options.push({ name: rows[i].name.toString(), value: rows[i].name.toString() });
interaction.respond([options]).then(console.log).catch((err) => console.error(err));
});
that's disgusting
I prefer an human readable solution
I'd argue that's less readable
Very imperative and step by step
as opposed to the declarative .map use
Shhh nobody likes map()
tysm this is super helpful. how do u display the options for autocomplete tho? i do understand that u have to use interaction.respond in the interactionCreate event, but is there a method for like .isAutocomplete() or smth?
You need to respond to your autocomplete interaction.
There's indeed a method to indentify an autocomplete interaction
oh whoops. i guess i missed that in the docs
ty
Well, interactionCreate takes an Interaction object, and Discord.js has an Autocompleteinteraction type, so you probably do need to check with .isAutocomplete() just to make sure.
okay. tysm
You can also check the interaction.type
just to say
Which is what djs internally does
👍
feel bad for asking again but uh im getting the error that interaction.isAutocomplete() isnt a function.
client.on("interactionCreate", async (interaction) => {
if (interaction.isAutocomplete()) {
// do smth
}
});
if (interaction.isAutocomplete()) {
^
TypeError: interaction.isAutocomplete is not a function
at Client.<anonymous> (/home/container/index.js:480:19)
should be v13
yep v13
Make sure you're on 13.6.*
ah. that might be the issue. ill reinstall djs
yea was using 13.1 lol
whooops
Yeah it doesn't throw any errors. For some reason though the options still don't appear.
Do they appear in your console log?
if (interaction.isAutocomplete()) {
console.log("test");
}
The event gets fired fine, but the options are still empty.
if (interaction.isAutocomplete()) {
console.log("test");
let choices = [];
con.query(`SELECT name FROM rbridge WHERE name like ` + "a" + ` LIMIT 10`, (err, rows) => {
if (!rows) return;
if(!rows.length < 1) return;
let options = [];
for(let i = 0; i < rows.length; i++) options.push({ name: rows[i].name.toString(), value: rows[i].name.toString() });
interaction.respond([options]).then(console.log).catch((err) => console.error(err));
});
}
I mean you didn’t enter anything
yea i would type "a" or "aseihrhawehoir" and nothing would appear. when sending the cmd "test" gets logged as expected.
And you’re sure the query even has results?
Console log your rows before sending the response
Well I didn’t change your query
You should replace the value you’re searching with "a"
It's probably because of that .respond
options is an array yet you're wrapping it in array
So what you got is [[{...}, {...}]]
Aka replace [options] for options
Ah yikes nice typo
also how about the .map instead of the for 
Yeah I didn’t remove the brackets
The simplifier.
I love my spelling.
like, come on. would you rather interpret this:
rows.map(({ name }) => ({
name: name,
value: name;
}));
Or this:
let options = [];
for(let i = 0; i < rows.length; i++) options.push({ name: rows[i].name.toString(), value: rows[i].name.toString() });
Simple is better. :)
I did that on purpose as usually as people will understand and see what the code does instead of minimalizing it’s directly
I mean everybody is free to adjust it of course
What I know is that I’m splitting that for statement into more than one line.
Just more easily readable with the whitespace.
Simple != Shorter
simple means one objective/task. like one braid
Thats efficient but not simple
your for loop has many objectives: create some value, check if it's still valid, increment, and use that value with other variables that still exist in your program
Ah I see. I didn't see that. Yea trying it rn. Is there a way to get the focused option though? Like the text the user is typing into the options
your for loop has many braids
if (interaction.isAutocomplete()) {
console.log(interaction.command);
let choices = [];
con.query(`SELECT name FROM rbridge WHERE name like 'a%' LIMIT 10`, (err, rows) => {
if (err) console.log("err: " + err);
if (!rows) return;
if(!rows.length < 1) return;
let options = [];
for(let i = 0; i < rows.length; i++) options.push({ name: rows[i].name.toString(), value: rows[i].name.toString() });
interaction.respond(options).then(console.log).catch((err) => console.error(err));
});
}
That's what I currently have atm
Code examples are usually more detailed and less compressed
I think interaction.options.getFocused()
Doesn’t mean he just has to copy and paste it
ty.
tbh i do understand your example slightly more than klay's. however klay's is shorter and easier to read
mostly because ive worked w/ for loops a bit more than map
Instead of discussing let the people prefer what they choose
That’s why I wrote it like this - on purpose
TYSM yea that works. imma work on fixing out the kinks for the code. ty and fake for all the help
never changed
why is it saying discord it not defined then?
or rather where am i suposed to define it
Because of your lower M
?
And your typo
also spelt wrong
maybe you're also looking for interaction attachments
Case sensitive
bruh i just typed it here not pasted it
the command used to work in v12
but i havent touched this part of the code
(cuz i forgot it was there tbh)
it says discord is undefined?
Err well it’s called a constructor not command, to be accurate
yeah
thats not MessageAttachment being undefined, rather discord
yeah thats what i said
Maybe also a typo or lower/capital letter issue?
no its cuz in v13 you dont have const Discord = require("discord.js") anymore
or you're missing this line
const Discord = require('discord.js');
I mean if you haven’t required djs in that scope you can’t access the var then
its still something you can use
if you wanted, or can also import just message attachment too.
const { MessageAttachment } = require('discord.js');
oh i see
i think thats the way i started the bot somthing like that
const {Client, Intents, Permissions, MessageEmbed} = require('discord.js');
i miss the days when you could just use ```js
const Discord = require("discord.js")
const bot = new Discord.Client();
cuz now i have to have like 7 lines of crap at the top now instead
It’s up to you if you import single structures or the entire lib
but which is faster though?
That’s what you do today, too
I mean you have to login as well and nowadays declare your intents
Once imported it’s cached
zero difference
guessing just doing the const DIscord is slower? cuz if so that would make sence
bruh
👍
Tim’s sympathy points +3
Tim is going to benchmark his own brain’s ability to compile js
lmao
Breaking news: faster than v8
so i can infact just impoer all of discord and cut out al these lines then? :```js
const {Client, Intents, Permissions, MessageEmbed} = require('discord.js');
const botIntents = new Intents();
botIntents.add(Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_PRESENCES);
const bot = new Client({intents: botIntents});
cuz this hurts my eyes
Imagine and endless recursion 
Gotta CTRL C his brain
ouch
bruh gtg il be back in a bit ping me
You still need to specify intents, and if you import it as const Discord = require('discord-js'); then you’ll need to specify Discord.Something() for anything within
That botIntents var triggers me
oh nice
thx
any way gtg
At least he’s using proper casing
But still
Unlike others I’ve seen naming variables like var SomeVariable and var SOME_variabLe and var some_variable all in the same program
Use whatever naming convention you want but KEEP IT CONSISTANT!
That’s right and everyone does it differently
I’m using this camel shit only for functions/methods and properties
For vars only lower case with words split by _
Anywhere
impossible if you use the raw api :^)
I use essentially typical java naming conventions for js
Java isn’t half bad it’s just got some... less than pleasant things about it
I do like it
The floor is Java, now what would you do?
But that mainly just applies to OOP
🔫
Functional isn’t my thing
For the most part at least
I’m gonna try to get into C a little bit
Jump in to end this mess 
More like stick yourself to the ceiling
uwu
🤯
how do you send an atachment?
cuz just puting the variable in doesnt work in v13 aparently
wait i might have got it
.send({files: [attachment]}) iirc
nice
Then it’s probably files
yeah it works thx
now my random command that i forgot was still on my bot works again
even though it was literally just for testing canvas and servs no purpose
Testing bots be like.
ping pong
Any idea when discord.js v14 will be released?
in the next week apparently
Oh nice
👀
error: syntax error at or near ")"
CREATE TABLE IF NOT EXISTS Users (
userId text NOT NULL PRIMARY KEY,
balance bigint DEFAULT 0,
);
CREATE TABLE IF NOT EXISTS Items (
itemId INT PRIMARY KEY,
userId text,
name varchar(21) NOT NULL,
description varchar(150),
value bigint DEFAULT 10,
rarity text NOT NULL,
CONSTRAINT fk_user
FOREIGN KEY(userId)
REFERENCES Users(userId)
);
Am I just blind or is there nothing wrong near any of the )
Regex is very inefficient
You should throw all possible prefixes into an array and check if the array includes your sliced content
I will never understand why that’s allowed in certain languages
ngl v14 sucks
so many un-necessary things
For example?
like for button colors
one sec, let me pull it up
style: ButtonStyle.Primary,```
like why, isn't just "PRIMARY" enough?
I just personally don't like it
You can pass primary as string
Or simply the integer you can find in the API docs
Or like you showed by using djs constants
As long as there aren’t major, breaking changes it’s okay
lol I love how SQL syntax errors are like "you did a wrong thing"
won't even tell you where it died
I mean it tries to tell where your error “could be around”

It’s something at least
thats annoying though
Hows that annoying?
making a list of all the possible combinations instead of an optional argument list
hows regex ineffecient
Regex is a synonym for inefficiency
Regex crashed cloudflare https://blog.cloudflare.com/details-of-the-cloudflare-outage-on-july-2-2019/
If you know all the prefixes and/or want to add/remove them dynamically an array is the best solution
Regex makes sense only if have no other choice and your patterns a very complex
Regex makes sense in many scenarios if you know how to work with them efficiently, not poorly written regex that can even cause a ReDoS, but for simple scenarios like the prefix checking model, simple data storage in arrays and checking for them is more efficient, although in some cases, regex can be even more efficient, it's all up to what it being checked, how large are the search strings and similar factors
just looks like a poorly written regex
Yes, but the actual cause was a culmination of things. I was just taking a jab lol.
pokes
So I'm making a library for an API to try to start getting used to sending and receiving data through raw api requests, and I'm wondering how I should be modeling responses in typescript. I'm using the chess.com api, and the docs aren't extremely clear on what fields are optional on the json, so it's difficult to tell what I should be doing.
I've got stuff like this: ```ts
async getPlayerData(playerName: string): Promise<ResponseTypes.ChessPlayer | null> {
const res = await Axios.get(Endpoints.PlayerEndpoints.PLAYER_PROFILE(playerName)).catch(() => null);
return !res ? null : res.data;
}
and my model looks like this: ```ts
export interface ChessPlayer {
url: string;
username: string;
player_id: number;
title?: ChessTitles;
status: string;
name?: string;
avatar?: string;
location?: string;
country: string;
joined: number;
last_online: number;
followers: number;
is_streamer: boolean;
twitch_url?: string;
fide?: number;
}
it works, but I'm just not sure if this is the way to approach stuff like this
Or should I just not bother modeling response types like this at all
You can use an interface, but knowing what's optional is tricky. In some APIs, the key won't be there, the value will be null, or both. Sometimes it's only available on certain conditions and most fields may be optional. Maybe the API will break its own rules and not be consistent on when something will be there or null.
Instead of trying to play around with that, I suggest you define the interface with no options (no ?s) at all, but use TypeScript's meta type helpers so you can derive types from old ones (i.e. return a new type with the options added). I forgot what it was exactly called.
hmmmm...
Of course, finding what is and isn't optional is harder, but given the alternative would be marking everything as optional, you may want to ask in the community if someone knows.
I love static typing but I hate it when there's bad API docs agh
There's a chess api lib out there for this, but sadly it's written in pure js with no typings
link?
here's the api docs themselves https://www.chess.com/news/view/published-data-api
The PubAPI is a read-only REST API that responds with JSON-LD data. Our goal is to re-package all currently public data from the website and make it available via the PubAPI. "Public Data" is information available to people who are not logged in, such as player data, game data, and club/tournament information.
well the api does say at times when something is optional
ha nerd
then shouldn't you assume that it will always be there
or are there times where it doesn't state that it's optional yet it still returns null
there's a set of dummy data they have, which instantly shows that there's some fields that are optional but not specified as such in the docs
anyone know why my djs v13 turns into v14-dev? i didnt even update any
"discord.js": "^14.0.0-dev.1640865766.780b7ed"
and should i update all of my codes into v13 = v14?
Well v14 isn’t out yet as well as it’s documentation
Use the undocumented version yes yes
So as I'm finding out, they use JSON-LD, which might help me out with typings
No idea how it works though
You can use a helper type to cover all the cases:
type Nullable<T> = T | null | undefined;
Should I do that though? I feel like it would be kind of annoying not knowing which types are guaranteed to be there or not, and therefore having to null-check your results
Ah actually, that isn't great as the field has to be present still. You still need ?
interface Person {
name: string;
phone?: string | null;
}
Well, if their API docs say the field is required, then great.
But if you are unsure, then allowing null or undefined is the safe option.
any source?
I would try to avoid catching the axios errors and casting them to null, as that makes debugging a real pain.
Either let axios fail, or transform the errors into another error type you control.
Getting a 404 error crashes the program is the problem
Also, does anyone have any clue how to use JSON-LD? This might solve my issues of typings, as there's a json-ld context for every endpoint. For example, the context for the basic player info is ```
{"@context":{"Player":"http://json-ld.org/contexts/person.jsonld","xsd":"http://www.w3.org/2001/XMLSchema#","avatar":{"@id":"http://xmlns.com/foaf/0.1/img","@type":"@id"},"username":{"@id":"http://xmlns.com/foaf/0.1/nick","@type":"@id"},"location":{"@id":"http://schema.org/URL","@type":"@id"},"name":{"@id":"http://xmlns.com/foaf/0.1/givenName","@type":"@id"},"last_online":{"@id":"http://schema.org/Integer","@type":"@id"},"joined":{"@id":"http://schema.org/Integer","@type":"@id"},"country":{"@id":"https://api.chess.com/context/Country","@type":"@id"},"status":{"@id":"http://schema.org/Text","@type":"@id"}}}
I just don't know what to do with this
You should probably handle that in your program lol.
myApiMethod().catch((err) => err.status === 404 ? null : throw err);
The docs are intentionally bad so an idiot can't abuse the api
an idiot can abuse the api easily, someone that actually wants to make something suffers due to the lack of up-to-date docs
it's easy because it sucks and it sucks because it's easy
Does the API docs have examples? You can just copy paste those into quicktype to start with.
The API docs have examples, it's just annoying because some of the data on the example doesn't exist on other profiles
(They only provide one example per endpoint)
Ah right. Quicktype does allow you to input multiple samples.
But also has outdated examples
the last time this api got a real update was in 2017
for chess.com at least
pretty terrible if you ask me, not sure why they don't upgrade their api more
"don't fix what's working" fallacy
it's pretty scuffed for such a massive website tbh
one of their endpoints returns EVERY titled player
Because they don't care about API devs
an array of 1400+ strings lmao
Just themselves
perfectly balanced, as all things should be
const res = await Axios.get<ResponseTypes.ChessPlayer>(PlayerEndpoints.PLAYER_PROFILE(playerName)).catch(
err => {
if (err.response.data) {
throw new Error(`Code: ${err.response.data.code}\nMessage: ${err.response.data.message}`);
}
throw new Error(`Something went terribly wrong: ${err}`);
},
);
that's probably terrible, but hey, it works
(if anyone has better suggestions let me know)
How about casting it to your own error representation
Since just throwing it with an error string is not easy for machines to consume
Just noticed, but is that a generic on js?
Understandable
what a beautifully designed api am I right
this is just GM players btw
there's like 10 other categories lol
👀 looks amazing
even better, just made a decoy account with literally 0 data, so I can see what's optional and what's not
wow okay that's way more barebones than I expected
ok so through a mix of testing and painful typing, I think I have a method down for finding the types
Is there a way to get the authors presence status?
looks like message.author isn't working
Probably not as painful as writing this was: https://github.com/tim-smart/discord-api-docs-parser
The rewards were nice though. I can update my discord library to support new features in a couple hours usually.
I then sit back and lol at discord.js taking weeks to implements modals.

lmaooo
I see ramda 
const escapeRegex = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const prefixRegex = new RegExp(`^(<@!?${client.user.id}>|${escapeRegex(Prefix)})\\s*`);
if(!prefixRegex.test(messageCreate.content)) return;
TypeError: Cannot read properties of null (reading 'replace')
message content is null if you don't have the message intent
not all messages have content anyways such as bot messages with only embeds
or just attachments
although in that case, they should be an empty string unless that got changed
on gateway v10, it is being enforced iirc
ok
regardless, message content is null and you need to check that
ok
prefix is null
The Prefix variable is null or undefined.
Haha yep ^^
lmao both tims randomly reply at the same time
thxs
after far too much work figuring out types, I've got all the player apis down
also how would I put this in an interface since props can't start with @
I would assume just like ```ts
interface Something {
['@id']: string;
otherStuff: string;
}
unless there's a better way
Props can start with @
I meant things like ```ts
interface Test {
@id: string;
}
If I do the way you’re doing my prettier gets mad and changes all of my props to be a string instead of a variable name
I’d like to still access them with .
Rather than ['name']
well you cant
its name same way with numeric keys
and any other symbols like dashes etc
Alright
I’ll settle with having to use subscripts for the id prop and normal dot for everything else
The prop isn’t even important really, I just wanted to include it for completeness
what theme is that lol
i use Moonlight II Dark ||extension name is just moonlight||
Deep Ocean 
const { Message, MessageEmbed } = require("discord.js");
//const { Default_Prefix, Color } = require("../../config.js");
const Discord = require("discord.js");
const db = require("old-wio.db");
const moment = require("moment");
const fetch = require("node-fetch");
const url = require("url");
module.exports = {
name: "ss",
aliases: ["screenshot"],
description: "Takes a screenshot of any webpage.",
usage: "screenshot <URL>",
run: async (client, messageCreate, args) => {
messageCreate.delete();
const user = messageCreate.author.tag
const urls = args[0];
if (!urls)
return messageCreate.channel
.send({ content:`${user},where is the link senpai :/`})
.then(m => m.delete({ timeout: 5000 }).catch(e => {}));
if (urls.length < 8)
return messageCreate
.reply(
{ content: "https is too short to reach - 8 limit"}
)
.then(m => m.delete({ timeout: 9000 }).catch(e => {}));
messageCreate.channel.send({ content: "Please Wait...."}).then(m => m.delete({
timeout: 3000
}).catch(e => console.log(e)));
const site = /^(https?:\/\/)/i.test(urls) ? urls : `http://${urls}`;
try {
const { body } = await fetch(
`https://image.thum.io/get/width/1920/crop/675/noanimate/${site}`
);
return messageCreate.channel.send(
{ content: `Here is a screenshot from requested URL`},
{
files: [{ attachment: body, name: "Screenshot.png" }]
}
);
} catch (err) {
if (err.status === 404)
return messageCreate.channel
.send({ content: "Could not find any results. Invalid URL?"})
.then(m => m.delete({ timeout: 14000 }).catch(e => {}));
return messageCreate
.reply({ content: `Oh no, an error occurred: \`${err.messageCreate}\`. Try again later!`})
.then(m => m.delete({ timeout: 13000 }).catch(e => {}));
}
}
};
no error, Not sending file
make sure you're filtering out localhost requests
because if there's sensitive data on localhost like, idk, mangodb compass then the data gets leaked
ok
how and I'm trying to filter out ||porn||
why are you filtering parm
You have to pass in the files property in the first parameter of the <TextChannel>.send() method, not the second
it's impossible
you have to restrict it to nsfw channels only
there was something like the us government tried to make an ai for detecting porn, but it gave false positives for sand dunes
everything is possible
gl making a porn filter though

might as well be a masochist and have a death wish because it will take you your lifetime to finish and it will be excruciatingly painful to make and train and expensive to maintain all of the training material
Alright. Still doesn't change the fact it will take you your lifetime to finish if the us government can't make anything that's totally accurate. Because that kind of filter absolutely has to be 100% accurate
natural language and intent processing is already difficult enough
then I'll make a challenge on Kaggle and set the reward to 100k so that some young machine learning enthusiast can do it for me
double 
I think what they meant was prevent ppl from screenshotting NSFW stuff lol
What's wrong ????
const Topgg = require("@top-gg/sdk");
const express = require("express");
const stats = require("../data/stats.json");
const app = express()
app.get('/', (req, res) => {
res.send('Currently Working.')
})
app.get('/dblwebhook', (req, res) => {
res.send('Currently Working.')
})
const webhook = new Topgg.Webhook("jesuisleroidumonde")
app.post("/dblwebhook", webhook.listener(async vote => {
const data = {};
let user = client.users.cache.get(vote.user);
if (!user) user = await client.users.fetch(vote.user);
if (!user) return;
client.webhook.logger.vote(user);
});
why does it spam suddenly
It never did that before
it will keep on sending the same payload until you acknowledge the request- by sending status code 200
ah wait you're using the SDK, it should handle that
Maybe an issue on topgg then
I mean you can end the request with a 200 anyway to make sure
what more can i add here ?
Uptime
thats a little complicated in python for me :/
What is .setCustomId for in buttons?
import time
# at the beginning of the script
startTime = time.time()
# ...
def getUptime():
"""
Returns the number of seconds since the program started.
"""
# do return startTime if you just want the process start time
return time.time() - startTime
Just seen it and got interested
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
ahh thanks ~
wait but thats not really how i want to show the time i want it to be readable like 25hours, 25m
n so on
thats just random numbers isnt ?
oh
using .customId to call another page of the command?
is that the thing?
or im losing
It is just for you. You know what button the user pressed when you have a custom id set
datetime.datetime.fromtimestamp(sec)
alright thanks for entertaining im going to read all of this ~ got interested about buttons XD
Yea no problem 👍🏻 Custom id is a thing on every message component, not only on buttons
or discord timestamp
ahh i see but doesnt discord.py have a built in time thing
like createdat something
💀 smh bruh
What
That's only for Discord objects and it gets the datetime of when the object was created
embed.add_field(name='Mem Usage', value=f'{bytes2human(psutil.Process(os.getpid()).memory_info()[0])}', inline=True) how accurate is that mem usage ?
huh ig ill do it old fashion way then
process = psutil.Process(os.getpid())
mem = round(process.memory_info()[0] / float(2 ** 20), 2)
Found this from my old bot, calculates the memory usage in MB
is that accurate ?
I wouldn't see any other way to calculate it so yeah
literally same mem usage as my code
btw hey quesntion
i got this shard latency but like its way to much how do you like not get that
cant you get shard latency in ms
nvm that was dumb
Math.floor(number); if it’s in decimals, use this to round down.
its python
round()
yeah i figured i fixed it lol
two things; is this a thing: msg.mentions.members.first().bot
and how do i add the bot invite to the bots profile?
@woeful pike svelte makes me want to cry
why the heck would they use labels for something so simple
web js
web js
ah
web1.js
web3.js
ethers4life
bruh web stuff moved to fast
reminds me of a web page i was making for school like 4 years ago
bruh cant find the screen cap
but it was literally just html gifs and tables
no css at all
i am going to actually cry now
like java.com
yeah
like govind tiwari's blog
Java + You = Suicide
Uninstall today!
just recently i found dome russian forum and it looks like its not been updated in the 20 years of its life
its called sysadmins.ru or somthing
So you can tell it that it should be reactive
yes but why labels
i would rather do useEffect with a huge dependency array
thats the beauty of svelte, it compiles everything to raw js, instead of using a virtual dom
I don't use svelte but appreciate the distinction with $: for reactive values beyond
Rather than being aggressive and treating any dependency on a reactive value as reactive itself
does msg.mentions.members.first().bot work or do i have to fetch the member and then see itf its a bot?
.bot does not exist on a member
use .users instead of .members
you dont need to fetch
yes
yeah I already filter that
wait
what does that actually return
would it just be true or false or would it just not exist
so if i was looking for a mentions user to be a bot it would looks somthing like
if(msg.mentions.users.first().bot) { }
I keep getting an Unknown webhook error but I am not even using any webhooks.
nvm im justbeing dumb
L
i mean just catch the error and just return
issue gone
lol
(probably not good practice but eh)
Wdym just catch the error
I am literally already doing that and the interaction still fails and sends an 404 webhook error
is there any way to make the text channel list automatically update when changing name?
either have an api that sends a channel list and fetch it in an interval or use websocket and send events on channel update
nope
you can make it so it refreshes every 24 hours or make a refresh data button 
no need for that
probably will want to use websockets then
either should do
oke
you want the page to update automatically when its changed in discord?
I'm doing a similar feature too
i'm planning to make a simple api to get server info
and it will use probably redis or something to cache the channels
a
😄
How so?
Well I am rather new to using raw sql so I am probably doing a lot of stuff inefficiently
https://www.toptal.com/developers/hastebin/lovaheqemo.typescript just look at this
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
:^)
absolute garbo
I wanna try and make that updateUserBalance method into just an update method and be able to use it to update any thing
even multiple fields at once if possible
you need 2 websockets, one for node, another for the browser
ws is for node
browsers have built in websockets, but with a different api

wat
hi ppl
Is there a way I can just make one update method that can update multiple fields at once tho?
what happened?
Good question. Idk.
damn I must of mistaken this for the development channel 😔
😦
nope, this is the #freeToDoWhateverYouLikeAndVeryMuchTrollOnlyChannelAsLognAsNoModIsPresent

thankfully no mods are present
Woo biggest troll ever ;D
lol
:D
love u woo
Just make a helper method that takes an object with the type of Record<string, any> and iterate through the keys and values to concatenate them to the SQL query string and update the said columns all at once
🤔
That makes sense
I think
Honestly that sounds like a great idea
How should I concat them tho if I have to iterate through the object for its keys and values
function updateColumns(columns: Record<string, any>) {
// Declare the SQL UPDATE operation on a table.
let sqlQuery = `
UPDATE table_name
SET `;
// Iterate over the keys and values to concatenate the column names and values.
sqlQuery += Object
.entries(columns)
.map(([key, value]) => `${key} = ${value}`)
.join(', ');
// With a condition if desired.
sqlQuery += `
WHERE ...
`;
// Perform the query.
...
}
why not just use a query builder like knex at this point
Me: puts the best phone case in the world on my phone
My phone: drops with the screen facing the floor
Or even some dsl
no idea what dsl is
A query builder can be thought of like a dsl
discord sql list
If you find yourself concatenating strings for some foreign program (like above), you probably want some kind of dsl
e.g. html generator
If I have an array:
const participants = [name, name2, name3, name4];
How would I convert this to JSON?
JSON.stringify(participants);
ty
can you have an example of how to do it?
tf you were supposed to have fixed that phone a month ago
hey,
yall know why a discord.py bot could straight up just literally stop working?
the bot is thousands of lines of code long and it worked just fine until recently
the bot logs in as it displays the on_ready message, but then just refuses to reply to commands, to handle events, tasks, nothing...
i'm not sure what's wrong with it...
I know... had no time yet
the bot is thousands of lines of code long
Didn't magically disappear for some reason
tell me, are we talking about a single file or the whole codebase?



