#development
1 messages · Page 1974 of 1
They originally provided mysql_escape_string, until that caused issues because it didn't actually give a shit about character encoding
Then you got real_escape which did do charset logic
Providing you bothered to set the charset
The extension support for this was dropped far ago
The newer extension for years now is mysqli which fixes lots this bottlenecks
iirc here
But yeah there’s no native support
At end it means thrrre no native solution to archive this, which is why you better use prepared statements
Yeah
Already got that the last time 
When you said it
Just didn’t think of it as well as I didn’t think of it being an extension for php and not natively being implemented
Legact Php is a pretty bad example in alot of cases
Hmm I don’t agree especially not with PHP8 in mind
But it’s not really worth to discuss about different use cases and preferences
what's the difference? Wikipedia's telling me it's the same thing
I love regexes.
Goodness. I was about to manually recode 650 lines but regexes are just life saving.
Wtf doesn’t your code editor support search&replace?
searching interaction.followUp({ embeds: as text string does the same as your regex 
You over complicate something damn simple
No?
The value of the index in embeds: is not the same.
It can sometimes be embed, embeds, lol, idiot, authorEmbed, etc.
i have a question, can I use markdown for my top.gg bot page?
It is my first time using top.gg and I want to write the description of my bot in Markdown instead of plain text.
Indeed.
Please confirm this at #support .
Also, I'm adding something at the end of the line.
work smart
Ok, thanks!
afaik prepared statement is a preprocessed query that takes parameters to execute, a parameterized query is a non-preprocessed query that takes the parameters and either performs a normal query, or builds a prepared statement internally and executes it
you use them when your lib/db doesnt support prepared statements, or when your query is not repeatable
if your query is not repeatable, theres no point in building a precompiled query if you're not gonna reuse it
ah alright. Good to know.
let pointchannel = message.guild.channels.cache.find(
(channel) => channel.id === "community-posts" //809659997423796247
);
if (!pointchannel ) {
channel1 = await message.guild.channels.create("community-posts", {
type: "text",
permissionOverwrites: [
{
id: message.guild.id,
deny: ["VIEW_CHANNEL"],
},
{
id: client.user.id,
allow: ["VIEW_CHANNEL"],
},
],
});
channel1.send(
"test"
);
}``` why the fuck does this create millions of channels
Hello, is this json in the body of the request? (Webhook)
dang i am a fucktard
yep!
dw, just a regular brainfart
happens to everyone
haha yeah, thanks for the help kuu!
yw
the body is { type: "json", value: [Getter] }
looks like you need to get the value
get the valeu?
how do i actually ping a message in the way of <@${id}>
but then for a message.id
yeah
I'm pretty sure you can only link to messages, not ping them 👀
owh how would i link to it usin an id?
youll need the guild id, channel id, and message id.
https://discord.com/channels/GuildIDHere/ChannelIDHere/MessageIDHere
for example, this is a message in #support
#support message
eh no library only typescript
with harmony as discord api client
can you show your code for receiving the webhook then?
hi everyone, i have pm2 and when an error occurs, it restarts the application why so?
i want it so if it errors, it doesn't auto restart the application
@client.command()
async def verify(ctx):
if str(ctx.message.channel) == 'verify':
role = 839159549260333121
roleTag = 839159549260333126
oldRole = 940251830980603975
# Change roles
await ctx.message.author.add_roles(role)
await ctx.message.author.add_roles(roleTag)
await ctx.message.author.remove_roles(oldRole)
await ctx.send("Success!")
I'm making a verify command that changes your roles. However its not working. Heres the error
aise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'int' object has no attribute 'id'
From what I know I'm doing this correctly. Is there any reason why this happens?
import { Application, Context } from "https://deno.land/x/oak@v10.2.0/mod.ts";
const app = new Application();
app.use(async (ctx:Context) => {
if(ctx.request.headers.get("authorization") == "---"){
console.log(await ctx.request.body())
}
ctx.response.body = "Hello world!";
});
so you are using the oak library?
yeah
looks like you just need to parse the value
JSON.parse()?
const value = JSON.parse(JSON.stringify(await ctx.request.body()));
I would presume
or just json.parse would probably work
grabbed that from a tutorial 👀
ive never used oak, not sure what's required.
there also seems to be a middleware for it.
https://codingshiksha.com/javascript/deno-js-tutorial-to-parse-json-objects-schema-in-oak-framework-using-jsonparser-middleware-in-typescript-full-project-for-beginners/
thx
isn't that the same as parseInt(aNumber.toString())?
Does that work for parsing json?
no, I mean, you're transforming something to string then transforming back to json
it's like x / 5 * 5
hi everyone, i have pm2 and when an error occurs, it restarts the application why so?
i want it so if it errors, it doesn't auto restart the application
Try pm2 logs and see what error
0|attitude | /root/bot/node_modules/discord.js/src/rest/RequestHandler.js:350
0|attitude | throw new DiscordAPIError(data, res.status, request);
0|attitude | ^
0|attitude | DiscordAPIError: Cannot send an empty message
Something like that
im a helper of @feral aspen and he kind-of got fedup
you're trying to send an empty message somewhere
show the full stacktrace
👋
Add a handler for errors
cuz that's a great thing they added on newer node versions
and I'm not even being sarcastic
Wait, the new node crashes the application on errors?
ye
HUH?
as it's supposed to be
WHY.
because crashes aren't really that evil
better a crash than a silent error slowly consuming your soul
you CAN make a global error handler tho, which would prevent crashes on any error
but you should always treat exceptions
I have one of those it just logs errors
That's the full one.
delete those urls
process.on('unhandledRejection', error => {
console.log(error);
});
That’s what I have
you just leaked the webhook's path
Oh my god.
you can spam with the url alone
redact the url, then show again
yeah, global handler
Could be the logs, I guess.
Can I just do this?
I don't want it to keep crashing, but I will soon read the errors and fix them without having the bot to crash.
you can, but treat all the exceptions whenever they occur
put that exact code in ur index
Even if I have sharding?
{ type: "json", value: {} }
Is that what you get back from a test request?
process.on('unhandledRejection', error => {
console.log(error);
});
Even if I have sharding, correct?
It shouldn't be.
Are you using any characters with accents in your url or auth?
À
yes, that's regarding process errors
._.
regardless of what u have in the code
yes, but didn't change anything
import { Application, Context } from "https://deno.land/x/oak@v10.2.0/mod.ts";
import { jsonParser } from "https://raw.githubusercontent.com/gjuoun/oak-json-parser/master/mod.ts"
const app = new Application();
app.use(async (ctx:Context) => {
if(ctx.request.headers.get("authorization") == "---"){
console.log(JSON.parse(JSON.stringify(await ctx.request.body())))
}
await delay(20)
ctx.response.body = "Hello world!";
});
async function delay(ms:number) {
await new Promise((resolve) => setTimeout(resolve, ms));
}
await app.listen({ port: 8000 });
``` is my code
I have a quick question though.. could you send me the documentation of where it mentions that it now restarts when there is an error? Can't seem to find it.
Bot ID? I'll vote for it and see if it works.
Maybe tests are broken for you?
706526290181619775
The thread button appears out of nowhere sometimes 
Threads: don’t open when wanted
Also threads: hey open one when you don’t want one!
it doesn't restart, it exits with non-zero code
Why should that matter in any kind?
Searching for interaction.followUp({ embeds: and replacing it by interaction.editReply({ embeds: does exactly the same as you RegEx.
Which does exactly means you over complicate things...
Search and replace works fine here.
The content of your embeds array doesn't matter as you don't wanna replace that, or do you?
what makes it restart is pm2
also { type: "json", value: {} }
👀
I'm not doing that, though?
I have no idea how to help further 
lol thought you just wanna replace the followUp by the editReply method

nvm then
Nope.. it was a node issue after all.
1
anybody working on anything cool they wanna share i wanna see some new projects or something idk
im making an among us machine learning bot
it finds things that look like amogus in an image and puts squares around them
Trying to find a thing to copy to send a erc-20 token from my bot. I found a few but they requre too much work
So more working
LMFAO
sus
take my money
no idea what any of this means but sounds tough
i’m currently working on a sharex cdn with a dashboard i have everything done and working i just need one last thing which is a button to remove all your ss’s from the cdn pretty simple but just need to get around to doing it

Lel
How would you calculate 1300 weighted towards 1105 by 50%?
i need this bot in my life
Wut?
Math
I’m just upset I didn’t think of this first 😔
mb math. i didnt explain that very well
Still doesn’t make sense though
More like meth
My guess is they want a random weighted number
Where there's a 50% chance of getting 1105 and 50% any other number up to 1300
but I could be wrong
High quality bot
step 1. find api that does ai image classification
step 2. interface with it
step 3. profit
step 1. dont use deno
step 2. dont use deno
step 3. dont use deno
step 4. idk man use some ml library
Incase anyone thought that
but i dont know if deno has any libraries like that
for node youd kind of just import tensorflow with mobinet and train a custom model
yeah ik how to do it for nodejs already
How do i let a function run in js each monday?
I don't think Speedy is hating on Deno.
Ah
Me personally, I haven't seen any hate towards Deno.
I personally don't like it.
But it was very trendy and popular
But not something I'd ever seen in production
Wanna start a discussion about what deno / node does better than deno / node
aka what 1 runtime does better than the other
in certain aspects
Deno has better security measures... and that's pretty much it
Sure, though I probably won't be able to name many.
I think "security" as its biggest advantage is just false.
And deno has native fetch
although nodejs is getting that soon
I wouldn't really say that's an advantage tho
That was kinda also the reason I loved using deno
As it's just saving the developer from accidentally doing X during development, but probably has no application in production with end-users.
And the security only accounts for a small fraction of all the security that actually goes into apps.
cron.schedule('* * * Monday', () => {
console.log('running on ondayr');
});``` is this the correct cron-way of handling a function each monday
It's still good to know nothing is going to write to disk, etc.
with node.js there are no guarantees
But that's true of almost every language
yes but we're comparing two js runtimes
Yet we don't block that because it's really just saving the developer, unless you got the user to somehow evaluate arbitrary code that would try to write a file
But you have more things to worry about if that's happening
languages/runtimes/blah
I think its good that there isn't just a single and only runtime you can use
dont think so
i think its 0 0 * * MON
As long as the program isn't writing to disk during development then it's not going to during production, either.
You're not Google though
then you can cry in c plus plus
Maybe the biggest feature I dislike about Deno is that it has typescript support out of the box. It hides the JS output from you 😩
like why
Never saw text in cron
You can still write JS though
My problem is that it hides the JS output
Ye, 1 to 7
Oh true, confused with 0-based system
ts-node is a nodejs lib that does the same because its a JIT for typescript
so maybe deno has a JIT for typescript too idk
Yes and I don't use ts-node, only when I want to run tests which are written in ts
Yes, but where's the advantage then? Is it really worth considering runtime X over runtime Y because X may save you from accidentally writing to a file in certain scenarios?
I don't like deno either, I just gave one of it's biggest distinct features from node.js
there isn't much
Oh fck
sad
cringe
random but
I wonder if british people have ever seen the sun on a sunday
ok bye
yesterday actually surprisingly
h
Can I require 2FA to be enabled for certain slash commands or text commands specifically?
Ex.
if (interaction.member.has2FA() && isStaff()) {
// allow cmd
} else {
// disallow cmd
}
The isStaff() is a placeholder for checking if the user has a Discord role.
I don't believe so.
A server owner can enable 2FA on servers
But I don't think bots can check if a user has 2FA enabled
If I were to check if an user has a specific permission (since 2FA blocks the user from utilizing actions that require BAN_USER, ADMINISTRATOR, etc.) could I theoretically check this?
Cause on my server I do have 2FA enabled.
@simple stump only way would be if they were to authorise with oauth2
that way you can check if they have 2fa enabled via a flag
How i delete collection in mongodb?
I'm using the lib: Mongoose
should be able to just do
mongoose.connection.collection('collection-name').drop();
would be cautious with it though since mongoose might bug if you have active connections or models
How can I effectively destroy a express session when logging out
The last time I did so the session still existed and caused problems when logging in again(cause I thought it actually did get destroyed)
You technically don't
All you can do is null the reference so the GC collects it on next pass
You can too forcefully free the port before starting the process
I do that for my spring api
pretty sure thats not what hes talking about?
Idk then
well im assuming its about express.js and express-session
express-session has a session.destroy() method, but it also has third party session stores you need to check with their own store.destroy()
Mmm I see
Well when I called session.destroy it removed all the added stuff to the session and removed it from the session store but when I went to go to a route that requires a session to be there it told me I was already logged in
and logging in again just caused even more issues such as the new session not being saved to the store
Also the session never expired like it should have
well i saw this on SO
you can try that
nvm that answer is from 8 years ago lol
how can dis apear (luca)
posting via the api
To have your bot's server count displayed on Top.gg, please read the documentation on server/shard posting.
Mmm I think that might still work tho
Cause it is right it only deleted it in the db
so maybe setting the entire session to null as well might work?
[Nest] 42667 - 02/07/2022, 6:09:04 PM ERROR [ExceptionsHandler] null value in column "key" of relation "users" violates not-null constraint
So I keep getting this error even tho I have made sure that the key being generated is not null/undefined and it is returning a hash like it should so key should not be null when setting it
async generateKey(): Promise<string> {
const nanoid = customAlphabet("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0987654321", 32)
return await nanoid()
}
async registerUser(user: SignupDto){
const existingUser = await this.usersService.findOneWithEmail(user.email);
if (existingUser) throw new BadRequestException('Email is already linked to another account.');
let u = await this.usersService.insert({
...user,
key: await hash(await this.generateKey())
});
return {
id: u.id!,
email: u.email,
role: u.role,
createdAt: u.createdAt!,
updatedAt: u.updatedAt!,
key: u.key,
};
}
isn't it insertOne
No
this isn't mongo
I am using typeorm + pg
also insert is a custom method on usersService
async insert(data: Partial<Users>): Promise<Omit<User, 'password'>> {
const user = await this.usersRepository.findOne({ where: { email: data.email } });
if (user) throw new BadRequestException('Email already is linked to another account.');
if (this.sequence > 4194303) this.sequence = 0;
const newUser = new Users();
newUser.id = ((BigInt(Date.now()) << 22n) + BigInt(this.sequence++)).toString();
newUser.email = data.email;
newUser.password = await hash(data.password);
await newUser.save();
return {
id: newUser.id,
email: newUser.email,
createdAt: newUser.createdAt,
updatedAt: newUser.updatedAt,
role: newUser.role,
key: newUser.key
};
Actually I realized an error in my registerUser thing I am already checking for an email in the insert so no need to do so there as well :^)
But anyway for some reason the key is becoming null when trying to set it
Listen here you little shit
Hmmm I wonder
cough async insert(data: Partial<Users>): Promise<Omit<User, 'password>> {}
It is TS if you can't tell by me defining the types
So I found the issue actually
to learn?
So by the looks of it setting req.session to null works
since I want to delete the cookie on logout and also destroying the session at the same time helps as well
Now the only thing I need to do is instead of giving the hashed key in the cookie I should probably change it to the plaintext key
👍
I was ghost pinged?
who knows
the ghost knows
ghosts aren't real
they are if they can ping people
ye
don't make me come for you personally
tell your bosses i said hi
I had a vague suspicion
or a skill one
why my bot not starting bruhhh
it took like 2hours
same thing shows
can someone help ;-;
;-;
no reply
Node issue.
Unless you don't have the skill to understand what I'm saying. ;-;
can u answr me also..
seems like everyone is so cut throat at each other. Geez
can u help me plz

If you want, you can ping @ everyone.
Please be patient.
idk. Can I?
All jokes aside, idk what the error is. The screenshot you posted literally shows nothing helpful. Therefor, I cannot help you
bro the main thing is it dosent start
just shows this
why are you using npx
why not just have the start command be just node .
if your package.json already links the main file as the index, then node . will work
if i start with node index.js token invid it shows
Then there's your actual error. The token you're providing to your bot is invalid
hmm id think so
becuase i have changed my bot token sevral times
can it be wifi issue??
Have you tried console logging the value of what you supply to the login to make sure you're not supplying it with undefined or anything unintentional
Seems like you have more issues then if your package.json is empty. Good luck sorting that out
good 4 u
Why it's not saving when i try to edit a value in the object???
console.log(data.progress.quests.find(x => x.id == 1).current) // Prints 3
data.progress.quests.find(x => x.id == 1).current += 1;
console.log(data.progress.quests.find(x => x.id == 1).current) // Prints 4
await data.save() // Not saving
same thing bruh
I told you to remove npx
let data;
try{
data = await schema.findOne({
userID: message.author.id
})
} catch(err) {
console.log(err)
}
ah. Mongo. I don't think I can help with that. Sorry
mongoose or other wrappers are weird imo
..
Now you're getting somewhere. This actually helps me realize that you are not using node 16
jhmm
the ?? operator only exists in node 16
idk
you don't have to know. I'm telling you
yeah thats why using npx
npx is an npm package runner that can execute any package that you want from the npm registry without even installing that package.
bro can i jsut invite u in replit?
oh
No. I'm not gonna do work for you. Or anyone
...
i love this kind of guys
help?
how?

ok
k
Was curious.
intents: [
Discord.Intents.FLAGS.GUILDS,
Discord.Intents.FLAGS.GUILD_MESSAGES,
Discord.Intents.FLAGS.GUILD_MEMBERS,
Discord.Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
],```
Because I have `GUILDS` intents at the top that just implicitly means to include everything within the GUILDS intent group right? If so I want to be very picky about what events I get then to reduce the amount of events are emitted to my bot.
I believe so yeah
From my knowledge it does mean you will get all events related to guilds
I think I legit just need reactions because interactions will always be sent lmao
You might also need members if you will be dealing with members
cause no matter if its message commands or interaction commands members aren't always cached
Yea
Good rule of thumb is to not even attempt to do anything every x amount of time imo
The bot is pretty basic in terms of handling events.
I just don't like the idea of possibly hitting a ratelimit
User reacts -> give/take role
I think reactions you won't generally have to worry about I could be wrong cause discord will ratelimit them if they react too quickly
It's in >2k servers at the moment but I haven't seen any complaints so far from Discord.
Again tho I could be wrong
I'll just go as ham as possible until hammered
Lmao
I should be good.
Hopefully
Users can't complain if they hit the confirm button now.
the opposite is true. A lot of people are complaining about their bot eating too much ram, but they don't think about what data they're storing or if they don't even need it
I spent too much money on building my server to NOT use all ram and cpu process power
I just figured out how to use redis for the first time
Idk why some people say it is hard to implement took me 5m
{
"cookie": {
"originalMaxAge": 60000,
"expires": "2022-02-08T06:39:02.200Z",
"httpOnly": false,
"path": "/",
"sameSite": true
},
"passport": {
"user": {
"id": "6896703353510690816",
"role": 1,
"key": "hgOhCiwSHL29dRBVDwJAgms1YYjYkN5e"
}
}
}
I get the key from a redis store
Gambler's fallacy. You will be paying absurd prices the more you scale. Solutions like such are not practical or economical if you literally do not have to.
It was obviously a joke. 😔
storing it in your bot's heap or redis doesn't change the fact that it's stored in memory. In fact, I'd rather store in bot's heap due to access times
my bad then. I'm horrible at picking up on jokes from people I don't know too well
I can't store this in the processes memory
it is important information that if stored in a map and the map gets emptied im fucked
It is the only way to keep the api keys persistent so I can re add them to sessions when they expire for users
redis doesn't have reliable persistence and it shouldn't be used
No. Redis is a cache. "cache" implies volatile. If you wanted to store something persistently, you'd be better off using postgres or the likes. Data you need for a short amount of time, sure; Use Redis.
Literally
Well I can still make use of it
I will need to cache some stuff
I will keep it implemented
I used to dump all of my Discord gateway data onto it, but since I moved to slash commands, I do not need any cache anymore
I am making a platform so I kind of need cached data sometimes
sitting at a nice 170MB consistently at 7k guilds and most of the heapdump is require.cache
I guess what I can do is make a table in my postgres db that just gets the plaintext key
tho I really don't like storing plaintext stuff in a db
JWTs can be stored in redis
I didn't like the idea of using JWTs for this project
that's valid
JWTs are nice for a smaller scale project i'd say but for something like this I want persistent logins and more flexibility
Persistent and permanent logins usually are a security vulnerability
I use psotgres and just query for the data for each command.
No reason for in memory.
Postgres is fast enough.
read the error. What does it say?
chant find module
Open shell and type cat replit.nix
If the file doesn't exist then you need to make a new repl or node can't run
Okay. So, how do you remedy the fact that a module isn't installed
You would install it, no?
can you run npm
there should be an npm dependency in the file too
Well looks like my best option is to save a plaintext version of the api key so I can readd it to the session's cookie to compare against the hashed version every new login
wherwe?
try doing npm i discord.js
k
If you're storing plain text, make sure the client never ever sees it
Yea I will
good lad
this happening
Actually that will be a bit hard since I am signing the plaintext key to the session's cookie

it’s downloading
Unless there is a better way to authenticate things internally since a lot of the endpoints will be key protected
no
read :/
i am using nix(beta) for node v16
send your package.json
what does discord.js need python for
{ "dependencies": { "@discordjs/builders": "^0.6.0", "@discordjs/opus": "^0.6.0", "@discordjs/voice": "^0.6.0", "@distube/soundcloud": "^0.2.2", "@distube/spotify": "^0.6.3", "@ksoft/api": "^3.1.9", "body-parser": "^1.19.0", "colors": "^1.4.0", "cpu-stat": "^2.0.1", "discord.js": "^13.1.0", "distube": "^3.0.0-beta.37", "ejs": "^3.1.6", "enmap": "^5.8.7", "express": "^4.17.1", "express-session": "^1.17.2", "ffmpeg-static": "^4.4.0", "http": "^0.0.1-security", "https-proxy-agent": "^5.0.0", "libsodium-wrappers": "^0.7.9", "memorystore": "^1.6.6", "os": "^0.1.2", "passport": "^0.4.1", "passport-discord": "^0.1.4", "session": "^0.1.0", "url": "^0.11.0" }, "devDependencies": { "node": "^16.6.1" }, "name": "music-bot-4", "description": "", "version": "1.0.0", "main": "index.js", "scripts": { "start": "node .", "node-update": "npm i --save-dev node@16 && npm config set prefix=$(pwd)/node_modules/node && export PATH=$(pwd)/node_modules/node/bin:$PATH", "node-clean": "rm -rf node_modules && rm package-lock.json && npm cache clear --force && npm cache clean --force && npm i", "node-update-then-clean": "npm run node-update && npm run node-clean" }, "repository": { "type": "git", "url": "git+https://github.com/Tomato6966/Musicium.git" }, "keywords": [], "author": "", "license": "ISC", "bugs": { "url": "https://github.com/Tomato6966/Musicium/issues" }, "homepage": "https://github.com/Tomato6966/Musicium#readme" }
Oh god
why does any package ever use python
hash what you pass to the client and the server compares that hash to a hash of the plaintext the server stores and then authoritates if the client is authenticated or not
“why not”
code913
I can assure you at least one of those dependencies was made by a drug addict
bruh drug adiict? wtf
also, it says your package-lock is old
But isn't storing plaintext anything in a db bad
can i invite you code913 in my project?
I am using my phone right now
i would suggest deleting it and rerunning everything
k
thos is simple node
rm package-lock.json && npm i
in this is dopsent even start
^
The server should store plain text so it can compare when the user logs in. The hash is for the cookie. When there is a cookie, you check if the hash from the cookie is equal to a hash of the password.
The checks should always be performed by the server
do it client side smh
done
Please don't meme about security. People might take you seriously
cant i jsut use npm install discord.js
So essentially I sign the hashed version of the api key to the cookie and then store the plaintext version in the db and when doing any protected route requests I just compare the hashed api key against the plaintext?
your package lock file is corrupted
delete it and install every single package again
npm install would redownload every package
ok
basically. Of course, you have to hash the plaintext to see if they do equate
i deleyed
I don't really have to
argon2 has a verify function that takes in a hash and plaintext
shoud it delete all packages also??
Then that should be fine if that's to compare
Tho I still need to store the hashed version anyway since I want to sign the hashed api key to a new session when old ones expire
I am now realizing how annoying making apis with api key protected routes can be
Unless I am just doing this in a dumb way which btw ophidian if you have a better suggestion I am all ears
You should not do that unless you're doing like how Discord does it with tokens.
The first string before the . is the ID of the User. The second is the time the token was created. The third is random garbage
Like how I suggested or do it "the discord way"
I can just rehash on every new session can't I
Theoretically
As long as the plaintext is stored it doesn't matter what the hash is in the new session
If the hash can decrypt to the plain text, then yes
I don't think you can decrypt a hash can u?
I am very iffy on my knowledge on encryption and hashing
You can. It might take for-fucking-ever
By decrypt, I meant if the hash is they plaintext before encryption. Idk how libs verify
password 1234 might encrypt to abcd
if you have multiple hashes of 1234 which aren't equal, so long as the plaintext is 1234 and the lib can verify that the hash is just an encrypted version of 1234, then you're all good
But I would suggest the Discord way if you want multiple tokens
Like, I can get the first part of any bot's token just by the ID. The timestamp and the random garbage, you cannot
Mmm
How exactly does discord handle it internally tho
Like I am logged in rn right and I assume the token is stored in a cookie/localstorage right?
Do they use that token in the cookie to get my data from different endpoints?
and then how do they verify that token is valid
Buffer.from(client.user.id).toString("base64");
they just base64 the token?
No. The token is base64 of the client's id, the timestamp the token was created and then some random garbage
Mmm
ye

Wendy coming in with the lurk
if you split the string by . the first entry is my client's ID
nice token I just logged into ur bot and downloaded all ur credit cards
I wonder what that random garbage at the end is probably some randomly generated string
I guess the rule: "Forfeit all mortal possessions to the cat girl" still applies
it is randomly generated
hence why I said random garbage
So I understand the creation of the token
mfa tokens are all random garbage
I assume they then sign that token to a cookie and what do you think they store in the db?
Oh I see
the token provides all the info necessary
So they just compare token to token
So basically they just leave it up to the user if you share your token that is your fault
finally my bot is online now ooooof
you can create relations from user name/email to user ID and then check if the token corresponds with that ID
the token contains the user ID in it
bro main problem was this spelling -_-
so you can get user info by ID
Hmmmm
I think I understand
So basically if I do it that way I have no need to really sign my userID to the cookie?
i can just sign the token
and then decode it to get their userID and query the db that way right?
can i have a script for music bot 24/7 in vc??
because they have the user ID, which can be predictable, but they also need the random garbage from the rest of the token to verify it is actually them
Yea
might be useful
yeah same I was looking through my archive channel for that
What is that HMAC shit
"random garbage"
google says
In cryptography, an HMAC (sometimes expanded as either keyed-hash message authentication code or hash-based message authentication code) is a specific type of message authentication code (MAC) involving a cryptographic hash function and a secret cryptographic key.
just random garbage to verify since you can't reliably guess random garbage
ye
so I'm guessing tokens are
id + time + hmac(id + time)
no. The last part is literally just random that follows no trend
asides from pseudo-random logic
but like I said earlier, multi factor authentication tokens are all random
Yup. All of them are invalidated
Oh god how do I manage that.
mfa tokens also expire every month
doesn't it mean you'd have to relogin every month?
or does it just regenerate
on PC, that's what I have to do
I don't have ot login every month
I don't think it would be called an hmac if it wasn't some sort of digest of the rest of the token + a secret value though
Well discord uses oauth2 doesn't it?
unless they're using that term loosely
can i have 24/7 script for music bot like !join to join that vc in which person is in... then !leave to leave that vc like this
but 24/7
in my code i m like filled with errors
It doesn't have to be the rest of the token because it's not useful on its own. It can just be a secret token that's hashed or just random bytes
write your own code bro
to whome u saying?
the only person in the channel begging for copy paste
-_-
I will pay you in hugs to do my authentication stuff for me ;)
this is a joke obv
an hmac wouldn't be useful on its own either I imagine. But I just don't know enough to tell I suppose
tempting
But that takes the fun out of coding wendy
you were on my ass before cause I didn't wanna do something like a json parser

Whatever works for you. You don't have to be an expert in cryptology to have a secure setup. I'm not an expert, but I guess I put on a decent facade. Just thinking logically and from the perspective of what issue experts are trying to fix
For instance, if a hmac isn't useful on its own, then it can't reference anything else
Honestly I want something secure as well but I am not that smart when it comes to understanding some stuff so It takes me a bit to fuly understand
Some libs do everything for you which is okay. My setup isn't secure. I just have permanent tokens the user inputs themselves and could theoretically share with others if they so desired
not that its a security concern since the resources they're accessing with the token hold very little weight
I just want something that will protect the user to a point where if their account gets compromised its not my fault its theirs 
sending plaintext to the client is definitely your fault

I do like the idea of doing what discord does
its where I got my idea for the ids I use
I am just still a bit iffy on how to actually implement it properly so as to make it as secure as possible
now you can definitely hash the IDs for the first part of the token. The rest is up to you
yeah but when ur json parser has a bug you don't risk leaking all of your users information 
Ayo uncalled for
actually that's not even true depending on the kind of bug I suppose
I will just make something that has bugs everywhere ez
I probably couldn't write a JSON parser. Too much unexpected tokens
or more like a lot to account for
So Ophidian this is my thought process
- Generate a token (base64) of their ID + Timestamp + Some random garbage
- Store that token in the cookie and database
- Authenticate requests using the decoded ID from the token and compare tokens from DB to cookie
- Let the request through if successful else throw error
looks a-o-good to me
why not use discord oauth
Cause I am stepping away from discord related dev stuff
oauth is also a pain in the ass to dev
the hero we didn't know we needed
At some point I might integrate the ability to login via discord
But that won't be for a good while
as I have no need as of now
isn't it better to always use a third party provider so you don't fuck up the security yourself
Make sure cookie is Secure + Http only + Same site is set to strict
I am also doing this entire project on my own so if I don't talk here in a few days send help cause i've likely gon insane
Already did so
What happens if that provider gets hacked
What provider
If i fuck up the security myself that is obv a me problem and i need to be better
and it also means i am not ready to make a large scale app that quickly

Oh I know i am not ready
security is like super hard to do wdym
reads the these guys trust us page on auth0
which is why I have no dead line for a release
I estimate it will take at least the entire summer to finish just the backend maybe even longer
How Discord did it seems hella easy to me. I could code a system reimplementing that no problemo
Come do it for me /s
assuming I wanted to
I need money and sanity since I already maintain some Discord libs which is already a pain in the ass and also my bot. I basically manage my bot's entire stack. I even remade lavalink in js
😢
why put yourself through that pain
Tho I am probably about to experience hell with this project as well
Especially when frontend comes
😔
frontend's easyyy
I could do CSS but I'm not great at designing whatsoever
portfolio
Like the design ?
I was meming that description tho I didn't know what ot put
But anyway the design sucks
because a lot of other's people's solutions are too expensive on system resources. Back when I was hosting on heroku, I made a plugin for Discord.js to disabled presence caches because gateway v6 was indiscriminate.
When that stopped being the end all solution, I just decided to migrate to the libs I now maintain, cloudstorm and snowtransfer and made a rest only cacheless Discord.js
I also didn't like how much lavalink consumed, so I remade that as well
rewrite it in rust but use .clone() to solve all lifetime issues instead of managing memory properly 
Rust did not look appealing to me at all. The syntax was too much for my brain to process
it has a huge learning curve, very daunting I agree
The syntax is the best thing about it

Their ambitions are admirable
I just find a lot of it is confusing
thats all ill say
A statically typed lang where everything is an expression 🤩
community has everything to do with a language imo
Yeah comparing it to py or js, rust has it better with its userbase
I can imagine a lot of rust devs are like c devs and wear pink thigh highs
compared to "learn to code js idiot ahhahaha" it's a breath of fresh air talking to people in the rust community about code stuff
If it has a bad community I am less likely to use it as I can't get any good support on it
pink top.gg custom thigh highs
😉
how do u know about this
who's leaking our uniforms
I have inside intel
I wont give up my source
My plan this summer is to get everyhting I need to make custom clothing
and make my own custom top.gg socks
I also heard you guys have pink top.gg hoodies is this true?
compiling a list of voice regions my bot comes across. If any of you have seen any not on this list, please tell me
No. The rest api doesnt show all of them
for instance, only people in south-korea can see south-korea
this was a while back obviously, but not much has changed
javascript is so easy an idiot can use it
and that's why so much javascript is pure bullshit
idiots usually have blue usernames/weeb pics
There are certainly a lot more voice regions than that
why so many us
because I live in the us
and the us is first world
people complain about audio quality
corona isn't real yk
Yes an idiot
Wait wrong reply
Fuck
Yes am idiot
4k weeb pic
most likely idiots like myself
agreed
lord have mercy on no colors
colors.js have no mercy on javascript developers
Ey you cunt!
I don't mess with libs that offer console colors. Just a waste of disk space
I see you there, green looking bastard!
It wasn't an insult. All I said was god have mercy
Tbh I could use some mercy indeed
Thanks for keeping us nocolors in your thoughts brother 🙏

living rent free
The only place where I can spend the night in peace
lgbtq matters!!!!!!!!!
What are their matters? Do they lead foreign relations?
idk
why
How to do in javascript addrole command?
I don't understand why I need to be pinged for this question
or anyone for that matter
from this behaviour i conclude hes using discord.js
so you will need that https://discord.js.org/#/docs/main/stable/class/GuildMemberRoleManager?scrollTo=add
civilised people use detritus
Good joke 
bruh I need to move my db over to a managed db but I'm using a custom image
how do I solve this dilemma
how do you check whether the bot is present with application.commands scope enabled...
I have system where the stored data is deleted when bot leaves the server...
But i have added slash commands now, it would required invite from the new links....but to invite using new links, servers will kick the bot first, and that will delete their data...
If there was a way, where if bot leaves with app.commands scope, it will deleted the data else not, hoping that the kick was for reinvite
No
you’re officially speaking for 190000 guild members?
woah fake has pfp again??
Of course there are but don’t ask to ask.
Ask your question and wait for a response.
The most weird I found on my phone 
lol
someone give me the name of a programming language (not in https://uwu.solutions/8iUzaS8X?)
rust
alr
to prove to my computer science teacher that more languages exist
they think js and py and c# are the only langauges

you sure
Hey i have a json file that looks like this: ```js
if(!test[message.member.id]) test[message.member.id] = {
name: [],
points: [0]
}``` How would i now get the top 7 entries that have the highest points?
she didn't know py for <variable> in <array>: existed
my college course i'm doing next year teaches c#
And like, put them in an order of:
- Highest points
- 2nd place
- 3rd place
etc etc
.sort and then .slice
i was looking through the docs as i never really used sort that much
const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// expected output: Array [1, 100000, 21, 30, 4]``` How does it sort?
ascending, but how can this be ascending?
we go from 1 to 100000 to 21"?
error[E0369]: binary operation `<` cannot be applied to type `std::result::Result<u32, std::num::ParseIntError>```
parse returns a result
oh ok
You need to check if it's ok before doing anythign else
if Ok(val) = string.parse::<i32>() {
// val is guaranteed to be i32 here
}
YOU ARE WEAK
or if you're sure that it's going to be a i32 you can just do .ok()
let val = string.parse::<i32>().unwrap();
// val is guaranteed to be i32 here
REAL MEN
NO FEAR
imagine panicking 🤭
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }', main.rs:7:8```
certified skill issue
you imagined panicking
idk if you can tell but i don't use rust 
yeah you just have to learn what a number is you idiot
ah yeah i'm just stupid
I love this about rust tho
you can't just ignore errors
I mean you can but when you do, you know exactly where
and your program doesn't just log an unhandled exception, it completely dies
🤤
if you know you have an error you know it's not a usable value and vice versa. Unlike stupid go
ok fixed it
fn main() {
use std::io::{stdin,stdout,Write};
let mut s=String::new();
print!("What is your age? ");
let _=stdout().flush();
stdin().read_line(&mut s).expect("Invalid input");
if s.trim().parse::<i32>().unwrap() < 15 {
println!("Sorry, you cannot watch this film")
} else {
println!("You are old enough to watch this film!")
}
}```
ignore shit code
real unwrap hours
i added .trim()
scoped use directive oh my
it works so 
s.trim().parse::<i32>().expect("Invalid input")
at what point would read_line fail anyways?
This function has the same error semantics as
read_untilwill also return an error if the read bytes are not valid UTF-8. If an I/O error is encountered then buf may contain some bytes already read in the event that all data read so far was valid UTF-8.
hmm
How would you design it?
I guess it's a bit tricky because the function can fail partially
maybe something like this?
enum ReadLineResponse {
Success { bytes: usize, buf: String },
Fail { error: io::Error, buf: String }
}
also not really pretty tbh
You have to provide a custom function to sort
I honestly don't know why you have to pass a mutable variable instead of the function just returning the buffer like you did, I think that's the most awkward thing about it

yeah that's the C-like part of it that bothers me
mutate parameters yuck, but at least it's all documented in types unlike C
I mean the whole point is because its a stream
you dont want to be creating a new buffer every time potentially
far easier just to provide a mutable reference for that to fill the buffer instead a) for flow control and b) performance
yeah rust takes some shortcuts in the name performance like with these cases but it's still safe because of the language semantics
just ugly
I mean it's also because its good practice
imagine if you wanted to read a line and a user passed you a 4GB line
and you have no control over how much you want to read into memory
thats what you'd have if you had it just internally do it
bearing in mind exposing it like this also allows us to use like virtual memory etc... without re allocating and/or having to first load into memory entirely anyway
yeah that's reasonable. Maybe the interface could be a little different though... like maybe have readline return a struct which you can .collect(), or .append(&mut buf)
well by convention append affects self mutably not the other way around
and collect generally implies an iterator which can be drained and merged into a type without erroring
also for the most part in the real world, you just dont read console input like ever
well yeah you could think of the console input like an iterator, just throwing ideas around
that would probably be quite in efficient
Just as an abstraction, ex. doing .next() would just read a single byte
until it hits EOF
Feud, it is not possible what you stated.
The sort isn't applicable on nested objects right?
let database = {"key1": {points: [5]}, "key2": {points: [3]},"key3": {points: [4]}}
for (const key in database){
let g= database.sort(function(a, b) { return a[key].points - b[key].points});
console.log(g)
}```
It works only for arrays
You could do Object.values(database)
Also get rid of that loop
also this is your daily reminder to stop using a json database.
makes it a lot harder and inefficient
with a proper database you could to this with a single query
sure but how do you handle that internally? Read a given buffer first and then do it? Or do you read one byte at a time and make a syscall every time? very easy to get very inefficient very quickly
order by gang
cluster keys gang
all I know is when I have a knee jerk reaction to a design choice made on something as fundamental as doing IO, I know the people working on it have spent like 50x more time thinking over it than I have criticizing it
so there's almost certainly a good reason for it if it doesn't feel super optimal
That's a good point 🤔
If I had to read from console once or twice I'd just use read_line, but if I had to read very very often at many different places I'd probably use an interface which makes it easier. It's a balance between memory and io calls. .next could read a chunk of bytes and save them into memory. When it runs out of bytes, get another chunk. until EOF.
but how much buffer? What if the buffer read returns an error?
generally also allocations like that are better to be explicit rather than implcit
If it strictly has to implement the Iterator trait, if the buffer read returns the error then .next would return None as if it ran out of bytes to read, maybe a custom method to tell what exactly happened. If a custom implementation, .next would return an Empty / Err / Ok enum. As for the size of the buffer, /shrug
yeah that's true
maybe the max size of the buffer is something the user could define?
With a default if they don't
main = do
putStrLn "What is your age?"
inputtedage <- getLine
let age = read inputtedage :: Integer
if age < 15 then print ("Sorry, you cannot watch this film") else print("You are old enough to watch this film!")```
am i stupid
what is wrong with that
ok wait i fixed it
well whats the error
main.hs:5:71: error: parse error on input `then'
you don't use parentheses to call functions in haskell
oh ok
normally you'd write this as
putStrLn $ if age < 15 then "Sorry you cannot watch this film" else "You are old enough"
equivalent to
putStrLn (if age < 15 then "Sorry you cannot watch this film" else "You are old enough")
the () is being used to group the big expression, not to call the function
getAge :: IO Int
getAge = read <$> (putStrLn "What is your age?" >> getLine)
decision :: Int -> String
decision age
| age < 15 = "Sorry, you cannot watch this film"
| otherwise = "You are old enough to watch this film!"
main :: IO ()
main = putStrLn =<< decision <$> getAge
kekw
that's so shitty but...oddly readable
once you understand what all the symbols mean it's actually really pleasant
what is <$> for?
f <$> a is the same as fmap f a where a is some kind of container and f is a function that converts the contents of the container to some other thing
it's a generalized version of array.map
or promise.then which are both the exact same thing conceptually
so you take a Promise<number> aka IO Int in haskell and convert it to IO String by applying Int -> String over it with fmap
getAge().then(decision).then(console.log) except in js >>= and <$> are both the same method .then for some reason
no but they are very similar concepts

