#development
1 messages · Page 189 of 1
anyone know if javascript has a function for comparing two strings with resistance to timing attacks?
ill probably need to use a library for this but would be nice if crypto had it built in
wanted to tag voltrex but of course hes banned
at this point theyre banning anyone remotely useful and competent
there's still tim
@quartz kindle any ideas?
but well, if both sides are hashes, how would a timing attack work?
id of course use a password hashing and comparing library for this usually but in this case i dont need anything hashing just some simple resistance to timing attacks
We do not ban people for being competent

I'm still green regarding hacker attacks and exploits
theyre not hashes in this case
but i think hashes are pretty good when it comes to timing attack resistance
ok so lemme rephrase: why are those passwords not hashed?
its too simple and i need to be able to change the passwords via a config file quickly
dont worry this is not production work
i think you can make your own timing resistant compare function with some random iterations and delays but i think someone sophisticated enough can filter through that with statistics
why is voltrex banned lol
well, couldn't you add a random ms delay at one of the steps?
god knows
this would give fake info to the attacker
Silly question but why are you worrying about timing attacks if it ain't prod anyhow? Genuine question as I'm dumb not tryin to question the decision itself
from what I know, something happened that made him burst and do or say something offensive
but that's as deep as my knowledge about it goes
nobody went into details when I asked
because it might be public at some point to a closed source of people and i dont want them breaching my passwords lol
better to be safe
afaik js itself is invulnerable to timing attacks
actually i think you can use hashes by hashing both the password and user provided password then comparing them
timing attack gone?
because the language itself is so random in terms of execution speed ]
Gotcha, thanks!
Sounds solid
yeah thats what i thought initially
simply jsfuck the sensitive parts
virtually nobody would attempt to translate it
or optionally, defer the comparison task to a separate api
its not the end of the world if it gets breached anyways
i think for added safety ill hash both passwords with sha1 then compare them
or i could always hash and salt the passwords on boot for all accounts in memory
sorry i believe sha1 is close to being not recommended for cryptography so# sha256 then
One message removed from a suspended account.
dont you look at that
One message removed from a suspended account.
tim always comes through
i dont see anything about it online so it must be new
ah node v21
my node is 3 generations out of date to use this
js ecosystem is so volatile that 300 libraries die are born every second
insecure hashing algorithm
iha
let the rename process begin for sha1
One message removed from a suspended account.
yeah its available for the latest node, how convenient
thanks
huh
it says it was added in node 6.6.0
oh fuck i was looking at the wrong thing
splendid
but as a side note its scary how many developers are unaware of timing attacks
but it just happens most crypto libraries handle that for you so they dont need to worry
One message removed from a suspended account.
using numerical indexes, I have to update all tracks after an index because the order gets fragmented. Going back to front like a linked list guarantees order albeit with it being O(n) to sort as each entry needs to find which other entry links to it. Plus you only need at max 2 updates for order
How much code currently goes:
const orderedTracks = []
let last = entries.find(i => i.next === null)
if (last) orderedTracks.push(last)
while (last) {
last = entries.find(i => i.next = last.video_id)
if (last) orderedTracks.shift(last);
}
My thing is that I need to reorder the tracks at any time to any index with minimal updates. My current solution suffers from needing all tracks in the code to sort and it being O(n)
^this tbh
linked lists are good, but if you're gonna be making database calls for every single link in the list thats probably gonna be terrible
option 1: store everything you need for the ordering in columns, use sql's own ordering functions when retrieving
option 2: store everything you need for ordering in a single row so that updating and reordering only takes 1 round trip to the db
It isnt like that. It's just fetch all entries in batch then sort with the code I mentioned. I'd like the db to sort the list, but I can't write sql statements that complex. Reordering already only takes at max 2 update calls
whats the sorting criteria?
The user can have their own order of the songs, so #1-length. Can return sections for pages
There is a mv command
if the user defines the order, you can for example have a position column on the db, where each entry has a position number, when fetching you can do SELECT * FROM table WHERE id = X ORDER BY position
when updating, you dont necessarily need to update all entries, you can for example start creating intermediate numbers when needed
oh?
like you want to move position 6 to between position 2 and 3, you can set its position to like 2.5 or something
I hate that idea lmao
lmao
I thought about just using another storage medium but lmao
err I guess I can also do something like this for updating:
UPDATE playlist_songs SET order = order + 1 WHERE order > ${index_moved_to} AND order < ${index_moved_from} for if index_moved_to is less than index_moved_from
Just one update operation
can easily flip the operators
I'm struggling with math mentally though for other cases I don't wanna deal with :(
How does Discord limit the size of attachments for bots?
This is the same limit as users
Wdym, how many images can it post at once, or how many times per second . Explain please
Unless the server allows more
idk You can try for() to figure it out.
Whats ur question here
send video and audio file and how does discord limit size
But anyways the limit should be 10 attachments if I aint wrong
8mb might be it
Not sure
Now it's probably 24mb
Maybe yeah idk
But this is the same limit as the limit of a regular user without nitro
Then that should be it
i tried send a video size more than 24mb and and got this error
Would be helpful to show ur code
I am new to discord.py and hence I was trying to learn how it works
Got a curiosity if we can send large files via a bot
I can send ones smaller than 8Mb but it shows error for larger files
discor...
Who is coding discord bots with py
Some people do. The explanation provided on the post applies.
Here you can find an explanation of what this error means and how to "get rid of it"
Can u please show us ur code
This has nothing to do with the code really
ohh i see if i send video file under 20 mb video will send without error if more than 20mb will got error
U never know, js tricky
If you have a poor internet connection, this error will still occur
Well u found the issue
Its probably 24mb as nynu said before
I would suggest to maybe write a function to check if a file size is more than 24mb , to compress it , would be cool
try sending a normal message with that attachment instead of a webhook?
Weirdly enough, it's not a 413 they got, but a 500.
Nothing to do with file size, just an internet connection issue.
here for my full code
const { MessageActionRow, MessageButton, MessageEmbed, Options, MessageAttachment } = require("discord.js");
const { SlashCommandBuilder } = require('@discordjs/builders');
const fs = require('fs');
const ytdl = require('ytdl-core');
const { v4: uuidv4 } = require('uuid'); // using uuid to create unique filename
function sanitizeFilename(filename) {
return filename.replace(/[\\/:*?"<>|]/g, '_');
}
module.exports = {
data: new SlashCommandBuilder()
.setName("yt2mp4")
.setDescription("Download video from YouTube to mp4 format (HIGHEST QUALITY REQUIRES BOOSTED SERVER LEVEL 2 ).")
.addStringOption(option =>
option.setName('link')
.setDescription("Enter the youtube link to download the video.")
.setRequired(true)
)
.addIntegerOption(option =>
option.setName('quaility')
.setDescription('Video option (1 - Audio and video , 2 - Video only (need server boot level 2) | deafult: lowest)')
.setRequired(false)
),
async execute(client, interaction, options) {
const ytlink = interaction.options.getString("link");
const quality = interaction.options.getInteger("quaility");
console.log(quality);
const videoid = ytlink.split("?v=")[1];
if (ytlink.includes('list=')) {
return interaction.reply("Playlist is not supported")
}
const videoinfo = await ytdl.getInfo(videoid);
const videoTitle = videoinfo.videoDetails.title;
const videoURL = videoinfo.videoDetails.video_url;
const Authordata = videoinfo.videoDetails.author;
const Videoauthor = Authordata.name;
console.log(`Got request download video: ${videoURL}|${videoTitle}|${Videoauthor}`);
if (videoinfo.videoDetails.lengthSeconds > 900) {
return interaction.reply("Due to attachment size limitations, the maximum length is 15 minutes.")
} if (!videoURL) {
return interaction.reply("Something went wrong, please try again later.")
}
else {
const embed = new MessageEmbed()
.setColor('#0099ff')
.setTitle('Downloading...')
.setDescription(`[${videoTitle}](${videoURL})`);
await interaction.reply({ embeds: [embed] });
const uniqueFilename = `${uuidv4()}.mp4`;
const sanitizedFilename = sanitizeFilename(videoTitle);
const videoPath = `cache/${sanitizedFilename}_${uniqueFilename}`;
// Download video
if (quality === 1) {
videoStream = ytdl(ytlink, { filter: 'videoandaudio', quality: 'highestaudio' });
console.log("lowest")
} else if (quality === 2) {
videoStream = ytdl(ytlink, { quality: 'highestvideo'});
console.log("highest")
} else {
videoStream = ytdl(ytlink, {filter: 'videoandaudio', quality: 'highestaudio' } );
console.log("default")
}
const fileStream = fs.createWriteStream(videoPath);
videoStream.pipe(fileStream);
// Wait for download to finish
await new Promise((resolve, reject) => {
videoStream.on('end', resolve);
videoStream.on('error', reject);
});
// Check if file is downloaded (debug only)
const checkfile = fs.existsSync(videoPath);
if (checkfile) {
console.log("file downloaded")
} else {
console.log("file not downloaded")
}
// Send file to user
const file = new MessageAttachment(videoPath);
await interaction.followUp({ files: [file] });
}
}
};
Can u followUp without defering ?
i'm trying sending video quality === 2 with no audio
Thats off topic but anyways
Do u have a domain ? Why dont u make the user download it via a url ? Push the video into a temp folder, tell the user to download it within 5 minutes . So you wont have discord attachment size limit
yes i have
thanks i'll try it
if it's via url wait until they find out about https://cobalt.tools xD
the command is kind of pointless
yeah. i use that one since it supports most social medias
What comes to my mind that would be useful in this style is some kind of API for e.g. Discord bots
hey does anyone know condition coverage criteria regarding structural testing?
why have they written a test case for the last if such that it evaluates to false and the last return statement is executed
is true seen as a condition as well?
no, true is a value on itself
they prolly did that because return (m == 4 || m == 6 || m == 9 || m == 11) && d <= 30 would be fairly unreadable
(31/ <= 30, 12, 1800 <= y <= 9999): e.g, (29, 12, 2023)
nope they did it explicitly to execute return true as well.
I asked around and apparently they do see it as a condition, everything that is or evalautes as a boolean. Just in such trivial cases no further tests are possible.
that's odd, because return true is by no means a condition
it's a result, just like doing return 1
I mean, you could argue it's an unary operation
they that's exactly what they said
it was unary something
it's vague but i ma just do what i've been told lmao
true (unary | has one value)
1 == 1 (binary | has two values)
true ? 1 : 2 (ternary | has three values)
basically
ternary operator, my lover
aaaaaa brain is smoking, stupid ricochet calculation
let's say I have a projectile moving at an angle X towards a target, given perfect reflection, how do I calculate the projectile angle after ricocheting on the target?
I'll try drawing
Or are you talking an angled surface
projectile is moving at an angle X (global space)
I'm trying to find Y
I have a function to find out angle between A and B, if required
going by that image "perfect reflection" looks like 90*
which would make y = 180 - 90 - x
but if its not precisely 90
wouldnt y = x ?
id agree with waffle
like, X being the ball's angle
if Y = X then it'd pierce the cube
since no change in trajectory would be made
and it's not always 90º, it might come from arbitrary angles
here's some animated context
isn't it the inverse normal?
note the first impact (I'm bad at aiming rotating things)
no idea, I'm lost at what to use here
if you pay attention to the projectile trajectories, it ricochets at really wrong angles
The angle is the same, the horizontal vector is just negated
that animation is majorly lagging my phone
what if it ricochets from below?
Then the vertical vector is negated
Usually movement is determined by vectors and not angle + magnitude
Though you can use both
for realism wouldn't it depends on the velocity
thing is, how do I manage to cover both horizontal and vertical cases in a single formula?
matrix maths
yeah
nope
Velocity would only matter if that surface you’re colliding with can move
At that point you’d be dealing with elastic/inelastic collisions
there's a matrix op you can do on a vector that will translate it like this but I don't remember it, it's been a long time since I did maths like this myself I just use an engine
for the walls I simply did PI - ang/2 * PI - ang since I always know when it hits horizontally or vertically
but for the enemies, there's not much way to check this
I mean, there is, by calculating the point of impact
simplest approach is what waffle said but the minute you add moving bodies, 3d space or anything complex...
oh total realism doesn't matter much, consider only the angle part
things like pong just invert the X and Y Velocity
so if your X,Y Velocity is -1,-1, after collision it's 1,1
guess I'll have to calculate which side of the rect the projectile hits then
or if it was -1,1 it would be 1,-1
you don't even need to do that
if you're just inverting velocities
if I invert both it'll go back the way it came in
well...not exactly
I saw the image and I thought inverse normal, like light bouncing from an object in a ray trace
the projectile displacement is calculated from its current angle * velocity
lemme get the formula I used
protected void move() {
float[] vector = Utils.angToVec(getAngle());
getCoordinates().translate(vector[0] * speed, vector[1] * speed);
}
there's an easy way to find out if you're in front of, parallel to or behind a plane
I can't remember the name of it
you'd use that to determine if how the vector intersects
then you invert it using the normal
which you get from the same function
Ideally you really want to avoid using an angle directly for movement
ah yes: dot product
everything is pre-calculated
meaning I'll lose the flexibility of calculating sin/cos at realtime, but doesn't matter much for this game in specific
you can use dot product to determine where you are in relation to what you hit I think
it makes a change to be discussing game dev here lol
I really need to study math more lul
CombinedPropertyError (2)
Received one or more errors
input[3]
| CombinedPropertyError (1)
| Received one or more errors
|
| input.value
| | ExpectedConstraintError > s.string.lengthGreaterThanOrEqual
| | Invalid string length
| |
| | Expected: expected.length >= 1
| |
| | Received:
| | | ''
input[4]
| CombinedPropertyError (1)
| Received one or more errors
|
| input.value
| | ExpectedConstraintError > s.string.lengthGreaterThanOrEqual
| | Invalid string length
| |
| | Expected: expected.length >= 1
| |
| | Received:
| | | ''
at _ArrayValidator.handle (/root/bot/paladium/node_modules/@sapphire/shapeshift/dist/cjs/index.cjs:1205:70)
at _ArrayValidator.parse (/root/bot/paladium/node_modules/@sapphire/shapeshift/dist/cjs/index.cjs:939:90)
at EmbedBuilder.addFields (/root/bot/paladium/node_modules/@discordjs/builders/dist/index.js:225:31)
at xpRequiredForJob (/root/bot/paladium/src/utils/expCalculator.js:361:10)
at Object.run (/root/bot/paladium/src/commands/6 - calculator.js:66:31)
at Object.execute (/root/bot/paladium/src/events/interactionCreate.js:53:25)```
I don't understand this error?
Your field values are empty.
you can use a matrix to keep track of line x, and basically write an arbitrary line y in any direction, given x and the object, with an arbitrary length (but atleast longer than line x is). You then easily calculate the projection matrix of y given x, lets call it y'. There's a specific formula for that. This projection matrix y' will be the exact line that would occur if x would shadow over to y.
my boy I have absolutely no idea how to work with matrixes
i messed up my bot and i need help! in the terminal, under the problem tab it’s showing this
thats saying theres something wrong with your package.json
but thats not the actual bot problem
what happens when you run it?
what error
1 sec i’ll get it
so
i tried to create a / command as a translator
everything was working perfectly fine
then i installed npm discord.js @vitalets/google-translate-api
and that’s when all of this started happening
that makes no sense
show your package.json
also show what happens when you actually run the bot
"name": "Build-A-Bot",
"description": "Top.gg Build-A-Bot Event",
"version": "1.0",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"@discordjs/builders": "^1.7.0",
"@discordjs/rest": "*",
"@vitalets/google-translate-api": "^9.2.0",
"canvas": "^2.11.2",
"date-fns": "^3.3.1",
"discord.js": "^14.14.1",
"dotenv": "^16.0.0",
"moment-timezone": "^0.5.45",
"sqlite3": "^5.1.7"
},
"engines": {
"node": "16.x"
}
}
I might see what it is....
that's the package.json
this is the error I get
C:\Users\Maurice\Desktop\Da-High-Roller-Bot-main\index.js:14
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MESSAGE_REACTIONS, Intents.FLAGS.GUILD_MEMBERS] });
^
TypeError: Cannot read properties of undefined (reading 'FLAGS')
at Object.<anonymous> (C:\Users\Maurice\Desktop\Da-High-Roller-Bot-main\index.js:14:47)
at Module._compile (node:internal/modules/cjs/loader:1376:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
at Module.load (node:internal/modules/cjs/loader:1207:32)
at Module._load (node:internal/modules/cjs/loader:1023:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:135:12)
at node:internal/main/run_main_module:28:49
Node.js v20.11.1
PS C:\Users\Maurice\Desktop\Da-High-Roller-Bot-main>```
Intents is undefined
how would that have happened? the bots always worked and I didnt change anything
show your index.js
The whole thing?
the beginning
ok
like the first 10-20 lines
const dotenv = require('dotenv');
dotenv.config();
const fs = require('node:fs');
const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');
// Require the necessary discord.js classes and variables
const { Client, Intents, Collection } = require('discord.js');
const token = process.env.DISCORD_TOKEN;
const config = require('./config.json');
// Create a new client instance
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MESSAGE_REACTIONS, Intents.FLAGS.GUILD_MEMBERS] });
// Load our commands
client.commands = new Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
const commands = [];
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.data.name, command);
commands.push(command.data)
}
// Register slash commands
const rest = new REST({ version: '9' }).setToken(token);
console.log('Started refreshing slash commands...');
rest.put(
Routes.applicationCommands(config.clientId), { body: commands },
);
console.log(`Successfully reloaded ${commands.length} slash commands!`);
// When the client is ready, run this code (only once)
client.once('ready', () => {
console.log('Ready!');
});
// Our slash command handler
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
your code is made for discord.js v13
you installed discord.js v14
I think that happened when I did this
if discord.js was not installed before, then npm install discord.js installs the latest version automatically, which is v14
either that or update your code for v14
you can install v13 like this npm install discord.js@13
I'm very new to this so I'm not sure how to do that
^ this guide explains all the major changes
is it necessary to uninstall v14 first?
ok i will readthrough it
not necessary, the new install will replace the previous
ok i re-installed v13
but it's still saying that there's a problem with the package.json
String does not match the pattern of "^(?:(?:@(?:[a-z0-9-*~][a-z0-9-*._~]*)?/[a-z0-9-._~])|[a-z0-9-~])[a-z0-9-._~]*$". [Ln 2, Col 13]
ok, let me run it
its complaining that according to the NPM standards, the package name should be lowercase characters
but its just a warning, not an actual error
that’s so random lol
it will go away if you change the name to "name": "build-a-bot"
ok gotcha
its not wanting to start
i did node . like normal and it's just sitting there
oh nvm its on now
just took way longer than normal
thank you so much!
👍
those pesky cold starts
@wheat mesa @green kestrel managed to get it working, used a cheap solution of checking which of the collision box' lines intersect with the projectile
since the box will always be an axis-aligned square
also reworked my screen-switching system to be stack-based because it was giving me a headache, and implemented a character selection screen
eventually I'll attempt implementing multiplayer, just need to figure out how
besides that, only thing that remains is the audio system that I managed to break in earlier updates
looks really good actually
yeah
looks fun
add explosions next and slight screen shake
will give the shots some 'weight'
and increase the speed of the whole game 50%
including movement of player ship
i think the game speed is fine
i would decrease the movement speed of the balls flying around, and make the player ship's speed upgradable via buffs
of course you can have a "hard" mode that increases game speed by 50%
for touhou enjoyers xd
i can send you an example of how to compute the projection matrix of a moving object onto another matrix/vector.
you use java right?
yes but my head is smoking right now
it is
the spawn rate of enemies that drop upgrades is too low atm
they appear in yellow, you can see one at the end of the gif
I also need to find a better algorithm for spawning enemies
I use a point-buy system, but need to make some kind of director for choosing the appropriate enemies
I ALSO need a bigger variety of them lul, atm there are only 3 enemies + 1 boss
understandable. I will write you a little snippet with explanation for each step.
might help you out
how are you currently representing your objects/directions? Using vectors i assume?
Depends
Projectiles have their movement vectors calculated from the angle applied on the forward speed
The other entities are simple x/y movement
The repo is public btw, if you want to see it
Name change is still todo
Regarding this, don't worry, my sines and cosines are pre-calculated
I still think that you should be using vectors instead of angles
Like you can have an angle but it would be significantly easier to use both
Calculating the projectile path would be considerably harder without angles
You can keep both
I kinda do use vectors tbh, like
Angle can be used for updating the position but for collision resolution it’s much easier to use vectors
A projectile moving at 45° would have [0.5, 0.5] movement multiplier
I just apply the projectile speed over that
Angle is only for movement
And hitbox
oof angled hitboxes are rough
Kinda, but java helps a lot at that
I'm already working with affinetransforms, so I just check if both shapes intersect
proj.getCollision().intersects(ent.getCollision()) basically
Ofc I won't be able to use my ricochet logic on that, but angled hitboxes only really matter for ultra long projectiles, like a laser
Now that I think about it, perhaps the formula gpt gave me earlier was probably right, I found that most of my issues were that the projectile was colliding twice, so changed direction twice
It was atan(-sin(ang) / cos(ang)) or smth
Can someone please explain what bot sharding is and how it helps? I've no idea whatsoever so start from basic
At a certain point the limit of servers your bot can handle will impact your performance and even the ability to be invited to servers. Because of this discord has implemented a system called sharding which essentially splits your bot into multiple "instances" as one would say. This allows your bot to handle more servers and not spam the api and gateway. The way sharding works is when you make a connection to the gateway you send a shard id and the number of shards your bot spawns. This creates multiple gateway connections and splits the guilds amongst those shards. To handle what guilds you need some libraries give you helper methods to broadcast to all shards to find the guild you need or if you know the id you can fetch it.
With discord.js they make sharding stupid simple but there is also libraries that add more features
Sounds pretty complex to implement. Regarding the js part, I sadly work with py so I'll have to do some research soon
Also is it just in-code stuff? Will I have to make some hosting-side changes to assure that the bot works perfectly in all guilds
No changes really need to be made hosting wise just make sure you have enough juice to support such a large guild size
It’s also not hard to implement at all
Especially with the progress of libs
What python lib do you use? Discord.py?
Ah so basically I'll have to have a stronger hosting to assure the performance
Well it’s not a necessity but with more guilds the more resources it’s going to use as it’s doing a lot more in response
Right now it's in 440 guilds so I believe I'm good for a while. I got told that I'll have to get over sharding once it crosses 1000
That's fair enough, considering the amount of commands it receives per hour I can tell that there's gonna be performance issues with time
Eitherway thanks for assisting, I'll probably revisit this channel when I actually have to implement it
I'll go over that now
Yea once you hit 1k or more it’s a good idea to start sharding it will split the guilds evenly amongst shards
Also another doubt, all of these shards are hosted by one same provider right? Or will I have to get 2 seperate hosting plans to host both shards? Does that sound silly
Nope it’s all hosted on the same instance
Alright, so are there any changes for the users of the bot? Or they won't find any difference
Splitting the workload amongst multiple providers is not really useful unless you’re really doing something wrong or your bot is so big it needs that much resources
No changes for users at all
It’s all a you thing as the developer
Ah awesome I'm less worried then
Got it
Also is there any issue if I just shard the bot right now?
Got it
its a good idea to start looking into it, at 1.5k its recommended, at 2.5k its required
yea
Makes sense, so it's only guild based or does user count of guilds has something to do with it
Guilds get allocated to shards typically at 1k per shard
only guild based
So 1.5k guilds with 2 shards is 1 shard having 1k the rest will go to the other shard
ah right
not exactly
oh?
they will each have ~750

so for example if a bot has 5 shards, won't it be slower than a bot which is in less guilds and no shard at all
I thought they made it spread out for 1k per shard
shard allocation follows a specific rule based on the guild id
i mean overall the performance is gonna get effected as its in more guilds
Also some commands of the bot processess all guilds it's in. For example
for i in bot.guilds: if ctx.author in guild.members: do this do that
pretty much yes, but 5 shards with 1k each will be better performance than 1 shard with 5k guilds, since it would overload the process
would that be a really big issue once the bot is in many servers
I see
those commands will need to be rewritten to account for shards
each shard will run on its own process, so your code only sees the current shard
so ill somehow have to add all shards into the commands is what youre telling me
for example, right now your bot runs in 1 process, so everything is inside the same program instance
you can broadcast to all shards tho if need be
when a user runs a command in a specific server, won't the bot just see which server he ran it in and use the shard for that server automatically?
oh
but thats done internally by the library
i see
and the library provides communication between processes
usually
so if your command needs to access data from other shards, like all guilds in the entire bot, your code will need to send a message to the other process to request that number
and wait for the message to return with the result
thats called broadcasting
ahem
ah this makes it clear
you will need to check if your library has that
i see guess ill need to read/ask at the library's support server
Also for a bigger project, like a bot in countless servers, what resources are a must have hosting wise? Will more Ram or vCpus help?
this is the sharding formula:
shard_id = (guild_id >> 22) % num_shards
for a python library, you can think about on average 200-400mb ram per shard, or per 1000 guilds
is that an operator
ideally you should have 1cpu per shard, but usually thats not needed, a single cpu can usually handle more than one shard easily
yes
The current hosting plan I'm using is this one https://prnt.sc/SerSCfzLbhJH
I believe it's good enough for a good while?
that should be good enough for 50k-100k
8gb of ram is fine
thanks a lot
Unless you use djs /s
hm
500mb of ram used just on launch 💀
I wish this was a joke but djs uses a lot of ram
lmao that sounds funny
yes, you need to convert it to bigint to do that in js
this is what a snowflake is made of
the bot still uses a lot of ram tho i believe and it connects to the database everytime someone runs a command
shifting to the right by 22 bits basically cuts off the instance and sequence parts
and leaves only the timestamp
the network usuage for the bot is usually really high
so its a 64 bit int
yes
yeah, to account for future timestamps
41 bit timestamp is good until 2039
then you need 42 bits
yes
now correct me if im wrong, but what the fuck does shifting it 22 bits even do
so depending on the guild's creation date, it will be moduloed into a specific shard
957347862314905610 like take this snowflake for example what does shifting it 22 bits do
wait do you code bots in c++
extracts the timestamp from the id
🤔
^
see I know how to count in binary but idk how to use >> and such
957347862314905610 >> 22 = 228249517039
228249517039 = timestamp for the creation of the id
aka the date when the id was created
where does the 22 come from tho
^ lol
Snowflake IDs, or snowflakes, are a form of unique identifier used in distributed computing. The format was created by X (formerly Twitter) and is used for the IDs of tweets. It is popularly believed that every snowflake has a unique structure, so they took the name "snowflake ID". The format has been adopted by other companies, including Disco...
but unless I am wrong, 22 bits is more than the timestamp no?
im also tired so I am definitely wrong
dear god no
moving 22 bits to the right, cuts those bits off from the righ to the left
leaving only the bits on the left
right right
so its removing the sequence and instance parts of the snowflake
binary is right to left
and extracting the timestamp
not left to right
ye
so it would start where that first instance is, and end at the last part of the timestamp
its exclusive not inclusive right?
What database do you guys stick to
but it doesn't include the last part of the instance
Sounds like my bot 
so its exclusive in its operation right?
its inclusive from right to left
i mean when counting lol
ah I meant when performaning the shift
but yes it excludes X number of digits
it doesn't include that last I
from right to left
Mongo db
it just starts there
postgres
keep in mind the db you use matters depending on how much you want to spend
sqlite
sqlite has its limitations and works based off the disk
postgres is in the cloud but it scales differently
mongodb is a shitty db imo, cause scaling it is so damn annoying

I see, I've the code written for mongodb
sqlite is more than good enough for 100k+ guilds
hm
ye you need to model your data into table-based scheme
I'm usually just storing object types on the database
unless sqlite has advanced since 2019
same with postgres tbh
although postgres supports json and arrays, its not recommended
I model my data around tables and relations
ye
cause that is what sql is about
exactly
a mistake I made in my early days was storing data that was meant to be attached to a table with multiple values was to use an array
and push to it
💀

only you would be someone that'd do that
yup
The free plan?
i do backups so i dont mind losing data
dont do what tim just said
there is no plans
oh
sqlite is free
I never worked much with anything except mongo sadly
you run it inside your host
the only thing sqlite costs you is your sanity and disk space
lmao
ah i see
sqlite is good af
its good for prototyping
i get 0.1ms latency on reads and writes
but I will 100% use a cloud db for anything that matters
imagine storing your data in an sqlite file and running windows 98
:D
lmao
sqlite technically supports more than 1tb of data
but my sqlite file is like 20mb rn
it should theoretically support as much as your disk no?
or does it just shit itself at a certain point
there are some limitations like everything
fair
stupid db /s
uses the disk but not even fully
smh
should write sqlite in rust ;)
uh...
its likely the numbers
How many users/guilds is the bot in
~10k
ah thats awesome
still waiting on that astronomy api
the only bot I will ever make
is an astronomy bot using tims api
:D
my mongodb is at 4mbs something and it's in 500 guilds
Automod moment
my db is at 400gb but thats because I am too lazy to delete test data /s
working on it :^)
lmao
because i have a paying client waiting
you said that every single year
The conclusion I came up with after working on a few projects is that card collection bots never go off trend 
nope but there are so many of them its useless
Yeh it's just the lack of creativity in them
I'm working at a bot following the similar theme, just taking it a step further so it's doing quite well
It used to be fun making bots, until you realize no one fucking cares about the art and just copies everyone
yes it's sad, so many bots have the same repetitive concepts
Because many people think that creating a bot will bring them a lot of money. Everyone wants a piece of this cake for themselves 
Making/owning a discord bot has to be the least rewarding task to take on honestly
Not including the bots you make for others at commissions
Obv there are exceptions but in 9/10 cases it has to be a lot of work for a very small amount of income. Considering how hard it is to advertise a bot with all the competition
This is true, and often those bots that are really worth attention quickly turn out to be completely unprofitable and people abandon them
making a discord bot to earn money is the stupidest idea ever
most of the time unless you are very luck you are breaking even
or making a very little profit margin
for bots you'd essentially want a connection pooler
For me that's just language of gods
pymongo, for example if you use it, it has a connection pool
basically it keeps N connections open and simply reuse them when needed
if you're using an external database, you need to keep the connection always on
opening and closing it every time it very wasteful
but thats likely not whats using most of the ram
most of the ram usage in discord bots comes from the library caching all the discord data, like users, members, channels, guilds, messages, etc
ah got it. thanks both of you
i gotta see where I can open the pool from
a tip if you want to reduce ram usage, is to disable presences and message content if you dont use them
or disable anything you dont use tbh
if you have the presences intent enabled, thats gonna hog your network like crazy
presences literally account for like 90% of a bot's network traffic if they are enabled
also, if your library is not already using compression, turning it on will also save a LOT of network traffic
Is there a more efficient json parse / stringify than the default in nodejs? Like something that you give the data schema beforehand and it can optimize it's code to stringify that schema
yes
if you have the schema, there is a json library with schemas
alternatively, if you want to go even faster and smaller, you can move away from json
for example messagepack or protobuf
both are binary formats that are faster and more efficient than json, but they are not human readable
protobuf uses schema, messagepack doesnt
Well the issue is that my API is sending quite big jsons
Around 400kb
And they sometimes take very long
Sometimes 200ms
Sometimes 3sec
you can give one of those fast json libs a try
alternatively there is also something you can do to speed it up by quite a alot
take all the parts of your data that are fixed/predictable and create a json string with string interpolation
and only use JSON.stringify for things you have no control over or that are too dynamic
I've them disabled thankfully
very small sample size but it demonstrates the performance difference between JSON.stringify and raw string interpolation
not sure how this difference scales tho
also check if your api has any "cacheable" parts and pre-compile json strings for those parts
Yeah I think I'm gonna cache full json string
The api doesn't update often
So it's probably fine
cool
The funny thing is
Someone managed to take down the entire server
By spamming those 400kb requests
Lol
Lol
One message removed from a suspended account.
btw, wouldn't jit simply ditch the interpolated string as a no-op, thus giving a much smaller result?
stringify cant be ignored since it's a function, but the string is immutable
if it were ditched it wouldnt take 60+ms
lmao
now I'm worried it wasn't ditched
why didn't js ignore that no-op loop?
i see will have a look and based on that send you a message on what you can do to project the angle.
i dont know the internals too well, but i believe object access is difficult to predict
i guess it doesnt realise its a no-op until after it accesses the object
property access might invoke getters and such that still need to run even tho its a no-op
what's the best way to deal with a lot of options in a command?
in discord.js
it feels weird just having a lot of getString and const
not much you can do
I'll just do it like this never mind

Are you going to be using these multiple times
like what is the use case here because you are doing this inside a switch/case
it's an odata filter and my idea is to modify it based on the user request
and looking through the minecraft marketplace database
🤔
yes but like, you are doing this inside a switch case
so this leads me to believe you are going to be using these options multiple times
so this is not the best way to handle this if thats the case
oh I a lot of sub commands the match and case is just for the search command
I just am not certain this is the best way to handle this, assuming any other case statements also rely on the options
I don't think I'm following
I have the switch statement for each command and sub command
they are all in their own scopes and get broken after it ends
is there a better way?
woah woah woah
now I think you are doing something seriously unecessary, unless I am not following
May I see the rest of the code? if its not too much to ask
old code I'm going through it and optimising it but yeah
That's a nightmare
tell me a better way to do this
Realistically you should not be handling the code like this, at least with commands.
Now i'd recommend making some sort of cmd handler that can handle sub commands.
Using a switch/case statement like this is by far the worst option
but why are they bad?
aren't they faster than having if statements for command handling?
because its messy, and even if they are "faster" it isn't always the best thing to use. Just like with if statements, switch/case also has its uses and stuff it is not meant for.
Also faster != better code
ehh
I recommend making a command handler, either a class based one or a function based one.
you will have an easier time managing everything rather than in a nested switch/case
though if you refuse to make any changes, then at least make functions to group your command code together and call them in the case bodies
I just want to finish this bot as fast as possible I'll worry about making it readable after it's done
I've been working on it for the past 3 months
suit yourself
Im just telling you that its a bad idea to do it the way you are doing
but its ultimately up to you
mind you thats what you asked of me so
I appreciate the feedback
what I do normally is first get the code/command working and then refactor it to make it readable
at least that way suits my style
its not even about readablity tbh
while switch/case statements are relatively faster at lookup than if statements it isn't meant to be a fix all solution
sometimes switch/case just doesn't make sense to use
and tbh, in this case neither would if statements
well ok
the way i'd personally do it is
- Make a commands folder
- Make a command class that handles loading any files that has a class that extends it in a specified folder (e.g command folder)
- Load it then call the run method (or whatever you decide to call it) and pass in the appropriate params to it e.g for interaction commands pass in the interaction.
- Write some commands
with this you can extend this to allow command level permission checks like some frameworks do (namely sapphirejs)
yeah I'm already working on that
one of the issues I have is that I have 3 global databases that most commands rely on
I want to try exporting them and pass them to the other files but always was too lazy
yeah
one for liked accounts to the bot and language control
one for stats and logs control
and one for extra items like linked channels, creators database, bot bans etc
they are firestore databases
trying to optimise them to reduce the amount of reading and writing to the databases

but the point of databases is to handle the read and write
you are just adding more overhead by using multiple
firebase has a limited amount of them to do in a day unless I need to pay
then dont use firebase
I assume you host this bot on a vps right?
postgres is free
even mongodb is free
firebase is a terrible db imo cause it costs to use, which shouldn't be a thing
I use firebase because I like the service and I'm already balls deep
fair enough
the read are writes are so much that it doesn't matter
not only are you balls deep but so is firebase, its a terrible service for what it offers
20k writes, 20k deletes and 50k reads per day
rookie numbers
databases can handle that and more so long as you use pooling and even without pooling it can still handle a hefty amount
it costs very little aswell
like $0.03 something for 100k writes
well 0.03 for reads and 0.1 for writes
yknow how much that is if you do 100k writes a day
Ik I don't even need it lol but I find the service great
I'm having a partnership with some companies soon and it's doing it's job flawlessly
neat
well good luck
I still think tim is right and discord channels are the best db @quartz kindle right?
lol
Someone I know made a library for this and I hate it so much

I think I know the lib you are talking about
Every technology that sticks around this long has a proven purpose or niche 🙂
and cortana?
indeed
i cant find the original repo for that old discord-fs lib
now there's a shit ton of them
What do you think about the possibility of setting a banner for bots? 
here i found it https://github.com/bobisai/discord-fs
the readme is a solid 5/7
i
pooling
makes life sm easier for connections
who needs pooling when you have a memory mapped db :^)
is discord giving anyone else an issue with updating their app directory info
its been over a week and the only value it wont edit is the expanded desc
LOL gotcha
the current for mine is so ugly/outdated and no matter what i do it wont update it. discord was like 'oh usually takes 24h' but its been a week
weird
im wondering if certain characters aren't able to be used
i use ⸝⸝➜﹒to format something in it but i don't know if that would be why it just wouldn't update
guys i was trying to get started to cloudfare
i installed it and did wrangler login and it opened a webpage where it asked for consent..i clicked allow and then this
it creates a temporary web server on localhost for you to verify with
now you are logged in with wrangler it won't be live anymore
what do i do
to fix it
nothing
you have already verified
thats just to login with cloudflare, nothing else
huh? so i dont need to do wrangler login??!
have you already done wrangler login
and did you click login on the cloudflare website
i did type it in shell but when it opened webpage..that problem occurred
hi i need some serious help like one of the serious one i am stuck in logic part idk what to do
its a logic part not code error and enything
someone help with this
So youre still trying to login?
i am needing to
Are you using a remote machine?
IE, you're running wrangler somewhere not on the machine you're opening the browser on.
Like a vps
i am doing on replit
Wrangler is typically intended to be run locally
But: https://developers.cloudflare.com/workers/wrangler/commands/#use-wrangler-login-on-a-remote-machine
Did you open the link?
yea
Should explain everything you need
I dont use replit, so I cant answer that tbh.
I've never heard of wrangler being run on replit, if someones done it before there might be a guide online specifically for that.
Hey, so i'm using sequelize as ORM and this happened,
as you can see for unknown reason this user_id isn't converted in string and i checked my types etc and i use Snowflake from Discord.js which is basically a string and even in my sequelize configuration for this table it's
user_id:{type: DataTypes.BIGINT({length:49}),allowNull: false,references :{model: Players,key: 'user_id'},},
but for a reason i don't know it doesn't work for this specific ID 447880780019138560
Just found that's not from sequelize, my integer code treats the id as an integer
but this one only
how many here are adding banners to their bots rn?
me
its funny because its already bugged
bots shouldn't have that tag
lol didn't see the nitro tag on mobile
it's technically correct; bots have all features of nitro
Me wondering why the command is not giving out the role for the member.
Meanwhile the code:
skull tissue 
another character
still need to write the description for it
basically a very agile ship with boomerang projectiles, which can pierce and hit once every 100ms
and can blink to the last projectile fired
fps is low on gif only btw, had to limit it to 30fps
Has anyone played with this?
https://developers.cloudflare.com/workers-ai/platform/pricing/
Yess it’s great
it's probably intentional to drive more nitro users 
dead chat
It is what it is
it's what it's
is it possible in current discord api to send components inside of an embed?
Ive been looking around and there really isnt much on the topic
Nevermind, I answered my own question. "Embed" Doesn't have any property for components 😦 sad times
You can add components under the embed
i just discovered that cloudfare doesn't use normal hashes using a hash function for protection, but they use a random generated hash based off fucking lava lamps??
that's so sick, who the fuck came up with that idea though. Genuinely 1000iq
lmfao yeah
madd
I hate you for this /s
It’d be better if they used out of context top.gg
Yeah they have an isolated room with many lava lamps and a camera to sample the bubbles' position
not really the bubble's position, they take a picture of all of the lava lamps and use the resulting image bytes to seed the hash afaik
Ah yeah
Hi
What if there's an earthquake
they'll just buy another set of lava lamps
just a few relations
They even invite you to visit the room as you add even more randomness to the resulting image
im designing a chat app which uses websockets in browsers for relaying events to users of course, but I'm wondering what the best way would be to handle this, thinking big production scale
should i delve in things like compression? i heard compression for js with things like zlib sucks because of its fragmentation, now this was for node so not sure about v8 in browsers (or even spidermonkey)
but given the small nature of 99% of messages i doubt compression would provide much benefit so id rule that out
i was more interested in using BSON instead of raw JSON since that would save massively on transmitting redundant JSON things like quotes and reusing names
i think that they got a backup...somewhere
backup lavalamps 
but on the other hand, the room must be pretty secured or not? Maybe like shock absorbing concrete coatings or sum
I've never tried either Karuto or Sofi bot in my life but one of my bot users wants me to implement a feature similar to those bots. How does that work? I don't believe if discord allows me to track what account belongs to which user. Isn't this similar to IP tracking or something? https://prnt.sc/2H0wJXMY3ACn
Well to people who cant look into image I'll copy paste the text
for new players, the bot should have a verifying thing like what the karuta/sofi bot has. this will prevent people from using their alts as it wont let them verify if they already have a main, you can like add this when theres more people using the bot or something
Comparing the IP addresses of two accounts is probably the only option when it comes to Discord, despite the fact that if someone wants to, they can quickly bypass it using a free VPN
Or if, for example, someone is able to register using mobile data on their phone and on their computer
Thought so, isn't it quite risky for any user to play your bot given that it tracks down IP?
Even tho the bigger bots most likely won't leak your data or use it for suspicious activities, still overall they are tracking the ip
Yes, but the IP address is not as "sensitive information" as it may seem. An ordinary Discord user doesn't have to worry about this, it's worse if you are a "public person"
Of course, there are data and password leaks, but if they are not interesting in any way, no one will be interested in them
Got it, thanks a lot
is it a lot for me to code in a listening event for my bot coded with discord.js with chat gpt?
I'm sure there's a node module I have to install but I just have a feeling that is a lot more complicated than a node module and listening event
compression is good if you can maintain a shared context like discord does
as well as protobuf instead of json
protobuf + zlib is pretty much state of the art bandwidth savings, you're probably looking at 90-95% size reduction
and cpu-wise its probably gonna be faster than json
but you need a pre-defined schema to use protobuf
I have no idea what a “listening event” is
I highly recommend against using chatgpt since the code it generates is pretty garbage
the events that you put in index.js
and i mean like, having the bot respond to @ as chat gpt
like if someone @‘s my bot a question, it will respond with an answer
i’m still learning discord.js and the terminology of coding so bare with me lol
to access a service like chatgpt, that service needs to provide an API
chatgpt does provide an API, both official and unofficial apis exist
(Also, the API is not free iirc)
there seems to be an unofficial proxy api that is free
but heavily rate limited
1 request per day ;^)
ah ok so it’s not really worth trying to do unless i pay for an official api
ah ok lol i won’t even bother then 😂
its pretty affordable
for my bot i use gpt as a base for conversational feature and it costs me like 4$
It's likely that such a feature will cost more than it earns, depends how you monetize it
I remember your pfp clearly from somewhere
Did you used to own the hypesquad bravery server?
Hey, I used to be part of the DMP and moderated in quite a lot of servers in the past, I've never owned them but probably had a moderator role in the 3 unofficial servers at some point
Yeah that's probably where I remember you from then
Thanks! 
Carl bot status page 🔥
So glad my bot doesn't connect to the gateway. It's sometimes a challenge and not always possible depending on what you want to do, but it avoids having to deal with shards like that.
yeah, my bot does connect to the gateway, but it could still work without it
mine also doesnt anymore
but honestly slash commends are unstable af
text message commands via gateway were much more stable
hi
im migrating the "v0" api
wondering if someone has a decent suite of uses to validate consistency
theres so many different api paths i lose track
/api/*
needs bot token
e.g. to check votes
the sdks should implement the routes iirc
requires auth for the first one
yeah the client ones are not part of the "api"
but cool
i dont think https://top.gg/api/client/entities/264811613708746752/reviews should be possible tbh
just allows people to create review incentives
anyways im getting sidetracked 
ok so v0 covers anything in the docs right
alr hard one
i got a file
im guessing it's sql
it's fixed width, 4096 kb
whole lot of these
Þï¾
how can I properly decode it
these are internal api routes
we use them to load the UI
they're also passed via props im pretty sure 
yeah
we cant do pagination or anything else then
tbf its impossible to block that since people can just automate getting props (nextjs my beloved)
yeah
is anyone familiar with the hoare triples and annotated programs? If so, can anyone help me to construct such an annotated program given an inference tree?
me
do u use any of the weird obscure undocumented stuff?
what about it?
im migrating the v0 api rn
trying to understand what's actually being used outside of our docs
routes will stay the same + documented flows will stay
errors are clearer now, which is nice
idk if there was a error type in the libraries
poggies
but that's slightly different
but stuff like accessing the api with user tokens (no longer obtainable) are removed
lesgo
just wanna keep the v0 api as little as possible
so we can move our focus towards v1
which will be actually clean

so essentially like structs but in javascript
possible but a bit inflexible





