#development
1 messages · Page 2033 of 1
even in C booleans take 1 whole byte
java uses its own jvm which further translates everything into its own data containers
so they use 1 byte to prevent cpu compatibility issues?
its the minimum possible amount of data that the cpu can process
A bool takes in real 1 bit, as you need only 2 different values. However, when you do a sizeof(bool), it returns 1, meaning 1 byte. For practical reasons, the 7 bits remaining are stuffed. you can't store a variable of size less than 1 byte.
that makes sense
But you have to keep in mind that we nowadays have 32-bit and 64-bit processors and while a single bit would be enough to hold a boolean, the processor just processes data that is either 32 bits or 64 bits in size. (Although it can compact data to 16 bits or even 8 bits.) But the processor also has a set of flags, which are basically 1-bit registers so it can store booleans as a single bit, depending on how the processor is used.
it's basically because of how registers work
this ^^
it's way easier and faster to flush a byte into the register than flipping through to change a bit
here's a nice explanation: https://www.quora.com/In-C-why-is-the-size-of-the-bool-1-byte-Isnt-just-1-bit-enough
Answer (1 of 4): Suraj Surve gives an almost-correct answer. But you have to keep in mind that we nowadays have 32-bit and 64-bit processors and while a single bit would be enough to hold a boolean, the processor just processes data that is either 32 bits or 64 bits in size. (Although it can comp...
all of this is why bitfields are so damn useful
you can pack dozens of booleans in a single 32bit int
where if you were to store them independently in memory, each of them would use a minimum of 1 byte, if not more
make a compiler that grabs all booleans during runtime and pack them in a global bitfield pool
yeah but how will you address them
hm, declaration order?
well the compiler still needs to write the number anyway
memory usage is a tricky business because everything is addressed by 8 bytes in 64 bit systems
even a single reference is 8 bytes
so 8 bytes to access the memory position where the bit field is stored, plus 1 byte for the index number in the bitfield
and if you go deeper, all memory access is controlled by the allocator, which further decides how to split the data across the physical ram and often does so in fixed size chunks
💀
you sacrifice memory for performance
i got a problem...from some reason i cant download anything with npm...i got this and thats all
no errors nothing
that means its already installed
if its not, then delete your node_modules folder and your package.json and package-lock.json files and install again

you need to have a package.json first
are you sure you are in the correct folder?
npm init
type dir
Same thing has happened to me just create a package.json
did it also say you had 24 packages installed? is npm that bad?
solve it
tnx for help guys
exception-based code flow 👍
but well, although your code tickles my security-leak sense, Error doesn't contain password property
yeah ik, is there anyway to ignore that?
cause there is noway Error gonna have password property
ignore? you don't simply ignore stuff, you fix the issue
return null if user doesn't exist
it is kinda bad :<
if u want to have an exception, print it before returning
cause I want to return as a Error message
wdym
return to who? the user?
const user = ...;
try {
if (!user) throw new Error(...);
} finally {
return user;
}
user will be either the user or null
I just want to return the error message
other than that, DO NOT STORE PLAIN TEXT PASSWORDS
hash the password then compare with the hash in database
Yes
If you wanna go the extra mile
Do hashing + salt
So that a rainbow table wont work lol
if u want to go EVEN further, hash the salt too 
The easiest way to do it
Use the crypto module
const {
scrypt,
} = require('node:crypto');
// Using the factory defaults.
scrypt('password', 'salt', 64, (err, derivedKey) => {
if (err) throw err;
console.log(derivedKey.toString('hex')); // '3745e48...08d59ae'
});
// Using a custom N parameter. Must be a power of two.
scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => {
if (err) throw err;
console.log(derivedKey.toString('hex')); // '3745e48...aa39b34'
});
scrypt
Yes
Provides an asynchronous scrypt implementation. Scrypt is a password-based key derivation function that is designed to be expensive computationally and memory-wise in order to make brute-force attacks unrewarding.
they missed the chance to call it JavaScrypt
const {
pbkdf2,
} = require('node:crypto');
pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => {
if (err) throw err;
console.log(derivedKey.toString('hex')); // '3745e48...08d59ae'
});
Both have the same purpose
sha512 holy fck
what are u trying to hash? an individual atom?
Security is no joke
chances are there's not enough silicon in the universe to make a computer able to crack that
Better that way
Better that way
At least that means the passwords cant be brute forced
now this...it just open terminal for like .5s and close it
Probably something in ur code that causes it to exit the event loop
allIntents is not a valid object parameter most likely
config.json UH OH
Try new Client({ intents: allIntents }) or whatever it is
WILL LATER
its on my PC soo no wories
you are God and an absolute legend ❤️
its super painful to webscrap a website, just if theres a npm to only scrape the website's head tags
u could use regex
i did use regex
what did u use and what are u trying to get?
only the head tag or the entire head block?
entire block
specific tags within it?
metas
i just send get request to youtube for example and axios will return with the html code, and from that code i filter only links and theres will be alot of duplication, so i remove duplicates and thats how i do it for now
Nah I needed that, definitely failed an exam today lmao
/(?:<meta.+?)(?:(?<key>\w+?)="(?<value>.+?)")+(?:.+?\/>)/gim
aight thanks
im currently using this :p
/(http(s)?(:\/\/)?)(?:[A-z0-9](?:[A-z0-9-]{0,61}[A-z0-9])?\.)+[A-z0-9][A-z0-9-]{0,61}[A-z0-9].+(?:[A-z0-9-])/gim
yours will grab links
mine will grab meta values, so u might still need to check if it's an url
actually, mine still miss second matches within the same line
(?<=<meta.+)(?:(?<key>\w+?)="(?<value>.+?)")+(?=.+\/>)
also to test an url u can just try to send a request to it
if it errors then it isn't an url or isn't reachable (which u wouldn't want to try anyway)
most fetch libs are fail-fast, so it'll do a bunch of checks before attempting a connection
i give up!!
registering slash commands is fucking inposible
literlay same code...i execute this file and...nothing, no errors, cmd opens and close after sec...
using prefix is just easy
index.js run normal but this dosent
Worst part there is no error
Maybe i should downgrade node
Maybe that could be a problem simce i use 18.0.something version
Are you even running anything in your index.js file? Your other files don’t just magically run because you put code in them
Node 18+ should not cause issues
Yea there is a code in index file i just copied it from djs guide since i wanted to see will everyrhimg work... Index file works and i get msg in console when i run it
But this deploy-commands... Dosent run
The worst thing is that there is no error
What is the easiest way to get all the guilds after identify to cache them?
listen to GUILD_CREATE events after identifying
they also give guilds in the ready event too iirc
yes, the ready event gives you a list of guild ids that you should expect
then you receive a bunch of GUILD_CREATES for those ids
Okay so I assume that on guild create I should just add those guilds to the cache?
yes
you will not receive any "real" GUILD_CREATE until you receive all those intial ones
I am starting to think about how I should even handle caching, cause right now the way I am doing it wont scale well
by not caching
bro im serious 😔
Cache raw structs in a Map<K, V>
Well I already basically made my own djs collection :^)
Trying to mutate the data returned by Discord is just so much overhead
Mmmm
or constructing classes I mean
I was thinking of just making a class called
GuildStore that extends BaseStore
You can do a similar thing to djs where they cache in Collections, but don't bother making so many structures like discord.js. It's just collecting garbage
The basic concept of making a good lib is you take all of what discord.js is doing and do none of that
I was thinking just make a class for each thing I cache like Channels, Guilds, Users, etc
Actually hol up
Some stuff I can understand like trying to get dates from SnowFlakes
but that can be a Util function
really, just store raw data
it'll save you a lot of pain of adding members to classes when you could just not update the lib at all unless totally necessary
You'll find out very quickly how volatile Discord's api is
import { BaseStore } from '../../../stores';
export class Guild {
public cache: BaseStore<string, Guild>
constructor() {
this.cache = new BaseStore<string, Guild>()
}
// Have all my guild related methods plus being able to keep the guild cache
}
Though now that I think a bout it this probably wont work either
storing Guilds in a guild?
Mmm, I am trying to think of how to reliably do caching for the important stuff but I am nub
Look at source code of other libs
i believe he's making managers for each cache like discord.js
Nah not anymore
why does it look like this then
I was thinking about doing that but then decided not to
what is your goal for the lib? Ease of use? Efficiency and scalability?
you can't have both
I wanna make it as user friendly as possible
Without holding their hands too much ofc
That's already discord.js
true
Well I can't really go for efficiency and scalability right now
I am not good enough to write code to achieve that
use raw net.Socket for a week and you'll be either good enough by then, or want to kill yourself before
wtf is that?
net.Socket is a very low level Stream based socket implementation for connecting to web servers
I think it still provides some helpful abstractions like dns queries
I mean I don't think I could even write efficient code at all so 
Welp. If you have a memory target in mind, you can install heapdump and start peeking into js heap snapshots and seeing what takes the most ram
as a warning, beginners will find it very hard to do that
discords raw data is actually pretty inefficient
but then djs takes it and makes it even worse
:^)
Better than dumping all of the data into some class' members
the size of the prototype just adds to the mess
discord.js' import size already makes me not meet my memory target
combination of the prototypes and module strings
alright so all I am reading is I suck 
I still think I suck after understanding how to do something at such a low level
that wont change
yknow what I am happy with how far I got with this lib
time to call it quits and leave it to the big dogs
make an lmdb based cache
fuck no im not smart enough to dick with other libs code
You dick with other libs' code to get smarter
I lack the confidence to do that tho so it will likely never happen
you dick with other libs to feel good about yourself
because other libs suck
:^)
true
If anyone does wanna take a look at my shit code https://github.com/MistyyBoi/strife here ya go :p
I might at some point pick it up again and start working on it but I lack the motivation now
Honestly, most of the stuff I work with is proprietary because I have very strict demands for performance. For better or for worse, I pushed myself to seek out or make better performing software and how I have it with my bots is good imo. Could be better, but my dep tree it totally clean of libs like axios and others that I consider to just be garbage in the heap if I was the GC.
They have their audience, but I'm not in it
I try to be performant as possible but I always end up lacking in that aspect, plus the stuff I generally make either a few people use or no one use it at all so it just doesn't seem like what I am making is very appealing to the public which blows my confident to even continue learning
You gotta either make something so mind blowingly better that it would be stupid not to use it or just be popular
Yea I suck too much to do either of those 
I tried to get the libs I maintain listed on the official community resources, but got ignored for like 2 months except for 1 comment by d.py dev correcting one of my statements about not seeing other modular libs in the list and that's it. Then harsher restrictions came and now I'm just fucked
first step is to make something that youre gonna use yourself
most of the stuff i made i started because i needed it myself
and i use it myself
if other people like it or not thats not important
Mmm, my end goal is to make something that people will enjoy using
The most cursed thing I made was a command documentation based argument parser because slash commands weren't a thing yet and I wanted something that gave me "type safety" without having to jump through so many hoops for each command
like
if you try to appeal to others first you just end up making the equivent of yet another multipurpose bot
!commandName user:User description:string [action:"add"|"delete"]
would parse properly
you have to appeal to yourself first
Mmm yea but a lot of the things I would want to make are just way too much for a single person to do without blowing my brains out
This shit is really cursed
xD
I need to come up with something that I enjoy doing, that lib was fun but it made me lose motivation
I decided a while ago to not make any more bots as there is no point anymore
the market is too flooded that no matter what even if your bot is better the popular ones will still be used over it
Well. Either bots don't do a specific thing or so many bots do it terribly
Like, I wanted to make a text based multiplayer rpg since that didn't exist at the time
I quickly gave up on that tho
I can't do that
i'd end up getting in over my head and try and do the impossible which then leads to me giving up since icouldn't do it
Plus the discord api in terms of making bots is getting boring for me, I don't want the discord api to define my entire career as a dev I wanna branch out into something more enjoyable that will bring enjoyment to other people as well as myself
My music bot has been in service for 4 years and is only at 6900 guilds (nice)
and I've received a lot of positive feedback that it's just so much better than other bots, but what can I do if I don't advertise it so cut throat like other bots that farm votes to reach front page
I mean shit for a music bot that is pretty nice
I suppose, yeah, but I see other bots that have existed for much less time and are in hundreds of thousands of guilds
Not like I'm jealous. Must be a nightmare to scale discord.js music bots
I bet those ones aren't nearly as good as yours tho
They are typically either made poorly or copy pasted
Well. That's for others to decide, not me. And it seems like people want whatever competitors offer
the meta is vote locking
wanna give people volume control? Vote lock
Is what I would say if I did do that, but I don't
That is what I dislike tho
Vote locking is just pain
I get it, wanna get your bot on front page but some people take it too far and votelock nearly everything
Whatever gets you to front page I guess
I still have a project idea that i have been reluctant to actually start on, mostly due to lack of people supporting the idea
The first week my bot got accepted onto a list I won't name because it isn't this one, It got 2,000 invite uses. That's only because it appeared on a "new bots" category on front page
what is it
I can dm you the idea (not like it is a very good one but yknow I don't want some rando sniping it)
Its a nightmare to scale discord.js bots
that's why I gave up on Discord.js
But I used it for most of its development cycle
only recently have I started using modular libs
lul, wants to use FX, you must vote to use dis command, me just make my own bot den kek
userId or userID?
none. just finding things that help me procrastinate
USERID is better
uSeRiD
Mmmm what should I use to make my api 
should I just stick with the basic express or hmm
what happened to coding in go 
I am probably just going to use ts and then microservice things or smth
I am not too confident with go as I am ts
do you have something against go?
ok, so i tried to console.log before rest.put() and it loogs --- Test --- and then close...
Do you get an error?
@fathom sonnet console log the commands
here we go
You tried removing the map which you are using to convert the data to json?
Like it does not show the slash commands na
yea there is no slash commands at all
Clientid is right?
Try removing the guildid to make it a global thing
Maybe you dont have perm in guid to add slash
But it should give error
Yea it is, alright gonna try that later
yea...removing guildID dosent nothing
mood
ok, i donwgraded node to 16.15 and now i getting errors again...tnx God
ok here is error
now...
...i was using my clientid instead of aplication id
ok ok... now i have this:
DiscordAPIError[50035]: Invalid Form Body
guild_id[NUMBER_TYPE_COERCE]: Value "undefined" is not snowflake.
at SequentialHandler.runRequest (C:\Users\emanu\Desktop\boolean BOT (recode)\node_modules\@discordjs\rest\dist\index.js:708:15)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async SequentialHandler.queueRequest (C:\Users\emanu\Desktop\boolean BOT (recode)\node_modules\@discordjs\rest\dist\index.js:511:14) {
rawError: {
code: 50035,
errors: { guild_id: [Object] },
message: 'Invalid Form Body'
},
code: 50035,
status: 400,
method: 'put',
url: 'https://discord.com/api/v9/applications/967483641393455104/guilds/undefined/commands',
requestBody: {
files: undefined,
json: [
[SlashCommandBuilder],
[SlashCommandBuilder],
[SlashCommandBuilder]
]
}
}
ok...
what next 
If you removed the toJSON thing try adding that again
Yep i tougjt that could be solve issue
Did it?
wait I forgot about the discordpy shit: Is there no python-based discord library that actively has the interactions stuff?
because the ones I'm finding are either abandoned or not maintained
I stumbled upon https://github.com/kiki7000/discord.py-components, though that one is archived, which makes it seem like development has stopped
welp, guess I know why
kinda not comfortable using the library from that dev mentioned there, so welp back to java
Still didnt try bxz im not at home
open but closed


but yeah, basically kills off my plans for doing this one private bot in python 
will discord.py be somewhat continued by someone else in the future or is it entirely dead
Ded
d.py was revived by Danny
^
honestly not getting the vibes of that when I'm not seeing anything referring to interactions or components on the docs
Try and if it dont work try consoling the clientId and guildId
like I am seeing changes on their repo, though not sure why only minor changes and not interaction stuff when discord gave a deadline about the message content intent
nevermind it is in there
and nevermind again, literally latest version is 1.7.3 which doesnt have it
istg
still same...
error occure after "test" si logged to console
Do console.log(clientId)
The url
guilds/undefined/commands
Ur trying to publish slash cmds to a non existing guild
You should be posting to global commands route, not guilds route
ah ye ik
habbits
Anyone know what this error?
What?
'cannont read properties of roles'
I can get your bot's token from just the client ID!!! See, the first part of the token is OTY3NDgzNjQxMzkzNDU1MTA0
Hackerman

Didnt set any role
The kt just have a addrole global command
That only thing of roles
at Object.module.exports.run (/home/runner/All-in-one-bot-with-SlashCommands/src/events/messageCreate.js:43:24)
Have mqny error
That doesn't help much
and its not working...
I just wanted to check if you had a valid client id and you can put that guildId thing i just asked you to remove it cause your code was not even giving any errors before
Paste the error, not a print of it
yea that was due to node
i downgraded to 16.15
Yup
Cant copy from repl.it
i was using 18.0
It do t allow
Reading stacktrace on mobile is hard enough, reading a stacktrace on mobile as a print of YOUR mobile is even worse
Just wanted to know if that is even running, so yea you can add the guildid thing and check if more errors
Are u sure u can't copy?
Show messageCreate line 43
Oh my
if (message.member.roles.cache.highest.position >message.guild.member.roles.cache.highest.position) return;
if (check) {
if (array.some((word) => message.content.toLowerCase().includes(word))) {
message.delete();
The if is at line 43
But well, message.member.roles is undefined
That or message.guild.member.roles
I bet on the second
Not all messages are sent in guilds
Wdym
message.guild.member isn't a GuildMember is it
I cant close the bot dm
Ah that too
idk
If i closed bot dms it will work?
That's not the issue, it's what papi pointed
if you want to check highest bot role, check message.guild.me.roles.highest.position
message.guild.member is not valid code
I replace with?
Collection<string, Role>.highest isn't a property as well
Ig dont use replit if you dont have there premium tho, peeps can search that url in ss and can see your token tho
Ok but can you check odes before
I don't think you understand my advice or totally forgot the context in which I posted that in. You might want to read it again and then your own code
This error
Wasnt showing before
It suddenly appeared
And every ckmmand was working
Everything else was probably broken or that command never ran or got to that point
You should also be checking that
what do you mean you can't
message.author is who created the message
message.guild is either a Guild or null depending on if the message was sent in a guild or not
Can i send my codes?
For what purpose
Using Discord.js, how can I acknowledge a button click without replying to it?
deferUpdate
message.guild.member.roles.cache.highest.position
to
message.guild.me.roles.highest.position
Ok. That should be it
yeah
I thi k will not work z it have sometng different see my code
Well. Try it and see
Ok
also, for guild only commands you should be checking if (!message.guild) return or something like that
Nothing working
ok. What's the error
I don't know how you manage to code on phone with replit lol
looks like you are using .roles on null
hmm, I could install other package but not enmap and better-sqlite3
?
Like, if you are using the .env or .config it will show
Replit no longer uses .env, it uses a separate config menu
Question (JavaScript): I have multiple objects that all relatively look the same, but some have a chain of objects in them, see examples
Normal object:
{
"type":{
"kind":"SCALAR",
"name":"String",
"ofType":null
},
Abnormal object:
{
"type":{
"kind":"LIST",
"name":null,
"ofType":{
"kind":"NON_NULL",
"name":null,
"ofType":{
"kind":"SCALAR",
"name":"Int",
"ofType":null
}
}
}
}
I need to get the name of the object, but in the abnormal objects its at a lower level. How can I go about grabbing the name of objects without having to check how many levels down it is?
Sorry if the question is a little weirdly typed out, deffo ask me for clarifications if needed
Is it possible to fetch an interaction by its ID? I'm using discord-modals (not asking for help with this, just giving context) and on the modalSubmit event it returns the interaction ID but not the message object.
I don't think modals are linked to messages, are they?
True
I'm trying to make it so when a button is clicked, it shows the modal, then when submitted it will edit the embed in the original message with the button
you could store the message id when someone press the button, and use it to edit the message later on
when (button is clicked) {
store messageId
show modal
when (modal is finished) {
message = get(messageId)
edit message
}
}
just example code in whatever lang that'd be
i'm now thinking of storing a unique id for the button, then looking up in the db for the message etc
actually
i can store a custom ID for the modal, i could set the message id as that and not even have a db involved

sure
yep that worked 
atta boy
hello developers
hello developers
let w1 = 3
let w2 = 1
let w3 = 2
how do i sort these variables from the smallest to the largest but still keep track of it
for example i could make it an array but it would just sort the numbers thus i wouldn't be able to keep track of which var it is
AKA objects
idk if js has it, but you could try to implement something akin to java's LinkedHashMap
which is a map but can be sorted
let workers = [
{
"workerName": "Grainger",
"shift": 3
},
{
"workerName": "GRRRRRRRRRRRRRRRRRR",
"shift": 1
},
{
"worker": "Idk",
"shift": 2
}
]
workers.sort((a, b) => parseFloat(a.shift) - parseFloat(b.shift));
worked
: )
Why are you calling parseFloat() on a number
I believe sort works even for numeric strings as long as it's below 10
then it starts acting sussy baka
what would i have to use then
There's no limit (except for the array element limit which is way too many that you wouldn't even reach it unless done purposefully)
+a.shift \😄
hm?
Just use a.shift, no parsing or casting required
- forces a string to be cast to number
yeah i did remove the parsing
I was talking abt numeric strings
Yeah you can cast numeric strings to numbers using the unary plus operator, although I'd recommend using parseInt() (or parseFloat() depending on the case) since they're more verbose and readable rather than syntactic sugar which can be unreadable to others who are unaware of what unary operators do
i prefer using Number(str) depending on the situation
{
"workerName": "Grainger",
"shift": 3,
"daysOff": [6,9]
},
i am working on a automatic shift manager
but its kinda funny that nobody uses String(n)
is the array on the daysOff ok?
Yeah
what i am trying to do is get all the requirements a certain worker want for example he has to go somewhere without ruining other workers days
Btw you don't need the quotation around the object keys unless you're in a JSON file
Usually parseInt() is faster than the global Number constructor, although you may have a specific case
usually my tests say otherwise, but could be depending on the situation
because parseInt does a lot more than simply translating the type
Yeah, depending on the case either way
My previous tests showed that parseInt() is faster, although that's probably changed now
it is impossible to use Replit specifically by android
replica
wow
smh
C:\Users\dyeaa\Documents\github\misty\strife\src\index.ts:23
console.log(await message.send('972334766399582218', 'Hello World'));
^
TypeError: message.send is not a function
import { BaseClient } from '../../BaseClient';
import { RESTPostAPIChannelMessageJSONBody } from 'discord-api-types/v9';
export class Message {
public client: BaseClient;
public id: string;
public content: string;
constructor() {}
async send(channelId: string, content: RESTPostAPIChannelMessageJSONBody | string) {
return await this.client.rest.createMessage(channelId, content);
}
}
public async createMessage(
channelId: string,
content: RESTPostAPIChannelMessageJSONBody | string,
): Promise<RESTPostAPIChannelMessageResult> {
const { body } = await request(Api.CREATE_MESSAGE.replace(':channelId', channelId), {
body: JSON.stringify(content),
headers: {
'Content-Type': 'application/json',
Authorization: `Bot ${this.client.token}`,
},
method: 'POST',
});
return body.json();
}
Have you checked if message is an instance of your Message class?
Although I assume that would already be checked since you're using TypeScript
For some reason it is not
Have you initialized a new instance of the class or just calling it right on the class like a static method?
import Message from '...';
// Instance
const message = new Message(...);
await message.send(...); // Ok
await Message.send(...); // TypeError Message.send is not a function
// As `send()` is a prototype method in your case and not a static method
So I think I found the place where I want to manage what the data is typed as right
this.manager.client.emit(GatewayEvents[data.t], data.d); so I have this right here that will emit any event if it is found in the GatewayEvents object, but the data doesn't necessarily correspond with the event being emitted it is just 'any'
Also no I have not done this
you are emitting the raw discord data
Yea, I am thinking here is where I wanna set what the data could be based on the event being emitted
you want to type the raw data or convert it into one of your classes?
I am thinking I should convert it so I can have the send method
What is the difference between converting and just type casting it?
like add types to the raw discord data
so you can have intellisense on message.content for example
basically what discord-api-types does
Ah, whatever makes it easier. I just wanna make sure my methods will also be attached to the data or whatever so I can like send and such
you need to convert it to your class then
like new Message(data.d)
and then attach all the data from data.d into your class
Mmmm I see
Okay so that works, now I just need to figure out how to do that based on the event being triggered
I guess I can do a case for every event possible but that seems tedious no?
So I did it in a really stupid way but it works :^)
you will need to do it for every single event type yes
Hey y'all! Working on my first Discord bot in Python and I'm having issues with something. I'm part of a server where it's become a meme to ban and unban me at random, and it's a good inside joke for the moderators and I. I'm looking to expand the functionality and make it a bit of a game. So I'd like a bot that when it hears ?Fuzzy it randomly sees if I'm getting banned. The issue is that it seems like I'm required to pass a username to the ban command, when I'd really just like to always make it me without having to pass a name as an argument. I've tried messing around with it for a few hours now but I'm coming up with nothing. Here's my latest attempt:
`bot = commands.Bot(command_prefix='?', case_insensitive=True )
@bot.event
async def on_ready():
print(f'{bot.user.name} has connected to Discord!')
@bot.command(name='Fuzzy')
@commands.has_any_role('Senior Admin', 'Admin', 'Moderator')
async def fuzzy_ban(ctx, member:discord.User=name):
#await ctx.send("Yo it's working")
await ctx.send("Banning Spark, probably")
await member.ban()
await member.unban()`
The name variable is currently set to a buddy of mine's Discord name for testing purposes in a server with just us.
Current error I get on running and trying the command is:
await member.ban() AttributeError: 'NoneType' object has no attribute 'ban'
Any ideas?
I'm just trying to get the ban working, then I'll work on the randomness of it - which should be relatively easy
I'm sure I'm missing some easy solution to this
Would there be a reason why my lib is sending the message twice? I have it set so if the message received in the message create event author is a bot it won't respond with the Hello World message but for some reason after I made a change to the websocket shard class it now responds twice
the event is probably being emitted twice
Okay so ignore this literally just found the issue :^)
Yea turns out I wasn't returning after emitting in the switch/case so the default was running as well
lol
@quartz kindle i need a break from low level 💀
I should do what this guy is doing and make a discord lib
lmao
one with a specific aim
i see people mostly focus on performance/efficiency but i usually see it comes at a massive cost
(e.g. simplicity)
make the slowest possible discord library
and make it use the maximum ram possible
i cant it goes against my morals
xD
ive ran into another one of those "undebuggable" bugs in my os
become a maintainer at tiny-discord
interesting
i do really like your storing objects in a buffer concept so
have you measured metrics to see how it performs?
im still finishing my binary serializer, i keep reworking parts of it over and over again
generally, serialization/deserialization is faster than json
but storing them in a buffer is a whole other story
my buffer storage project is currently shelved
i imagine it will be much slower than native objects/maps
it is quite simple, all you need to do is fetch your guild user profile by ID and ban that instead of using parameters
ctx.guild.get_member(your_user_id) i believe is the syntax, then you can call things on it like .ban()
are you storing them in a struct like format?
the serialized object or the buffer storage?
uh
like, the serializer is just for converting an object to a buffer
storing multiple buffers in a map-like buffer structure is a separate project
So I just tried that after some more Google Fu and I get back: "discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'ban'"
With the block now being:
async def fuzzy_ban(ctx): member = ctx.guild.get_member(<ID>) await ctx.send("Banning Spark, probably") await member.ban() await member.unban()
im talking on whether you store the objects in the buffer as a "string" or a "struct" (aka all in a linear buffer)
can you print the value of member? are you sure you are using the correct ID? also are you using the members intent if you know what that is? if not you should use await ctx.guild.fetch_member(ID) instead
interesting way of parsing it
Prints "None". I even just tried member = ctx.guild.get_member_named('<TheirName>') and still prints "None"
what if the number is above 255? does it use more bytes?
yes, all data types are prefixed with a type byte that tells what kind of data follows it
the number of bytes in a given number is also included in the type byte
numbers from -32 to 64 can be represented in the type byte itself
the rest of the numbers require more bytes
basically its exactly the same as MessagePack does
but MessagePack only gives you stuff like uint8, uint16, uint32
mine always uses the exact number of bytes a number needs, never more
if a number is 24bit long, then it will use 3 bytes, not 4 as if it were int32
i can imagine that gets really complicated quickly
have you considered making a node gyp type plugin
lmao
lower level languages deal with lower level objects much better and easily
at the cost of the object conversion between js and assembly of course
its not worth it
honestly i'd just make ints 4 bytes for everything and call it a day
i'll help out with the discord lib for sure but for your parsing lib i think i have to pass because i may lose my remaining sanity
lmao
I see the ACPI specification flashing before me during sleep
hey tim, quick question
most of the hard work is already done, i mean dont even get me started on string compression and char mapping
_write5(data, start) {
let temp = 0;
let bits = 0;
let end = start;
for(let i = 0; i < data.length; i++) {
let c = data.charCodeAt(i);
let small = false;
if(c > 96 && c < 123) {
c -= 97;
small = true;
} else if(c === 32) {
c = 26;
small = true;
} else if(c === 45) {
c = 27;
small = true;
} else if(c === 95) {
c = 28;
small = true;
}
if(small) {
temp <<= 5;
temp += c;
bits += 5;
} else if(c < 256) {
temp <<= 5;
temp += 30;
temp <<= 8;
temp += c;
bits += 13;
} else {
temp <<= 5;
temp += 31;
temp <<= 16;
temp += c;
bits += 21;
}
while(bits >= 8) {
bits -= 8;
this._buffer[end++] = temp >> bits;
temp &= (1 << bits) - 1;
}
}
if(bits) {
this._buffer[end++] = temp << (8 - bits);
}
return end - start;
}
lmao
let's say I have an array of 5 ints that won't go above 100 (guaranteed)
is it more efficient to pack them into spaces of 1 byte for each inside an integer or use actual arrays?
my bot never told me my token
and i cant reset it because it asks a code
i never set up 2FA for my bot
integer by an order of magnitude
like, very much?
an integer will cost you 8 bytes if stored as a double, plus whatever overhead the lang has
an array will cost basically 5x that minimum, plus the array overhead which is much larger than the number overhead
you should contrib to my discord lib more like 
does anyone knos
ic
github? (if its public)
the only issue is that if you're using js, you cant do bitwise on 5 byte numbers natively
It is public yea
nah, java
although there are workarounds for that
should be fine then
also im pretty sure doing 2 bitwise operations is gonna be 100x faster than an array lookup
where 
bitwise operations usually take under 1 clock cycle
https://github.com/MistyyBoi/strife on my personal account rn but will later switch to its own org if it gets popular enough
wait
memory reads take around 50-70 assuming no cache
I'm asking bcuz my tcg has dodge/block chance for all cards, which can be influenced by other cards in the game
can operations take half a cycle?
my bot never told me my token
and i cant reset it because it asks a code
i never set up 2FA for my bot
yeah you can do multiple things in one cycle
im dyin
the array is of fixed size of 6 entries
???
1 for effects + 5 for each slot index
Turns out it was my intents
Thanks for pointing me in the right direction!
and currently I use arrays, but ik they aren't the most efficient I could get
yeah you can fit that into a 6 byte number
6 byte numbers sound so illegal
ah
if you need more than 8 bytes you can always use bigint, does java have bigints?
and i cant get it
long
why did they change it
I first read 6 bit and was like, HOW
this sucks
after long there's BigInteger, which is as big as your ram allows
yeah, biginteger can do bitwise operations as well
you can store data there
but its probably much slower
bruh
your bot token is in your discord developers application
what tf do i do
where?
im under bot
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
it says reset token
yes
Click it
you cant copy the token anymore
yes, click reset token, and you get a new one
no but that doesnt even work
i dont have 2fa for my bot
but it says i do
what do you mean that doesn't even work
is your account 2fa enabled?
ya
that's the code
but where
your bot = your 2fa
you forgot your 2fa?
holup
the code you use to login
how am i supposed to remember that
you arent
that same code
i use my phone number
where do you get it
except the ones u got as backup codes
when you login into discord, how do you login? doesnt it ask you for 2fa to login as well?
holup
that's when it clicked
i just use my phone
well...nvm
btw speedy if you ever do contribute ty in advance <3
mov eax, [bot]
mov ecx, [server]
add eax, ecx
perhaps
i saw a lot of things you may want to improve early tho
like making a central handler for http requests
Mmmm, yea that makes a lot of sense. I just have been mainly focused on actually getting this to work and honestly I am shocked I have not run into issues yet regarding errors from the discord gateway and shit
Also, can you go more into depth on what you mean with this? I think I have a general concept of what you mean but I am also not entirely sure if we are thinking the same thing when you say 'central handler'
i mean a function that will handle all and future requests, simplifying your api requests a lot
for example it will handle rate limits for you
and it will pre-fill all mandatory data like tokens
Ah yea, that makes sense I thought you meant an entire separate class or smth
so instead of doing request({method: "POST", ...}) you can make something like
discordAPI.post("/members", { ... });
hey, would the guildmemberupdate event be triggered if a user stops his/hers nitro server boost?
Ah yea, that makes a lot of sense
I am wondering if I should just have the post, get, delete, patch, etc methods in the RestManager class and then utilize those in the Structure classes to do what I need
but idk
sure if you think it'd make your code cleaner
client.on('guildMemberUpdate', (oldMember, newMember) => {
if (oldMember.premiumSince !== newMember.premiumSince) {
}
});``` well yeah I found this, pretty sure both member properties will change so it will work for both i guess.
I just don't have nitro so i can't test it. Anyone that knows an alternative to test this out?
how can I get the hex code from that?
color.toString(16)
although that method will require certain corrections
color.toString(16).padStart(6, "0") would be more accurate
What would be the most logical way to cache the channels the client currently has access to without spamming the api/gateway on ready (I am assuming on ready would be the best time to cache them anyways if there is a better way please do tell) Unless caching on GUILD_CREATE would be better?
on ready discord sends you all of the channels and guilds I believe
you then choose whether you want to cache them or not
Mmmm I see
I knew ready sends you the guilds as unavailable I didn't know they sent the channels as well
if you don't cache everything you need to have some kind of fetch function
the channels are included in each GUILD_CREATE
So should I cache the guilds and channels on guild create?
if you need them, yes
that's really up to you but as a kind of required minimum you should cache the guilds
its something that should be customizable
It will be customizable
always good to have a local copy of the guilds
but by default it will cache the guilds & channels
sure
what is the difference between icon and icon_hash in the discord docs?
both say they return a hash
I would assume that at least a role gets changed, since boosting a server gives you a nitro role that cannot be taken away I believe
Nevermind
Does not guarantee a role change
ah ok
@split hazelimagine making a json format that supports bigints of up to 2gb length
isnt that what floating point types are for tho
to some extent of precision
since they support exponents
(or have I misunderstood something about how floating points work)
thats what bigints are for, when you need more precision
ah
doubles only give you 53 bits of precision
bigint has arbitrary/infinite precision
a ~2mb bigint has 7 million digits in it
imagine a 2gb bigint
exdee
has anyone used sveltekit? how would i refactor the {#each loop into a function?
you could put it into a separate component and import the component
or you could make a js function that outputs html string and call the function in there
but idk i havent used svelte yet
mmkay, i'll try putting in a different component. i dont think sveltekit lets functions return components
you can do {@html yourvarhere}
and it lets you insert raw html
so you can do any html string building in pure js instead of svelte loops
case GatewayDispatchEvents.GuildCreate: {
if(this.manager.client.options.cacheEnabled && this.manager.client.options.cache.guild) {
this.manager.client.guilds.set(data.d.id, new Guild(this.manager.client, data.d))
for(const channel of data.d.channels){
this.manager.client.channels.set(channel.id, channel)
}
}
this.manager.client.emit(GatewayEvents[data.t]);
}
Alright so I am going to go out on a limb and say this is not the most efficient way to do it right? Though with my knowledge this is the only way I see to do it
do you want your Guild class to be available only if cached?
Well yea, cause I want guilds, channels, roles to always be cached unless they say they don't want it to
yeah but i mean
if cache is enabled, client.on("guildCreate") gives you a Guild object
if cache is disabled, then client.on("guildCreate") gives you a raw discord guild?
without any of your Guild class methods?
Mmm, yea I don't think that is right
Even when not cached it should still have the guild class methods
case GatewayDispatchEvents.GuildCreate: {
const guild = new Guild(this.manager.client, data.d);
if(this.manager.client.options.cacheEnabled) {
if(this.manager.client.options.cache.guild) {
this.manager.client.guilds.set(guild.id, guild);
}
if(this.manager.client.options.cache.channels) {
for(const channel of guild.channels.values()){ // assuming the Guild class also processes channels
this.manager.client.channels.set(channel.id, channel)
}
}
}
this.manager.client.emit(GatewayEvents[data.t], guild);
}
yea I was planning on processing channels with the guild class but wasn't entirely sure on how i should do that
import Channel from "./Channel.js"
class Guild {
constructor(client, data) {
if(client.options.cache.channels) {
this.channels = new Map();
for(const rawChannel of data.channels) {
const channel = new Channel(client, rawChannel);
this.channels.set(channel.id, channel);
}
}
}
}
Alright thanks :)
That was very helpful I didn't think it would be that easy to do that
I give up doing that 1 hour after starting a project, after that I just remigratre my project to vsc lol
whatever createMessageComponentCollector is being used on is undefined
DiscordAPIError: Invalid Form Body
components[1].components[0].options[1].emoji.id: Invalid emoji
at RequestHandler.execute (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:350:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:51:14)
at async TextChannel.send (/home/container/node_modules/discord.js/src/structures/interfaces/TextBasedChannel.js:175:15)
at async Object.execute (/home/container/commands/info/help.js:207:23) {
method: 'post',
path: '/channels/960462723836170271/messages',
code: 50035,
httpStatus: 400,
requestData: {
json: {
content: undefined,
tts: false,
nonce: undefined,
embeds: [Array],
components: [Array],
username: undefined,
avatar_url: undefined,
allowed_mentions: [Object],
flags: 0,
message_reference: [Object],
attachments: undefined,
sticker_ids: undefined
},
files: []
}
}
TypeError: Cannot read properties of undefined (reading 'createMessageComponentCollector')
at Object.execute (/home/container/commands/info/help.js:215:35)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
Show code
which folder
Tho it seems like you are sending something incorrectly thus it becomes undefined to where createMessageComponentCollector is not going to work
the message content can never be undefined, but null if you send an embed
invalid emoji
(... or component)
at (.../commands/info/help.js:215:35)
once tested djs v14 and it's pissing me off instantly
wtf it doesn't even wanna receive any event
strife > djs /s
at least guild messages and direct messages are set as intents (4608) but I'm not able to receive any of it
just the ready event, nothing else anymore
djs fucking stuff up?
idk regarding the debug log, the gateway connection is ok
Well I am not having any troubles receiving those events so it def isn't a gateway issue, so it is likely djs just fucking their code up
DEBUG [WS => Manager] Spawning shards: 0
DEBUG [WS => Shard 0] [CONNECT]
Gateway : wss://gateway.discord.gg/
Version : 10
Encoding : json
Compression: none
DEBUG [WS => Shard 0] Setting a HELLO timeout for 20s.
DEBUG [WS => Shard 0] [CONNECTED] Took 221ms
DEBUG [WS => Shard 0] Clearing the HELLO timeout.
DEBUG [WS => Shard 0] Setting a heartbeat interval for 41250ms.
DEBUG [WS => Shard 0] [IDENTIFY] Shard 0/1 with intents: 4608
DEBUG [WS => Shard 0] [READY] Session 40401f6fe1a7f38c0a7db7b03edc1391.
DEBUG [WS => Shard 0] [ReadyHeartbeat] Sending a heartbeat.
DEBUG [WS => Shard 0] Shard will not receive any more guild packets.
Unavailable guild count: 1
NOTICE Logged in as Test app#7080
Weird
while Logged in as ... being logged within the ready event
no message create event, nothing
and you have the guild messages intent right?
I don't the intents calculation for that :p
which is GUILD_MESSAGES and DIRECT_MESSAGES
{
Guilds: 1,
GuildMembers: 2,
GuildBans: 4,
GuildEmojisAndStickers: 8,
GuildIntegrations: 16,
GuildWebhooks: 32,
GuildInvites: 64,
GuildVoiceStates: 128,
GuildPresences: 256,
GuildMessages: 512,
GuildMessageReactions: 1024,
GuildMessageTyping: 2048,
DirectMessages: 4096,
DirectMessageReactions: 8192,
DirectMessageTyping: 16384,
MessageContent: 32768,
GuildScheduledEvents: 65536
}
yea
Mmm, maybe they are changing some stuff around and haven't fully implemented it?
doesn't matter, i should still receive the message_create event
even without content
but I'm not gonna get anything except ready wtf
even reinviting and deleting the app didn't work
mmm
which means it has to be djs, or not?!
I'm not sure how I could init the client wrongly
Well it doesn't seem to be a gateway issue as far as I can tell I just tested it with my lib, so it is very likely a djs problem or smth they haven't documented that is required to be done before it works (which I would 100% believe as it has happened before)
Didn't they change the message event to something else in some version
you mean message to messageCreate?
yea that was v13
you need guilds intent
i'm pretty sure it's required to receive guild messages now for discord.js, since it heavily relies on caching
Also tried that before with all intents, no success
client.on('message', message =>
{
read = message.content;
output = `${prefix}${read}`;
message.channel.send(output);
})```
this starts an infinite loop, how to stop it after 1st execution?
Also direct messages don’t need guild intents
i didn't say direct messages
He wasnt receiving any events tho
other than ready
well that's odd
It is indeed
DiscordAPIError: Invalid Form Body
components[1].components[0].options[1].emoji.id: Invalid emoji
at RequestHandler.execute (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:350:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:51:14)
at async TextChannel.send (/home/container/node_modules/discord.js/src/structures/interfaces/TextBasedChannel.js:175:15)
at async Object.execute (/home/container/commands/info/help.js:207:23) {
method: 'post',
path: '/channels/960462723836170271/messages',
code: 50035,
httpStatus: 400,
requestData: {
json: {
content: undefined,
tts: false,
nonce: undefined,
embeds: [Array],
components: [Array],
username: undefined,
avatar_url: undefined,
allowed_mentions: [Object],
flags: 0,
message_reference: [Object],
attachments: undefined,
sticker_ids: undefined
},
files: []
}
}
TypeError: Cannot read properties of undefined (reading 'createMessageComponentCollector')
at Object.execute (/home/container/commands/info/help.js:215:35)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
well you can make a variable to store the times it has executed and stop after the first one but idk if you wanna do that
help command is not working
We tried helping and you never responded
it says whats wrong...
what is helpmsg
it was working before
ok cool not what I asked
btw can i get the id of message sender?
hmm, i think it should work like this, right?
var sender = message.author;
read = message.content;
output = `${prefix}${read}`;
message.channel.send(output);
message.channel.send(sender);
if i want to print author id
try it and see
author is an object
thx, found a way to get author id and hence a way to stop repeating executions
Okay so it does seem to be a gateway issue, I just relaunched my test bot with the v10 gateway and it was only receiving the ready event.
I then swapped back to v9 and it works fine
C:\Users\dyeaa\Documents\github\misty\strife\src\client\rest\structures\Guild.ts:16
for (const rawChannel of data.channels.values()) {
^
TypeError: Cannot read properties of undefined (reading 'values')
Alright so for some reason this is starting to act up now. I don't see why data.channels is undefined when in the scope of the if statement
import { BaseClient } from '../../BaseClient';
import { GuildData } from '../../../util';
import { BaseStore } from '../../../stores';
import { Channel } from './Channel';
export class Guild {
public client: BaseClient;
public channels = new BaseStore<string, Channel>();
public id: string;
constructor(client: BaseClient, data: GuildData) {
this.id = data.id;
this.client = client;
if (client.options.cache.channels) {
console.log(data.channels);
for (const rawChannel of data.channels.values()) {
const channel = new Channel(client, rawChannel);
this.channels.set(channel.id, channel);
}
}
}
}
But outside of it, there is no issue
SHARD_LIST what's the replacement for this in djs 13
scrapping some old code for future use
Weird… I don’t see why
Discord probably fucked up on their side
v10 is still experimental iirc to be fair
Probably but I wonder if I’m the only one noticing
And discord didn’t fix it yet
I mean people are supposed to develop stuff to move to v10
Mmm, maybe or again it could be something we don't know about yet and there is a weird requirement
Yeah I thought about that, too first but then a working gateway connection only receiving the ready event wouldn’t make sense, too
true
I am trying to find the easiest way to set the guild for the channel and everything i've tried so far doesn't seem to be working/logical when looking at it from the standpoint of the channel must belong to the guild it represents.
I was thinking of just setting the guild based on passing a guild to the channel's constructor when creating a new channel class instance but that wouldn't work for when I am setting the channel cache in the different channel events
components[1].components[0].options[1].emoji.id: Invalid emoji
at RequestHandler.execute (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:350:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:51:14)
at async TextChannel.send (/home/container/node_modules/discord.js/src/structures/interfaces/TextBasedChannel.js:175:15)
at async Object.execute (/home/container/commands/info/help.js:207:23) {
method: 'post',
path: '/channels/960462723836170271/messages',
code: 50035,
httpStatus: 400,
requestData: {
json: {
content: undefined,
tts: false,
nonce: undefined,
embeds: [Array],
components: [Array],
username: undefined,
avatar_url: undefined,
allowed_mentions: [Object],
flags: 0,
message_reference: [Object],
attachments: undefined,
sticker_ids: undefined
},
files: []
}
}
TypeError: Cannot read properties of undefined (reading 'createMessageComponentCollector')
at Object.execute (/home/container/commands/info/help.js:215:35)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
Show code alongside it please
do you all make a constructor with default values then define them later? or make a constructer with actual parameters then just do something like this.x = x;?
Depends on the use case
Most of the time I find myself just using params tho and giving them values as I need em
why does the {} brackets indentation pains me 💀
Looks like what you'd do in C# always line breaking the brackets
fr
should I use function foo({x, y}) {} or function foo(obj) {}? I believe they act the same
Why do that in the first place?
Unless you are going to use the object for something then there is no need for foo({x,y})
Unless I am unaware of the benefits of doing so
do what?
It just does the same, the only difference is that you would have to access the x and y as obj.x , obj.y on the second method. While on the first, you can directly access the x and y since they are already destructured
i dunno.. do i want to access x and y directly or not?
I mean... that depends on you?
which is more commonly used?
milk privileges denied
Lets keep the chat related to it's topic, and also SFW :D
@quartz kindle you might know about this - I wonder if you can make a mail server in node?
like a proper server that receives emails
i dont see why not
but i know nothing about email, its an old ass weird ass protocol that nobody understands
i dont either
it is a weird protocol
just like ACPI and USB
too bad the whole world uses it and transitioning to something new could be difficult
there are plenty of smtp libs for node
yeah but thats for sending
what about receiving
unless it does both
idk email is so confusing
it does both but doesnt have any storage, just emits an event
you need to combine it with an imap server
and some kind of storage
what is imap for
i see so it just emits and receives
can you just skip an imap server and use your own database
it wont be accessible from external clients anyways only from a dashboard
possibly yes
imap is for accepting third party clients like thunderbird to sync with your server
also take a look a this (although its old af) https://github.com/Flolagale/mailin

