#development
1 messages ยท Page 2030 of 1
see? everything i said holds true
you were doing the wrong thing all this time
and refusing to show us
How da heck do I make a ready event request thingy
just log the websocket output
I am but not getting anything back
you will receive more stuff as soon as you send the identify
I sent the indentify but I get nothing back after
ws.on('message', (message) => {
const data = JSON.parse(message.toString())
console.log(data)
switch (data.op){
case GatewayOpcodes.Hello:
const heartbeat_interval = data.d.heartbeat_interval;
ws.send(JSON.stringify({
op: GatewayOpcodes.Heartbeat,
d: heartbeat_interval
}))
break;
case GatewayOpcodes.HeartbeatAck:
console.log(data)
break;
case GatewayOpcodes.Identify:
ws.send(JSON.stringify({
op: GatewayOpcodes.Identify,
d: {
token: 'discord yelled at me not to send it',
intents: 513,
properties: {
"$os": "win32",
"$browser": "strife",
"$device": "strife"
}
}
}))
break;
}
})
they dont send you identify
you have to send them
this is what they send you
those are the things you make a case for
everything else its you that has to send
I see, so I assume i would send the indentify when they acknowledge my heartbeat right?
you can send an identify right after you receive the hello
also your heartbeating is wrong
oh?
anyway got any other solutions?
in the d key you have to send the sequence number, not the interval
i did what u asked me to do
everything you receive after hello, will have a sequence number here
the first heartbeat you can send d: null, but every heartbeat after that, you have to send the sequence number of the last packet you received
and the heartbeat_interval you use to create a setInterval to send a heartbeat every x time
ah
setInterval(() => {
ws.send(JSON.stringify({
op: GatewayOpcodes.Heartbeat,
d: data.s
}))
}, data.d.heartbeat_interval)
so it would essentially be this?
you showed this but didnt show what this printed
basically yes, but you have to store data.s somewhere
for example js if(data.s > sequence) { sequence = data.s; } then ```js
d: sequence
๐
and store sequence somewhere
Could I use a map or something similar then?
or would it not matter just putting it in a variable
doesnt really matter where you store it
ok i'm thinking of using javascript
if later on you make it into a class, you will store it in the class somewhere
can one use csv with javascript?
like this.sequence
sure
ok
Yea I plan on using classes I am just trying to get a basic understanding of the gateway right now :^)
good choice
recommend it for me?
My issue later on though will be how I wanna structure the package when I actually start going for it
like best programming language for discord bots?
most devs here are js devs, so we will recommend js.
there is no "best" language
its probably best to not ask this community alone, but multiple communities, or do your own research
wrong
no, both will fuck you up so its twice the fun
anything but python is the best language
ok but it's like a sea i mean i'd need a lot to do anything with it
what lang do u know?
let me guess, nada?
i made a dumb bot with js before but i had to torture some one for it and he almost dioed
so i decided to try python
lord almighty
so... you decided to learn bot dev before learning the language?
lol
my general reccomendation is do 2-5 small other projects and maybe 1-2 big projects with a language before bot development
i work at a leather company i usually erase my memory every once or twice a month so i lose some knowledge of whatev language i know
start with a calculator that has every answer hardcoded
o
A bot was how I learned to code. Was a pain in the ass, but I turned out okay. Didn't really bother with basic language issues either so I'm kinda proud
my favorite project!
i know C C++ and python but my memory is like RAM
wwhat
x doubt
then i deleted them because i hosted them in an indian website
done that
i'm good at programming i just have to store my memory every where and explain to me what i stored because after i sleep i lose some memory of what i've done

programming isn't about memory
-_-
programming is about knowing how to use your tools to solve complex problems
which I don't ^
90% problem solving, 5% IDE suggestions, 105% stackoverflow, 5% memorizing syntax
(we're not good at math)
i rather ask the humans
google is very pog
i don't always use google
@quartz kindle I have question
but i do tho
google should be your first resource when you have a question
If I am sending an indentify every heartbeat ack will that fuck shit up?
when your question becomes too obscure or complex to ask google, that's when you ask other people
i believe reaching 1000 identifies in a day resets the token
so probably
I don't think that is entirely true here
use mr.potato-milk's calculator to help you 
Actually nvm ye you right
anyway thnx for your trying to help i'll find me another apprach to it
by the way, I'm working on a framework in Java for making CLI commands quickly and reliably, how does this look? ```java
@TextCommand(
name = "test"
)
public class TestCommand extends BaseCommand implements DisposableArguments {
static class TestCommandArgs {
public String name;
public int age;
}
private TestCommandArgs parsedArgs = new TestCommandArgs();
public TestCommand() {
super("test");
}
@Override
public void run(String[] args) throws CommandException {
parseArgs(args);
System.out.println(
"You used the "
+ getName()
+ " command. Your name is "
+ parsedArgs.name
+ ". Your age is "
+ parsedArgs.age
+ ".");
}
@Override
public String getDescription() {
return "A test command.";
}
private void parseArgs(String[] args) throws CommandException {
args = CommandUtils.removeEmptyArgs(args);
if(args.length < 2) {
throw new CommandException("Too few arguments provided.");
}
parsedArgs.name = args[0];
if(CommandUtils.tryParseInt(args[1])) {
parsedArgs.age = Integer.parseInt(args[1]);
} else {
throw new CommandException("Second argument must be a valid integer value.");
}
}
@Override
public void disposeArguments() {
this.parsedArgs = new TestCommandArgs();
}
}
absolute ass
you look like absolute ass misty
ok woah
btw if you noticed the -,*,/,+ are the ones needed in a calculator so a smart person would recognize that i was trying to made a bot that is able to do calculations, the code for that is already done i needed to make sure the bot would recognize the operators in a message to understand that the user is trying to make a calculation and thus helpin them(the user) out
but i'll go the hard way for that as usual
dude just use loops then
the hard way always works
for each character in the string, check if it equals one of those operators
you dont need to overcomplicate it if you're having trouble getting it to work
just do it as simply as you can
the way you know how
i wanted something new something less lines of coding
now i have to do it that way
loops... make it so you have less lines...
the old boring way
tim I think I am doing something majorly wrong
you could write a full on recursive descent parser and have more lines of code instead if you'd prefer :^)
giving them too much credit waffle
also less lines does not necessarily mean more performance
there are 4 operators so not very much less lines
Smaller != Better
honestly, I often code with more lines intentionally
enjoy writing if statements when your operators expand into double digits
there's probably hundreds of mathematical operators out there
write more lines now, write less later
much easier
let seq = null;
ws.on('message', (message) => {
const data = JSON.parse(message.toString())
console.log(data)
switch (data.op){
case GatewayOpcodes.Hello:
setInterval(() => {
ws.send(JSON.stringify({
op: GatewayOpcodes.Heartbeat,
d: data.s
}))
}, data.d.heartbeat_interval)
break;
case GatewayOpcodes.HeartbeatAck:
console.log(data)
if(data.s < seq) {
seq = data.s
}
if(seq === null) {
ws.send(JSON.stringify({
op: GatewayOpcodes.Identify,
d: {
token: 'dasd',
intents: 513,
properties: {
"$os": "win32",
"$browser": "strife",
"$device": "strife"
}
}
}))
}
break;
}
})
So I think this is failing to do what I meant it to do. It seems like every heartbeat ack it is sending the indentify (unless discord just ignores any after the initial identify)
i'm not making a bot called fuckery for science students thanks lol
case and point
you know, believe it or not, a lot of people use more than just the 4 most basic operators ๐
yes thats very wrong
unlucky
totally didn't mean to reply to misty
anyway i'll come back to ask how to fetch so good quality pics from REddit subs lol so be prepared for future me :p
some*
fetch some bitches misty
ok one pump chump
Wait what
js is a headache x-x
so are you saying during the Hello I should make the indentify ?
you send the identify right after you receive hello, you dont need to wait for heartbeats
and sequences have to be recorded on every packet
Ah
not acks
you dont really need acks for anything basically
they're just there to confirm your heartbeat was received
also
right also
is there a reason it responds twice with the heartbeat ack?
because you console.log it twice
You said the sequence number would change when receiving the heartbeat ack right?
Does it just increment or is it a random one every time?
it increments on every single packet after hello
because you stop receiving? or did you receive multiple packets with the same sequence (which is not possible)?
Well I am still receiving the heartbeat ack every 41 seconds roughly
so that means it should increment right?
pretty sure acks dont count
Mmm I thought they would
gotcha
did you receive a READY after sending the identify?
Yea
then from there on you should start receiving data
Mmmm there must be some data I am not known about since the seq should be 1 if that was the case right?
I am just seeing the initial heartbeat interval thing and getting back the ready event with a s of 1
and nothing else after that?
so yeah each of those should have an increasing sequence
:)
So how do logins work?
like do you know what djs does with the login method they have?
I assume it is something separate from the indentify or am I wrong?
nah, its just the identify and setting up the sequences/heartbeats/etc
the login method creates a new WebsocketShard instance, if it doesnt exist yet
then the WebsocketShard instance connects to /gateway/bot
then connects to websocket
Mmmm
and identifies
Sounds like a lot
and sets up the sequences and heartbeats to keep alive
as well as all the shit to reconnect/resume/etc
the READY event has an array of guild ids
those guilds are added to the guild cache as unavailable guilds
then it receives a bunch of GUILD_CREATE events
that will fill up the data for the guilds in the cache
after all guilds are accounted for, it emits the client ready event
if you use internal sharding
basically do the same, but with multiple websocket instances
so much words and letter
if you're lazy feel free to steal my websocket code lel
async connect() {
const invalidToken = new Error(WSCodes[4004]);
const {
url: gatewayURL,
shards: recommendedShards,
session_start_limit: sessionStartLimit,
} = await this.client.api.gateway.bot.get().catch(error => {
throw error.httpStatus === 401 ? invalidToken : error;
});
const { total, remaining } = sessionStartLimit;
this.debug(`Fetched Gateway Information
URL: ${gatewayURL}
Recommended Shards: ${recommendedShards}`);
this.debug(`Session Limit Information
Total: ${total}
Remaining: ${remaining}`);
this.gateway = `${gatewayURL}/`;
let { shards } = this.client.options;
if (shards === 'auto') {
this.debug(`Using the recommended shard count provided by Discord: ${recommendedShards}`);
this.totalShards = this.client.options.shardCount = recommendedShards;
shards = this.client.options.shards = Array.from({ length: recommendedShards }, (_, i) => i);
}
this.totalShards = shards.length;
this.debug(`Spawning shards: ${shards.join(', ')}`);
this.shardQueue = new Set(shards.map(id => new WebSocketShard(this, id)));
return this.createShards();
}
so this is what djs does when using the login method
yup
Mmm I don't really wanna model after djs tho
I guess I should start actually developing this library though
Yea I will figure that out as I go
congrats
Well fuck I am stumped on what I should do first when actually making the WebsocketManager
๐
love it when I know what to do but now how i should do it
if you wanna go straight into internal sharding, first step is connect to /gateay/bot
i can't believe i could do it all this time if i didn't just be stupid to try stupid new things
then create multiple websockets
wtf
lol
my shit got deleted
seen that
yea prolly cuz you sent like 100 code in one night
one of them must've been like .-. this dude
nah it is likely cause some bot is noticing a discord link and thinks it is a scam link
uhhh
lemme see
well our scam bot would've kicked you
im not really sure what happened ngl
RIP X'D
It deletes the link when I send it
wait you have a scam bot that auto kicks?
it is just the gateway link
what if i post a scam link as a joke
X'D
well tim this is what I was trying to do at first but realized doing the websocket like this might not work in the long run and will just get annoying
import { EventEmitter } from 'node:events'
import WebSocket = require("ws");
export class WebsocketManager extends EventEmitter {
private sequence = null;
public ws = new WebSocket('gatewaylink/gateway/bot?v=9&encoding=json')
constructor() {
super();
}
async connect() {
}
}
yea we use zerotwo to protect against all of those scam messages
i would initialize ws as null
since you will need to destroy it and recreate it when resuming for example
Mmmm
See I tried looking at your tiny-discord code and it all looked very confusing
:^)
xD
I actually wouldn't recommend trying to make your own gateway implementation and instead just rely on some low level module like cloudstorm or tiny-discord or detritus ws module
Not because I want you to use one of them specifically, but because it's really difficult
but thats kinda why its fun
Kinda yeah
but well, also annoying af
I wanna do it all myself for the learning experience
I wouldn't be making my own discord lib if I didn't wanna learn how the internals work
its fun at the beginning, but then it gets annoying when you're just hunting and patching flaws and edge cases and connection issues
so what is this tim
const req = request({
hostname: this.url,
path: path,
headers: {
"Connection": "Upgrade",
"Upgrade": "websocket",
"Sec-WebSocket-Key": key,
"Sec-WebSocket-Version": "13",
}
});
you seem to make a request to smth
i made my own ws
I see
thats basically part of whe websocket spec
Websockets are just http requests, but the connection isn't destroyed
to verify that the websocket is conforming to the rules
I see
that code is basically useless
because the only target host is discord, and they would never not conform to those rules
Mmmm makes sense
Discord might go under and someone steal their domain
this will basically never fire
but since it only happens once per connection its not really a meaningful performance hit
so i let it be
if you're looking at tiny-discord and using ws you can basically skip those parts
and go straight to _processMessage()
ok so how's everyone doing? :^)
should i say or should i not
๐
ich habe a new error
thats not the full thing, but from the looks of it you got cloudflare banned
wait about 1 hour and try again
go sleep
no
this is not related to my job but i want to do it
for fun
my sanity like the speedy NFT says lol
what have i done?
i feel like y'all escaping me lol
understandable
have a good night
i just added my calculator to the code and got cloudflare banned -_-
Is it possible you got a restart loop?
no but it's possible that god hates me
the only loop i added is the if / elif loop
and that too has an exit
maybe if i make it in a different class method and call it's result by the return in a different function
maybe that's what could be making it loop when a calculation is triggered
can't believe i'm the only one using python in this godforesaken website -_-
no matter what you do, it will not stop erroring until the ban is lifted
what does processFrame do?
basically what ws does for you
I see
the websocket protocol has its own opcodes and stuff
so essentially I would just model after _processMessage?
yup
ok i'm bored now fr braincrush.exe has been executed
i still got the same error like wtf now
aren't there calculator bots in discord? or is using a calculator forbidden in here
because i'm so moving on to the next step if so
i still got other plans to do
replit issue, do kill 1 on shell
why would they be forbidden?
there's lots of calculator bots
but most of them use a 3rd party api like wolframalpha to do their calculations
hosting in replit is like playing russian roulette, never know when it will fuck u up
thays good then
Why do you make a timeout then a interval when sending the heartbeat?
yea the return fuction i wrote isn't being called but at least that's one step forward
do kill 1 every time there is a rate limit
it's not showing the calculations
let the other suffer for your api abuse 
i knew programming is reason of violence
thats what they ask you to do, although they are not strict about it, nothing will happen if you dont
After receiving Opcode 10 Hello, the client may begin sending Opcode 1 Heartbeat payloads after heartbeat_interval * jitter milliseconds (where jitter is a random value between 0 and 1), and every heartbeat_interval milliseconds thereafter. You may send heartbeats before this interval elapses, but you should avoid doing so unless necessary. There is already tolerance in the heartbeat_interval that will cover network latency, so you do not need to account for it in your own implementation - waiting the precise interval will suffice.
always must kill1 for code to work lol
killing your container
XD
they do that to randomize the timings for people to send their heartbeats and spread the load a bit more
and i was going to knock on my neighbors for code sacrifices hehe
if you can automate that, there wont be any rate limit forever 
not all of it is strictly necessary
Ima just do the stuff I think is necessary
like the connectedAt, readyAt heartbeatInterval lastAck and such
yeah, some stuff i might remove later, like the last sent and last received
handle how? like creating structures like djs does?
fuck yeah
Yea, I wanna make it as easy as possible for people to be able to use events
now i can go sleep T^T
I was actually thinking of in this library bulding a build in event handler and command handler ya know
you will need to look into djs since i dont use them
Well really all I need to do is find a way to effectively make a event handler
start by thinking what you would like to have if you were to use that event
ok turns out for some reason it's a little stupid can't count past ten but i'll look it over tomorrow
Wdym?
weird
like if you were to make a bot with your lib
what would you want the lib to do for you
to get dressed
how would you want it to handle the events for you
not be visible to all devs lol
Well I am trying to make a lib that is easy for beginners so I would like it to handle majority of the processing for me and just return the data for that event
then do that
ok good night y'all :p
๐
Almost forgotten lol
I'm gonna come back tomorrow to ask how to fetch images and posts from Reddit
So be prepared hehe
Y'all gonna be like oh fuck. This python dude again
Tag me on this so i remember tomorrow
Copied to the keyboard ๐
Still can't believe it took me 30mins to write the code but a full night to run it
A whole night on discord to get it running T^T
skill issue
Could've been worst if i just copy pasted it to the bot without testing the bot's capability of detecting all the operators '+,-,/,*'
Yeah ik that's why i in the end had to work it out on my own ๐
Good night you too ๐
Please, just write + - / *
It's weird that u keep writing as a single string
Help
Did you even sleep? o.o
step 1: be an insomniac
step 2: 
Lol
Took me 2 hours to make a page with a navbar that has a dropdown
We all have our struggles, it's okay
Same
What catching have you disabled?
alot, like message, user, reaction, guild related, thread, voice state, etc..
depends on what your bot does I guess
hi, i am facing a problem with the permissions for my bot
it can't add a role
- Bot's role higher than the role

- Bot's role higher than the member's role

- Bot has admin or manage role permissions

Yet i still face this issue
File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 375, in _run_event
await coro(*args, **kwargs)
File "/home/container/griselda_blanco.py", line 153, in on_message
await _function.voteFunction(int(userID))
File "/home/container/griselda_blanco_cogs/functions.py", line 70, in voteFunction
await member.add_roles(role)
File "/home/container/.local/lib/python3.10/site-packages/discord/member.py", line 1012, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
File "/home/container/.local/lib/python3.10/site-packages/discord/http.py", line 495, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access```
missing access is not a permission issue
it means your bot is trying to access something that it has no access for, or was deleted
for example trying to access a guild your bot is not in, or trying to access a channel that your bot cant see
seems to not be able to access something on a member, are you trying to direct-message a user when voting?
since you're calling add_roles too, is the member on the guild to begin with? is the bot also there?
https://uploadi.ng/FAX0zHsE
how can i fix it
i have form and i want from form user details and form data to mongodb
i want to have all data in one collection form data & user details
what is profile?
js isn't about easy it's a sea, u can never really say i got good at js because there's always something u didn't know yet, but it's not a bad language because you can achieve lots with it there's always more than a way to do anything with js unlike other languages that u only have one way only to do something, however it always requires a big number of lines to do the simplest thing.
or so i heard ๐
that defines pretty much any language
more than a way to do anything with js unlike other languages that u only have one way
except for this, there are NO languages where there's only 1 way to do something
the very requirement for something to be a programming language is the ability to do anything, including producing and running a copy of itself, so by default all languages can do anything in an infinite number of ways
regex is turing complete
@spark flint sorry for the ping but which api key i can use in a music bot for lyrics
Earlier it was ksoft api
with a bit of scrapping, https://www.lyrics.com/lyrics_api.php
The Lyrics API from STANDS4 enables you to get album, artist and songs information for a given search term โ along with direct links to the respected object pages on Lyrics.com.
O thnks man
tf is a semaphore
a traffic light but for code
i need to implement it and its the first time i've seen it
is it so threads do things in a specific sequential order
@lyric mountain but how to get the key please tell me that also
not necessarily "sequential" as in a semaphore doesn't guarantee fifo or filo
const DiscordStrategy = require("passport-discord").Strategy;
const passport = require("passport");
const DiscordUser = require("../modules/DiscordUser");
passport.serializeUser((user, done) => {
console.log("Serializing user...");
done(null, user.id)
});
passport.deserializeUser(async (id, done) => {
console.log("Deserializing user...");
const user = await DiscordUser.findById(id);
if(user)
done(null, user);
});
passport.use(new DiscordStrategy({
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
callbackURL: process.env.CLIENT_REDIRECT,
scope: ["email", "identify"]
}, async (accessToken, refresToken, profile, done) => {
console.log(profile);
console.log(profile.email);
try {
const user = await DiscordUser.findOne({ discordId: profile.id })
if(user) {
{
console.log("User exists in our user DB...")
done(null, user);
}
}
else {
console.log("User does not exist in our user DB...")
const newUser = await DiscordUser.create({
discordId: profile.id,
username: profile.username,
email: profile.email,
tag: profile.discriminator
});
const savedUser = await newUser.save();
done(null, savedUser);
}
}
catch(err) {
console.log(err);
done(err, null);
}
}));
In computer science, a semaphore is a variable or abstract data type used to control access to a common resource by multiple threads and avoid critical section problems in a concurrent system such as a multitasking operating system.
whats the problem please?
After logging it then
you didn't supply clientID
yeah but cant you just use a mutex for that
mutex is 1<>1 usually
process.env.CLIENT_ID was undefined
in tag?
like, only 1 process can hold a mutex at any given time
while a semaphore is 1<>N
wut
like, there are 2 kinds of semaphores
counting and binaries
binaries are effectively mutexes
@lyric mountain is this the api key
what @lyric mountain ?
bruh did u even bother to read?
papi replied to u
and how i can fix it if you can tell me ๐
^
By actually putting the env var in the env variables file or table on your host if it has that. Also make sure your env file is being loaded if it is a file
I am confused man what to do
counting are the ones im interested in
honestly i might just implement it without completely knowing the purpose
..?
it seems easy enough
^
what do you not understand. If it's undefined then that key either isn't in the env file or the env file isn't being loaded at all
look at the env module to see how it works because you don't require it
and there is discordstrategy.js
That's great and all, but #development message
My guy, you're not supposed to directly import the .env file, you're supposed to load the environment variables using what Papi showed
Which'll load them to the process.env object
i have now this const env = require("../env)
but i have another problem
public class JustExample {
private final Set<Class<?>> holders = new HashSet<>();
private final int cap;
public JustExample(int cap) {
this.cap = cap;
}
public synchronized boolean hold(Class<?> klass) {
return holders.size() < cap && holders.add(klass);
}
public synchronized boolean release(Class<?> klass) {
return holders.remove(klass);
}
}
for example
Did you even read
would semaphores use a mutex under the hood? because apparently when waiting or posting/signaling the counter cant inc/dec at the same time
haha
im retard
@lament rock and @earnest phoenix thanks for helping
from what I understood, a process can't hold a semaphore if there's no capacity
so basically a mutex with multiple uses
JS can be fun, but really weird on edge cases and it's quite different in syntax
mouse programming 
do you understand the purpose
im trying to i cant lmao
i'll just implement it and get on with my life
to limit flow ig?
I mean, that also reflects real life semaphores
you have a crossroad, you need to limit flow to prevent disasters
and why i had this in console log https://uploadi.ng/2aZH69zr
did you clone that project from somewhere?
don't use body-parser for express. Express has one built in, so use that
from a quick look i think its a multithread mutex kinda
if u limit to 1 holder per thread, yeah
R u doing in pc or anything else
you bought a dedi?
if I build a crud app and I can do either Nestjs MVC or Nestjs + Vue, which way is faster?
anyone here good at lua?
@lament rock how can i make that if i close server.js it will send before it webhook with: Server offline ๐ด
or someone
please
listen for process kill signals like signal interrupt or signal kill
can you make example ๐
please โค๏ธ
no
โฅ๏ธ
because its not recommended, because there are a ton of signals you have to possible account for and properly handle an exit
okay
can i use
process.on('exit',
const embed = new MessageEmbed()
.setTitle('Api Status:')
.setDescription('Offline ๐ด !')
.setColor('#5865f2');
console.log("[HEYDISCORD LOG] Webhook Api_Status was sened");
webhook.send
);
or
@lament rock
Use a codeblock at least, not an inline codeblock
ah, im sorry i understand :/
@lament rock or @earnest phoenix how can i make mongo db collection with discord user email name etc and data from form i still have errors
please help me
const DataSchema = {
Text: String,
// userId: String,
// Name: String,
// username: String,
// usertag: String
Email: String,
}
const Data = mongoose.model("Data", dataSchema)
const DiscordStrategy = require("passport-discord").Strategy;
app.post("/", function (req, res) {
let newData = new Data({
Text: req.body.data,
Email: WHAT HERE?
});
newData.save();
res.redirect('/')
console.log("New data:" + newFeedback);
idk. I don't use mongo. Look at code which does similar stuff to you and take inspiration
I don't understand why it doesn't work?
thats a direct file url, not a web url to an image
use something like https://imgur.com to upload images and embed them
Looks like Discord is getting their way 
At this rate my users will have probably almost completely adopted slash commands by this summer ๐
hmm
I also tried doing that before but it doesnโt work either
then you did not properly embed it, it has to be a direct image url
right click the image and copy image url
nvm i figured it out
Where did you got this info?
I started tracking if commands being run are prefixed or slash back when I released slash commands to my bot
Let me quickly aggregate my data
Note the only advertising promoting the use of slash commands I've done is in the bot status where it says /help and on the Top.gg page. Otherwise, if my older users who are used to prefixes are still using their prefixed commands they would barely notice.
So I'm guessing a lot of the slash command users are new users but that's just a guess
Statistically, it should be a 50:50 split by the end of the month
thats just chart.js?
It's not that sophisticated I'm just pasting the sql data into a google sheet
but I use chart.js for my stats dash yep it's poggers
I want do make a trend line in chartjs, just havent even tried.
seems I need to calculate the trend on my own.
HELLO anyone using hybridesharding
some reason my bot wont start up? Im new to coding can i have some help?
They have a support server where you can get help quickly
might be config.json
Check your logs when you start it to see if you get any errors and work through it from there
node.?
they are bad they told me too use discord.js sharding
๐
and i just asking him that how we can map shard uptime for all shard
node. is discord bot start-up?
Even if their support server is telling you to use discord.js' native sharding then you should do so, I don't recommend using third-party libraries to handle sharding for you
yeah sure
then i will go for it
node . should start up your bot if the main entry file is set correctly in the package.json file (the main field)
You can use the https://discord.js.org/#/docs/discord.js/stable/class/ShardingManager?scrollTo=broadcastEval method to evaluate this.uptime to get all of shards' uptimes
"name": "amt",
"version": "1.0.0",
"description": "A bot for A mythical tale",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "tsc index.ts && node index.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"pkg": "^5.6.0"
}
}
incorrect?
If you have index.js as your main file then yes that's correct, although I assume you're using discord.js but you don't have it installed
how do i install it?
sorry to ask.
in the start script you seem to be using tsc, did you write your bot in TypeScript?
nope what i was told to type
its just a very basic js bot like a ping pong sorta thing
Then I would recommend removing the start script as it's incorrect in this case
And you can install discord.js by running npm i discord.js
node. : The term 'node.' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a
path was included, verify that the path is correct and try again.
At line:1 char:1
+ node.
+ ~~~~~
+ CategoryInfo : ObjectNotFound: (node.:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
node ., a space between the node and .
seems to work i think i might need to get a newer index.js whats the most basic script just to get the bot online?
Discord.js got a really good guide https://discordjs.guide/#before-you-begin
Just follow the steps in the sections on the left https://discordjs.guide/preparations/#installing-node-js
*** I NEED HELP***
file: https://www.mediafire.com/file/e7ciy9z88p28hwy/login.rar/file
there is all files of login
and i need to import there to schema of feedbacks userID etc
and after i had app.js with this:
`const discordStrategy = require("./strategies/discordstrategy");
const feedbacksSchema = {
Text: String,
// userId: String,
// Name: String,
// username: String,
// usertag: String
Email: String,
}
const Feedback = mongoose.model("Feedback", feedbacksSchema)
const DiscordStrategy = require("passport-discord").Strategy;
app.post("/", function (req, res) {
let newFeedback = new Feedback({
Text: req.body.feedback_idea,
Email: WHAT HERE
});
newFeedback.save();
res.redirect('/')
console.log("[HEYDISCORD LOG] New idea: " + newFeedback);
})`
yea
was just making sure
very good server btw people there aren't stuck up like other cpp servers
from all storage sites u had to choose the one with the worst reputation around
js isn't typed btw, so doing Text: String ur actually assigning the class itself
also use ```
for codes
see?
way better to read
and u can't get an user's email without using the scope
i had
you had what?
Require stack:
- C:\Users\savir\AppData\Local\npm-cache\_npx\c67e74de0542c87c\node_modules\readable-stream\transform.js
- C:\Users\savir\AppData\Local\npm-cache\_npx\c67e74de0542c87c\node_modules\through2\through2.js
- C:\Users\savir\AppData\Local\npm-cache\_npx\c67e74de0542c87c\node_modules\hyperquest\index.js
- C:\Users\savir\AppData\Local\npm-cache\_npx\c67e74de0542c87c\node_modules\create-react-app\createReactApp.js
- C:\Users\savir\AppData\Local\npm-cache\_npx\c67e74de0542c87c\node_modules\create-react-app\index.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
at Function.Module._load (node:internal/modules/cjs/loader:778:27)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (C:\Users\savir\AppData\Local\npm-cache\_npx\c67e74de0542c87c\node_modules\readable-stream\transform.js:1:18)
at Module._compile (node:internal/modules/cjs/loader:1103:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'C:\\Users\\savir\\AppData\\Local\\npm-cache\\_npx\\c67e74de0542c87c\\node_modules\\readable-stream\\transform.js',
'C:\\Users\\savir\\AppData\\Local\\npm-cache\\_npx\\c67e74de0542c87c\\node_modules\\through2\\through2.js',
'C:\\Users\\savir\\AppData\\Local\\npm-cache\\_npx\\c67e74de0542c87c\\node_modules\\hyperquest\\index.js',
'C:\\Users\\savir\\AppData\\Local\\npm-cache\\_npx\\c67e74de0542c87c\\node_modules\\create-react-app\\createReactApp.js'
]
}``` how to fix this error i cant install react app
projects are meant to have many files
The index is like full
then put things out of index
also it isn't full, unless u managed to write more than 2 billion lines
and it isn't a limit, it's just how far you can go before most file readers refuse to open it
the amount of files/lines doesn't really matter, WHAT is in those files do
you can have a 100k lines bot be faster than a 50 lines one
How come when I pass an array with ejs, it no longer acts like an array?
wdym?
https://capy-cdn.xyz/mebbLoN3Ax66.png console.log
ejs
the actual output is like 744657468222865438,[AUTOMOD] Sent PHISHING links,Blacklister#3409 (866364881917837312),3/5/22,784278333075750922,[AUTOMOD] Profile picture matched anti-scam filter,Blacklister#3409 (866364881917837312),3/5/22,840706801921163264,[AUTOMOD] Sent IP_LOGGER links,Blacklister#3409 (866364881917837312),3/5/22,724670236955246713,DM ads,big.bun#6969 (471409054594498561)
i added [] either side
shouldn't u be using objects for each block?
Owo
since they have a common structure
The code does make it like tat
no, I mean, here
{
id: "12312512512",
description: "[AUTOMOD] something",
infractor: "black#1234 (id)",
date: "3/5/22"
}
like this
eh
I have also a question
If some commands linked to a mongodb in a project i can make commands not related to that db
Right?
yeah
just remember to put each thing in the proper file
flooding index isn't the answer, albeit js allows it
index is like when u open a book and have a guide of where to open for a specific content
Iam working but the end is that bcz iam not 16+ and my bot in 60servers iam scared of a deletion
this is an index
index.js should just guide the code to know where it can find the beginning (and stuff like creating bot client, setting endpoints, db connections, etc)
Ohh
Ubuntu can be booted without graphic card?
depends
if you have an integrated gpu, then your motherboard will have a video out plug even if you dont have a dedicated gpu
so yes it will work
but if your cpu does not have integrated graphics, or your motherboard does not have a video out, then you need a dedicated gpu to even have a video out plug to plug in your screen
if you're talking about network boot or vps, then yes it will work without gpu regardless
what is that?
oh
idk what that is
on windows it depends on file format
on unix it depends onn? chmod type
Yes pls
Ty
No problem.
extension is just a suggestion to what kind of programs open what files
and what icon to put in it
they're entirely optional, such that linux doesn't even care abt them
I could rename chrome.exe to chrome.txt and still run it
like you arent able to do that
windows is sussy baka
I went to sleep yes
I still failed at making the basic part of library tho
It seems like the event is stopping short. I am not to my knowledge receiving the ready event, here is the code: https://www.toptal.com/developers/hastebin/aniqudibag.typescript
Received hello. Heartbeat interval = 41250ms. First heartbeat in 18617ms
Identifying
This is the response I get from debug
Received hello. Heartbeat interval = 41250ms. First heartbeat in 33658ms
Identifying
Sending heartbeat
Sending heartbeat
Sending heartbeat
Sending heartbeat
Sending heartbeat
Sending heartbeat
Sending heartbeat
Well now I know why nothing is happening
It is spamming the gateway after the heartbeat interval is up
you didnt add the timer to setinterval
but you should still get the ready before that
Yea that is weird
also wdym by this?

listen man I was tireddd
Is it supposed to start identifying before sending the heartbeat or does it not matter when you identify?
Heartbeat even when not identified
its doesnt matter
Discord recommends you to keep heartbeating until the gateway can assign you a session
and of course continue after that
Well I still don't see why I am not receiving the ready event back
log the identify data youre sending
Mmm, for some reason intents is undefined huh
Ok so it was another one of me being so damn tired I wrote shit code and forgot to define intents having a value of options.intents
:^)
I now receive the ready event
max_concurrency
what is that
resume
Isn't resuming just checking if there is a session available and then if so that means there was a previous session?
max_concurrency is an int from GET /gateway/bot where it defines how many identifies you can do within 5 seconds instead of just 1
yes, you also need to listen to the resume opcode and restart the connection
the resume opcode is 6 right?
receive resume is op 9
you receive op 7, reconnect ws then send op 6 instead of identify
resume also doesn't count towards identify call limitations, so if there is a session you can resume, you should do so
does anyone have a solution for this? those weird symbols are supposed to be accented letters (the correct lyric would be "Dipenderรฒ da te, perchรฉ non so piรน stare sola"), this is requested to Genius api and converted to utf8, but accents show up with this weird รฏยฟยฝ
(nodejs btw)
how is it converted to utf8?
_initReconnect() {
if(!this._internal.reconnectPromise) {
let resolver;
const promise = new Promise(resolve => { resolver = resolve; }).then(() => { this._internal.reconnectPromise = null; });
promise.resolve = resolver;
promise.offline = false;
this._internal.reconnectPromise = promise;
}
}
Btw tim, I notice you do this in initReconnect in your code but this doesn't actually resume the connection dose it?
since im lazy require("utf8").encode(data), idk if this could be the problem
bad way to do that
Buffer.toString("utf8");
where Buffer is usually the response body
ill try, thnx :)
utf8 is the default anway
after calling initreconnect, i send a close code to their websocket, and wait for discord to close it
i might change that tho
since it can cause issues in unstable networks
Mmm but if you are wanting to reconnect why not just call _resume?
the websocket has to be fully closed and reconnected
Mmmm
So could I not just call websocket.close()and then do this._resume()?
where do you get data from?
does this api youre using have an npm package ir are you doing the request yourself?
you need to call close, then call connect, then wait for hello, then call resume
after you receive hello, you resume if you have a session, and identify if you dont
its a package, i want to do it myself but i had no time honestly lately so i went for an easy option (@jeve/lyrics-finder)
Actually wait yea
I just thought bout that
What close code do you use I don't remember seeing it in the docs
you dont need to send a close code
Oh? I thought you did
I moved away from genius personally and just use https://some-random-api.ml
case GatewayOpcodes.Hello: {
const interval = d.heartbeat_interval
const timeout = Math.floor(interval * Math.random())
this.emit('debug', `Received hello. Heartbeat interval = ${interval}ms. First heartbeat in ${timeout}ms`)
internal.heartbeatInterval = setTimeout(() => {
internal.lastHeartbeat = Date.now();
this.emit('debug', 'Sending heartbeat')
this._socket.send(JSON.stringify({ op: GatewayOpcodes.Heartbeat, d: this.sequence }))
internal.heartbeatInterval = setInterval(() => {
internal.lastHeartbeat = Date.now()
this.emit('debug', 'Sending heartbeat')
this._socket.send(JSON.stringify({ op: GatewayOpcodes.Heartbeat, d: this.sequence }))
}, interval)
}, timeout)
if(this.session && this.sequence) {
this._resume()
} else {
this._identify()
}
break;
}
case GatewayOpcodes.Resume: {
this.emit('debug', 'Discord asked to reconnect')
this._socket.close()
this.connect()
break;
}
So theoretically this should work right?
thr close code you send is echoed by them, so i send a custom code , so when i receive the close confirmation i know if i was the one who closed it, or if they were the ones who closed it
thank you :))
you can also try data.toString("latin1")
but if youre using an npm package, it should be giving you the decoded data already, not a buffer?
yes, you need to await close, otherwise you connect before the close finishss
right
ty for that
Also another thing to work on is helping with rate limiting
At least I think that is something I should do right?
That way people don't get banned as easily
websocket rate limit is very straight forward, its 120 requests per 60 seconds
but these requests are only for presence updates, voice state updates and requesting guild members
feel free
Tyty
Also ty for all the help with my endeavor I'm a complete noob with this so sorry if I bother you with all the questions
just add a coment/license about it when you release it
Yeee
np
I think everything gateway wise is done (other than voice state update thingy)
Also I notice you do a lot of stuff on close that is smart
Yea, that makes a lot of sense
I am kinda just going with the flow rn so I am not thinking of every possible thing that could go wrong, plus I am not entirely sure of what could go wrong as I am new to the whole socket thing so I have no idea what possible outcomes can occur
i got dpp to name its threads ๐
gonna use that in my bot's admin panel to report on specific cpu usage per shard
I keep on getting with this command that I did not mention a channel properly but I did and I do not understand why
https://paste.pythondiscord.com/olabunixul
debug it
you know where the error happens, you know which line is causing the error
log it and test it independently to see whats wrong
print answers, print answers[0], print answers[0][2:-1]
and eventually you will find whats wrong
wtf is answers[0][2:-1]
is that like answers[0][2] if it exists, but answers[0][finalIndexOfAnswers] if it doesn't?
im assuming its some weird syntax for .slice(2, -1)
oh yeah I forgot python has slice syntax
If shard dont have any sessionId that mean its dead?
yes
No way, real shit? This changed everything
wdym by that eh?
that hes gay
lol
Man tim I am stumped on how I wanna handle the events. I even looked at djs way of doing events and it is a rabbit hole
:^)
I know they emit the events in actions but idk how the actions are called or how they work
djs converts every single event into a djs structure before emitting
actions are called from handlers
some of them call the action directly, others do a lot of preprocessing before the action
its a mess
Yea it is very hard for a nub like me to follow this
some of the events are just done directly in the handler file
register(Action) {
this[Action.name.replace(/Action$/, '')] = new Action(this.client);
}
wtf is this bs
Are they just getting the name and setting the action for it or?
Alright so from what I can tell, the websocket manager catches the events, uses the handlers for that event, and then the action processes the data and does what it needs with it and then emits it?
yes
and the reason handlers and actions are separate is because
for exanple
when your bot sends a message with the rest api
discord responds to the http request with the created message
but also sends a message create event for the same message
I am now realizing how fun yet how fucking annoying this project is :^)
the response from the http request also goes through the actions
so actions are used by both websocket and rest
handlers are only websocket
I get that
But I really don't wanna make my system in such a messy way even though it will likely end up like that
I was also thinking of just doing that and having something similar to discord akairo
listener and listenerhandler ya know
The listener would essentially do what actions in djs do
and the handler would be for registering those events with the code base
I think before I focus on events though ima work on the websocket some more
๐
@sharp geyser for when you see later, I really highly recommend you don't try to make the next Discord.js as you'll burn yourself out faster than anything
omg akairo ๐ฅบ
using import() instead of require() or change the module to be a common js module instead of esm
ok
how the hell does nest work? I thought there were docs
Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Progamming), FP (Functional Programming), and FRP (Functional Reactive Programming).
aah thanks volt
const { REST } = require("@discordjs/rest");
const { Routes } = require("discord-api-types/v9");
const { readdirSync } = require("fs");
const path = require("path");
const { CLIENT_ID, GUILD_ID, TOKEN } = require("./config.json");
const commands = [];
readdirSync("./slashcommands/").map(async dir => {
readdirSync(`./slashcommands/${dir}`).map(async (cmd) => {
commands.push(require(path.join(__dirname, `./slashcommands/${dir}/${cmd}`)));
})
})
const rest = new REST({ version: "9" }).setToken(TOKEN);
(async () => {
try {
console.log("[INFOMATION] Start refresting application (/) commands.");
await rest.put(
// if you want to use global slashcommand use here => "Routes.applicationCommands(CLIENT_ID)"
//Routes.applicationGuildCommands(CLIENT_ID, GUILD_ID),
Routes.applicationCommands(CLIENT_ID),
{ body: commands },
);
console.log("[INFOMATION] Successfully refreshed application (/) commands.");
} catch (error) {
console.log(error);
}
})();```
is that the code for registerSlashGlobal.js?
yes
the error says the problem is on line 1
i dont need anything wrong on the first line of that code
timhadastroke
node 8? wat
Replit uses v8
no?
lel
exdee
Yea I'm trying not to but I've never done it before so I have no idea how I should structure it so I'm taking a lot of inspiration from djs and tiny discord tho I am probably just going to start over from scratch and do it my own way
How can we check if any shard got issue or off
Yes
๐ฅด am new in shard
In replit we must use npx
check its status
the shardmanager should contain all managed shards
loop though it to find your faulty shard
status is 1 or 0 in some shards 5
so any scale for status?
are you using discord.js?
hybride
How would I go about using blobs in NodeJS, need to use new Blob
discord-hybrid-sharding?
yes
client.ws.shards has a list of shards on each cluster
yes
can you dm me this docs
the docs for the shards are from discord.js
what do you want to use blob for?
I am trying to respond to a button interaction on the raw event so it works even after a restart, I am trying to send an image alongside the data, which requires form data and payload json
I am struggling to get this working ๐ญ
This is what I got currently, seems to be a bit further now, may not even need blob
current issue now is cannot send an empty message api response ๐ฆ
https://i.callumdev.xyz/dEviPESo18.png
your append is wrong, and you're missing the boundary headers
formData.append("files[0]", data, filename);
headers: {
...formData.getHeaders(),
content-type: "multipart-formdata"
}
also what type is captcha.dataURL? not sure if formdata supports base64 dataurls
its better if its buffer or stream
Yeah, I can try a stream for it one sec, the above code has gotten it to send a file now but the image is just blank and it doesnt have the embed either
Cool, it sends the image now just fine with the stream, only issue is it sends ONLY the image, and it sends it as a file
try instead of filename
{filename: 'captcha.png', contentType: 'image/png'}
you're using the form-data npm package right?
I am yeah
Where would I put this?
Once again it just sends as a message attachment and does not include the embed either ๐ฆ
still no difference
not sure then, can you show your current code again?
This is it currently
const captcha = new Captcha(100),
newData = new FormData();
newData.append("files[0]", captcha.PNGStream, { filename: 'captcha.png', contentType: 'image/png' });
newData.append("payload_json", JSON.stringify({
"type": 4,
"embeds": [
{
"title": "Verification Code",
"type": "rich",
"description": "Please click the verify button and enter the code you see below.",
"timestamp": Date.now(),
"color": 16777215,
"image": {
"url": "attachment://captcha.png"
},
"ephemeral": true
}
]
}))
axios(`https://discord.com/api/v8/interactions/${interaction.id}/${interaction.token}/callback`, {
method: "POST",
data: newData,
headers: {
...newData.getHeaders(),
"Content-Type": "multipart-formdata"
}
});
since its an interaction callback, it should have a data object
{
type: 4,
data: {
embeds: [...],
attachments: [...]
}
}
Thank's Tim, that works now, just curious, do I have the "ephemeral" in the wrong place?
yeah it should not be inside the embed
How do i make a bot with auto-mod?
Like i want to create my OWN Private bot
To moderate the server
you need to set it in flags
i don't know coding..
data: {
embeds: [...],
flags: ephemeral flag here
}
or how to even input a code into a bot
great thanks



