#development
1 messages ¡ Page 38 of 1
And we still love you Misty

;)
đ¤Ł
But nah I am making a chat app to practice websocketing
and am having troubles displaying the messages to all clients in real time
as soon as they are sent
Doesn't help that the thing I am using to receive from the server uses a package I have 0 clue how to use right now
Donât u just use some event system which emits an event being send to the client when a new message has been sent!
Indeed
Isnât that sort of the easiest way of doing it
The client sends an event to the server that it receives and processes and sends smth back to the client
the smth back right now is the message and sender
but I have never used rxjs so whats being received in the client is turning into an Obeservable and I have 0 clue how to efficiently extract the data from an Observable without making spaghetti code
huh createdAt doesn't return ms
@boreal iron just tell me this and I can go to jail peacefully
it returns a timestamp
Ok nothing I can help you with, too unfortunately
I made very simply System using only basic JS
Yea I am using Angular
and Nestjs
and the only popular package I see for implementing a "easy" client implementation of client socketing is ngx-socket-io
but it turns everything into an Observable
and I have no idea how to use rxjs
and frankly I don't wanna learn
Hmm well never worked with em
if that's what it returns then how the hell does my whois command works?
I'm using the exact same thing and it somehow converts it to normal time
my timeAgo function takes in MS???
You should one day, it can be very useful.
No 
Guess youâre fucked then Misty
const Target1 = interaction.options.getMember("user") || interaction.member.user
if (Target1.memberPermissions.has("KICK_MEMBERS")) {
^
TypeError: Cannot read properties of undefined (reading 'has')
I'm trying to make a user info cmd

thanks
memberPermissions?
no idea what that is
Do user instances have permissions?
Users donât have member permissions
No but guild members have
wot
but djs probably does something when its called on its own and sent to a channel
and turns it into a readable format
same with if you try and send a member object without putting it in code blocks or whatever
iirc it just pings the user
then how come this returns false ? member.user.createdAt <= 6.912e+8
the account age is 6 days the amount of ms adds up to 8 days
you are trying to compare a timestamp to a smaller number...
a timestamp will end up being a massive number in ms
do you think that massive number will be less than 6.912e+8ms?
no the createdAt adds up to 6 days, right? and the 6.912e+8ms is 8 days
so what's going on?
I think I'm actually bad at maths lmao
wait one sec I think I might be doing math wrong
my brain is hurting
no it's definitely not
I tried 30 days timestamp
still returned false
what the actual hell..?
@civic scroll hello qt
I have angular question from last night when u available
<3
Im continuously offline
Also where are all my messages I sent when I was offline?
what does
Going into the void
Wtf is going on here
huh
time to delete my discord account I guess
Wut?
when I run it over my timeAgo function it returns 6 days ago
when I compare it to 8 days ms it returns false even though 8 days is larger than 6 dyas
WHY
WHAT IS GOING ON
What are you actually talking about?
I just want to check whether an account is younger than a week
but then how come my createdAt changes into MS????
my timeAgo function takes in MS and somehow when I do createdAt it turns it into regular time?
I am
I think we live in a simulation
that can't be real bruh
đ
how does that work
I feel like we should ask to see your function but no, that wonât happen
Not falling for it this time

Math.floor((new Date() - new Date(date)) / 1000);
``` date is the thing that is going into the function
somehow this turns createdAt weird shit into MS
There you go

I'm such a dummy
you don't even need new Date(date) iirc
since whatever date is will already be a Date object
Should have kept my mouth
Ur not the only one
valueOf abuser smh
lmao
gn
so did they leave the content intent thingy paused half-way?
my bot doesnt respond to text commands on my server anymore, but its still responding to other servers in my logs lol
Just gets rolled out slowly
people still insist on using text commands
Oh
even though they are given a big ass warning on every text response
Is it sharded?
yeah, not many tho
They said they re careful to not disconnect all shards at once especially for large bots
Enjoy your last moments I guess
With so much variety Discord tries to archive I guess things will and can go wrong
Or not as planned
v9 deprecation soonâ˘ď¸
/command ... that's actually smart af
wouldnt it be funny if after the intent enforcement there remained a few bots they forgot to apply the changes to
and they become the only bots in the world that can still read messages without the intent
i just hooked up everything together into a messy multi-version/multi-api thing lmao
To be fair if discord would have released slash command mentions as part of the message formatting earlier it would have been easier to add them as examples to your user notifications screaming to use slash commands from now on
timo timo timotei
exists yes
but im gonna shut down the whole process
my bot has 2 processes running rn, one for slash commands, another for websocket
both processes access the same command files lmao
yeah except the slash command process has to load all the legacy crap from the other process to be able to use its commands
my bot is literally 2 cars hooked to the same battery rn

even worse
one car has the engine, the other car has no engine and instead has a bunch of gears that hook into the first cars engine to power its own wheels
nop
Okay so can someone help me think something out real quick
Heres the current process of how I handle messages
User Types message -> They Press send and it gets sent over the socket to the server where it is saved to a db or whatever -> Server responds back with the message and the sender and any other relevant information -> How should the client display this message?
Tim close to be scratched off the list of proficient developers
I have a feeling I should be updating the div unordered list when I receive a message from the server instead of in the html file itself
<button (click)="this.sendMessage('Hello, World!')" >Send Message</button>
<div *ngIf="messages.length !== 0">
<ul *ngFor="let message of this.messages">
<li>{{ message.message }}</li>
</ul>
</div>
that looks like hell
good thing I have 0 clue what you're doing too
rxjs makes everything an Observable so I am doing it in a weird way
import { Injectable } from '@angular/core';
import {Socket} from "ngx-socket-io";
import {map} from "rxjs";
@Injectable({
providedIn: 'root'
})
export class ChatService {
constructor(private socket: Socket) {}
sendMessage(msg: string) {
this.socket.emit('message', msg)
}
getMessage() {
return this.socket.fromEvent<{ message: string, sender: string }>('message').pipe(map(data => data))
}
}
This is my ChatService that handles actually sending and receiving messages
import { Component, OnInit } from '@angular/core';
import {ChatService} from "./chat.service";
@Component({
selector: 'app-chat',
templateUrl: './chat.component.html',
styleUrls: ['./chat.component.scss'],
})
export class ChatComponent implements OnInit {
messages: Array<{ message: string, sender: string }> = []
constructor(private chatService: ChatService) { }
sendMessage(msg: string) {
this.chatService.sendMessage(msg)
}
getMessages() {
const message = this.chatService.getMessage()
message.subscribe(data => {
this.messages.push({ message: data.message, sender: data.sender })
})
return this.messages;
}
ngOnInit(): void {
}
}
This is how I send the message to the service and how I get the message and add it to the this.messages array
but I realized I don't need to return this.messages anyway cause I can just access it
yeah why have encapsulation when you can just make everything public C:
misty how do you like my plans for making a bytecode VM ```rs
/*
- TODO:
-
- Redo operations to allow more than 1 byte access to constants
-
- Each op is still 1 byte, but can be followed by data greater than 1 byte
-
- Use Cursor instead of BufReader
-
- String format: LEN, BYTES
-
- Store all floating points as u64, then use f64::from_bits to convert
- BYTECODE FORMAT:
-
- First 4 bytes: Number of constants in section - "C"
-
- Second 4 bytes: Amount of bytes following the constants section - "N"
-
- Bytes 9 to "C": Constants (Strings, numbers, etc)
-
- Bytes "C" to "N": Opcodes and data following opcodes
*/
- Bytes "C" to "N": Opcodes and data following opcodes
I don't think you even can with angular
at least when I tried I ran into issues
I don't even know how to make a websocket server in rust
I would if I did
and I am not confident in rust and am too scared to try
đĽ˛
Does interaction return a guildMember object?
If its used in a guild I think so
As property yes
Looks nice
I understand only half of that tho
basically I have funny bytes in a file that represent different operations
and I'm thinking of a way to refine my current implementation to better support things
If I have an array of role IDs, how can I check if a user has any one of those roles?
I just like low level
const memberHasRole = serverConfig.modRoles.some(async (role) => {
interaction.member.roles.cache.has(role)
});```
I got there but it doesn't work
don't use async there
ah
But that would be the way to do it from what I can tell
ah you didn't return anything from that
ah
try js const memberHasRole = serverConfig.modRoles.some(role => { return interaction.member.roles.cache.has(role) }); or ```js
const memberHasRole = serverConfig.modRoles.some(role => interaction.member.roles.cache.has(role));
elseif ($piece[0] !== basename(dirname($_SERVER[PHP_SELF]))) {
echo '<a href="'.$piece[1].'">'.$piece[0].'</a>';
}```
@boreal iron your domain here
wdym
Compare what I wrote with yours
Youâre using PHP_SELF as constant not as key to the global $_SERVER array
Ow yaay am I offline again?
it works
Discord being dumb
This is likely unrelated to the main issue
Nah Iâm continuously being offline like every few minutes today
Maybe already reached my traffic limit
Idk
How do I call client deep in another file?
Wdym
client is defined in index.js when it's ready, its going to call ./tools/tasks.js (init()) which is going to call ./update.js (update()) which needs to access client
You can keep passing client down the chain
in the function parameters?
Yea
Or export it and import it
wont that get messy af?
how about this?
Tbh I would create a class in your tasks.js and pass client in your index to it when initiating the class after importing tasks.js
it lets you create a system where the bot cannot be invited until the person obtains special permission to invite it, for example some kind of registration system where the bot cannot be invited until the registration is complete
So you can essentially make a private beta cool
> sayuri runtime init
dont
ok
never export stuff from index.js
Don't listen to Tim rebel!!!
unless you know what you're doing
> sayuri pause
Rebel against Tim
that also sounds messy af
Define a class in your tasks file, export it, import it in your index and initiate the class, pass client to it
Easy
no
Yes
the only safe way to export stuff from index.js is to import it inside functions and not in the root file
function callbacks are the most optimal
otherwise you have circular deps
hmm?
what's the context that the client is accessed
if you export it from index and import it elsewhere?
use event emitters with callbacks
this is, similar stuffs to websocket and rxjs
maybe, but you will have to instantiate the instance first
something like a singleton container
Heâs asking how to pass a var to another module and youâre recommending him to overengineer stuff
Poor dude
is there any guides to help me with this?
hacker mode: ```js
// index.js
global.client = new Discord.Client(...)
// file.js
global.client.channels.cache.get(...).send(...)
explain to me how you place things
so in index you define a client
and in that same file when a command occurs it calls the function from another file
is that right
literally this
and that another file tries to import the client
if that's the case with this solution, this man clearly never knew function binding
wait, where is it invoked
index?
yeah it defined in index
export the files as functions
inside index you bind the callback with the client
so that inside other file you can access it
here's an example
evt/interactionEvent.js
export function interactionEvent = (client, interaction) => console.log;
index.js
//... you set the client up and stuffs
const eventData = await import("evt/interactionEvent.js");
client.on("interactionCreate", event.bind(null, client);
check if it does console log the client
await import on an es6 export? lmao
words cant define how confused i am
callbacks with events
Sayuri won the prize to be the number one âconfuserâ trying to help somebody
I'm not using events
can you show some code so we can see what exctly you're doing?
i just don't get you are trying to do
//index.js
client.once("ready", async () => {
console.log("Ready!");
require("./tools/tasks").init();
});
//tasks.js
const { getOrangeAppsUpdates } = require("./orangeapps");
async function init() {
await getOrangeAppsUpdates().bind(null, client);
//somewhere in getOrangeAppsUpdates
client
Just passing a var he defined in his index to another module

you are doing it the dumb way, thanks
wdym
you.
you exports as functions to be used later
you pass the client into one of the consumer functions to be used it its body
not this circular import
this is gonna cause you errors later on
ever heard of circular depedency error?
no?
Imagine simply exporting a class in your tasks file you import and initiate in your index
I like people choosing the hard way
Instead
index import tools and execute itself
tools import index
index import tools
this will go on indefinitely
this man is stubborn af, hold lemme boot up the pc
that getOrangeAppsUpdates doesnt make much sense, can you show what the function does? await bind is not a thing
it consumes the client variable
init() suggests you are initializing something, not running the function
so why can't he export it as a function
aka preparing the function for running it later
he should have exported it as a class
so does getOrangeAppUpdates get initialized when you call it in init?
and then has a separate function to actually run ?
or is the getOrangeAppUpdates the actual function that is run on every event? in which case why is it being run on init?
Not that I already mentioned this like 10 times

đż
let me see the scheduler
can you show how is it scheduled?
now.
async function init() {
await getOrangeAppsUpdates().bind(null, client);
//Busy school days
schedule.scheduleJob("*/30 8-16 * * 1-5", function () {
getOrangeAppsUpdates();
});
//Idle school days
schedule.scheduleJob("0 0-7,17-23 * * 1-5", function () {
getOrangeAppsUpdates();
});
//Weekends
schedule.scheduleJob("0 * * * 0,6", function () {
getOrangeAppsUpdates();
});
}
im using no events...
//index.js
const tasks = require("./tools/tasks");
client.once("ready", async () => {
console.log("Ready!");
tasks.init(client);
});
//tasks.js
const { getOrangeAppsUpdates } = require("./orangeapps");
module.exports = function init(client) {
const myOranges = getOrangeAppsUpdates.bind(null, client);
schedule.scheduleJob(..., () => {
myOranges()
})
}
or simply this ```js
//tasks.js
const { getOrangeAppsUpdates } = require("./orangeapps");
module.exports = function init(client) {
schedule.scheduleJob(..., () => {
getOrangeAppsUpdates(client)
})
}
no real need to bind there
no need for async either
so just pass client as parameters?
yeah
i told you
I was here to avoid that..
no point in avoiding that
question is, why?
seems messy
unless you want to use this
you can do js const myOranges = getOrangeAppsUpdates.bind(client); schedule.scheduleJob(..., () => { myOranges() }) and then use this to access client inside the function
yeah, im just gonna pass client as parameters
i dont get it either
imagine it like this: how do you want to access the client inside the function?
if you want to access it via client -> pass as parameter
if you want to access it via this -> bind it
if you want to access it via this.client -> create a container class to hold the functions
yes ok fine, im just gonna pass it by parameters
looks insecure
sorry for the tantrum, i just woke up to see this abomination
if you want to be extra cool: export client and use require("../index.js") inside the function (not outside)
wait, by cool do you mean stupid?
@wheat mesa Is it a mistake to try and use rust for the backend of my chat app when I have 0 clue of what I am doing and where to start

researching a lot rn
yes mistake
Any of y'all ever forget to add untracked files in git, and end up running into massive errors when you clone your repo down the line?
oh well
I am
never
i don't use git CLI
rust has good backend capability but it also requires a little more advanced knowledge of rust since backends like that typically are multithreaded and/or share global state to some extent
which is difficult for a beginner to work with in rust
Rc<Refcell<State>> moments
Does that actually helps with not forgetting untracked files?
i use VCS inside IDEs
so if there are untracked files, it will let me know
Now that I think about it, I have tons of random untracked files that I create when I stash changes I try.
It's probably just a me issue.
When did I say it's not that bad
storing booleans as strings when you can just store the boolean itself
mmm
apparently a byte is more than a bit

String booleans are just the worst, not only are you wasting way more memory by allocating them for the strings, but you're also slowing down the comparisons and shit as you're comparing multiple characters instead of just a byte comparison
unless the interface explicitly only communicate via strings, don't ever store booleans as string
thank you
is there something like const messages = await webhook.fetchMessages({ limit: 100 });?
No
nop
ok thanks!
So I have a basic ws implementation going with axum
so I am psyched I got this far

You'd basically have to get the channel that webhook is bound to and then fetch the messages
The channel ID is provided in the webhook so it's pretty simple
rust 
Yea I am trying to use rust more
get outta my comfort zone
:p
This no commands channel
!play jutt da yar
Try fetching the channel
@boreal iron also there is your explanation 
#development message
use axum::extract::WebSocketUpgrade;
use axum::extract::ws::{Message, WebSocket};
use axum::response::Response;
use axum::Router;
use axum::routing::get;
use serde::{Serialize,Deserialize};
#[derive(Debug, Deserialize, Serialize)]
pub struct MyMessage {
pub message: String
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(|| async { "Hello, World!" }))
.route("/ws", get(websocket_handler));
axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap();
}
async fn websocket_handler(ws: WebSocketUpgrade) -> Response {
ws.on_upgrade(handle_socket)
}
async fn handle_socket(mut socket: WebSocket) {
while let Some(msg) = socket.recv().await {
let msg = match msg {
Ok(msg) => msg,
// Client disconnected so just return
Err(_) => return,
};
let parsed = match serde_json::from_slice::<MyMessage>(&msg.into_data()) {
Ok(parsed) => {
println!("{:#?}", parsed);
parsed
},
Err(error) => {
socket.close().await.unwrap();
println!("{}\n", error);
return;
}
};
if socket.send(Message::Binary(serde_json::to_vec(&parsed).unwrap())).await.is_err() {
return;
}
}
}
@wheat mesa rate

I had a lot of help from a cool guy
hi qt
Hey Misty
anyone use Koyeb? everything works great but it fails the health check after 15 minutes because the bot isn't listening on port 8080
Yeah i already replied to it but it seems it got yeeteed into the void again when my internet died while sending it
Idk whatâs going on the last days
It's probably because of Discord, they've been having some issues lately due to the gateway connection invalidation for many bots at the same time and stuff
Yesterday I sent an imagine together with some text and the text disappeared
They already had 2 incidents yesterday
So discord having issues together with my mobile internet dying every few minutes seems to be a catastrophic combination

Tim must be jealous
Discord is very stableâ˘ď¸

Always
I've been getting a lot of EAI_AGAIN DNS lookup errors
specifically for resuming
I'll have to cache lookup results
TypeError: Cannot read properties of undefined (reading 'id')
let messages = await client.channels.fetch("943705642416373850").then((c) => c.messages.fetch({ limit: 100 }));
if (!messages) return;
for (const message of messages) {
console.log(message);
if (!ids.includes(message.content)) webhook.deleteMessage(message.id);
}
You're iterating over a collection, which gives you both the keys and the values
You seem to only need the values so iterate over the values with messages.values()
got it! Thanks!
is there a way to know if my webhook created the message?
Not faster, not slower but it will work, too
something like webhook.id?
Nerd
If a message is a webhook djs should attach webhook as property
At least with the id as property
but isnt that message.author.id?
I wanted to check if my webhook created that message so I can delete it if so
Message.author will be a bot with the info from the webhook message create. Message.webhook will link to the webhook that send the message if it was sent by one. If you want to work with raw api, check message.webhook_id
If my bot auto reset like 5mins / time with this method
is it oke? is it touch the Discord Develop TOS?
why do you want to reset your bot?
You rlly shouldn't do that, especially at a large scale
it might not even be possible to do reasonably once sharded.
@rustic nova@pale vessel I think I will use uptimerobot to wake up my bot if it offline
Just use a VPS, God damn
Oke I am going to use uptimerobot, hope it solve my problem
I mean go ahead if you want but if you use a VPS you don't need to bother with things like UptimeRobot and stuff like that just to keep your bot running
why wouldn't you use a vps, you can get some good ones for free
like oracle cloud free tier
good ones
i mean they work xD
i use em to host 2 mc servers and 2 bots and sofar i've had no issues
do you know any free vps?
Good VPSes aren't even expensive nowadays
You can get a pretty decent VPS up and running for a few bucks
vanilla?
because how the heck did u manage with only 1gb ram?
modded
they give 24gb
...what free tier is that tf?
There aren't really "free" VPSes, except for the ones that provide free trials which I wouldn't recommend, just throw in a few bucks and get an actually good VPS
kekw
i was gonna buy one but that seemed better than most and it was for free
ah yes the infamous oracle free tier
If you don't have a card skill issue
btw, how long does an average bot take to get approved
oracle support is just... god bless oracle
bro tell me about it
their support sucks so much
i opened multiple support tickets for issues i had
all i got was "open a ticket with our technical team"
not even satan would accept to bless oracle
I'm all in for java but...it doesn't deserve oracle
thanks, that's nice đ
sun sounds better
added two new commands to my bot for the next update
mods been needing them for a while
basically a way for staff to see if someone has premium, and what state its in, and one for them to move someones premium to another server for them
ive been having to move them by hand with sql commands, its a pain in the ass especially if im not at my pc
I am currently trying to parse a big JSON data using TypeScript
What's the best way to do it tbf, it's from Patreon and it's really messy
In all honestly, it sucks
Yes
It takes like
Forever if you want to validate their data
theres nothing better than json.parse
Using TypeScript
you can however isolate specific data instead of parsing everything
yeah, that's what I am going to do
using string manipulation
Doesn't make it better
it will make it faster
what kind of "better" are you looking for?
Less hell of implementing interface and type validation
I think even patreon-ts gave up because of now non-sensible their stuff is
you dont really need to type the entire response do you? you can just type whatever you actually need
Pretty much narrowing down is possible
The structure is just messy overall
i would just do something like const data = JSON.parse(body) as MyPartialDataType
and just implement the useful parts in the interface
Yes
It's funny
Because for whatever reason
They don't really try to group data and included as one
After all if you really need to get specific type you can just filter by type and the entire structure of the data are basically just attributes, id and type as necessary requirement
the next step is finding out which of the 124706124 copies of the same data is the correct one
I gonna just
SHove it to a database and deal with it
kahfjksdkdf
It's also that
WHY DO THEY FEEL THE NEED TO HAVE data of every freaking key value
It doesn't make sense, it makes it really hard to parse in a clean way
I mean, I can still do type validation
IRONICALLY
But it DOESN'T MAKE IT ANY BETTER
I'm uploading a large file with python using requests but I think what I'm looking for isn't limited to python. Is it possible to resume a download after interrupting a program?
that's up to the HTTP server serving the request, whether it supports range requests or not https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests
An HTTP range request asks the server to send only a portion of an HTTP message back to a client. Range requests are useful for clients like media players that support random access, data tools that know they need only part of a large file, and download managers that let the user pause and resume the download.
thank you
so, let's say I'm using opencv to draw stuff, is using GpuMat better than Mat if it's just 2d stuff?
if i edit a sent embed and add a ${role} ping
would it actually ping the role or only display the role?
neither embeds nor edits will ping the user
It's sent as a content above the embed.
so when editing the content and embed, it won't ping?
like this @uneven heath
you see the yellow stripe, but u didn't get the ping notif
Good example
+10/10
Anyway
Is it possible for one user to have multiple tiers in Patreon?
I saw the API return entitied tier as an arrary
I think only the highest counts
HUH
Then why does the API return the entitied tier as an array that doesn't make sense
99% of the api payload doesn't make sense
iirc, patreon includes all available tiers into it for reference
Yeah, that's the thing
No, the tier are included if you specify for it
But the entry in relationships.currently_entitled_tiers are declared as an array
Which btw
Only show the highest entry
I don't understand why it is presented as an array
How do I update my process.version for nodejs
Nvm says Iâm already using v18.8, node -v shows 18.8, but Iâm console logging my process version and it says 16.6 
Iâve never had this issue updating before so Iâm lost af
your process is getting the node from the wrong path
Hey all for what ever reason my bot's music modules would spam trackStart when someone loops the queue, however it would also spam the chat with "Starting to play songname here". Is there any solution for me to prevent that? (discord.js v13-lts, erela.js@2.2.3)
where code
for the issue reference
What does it say when you run which node?
v18.8.0
i believe the error happens at:
.on("trackStart", (player, track) => {
console.log("trackStart announced.")
client.channels.cache.get(player.textChannel).send(`Started playing **${track.title}** (**${format(player.queue.current.duration).split(" | ")[0]}**).`);
})```
where is that code in?
I'm not talking about the version, the which command outputs where the binary of the provided command is
Official documentation for the Lavalink client of Erela.JS
it's inside my lavalink/manager.js file
My bad lol
do you create a manager for every song?
i think yeah
Hmm weird, where exactly are you logging the process version? In an eval command or something?
Who use bdfd here
then that's ur issue
you're creating one listener every time you add a song
here is the loop code:
if (!player) return msg.reply(':error: There wasn\'t any video to repeat.');
if (player.queueRepeat) {
player.setQueueRepeat(false);
msg.reply(":success: Player no longer repeating.");
} else {
player.setQueueRepeat(true);
msg.reply(":success: Player now repeating.");
}
I'm running into "Object.hasOwn is not a function", which is only available after 16.9, but I updated and still can't put it online
no, show where u create a player
Do you use a process manager (such as PM2)? Or something like Docker?
PM2
I think PM2 is using the older Node.js binary from the different path
Ah rats
I would recommend uninstalling the older Node.js version
it should be: @lyric mountain (update: added the player creation)
const player = client.manager.create({
guild: message.guild.id,
voiceChannel: message.member.voice.channel.id,
textChannel: message.channel.id,
});
player.connect()
player.queue.add(res.tracks[0]);
message.channel.send(`Enqueued track **${res.tracks[0].title}** (**${format(player.queue.current.duration).split(" | ")[0]}**) at position ${position}.`);
if (!player.playing && !player.paused && !player.queue.size) player.play();
Will do, thank you so much
You're welcome, although I wouldn't recommend using the v18 releases of Node.js yet because we haven't marked them as LTS, the v16 releases should work just fine
You can run nvm install --lts to install the latest LTS release

pinging on edit doesn't ping me again
show where u create a player, not where u connect
const player = client.manager.create({
guild: message.guild.id,
voiceChannel: message.member.voice.channel.id,
textChannel: message.channel.id,
});```
well, idk then, but that's the only reasonable explanation
I'm seeing a distinct lack of await for things that look like they're async
ÂŻ_(ă)_/ÂŻ
I never used erela, but multiple listeners is the only thing that could explain the notification spam
There is no error, this is intended behavior because that listener is emitted every time the song is played, and looping is no exception
The problem is that it would spam the text channel which I'm trying to avoid.
You can check if the player is set to loop so you can return from sending the track playing message repeatedly
ah, just noticed it isn't a listener issue, but a 1-second song
then yes, that's a logic issue not code
u could check what's the last sent message by the bot, if it's the same as the one about to be sent, return
i did try that but the new problem is the bot wouldn't announce any new songs if the music is being in a loop
or check if song == nextSong
at last, managed to draw a rounded rectangle 
low-level drawing is awful
and I just noticed the corners have the wrong thickness
I did try with if (player.queueRepeat) return; but that didn't work so idk
Set a temporary variable, and give the songs an ID, if the ID of the previous song matches the new one, then don't send the track playing message, otherwise change the value of that variable to the current song ID
Basically
let prevSongId = null;
...
.on('trackStart', async (_, track) => {
if (track.id === prevSongId) return;
prevSongId = track.id;
await channel.send(/* Track playing message */);
});
so assign the id when a user uses the play command?
Yeah
Should i let ```js
let prevSongId = null;
Both code?
it didn't work
Show code then.
let prevSongId = null;
const player = client.manager.create({
guild: message.guild.id,
voiceChannel: message.member.voice.channel.id,
textChannel: message.channel.id,
});
player.connect()
player.queue.add(res.tracks[0]);
console.log(prevSongId)
prevSongId = player.queue.id;
message.channel.send(`Enqueued track **${res.tracks[0].title}** (**${format(player.queue.current.duration).split(" | ")[0]}**) at position ${position}.`);
if (!player.playing && !player.paused && !player.queue.size) player.play();
And what do you have in the trackStart event listener?
.on("trackStart", (player, track) => {
console.log("trackStart announced.")
let prevSongId = null;
if (track.id === prevSongId) return;
console.log(prevSongId)
client.channels.cache.get(player.textChannel).send(`Started playing **${track.title}** (**${format(player.queue.current.duration).split(" | ")[0]}**).`);
})```
You aren't supposed to initialize the prevSongId variable in the event listener, you're supposed to use the one you initialized before creating the player.
but it would be undefined then
It wouldn't be if it's defined in the same file
manager.js and the play command isn't in the same file path
Although what I meant by giving the songs an ID is to assign them to the track, literally, but I suppose that's not needed as the ID is from the player
So you can do this:
let prevSongId = null;
...
.on('trackStart', async (player, track) => {
if (player.queue.id === prevSongId) return;
prevSongId = player.queue.id;
await channel.send(/* Track playing message */);
});
there isn't any ID system
the only things you can do with the player.queue property
And that was the concern, you should assign them manually if it doesn't exist
uh someone said that i should try to check for the previous song and if it were the same song then try not to send it again
but i don't know how erela.js does that
not the previous, the next
erela has a queue, u can simply compare current against the next
Well they would technically have to compare the current one against the previous song to check if it's the same song to not send it, if they check for the next one they would have to use a variable to acknowledge it the next time
ah true, I forgot the event happens after changing songs
tbh, u can compare the current against the last song
since the previous will be sent to the end of the queue
and how to do that exactly
^
curr.id == queue[queue.size - 1].id
if that's how u get the id
Yeah, I don't know what information the tracks contain in ErelaJS but @ashen saffron you can do something like this:
.on('trackStart', async (player, track) => {
if (track.name === player.queue.at(-1).name) return;
});
damn js and its negative indexes 
there isn't any player.queue.id
Can anyone make me a logo?
no
see volt's answer
JavaScript doesn't really have negative indexes, the at() method was added a while ago to make it easier to reverse the indexing
ik, it's just weird to pass negative values for array access
uhhh i think it's player.queue.current.title
yeah it's title
Or just track.title since you just have access to the current track there directly
so uh
use the identifier since it's guaranteed to be unique
no
Also yeah better to use the identifier
if (track.identifier === player.queue.at(-1).identifier) return;
TypeError: Cannot read properties of undefined (reading 'identifier') ÂŻ_(ă)_/ÂŻ
I guess ErelaJS removes the current song from the queue list so there wouldn't be any songs in there if only a single song was queued?
Try checking for the size of the queue first then
if (
player.queue.size !== 0 &&
track.identifier === player.queue.at(-1).identifier
)
return;
it doesn't work
What's the current behavior?
and the code is:
.on("trackStart", (player, track) => {
console.log("debug: trackStart announced.")
console.log(`track identifier: ${track.identifier}`)
console.log(`queue size: ${player.queue.size}`)
if (player.queue.size !== 0 && track.identifier === player.queue.at(-1).identifier) return;
client.channels.cache.get(player.textChannel).send(`Started playing **${track.title}** (**${format(player.queue.current.duration).split(" | ")[0]}**).`);
})```
Weird, can you try logging both track and player.queue?
hm
Oh nevermind, I know what the issue is, the current way will only work if there are multiple songs in the queue, to make this work for single songs you would have to check if the player is being looped
Does the player give you a property to see whether it's being looped?
console.log(`track identifier: ${track.identifier}`)
console.log(`player identifier: ${player.queue.identifier}`)
console.log(`track queue size: ${track.size}`)
console.log(`player queue size: ${player.queue.size}`)```
eh
Wait a minute, it seems like track.size and player.queue.size gives different results in your logs, so what's the player.queue for?
Unless the 0 0 2 in your logs are something else
it's the timestamp for the current track
@ashen saffron alright looking through the documentation, I found a sold solution to this
let prevSongId = null;
...
.on('trackStart', async (player, track) => {
if (track.identifier === prevSongId) return;
prevSongId = track.identifier;
await channel.send(/* Track playing message */);
});
The solution is the one I proposed at first, just with the identifier property
okay will test if discord is up
also let prevSongId = null; should go to the play command too or just to the trackstart code one
Just to the track start one
oh okay
nothing:
Show code
.on("trackStart", (player, track) => {
let prevSongId = null;
console.log("debug: trackStart announced.")
if (track.identifier === prevSongId) return;
prevSongId = track.identifier;
console.log(`prevSongId value: ${prevSongId}`)
client.channels.cache.get(player.textChannel).send(`Started playing **${track.title}** (**${format(player.queue.current.duration).split(" | ")[0]}**).`);
})```
This is probably related to https://discordstatus.com/incidents/lrjvz22yb5qb
It is related to
The prevSongId variable is supposed to go outside the trackStart event listener
oh okay
production push at friday tsk tsk
okay it seems that it works
lmao
Anyone here experienced with opencv?
If so, how can I draw an image on top of another?
@wheat mesa https://github.com/Mistyerious/Conqur rate my starter code

I feel like a fucking genius
infer is so goddamn powerful
The shit I do for accurate type narrowing
mapped union types are so painful if you don't want them inside an object
hi uhmm i wanted to ask if someone can send a code in python to make so when someone votes to send a messasge
good luck getting people to write code for you here
no i dont want you to write them
I think it would be better to refer to the docs for the top gg api library you're using and then check google if someone else has a solution
if you have already to sent me but if you dont have the code its okay
what you need to know is how to listen for votes and how to send a message to a specific channel. If you know that, you know how to solve your own problem
we don't "send code for X", but we can help if you have something already going
ok thanks
it dies everyday
based
not based
angular
rounded
good now do parallelization :troll:
Waffle
just in time
I have a question
match parsed {
WebMessage::MessageCreate(message) => message_create(message),
WebMessage::MessageDelete(message) => message_delete(message),
}
I am matching an enum, and I have one question about it so far
Do I really have to do WebMessage::MessageCreate()
Why can't I just do MessageCreate(message)
no idea what this means
multiple threads
waffle waffle, thou who delve deep into low level languages, have u ever used opencv?
hold on ill help in a sec
ok ty
because that could lead to scoping issues with other enums
say you have ```rs
enum MyOption<T> {
Some(T)
None
}
that could cause issues with implicitly imported types like the default Option<T>
Mmm thats fair
also nope :C
It makes more sense now why I was getting that error earlier
I looked through stack overflow and got my answer even tho it wasn't to the question I was asking kek
My websocket stuff is one step closer to being completed.
Now I just have to fully implement everything now that I got a method to the madness
Also, I have a qualm against just outright closing the socket if they provide false data
Like say the event name is right, but they misspelled one of the data properties
or they accidentally leave one out
sounds like a bad idea to allow websocket connections to send false data
Mmmm true
But I need to at least provide a reason why
right now it just closes without a reason
but idk how to send the reason with the close
that would be annoying for both ends, you'd have to handle it and then the lib dev would need to figure out why their thing is still working despite not sending correct data
Fair point
but so far the reason for the close is literally nothing
so its even harder to tell why something happened
nhe
just let them suffer like C devs whenever they get a segfault with no other info
but I dont see a way to provide a reason with axum's websocket implementation
I nearly just had a fight with it

I was making big oopsie and was not properly typing my helper functions
I was trying to move it into there and use it other places
Now I need to implement a database connection
đ
It's funny that people complain about error messages like from java, while there are way waaaaaay worse messages
Worse than big errors are errors that don't make sense or no errors at all
well java error messages do look awful
At least they do point at the error
except when they don't 
interaction is working fine
but stil i got This interaction failed
why?
and what are the solutions
Try debugging your program more (e.g. logs) since we can't tell anything with that
interactions expire after 15min
Most commonly, buttons that are older than that will always fail on the user's end. The INTERACTION_CREATE is still sent, so you can ignore those errors.
Trying to respond to the interactions via rest will return a 404 Unknown Webhook
Not responding in time will also expire the interaction and cause it to fail
If you're using the gateway for interactions, most of the overhead comes from decoding gateway messages especially at scales with a large volume of inbound messages. Only really lightweight ws solutions can keep up and even then, It'd be advised to put your sockets on a separate thread (not all on separate threads unless you have a load balancing technique that round-robins between all or divides them roughly equally)
Another solution on the gateway end is to only use intents you really need. I've migrated to slash commands pretty much entirely and I do not miss all of the message creates I used to get
told you C:
I am also sure what I am doing to solve it is not recommended at all
what are you struggling with
Well heres where it started
pub fn message_delete(message: MessageDelete, socket: &WebSocket) {
// This here will handle everything related to deleting a message, e.g removing the message to the database and then responding back to the
// client with the appropriate data
socket.send(Message::Binary(serde_json::to_vec(&message).unwrap()));
println!("Message ID: {}\n", message.message_id)
}
So I have this bit of code, and it is crying cause of the socket.send usage
Cannot borrow immutable local variable `socket` as mutable
so I made socket: &WebSocket -> socket: &mut WebSocket
and now
Ok(parsed) => {
match parsed {
WebMessage::MessageCreate(message) => message_create(message, &socket),
WebMessage::MessageDelete(message) => message_delete(message, &socket),
}
},
this is crying cause message_delete(message, &socket) is not &mut WebSocket
so I did message_delete(message, &mut socket)
Is this the proper way to handle this?
Yes
Okay next question
What does it mean by Cannot borrow immutable local variable `socket` as mutable
How is it considered mutable?
yea
socket.send is likely a function that requires a mutable borrow of the socket, aka the internal impl probably looks something like fn send(&mut self, otherstuff)
Ah
So to use a mutable function on the socket you need a mutable borrow of it
you're right it does
this is a lot more fun than I thought it'd be
I thought I would be pulling my hair out doing this in rust
me out here manually debugging my bytecode
like 90% sure that's wrong
yes I know what this all means
basically I have bytes that signify things in the beginning and now it's successfully using that information to decode the rest of the file
strings work too
cool
Hello, when I type member.guild.id in the guildMemberAdd event, I cannot get the server's id, how should I do this?
Do you get any errors?
const data = require("../models/Guild")
module.exports = {
name: 'guildMemberAdd',
async run(member) {
const config = await data.findOne({GuildID: member.guild.id})
if(config.Autorole.active === false) return;
if(member.user.bot) return
if(config.Autorole.active === true) {
let role = config.Autorole.role
member.roles.add(role)
}
}
}
How are you loading these events
module.exports = (client) => {
const events = fs.readdirSync("./events/").filter(f => f.split(".").pop() === "js");
events.forEach(f => {
var event = require(`../events/${f}`);
var client = global.client
client.on(event.name, (...args) => event.run(client, ...args));
console.log(`${f}`)
});
};
this is my eventLoader file
there's your issue
What should I do?
your run function in the guildMemberAdd event is expecting the first param to be client
client.guild.id isn't a thing
How can I fix?
I don't even know if your event loader works, but you can try async run(client, member)
in your event
I did ty
@wheat mesa getting linker errors in cargo install 
@earnest phoenix you tried using run: async? Instead of
The thing is that "member" isn't catching
No client
Look line 6
And look error
Why he put (...args)
Like
There's no args
Huh
ofc there is...?
whatever you get from the event e.g guildMemberAdd returns a member object of the user who joined
so ...args if that's even the correct way to do it would be a member object
thats the typical way
I know
So it catch what your using or it changes to client or null
I think that he need to try that
Idk
Well, byee
So I have a many-to-many relationship table store in my database (Patreon and Tiers)
Currently I am setting up in a way where an User can have many Tier and a Tier can have many User
The question now is that when the user update their tier option, how would I deal with purging the junction table
^ Yes, it's a many to many because gods know why Patreon decided like that
I mean its not bad for it to be a many to many
Yeah, but I am thinking on how I would deal with the junction table
Let just say I can obtain a list of user tiers through their payload
You can cascade delete and add the user to a new tier when they wanna join another
So completely delete all of previous entry and add the new one?
Essentially yea
It should delete them from the tier table and then in turn delete the tier from the user
so you can just add a new one
Oh yeah, that's a way.
I essentially wired up to some hooky shit lol
I think it would be more correct that I would delete them from the junction table
lol
or that
Since my database saves both former_patron and active_patron anyway
This should not be a problem if I am refreshing the database every 24 hours right?
I assume it should not
Well, let's hope there is no edge case...
That would be scary
I gonna just do this then
Add all entry from Patreon API
After then check if there is any entries that doesn't exist in the Patreon API (If the user change tier, the new tier in the database doesn't reflect that in the payload)
It is confusing but I think this is the correct way to do it?
#commands for bot commands
What would be the best datatype to use in my postgres table for storing a user id, in my rust structs all my ids are u64's but idk what datatype would be suitable for postgres
should I just use NUMERIC ?





