#development
1 messages Β· Page 180 of 1
client.on('ready, async () => {
await client.application.commands.set(arrayOfSlashCommands)
})
Ummm where do i put this 
index but listen to @deft wolf first before me
Okie
There are 2 types of commands: global and server. Your code tries to create server commands on a server where your bot is not allowed to do so. You most likely added the bot without application.commands
There is everything you need: https://stackoverflow.com/questions/65539808/missing-access-for-slash-commands
ohhhhhhhhhhhhh
Fk yea bro
@deft wolf still same
Then I can't help you if the bot is on the server where you want to create commands and you added it again with the appropriate permissions. This is something you have to deal with yourself because all I could do was already done
i added the wrong guild id first but now errors change
Yep, command name must be lowercase
sql has a time and place which isn't always. Object storage is no place for sql and is more suited for solutions like redis
by "Object" I mean ephemeral data which is usually a json encoded string
The Object storage that people refer to when talking about cdns is its own monster
How am I just now discovering ??= In nodejs.
redis is more suited for fast I/O, not so much as a permanent storage solution
aka a cache
but yeah, I do agree that no-sql is the best option when you need to store a lot of arbitrary data with no relationship whatsoever
yup I said ephemeral for a reason
redis does have persistence but it isnt meant to be persistence
What does it do
assigns if null
It's an null coalescence assignment
It's like x ?? y
But it assigns Y to x if x is null.
let x;
const y = 2;
x ??= y
x is now 2
Great for default values.
it works especially great for web/app frameworks like react or flutter
because it'll assign a component to a variable on the first render, and then use it without recreating
im getting: error on saving mongo data
let Guild = client.mongoManager.Guild;
let id = int.guild.id;
let guild = await Guild.findOne({ _id: id });
if (!guild) {
guild = await new Guild({
_id: id,
}).save();
guild = await Guild.findOne({ _id: id });
}
guild.roles.push({
contract,
role,
});
await guild.save()
circular structure means you have an object inside itself
in your case, if I'd have to bet, it'd be ```json
{
guild_id: "12345",
members: [
{
user_id: "123",
guild: {
guild_id: "12345",
members: [
{
user_id: "123",
guild: {
guild_id: "12345",
members: [
...
]
}
}
]
}
}
]
}
the guild has members, which have that guild, which have members, which have that guild, ad infinitum
so either remove the guild from the member, or remove the members from the guild
optionally, use a proper database for relational data
okay indeed i must give you that it depends on what it's gonna be used for
but whenever i need to create a normal program that needs to store data, i usually would prefer sql over nosql anytime
definitely
i haven't used nosql a lot of times, just a few for some smaller projects. However, what i really liked about sql over any nosql database was that in sql you actually can see the whole structure of the database as a sort of table
which is like so easy to search through and it provides a clear overview of what you are doing
it's structurally well defined. Not sure whether something like mongo uses such way of storing and displaying as well?
goofy code
this u πΈ
my regexing skillz are great
we got something in common

public static void BFS(int[][] graph, int source) {
state[] explored = new state[graph.length];
int[] predecessor = new int[graph.length];
Queue<Integer> frontier = new LinkedList<>();
colors[] coloring = new colors[graph.length];
coloring[source] = colors.RED;
for (int i = source + 1; i < graph.length; i++) {
explored[i] = state.UNDISCOVERED;
predecessor[i] = -1;
}
explored[source] = state.DISCOVERED;
predecessor[source] = -1;
frontier.add(source);
while (!frontier.isEmpty()) {
int CurrentElement = frontier.remove();
for (int i = 0; i < graph.length; i++) {
if (graph[CurrentElement][i] != 0 && coloring[CurrentElement] != coloring[i]
&& explored[i] != state.DISCOVERED) {
predecessor[i] = CurrentElement;
explored[i] = state.DISCOVERED;
frontier.add(i);
if (coloring[CurrentElement] == colors.RED) {
coloring[i] = colors.BLUE;
} else {
coloring[i] = colors.RED;
}
}
}
}
System.out.println("\nMatches and Chosen Colors:");
for (int i = 0; i < edges; i++) {
System.out.println("Vertex " + i + " Color: " + coloring[i]);
}
}```
goofy, but i mean it works
I only like goofy code when it's fast
its runtime is 0(V + E)
yeah but this code is a 2-coloring algo
it's hard to make it faster than this i think
unless i remove bfs and move on to something faster..
bipartite matching maybe? Using capacity scaling or edmond karp?
Microsoft and Mojang do have really goofy code
but 
is that mojang?
bro i just realized, null === ... hell nah
why tf they checking null values like that
goofiness
I feel like I'm doing this wrong yet it works and don't know how to make it better
why arrays
linked creators
it's marketplace creators
when one of the creator names uploads an item the channel gets notified
and want only one linked channel per guild
- I need to do it that way because I'm using firestore
it's weird
there are so so many edge cases that it makes me want to die faster
i just find that painful
it is
the bot has it's own custom made account linking system using oauth which was even more painful to make a working api wrapper for
mostly because the microsoft official library sucks ballz
lol
everything was fine until i registered second command
@warm surge @grim aspen @deft wolf

Names cannot have capital letters or spaces
Man imma have to start setting a schedule in this channel of when Iβm available. Was about to go to bed.
You arent obligated to help. Just live your life
True
yes
why does that look cursed
js itself is cursed
@sharp geyser sorry for being inactive with your project, i've been really busy lately

the first half of 2024 is not really the best time to code
that's just the syntax for using variables in keys ig
ngl i did not know that
it's good for one liners, that's for sure
yea but I see no practical use outside of it
how do I treat functions as variables guys
this is quickly becoming a clusterfuck of a language
I guess I check the type of the callee's arguments, and if it has a function I look at my functions table for what was passed in
I am rubber ducking because this problem is very specific to my poor design decisions and I am sorry
this makes sense when you think about how js handles properties, you can access props of an object like so object["propertyName"]
so it makes sense you can define objects with variable keys like that
so you could directly pass an object that includes the key and values instead of doing const obj = { ... }; obj[key] = "value";
someFunctionCall({ [key]: "value" });`
fuck this is disgusting
I guess it's my fault for having a TypeAnnotation enum and a TypeInfo enum
but to my actual question, what would be the "idiomatic rust" way of doing lines 42-45
Some combination of .iter().some_function().collect()
I tried .map but since from_annotation returns a result, the closure wants to collect into a Vec<Result<TypeInfo, TypeError>> when I really just need it to bubble errors up and collect into Vec<TypeInfo>
I mean if the key is dynamic sure
but like
yea but like I dont see many cases where its needed so I guess i've just never seen it
same ngl
its a cool thing to learn
@sharp geyser ```json
{
"table_name": "test",
"columns": [
{
"name": "test2",
"columnType": "text"
},
{
"name": "test3",
"column_type": "int",
"default": 0,
"not_null": true
}
]
}
parsing the entire JSON here or just the column_type property?
well I want to parse the default field into its proper rust type, so if they provide a int then it will be parsed as an int if its a string then a string and so on
guys, i spent 4 months learning haskell. I am reasonably good at it, but is there any function use for it? Do any jobs require haskell.. it seems like an old fucking language no one uses 
π
ask xetera maybe xD
you can use https://docs.rs/serde_json/latest/serde_json/value/enum.Value.html for that
Represents any valid JSON value.
if you are unsure with the type
does xetera know haskell?
he's sure about the type but he doesn't know how to parse it/make a deserializer for it
i believe so
hm
I mean it's a fun language don't get me wrong, it's really compact and powerful but to be fair imo imperative/oop obliterates functional programming
i mean, if the purpose of the property is that it can handle various types, why make another enum just for handling multiple types when serde_json::Value exists
maybe check his projects and find inspiration
fair
buildM :: (Monad m) => m (Maybe a) -> m [a]
buildM mm = do
ma <- mm
case ma of
Just a -> do as <- buildM mm; return (a:as)
Nothing -> return []```
like the syntax is so cursed but it grew onto me and now i can't stop using haskell for computations in my code.
i could explain it if you'd like
like in what way
like I have a sanitize_input function that makes sure it is only a-z 0-9 and it takes in an input
what's your code
let data_type_str = sanitize_input(column.column_type.to_owned());
or is it better to make the sanitize_input type be &String instead?
yes
and then just do &column.column_type
What does to_owned actually do? I know it essentially makes a new reference
or at least thats what I assume
it basically clones the string
I see
if a reference might outlive the original value, that must be owned
the way i grasped the concept is just that a monad is an unpure function. Haskell basically relies on pure functions, whenever you use the same params you will always get the same output. Obviosuly in other languages that is not the case. However, suppose you want to do something unpure, say you want to generate random data or get console.input (this is something that's not always the same as haskell likes), you must use monads. See monads as regular boxes that wrap around a certain value. See it as a condom protecting the values inside \0/ while it's being passed around functions.
In the end, to be able to use and extract values from that condom you must use <- or use applied chaining (many different other ways as well). For all functions that use such unpure actions such as console inputs or generating random numbers, you MUST have as an output the same condom wrapper. that's it
this is for you @radiant kraken hope it helps
Also is it better to use Result for functions that return something that could possibly error?
yes
Seems like result is kinda like a try/catch 
oop
it's way better even because it requires you to handle the error before retrieving the output of a function
Does using unwrap on a result defeat the purpose of using the result?
Cause doesn't the unwrap mute the error?
actually no
it panics if it runs into an error
no
though you don't really have to constantly use unwrap
since if it panics it stops the entire program
i recommend you make use of the ? operator instead```rs
fn some_func() -> Result<i32, YourErrorType> {}
fn my_func() -> Result<T, YourErrorType> {
let value = some_func()?;
// value is i32, if it errors, it immediately propagates the error out of this function
// to use the ? operator, the return type of the function calling it must be a Result, and the error type matches too
}
hm
it seems I can't use it on something that returns a Result<String, HttpResponse> cause String doesn't implement trait FromResidual
wdym?
error[E0277]: the `?` operator can only be used in a closure that returns `Result` or `Option` (or another type that implements `FromResidual`)
--> src/tables/create_table.rs:38:72
|
37 | .map(|column| {
| -------- this function should return `Result` or `Option` to accept `?`
38 | let data_type_str = sanitize_input(&column.column_type)?; // Ensure uppercase for consistency
| ^ cannot use the `?` operator in a closure that returns `std::string::String`
|
= help: the trait `FromResidual<Result<Infallible, HttpResponse>>` is not implemented for `std::string::String`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0277`.
can i see the code
use actix_web::{HttpResponse, post, Responder, web};
use serde::{Deserialize, Serialize};
use serde_json::{Value};
use sqlx::{Pool, Postgres};
use crate::database::sanitize_input;
#[derive(Deserialize)]
struct CreateTable {
table_name: String,
columns: Vec<Column>
}
#[derive(Deserialize)]
struct Column {
name: String,
#[serde(alias = "columnType")]
column_type: String,
default: Option<Value>,
primary: Option<bool>,
#[serde(alias = "notNull")]
not_null: Option<bool>
}
#[derive(Serialize)]
struct TableCreation {
success: bool,
reason: String
}
#[post("/")]
pub async fn create_table(pool: web::Data<Pool<Postgres>>, table: web::Json<CreateTable>) -> impl Responder {
let query = format!(
"CREATE TABLE IF NOT EXISTS {} ( {} );",
sanitize_input(&table.table_name).unwrap(),
table.columns
.iter()
.map(|column| {
let data_type_str = sanitize_input(&column.column_type)?;
let default_clause = match &column.default {
Some(default) => format!("DEFAULT {}", sanitize_input(&serde_json::to_string(default).unwrap()).unwrap()),
None => String::new(),
};
let not_null_clause = if column.not_null.unwrap_or(false) { " NOT NULL " } else { "" };
format!("{} {} {}{}", &column.name, data_type_str, default_clause, not_null_clause)
})
.collect::<Vec<String>>()
.join(", ")
);
HttpResponse::Ok().body("Works")
}
the map closure doesn't return a Result<String, SomeError>, it returns a String
well yea cause it returns a format!
does actix_web allow functions to return a Result?
it should yea
Honestly I think I could be doing this all a lot better
but idk
I am not used to results even my sanitize function is probably ass 
pub fn sanitize_input(input: &String) -> Result<String, HttpResponse> {
let pattern = Regex::new(r#"[^a-zA-Z0-9]"#).unwrap();
if pattern.is_match(input.as_str()) {
Ok(String::from(input))
} else {
Err(HttpResponse::BadRequest().json(SanitizeError {
reason: "You provided an unauthorized character in one of your fields (can only be a-z 0-9)"
}))
}
}
ah
this is ass
im pretty sure even if it error it wont use the HttpResponse thing
π
you can make sanitize_input return a Result<String, actix_web::error::Error> instead
and ```rs
Err(actix_web::error::ErrorBadRequest(serde_json::to_string(json!({
reason: "You provided an unauthorized character in one of your fields (can only be a-z 0-9)"
}))))
and instead of using map, use a for loop
huh
This isnt possible btw
why?
oh wait
to_string takes in a reference
I was reading the error wrong and got confused
π
Err(ErrorBadRequest(
serde_json::to_string(&json!({
"reason": "You cannot use unauthorized characters such as semi colons or anything that is no numbers or letters."
})
)?))
this is what I had to do
?
Err(actix_web::error::ErrorBadRequest(String::from("{\
\"reason\": \"You provided an unauthorized character in one of your fields (can only be a-z 0-9)\"\
}")))
to use multiline strings in rust, just end your string literal with \
oh okay lol
you dont need to use ? here, just use .unwrap
since the error is not worth propagating
π
you told me not to use unwrap
I had unwrap before but then swapped it to use ?
serde_json::to_string should never error as the input would always be a valid json value
fair
the `?` operator can only be used in an async function that returns `Result` or `Option` (or another type that implements `FromResidual`) [E0277] Help: the trait `FromResidual<Result<Infallible, actix_web::Error>>` is not implemented for `HttpResponse`
I still dont understand what this error is actually saying other than I am doing it wrong
:D
send code
pub fn sanitize_input(input: &String) -> Result<String, actix_web::error::Error> {
let pattern = Regex::new(r#"[^a-zA-Z0-9]"#).unwrap();
if pattern.is_match(input.as_str()) {
Ok(String::from(input))
} else {
Err(ErrorBadRequest(
serde_json::to_string(&json!({
"reason": "You cannot use unauthorized characters such as semi colons or anything that is no numbers or letters."
})
).unwrap()))
}
}
#[post("/")]
pub async fn create_table(pool: web::Data<Pool<Postgres>>, table: web::Json<CreateTable>) -> impl Responder {
let query = format!(
"CREATE TABLE IF NOT EXISTS {} ( {} )",
sanitize_input(&table.table_name)?,
""
);
HttpResponse::Ok().body("Works")
}
create_table must return a Result<..., actix_web::error::Error> as well
just replace HttpResponse::Ok().body("Works") with Ok(String::new("Works"))
and replace impl Responder with Result<String, actix_web::error::Error>
what status code?
like 200, 404, 500 etc
ErrorBadRequest already does it for you
it returns an actix_web::error::Error with status code 400
that only handles bad requests not successful ones. What if I wanted to return a status code of 201 as this endpoint creates something
wdym?
Well I have to return something from the sanitization either the input back or a bool value saying it is sanitized
you can still use ? on the sanitation function and use the String output
the sanitation function return type just needs to be Result<..., actix_web::error::Error>
oh okay
So wait how does serde_json::Value work?
serde_json::Value works for any json value
or json property
it's like JavaScript any
but how do I know what the type actually is?
I know you can do something like unwrap_or(Value::as_str)
but that casts it no?
match value {
serde_json::Value::String(s) => { ... },
_ => {},
}
I see
@radiant kraken Is there an easy way to do this for loop? cause I feel like making a variable and setting it in the for loop is not the best idea
let mut columns = "";
for column in &table.columns {
let default_type_str = sanitize_input(&column.column_type)?;
columns = format!("{}", "").as_str();
}
let query = format!(
"CREATE TABLE IF NOT EXISTS {} ( {:#?} )",
sanitize_input(&table.table_name)?,
columns
);
also ignore the fact this is overwriting the columns variable each iteration I know that I am tired π
just create a vec, push stuff into it, and then join
@radiant kraken Omg I am trying to do something that is requiring me to use lifetimes I think
π
https://hatebin.com/jpdhhziizy I made a convert_default method on the column so I can convert the default value directly into a string as I don't really need it to be anything else if all I am using it for is to build an sql query
but I was googling and it seems that the error i was facing prior to trying to use lifetimes was because it didn't know how long the reference was going to last so I needed to use lifetimes to specify such thing
for context here is the error I was facing before
cannot return value referencing temporary value [E0515] returns a value referencing data owned by the current function
impl Column {
fn convert_default(&self) -> Option<String> {
match self.default {
Value::String(string) => Some(string.clone()),
Value::Number(number) => Some(number.to_string()),
Value::Bool(bool) => Some(bool.to_string()),
_ => None
})
}
}
``` does this work?
yes
π
why didnt I think of it
@radiant kraken bro wtf am I seeing in my console rn
I mean I guess the only important thing is called `Option::unwrap()` on a `None` value
Seems to be happening on my convert_default method hm
OOOOO
Its because I don't always supply a default value
impl Column {
fn convert_default(&self) -> Option<String> {
match self.default.as_ref() {
Some(v) => Some(match v {
Value::String(string) => string.clone(),
Value::Number(number) => number.to_string(),
Value::Bool(bool) => bool.to_string(),
_ => String::new()
}),
None => Some(String::new())
}
}
}
what do you think of this null? I have no idea what it actually is doing but internet helped me come up with it :D
and it seems to work
why use an Option when the function constantly returns Some
Again this was from some internet post
I dont understand it myself
bru
impl Column {
fn convert_default(&self) -> String {
match self.default.as_ref() {
Some(v) => match v {
Value::String(string) => string.clone(),
Value::Number(number) => number.to_string(),
Value::Bool(bool) => bool.to_string(),
_ => String::new()
},
None => String::new()
}
}
}
So what exactly was the above doing?
like before yours
what I posted
converts the enum to a String representation of it
this?
gotcha
any recommends for free hosting?
Nope
Using a computer at home is the only one id realistically use.
Well, oracles free vps's are actually not bad. If you don't mind arm, and don't load them up too much(they have harsher restrictions now) and you must provide a debit card even though it's free.
no not necessarily. Well, mutable variables are another monad denoted by IOREF. However, monads are a collective box of all sorts of unpure functions/usages. So think about:
IOREF -> mutable variables
IO -> for input ouput actions, hence unpure again.
And many more, you can also create your own monads to denote that a custom data type is used for unpure actions
the wrapper is not pure, it's basically just a box that holds values that's it. Just those values are unpure as they were generated from an unpure action/function
if you are really into it, hit me up in my dm and i can give you a more in-depth explanation with code etc
what do you guys think about this ransom font generator 
Just made it, but kinda not happy
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
yeah, I don't really know how I should do that
I mean I can split words, breakline and then resize them, but I dunno
One message removed from a suspended account.
ahh you mean the mobile mode? there is an option on the inspect element tab
One message removed from a suspended account.
looks like this, but ik on actual mobile looks worse
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.

god adding translations to a bot is annoying https://fs.rjns.dev/v/SnbUrJMpCkrbXwqbbS
13 files in 4 hours
even with copilot
damn I just have an api that does it for me and a /config command to pick the language
that's why you always begin a project with i18n in mind
adding it afterwards isn't doable
btw you have a lot of levels there, are you using a locale file or what?
yeah in combination with a website
idk what webui is
but well, a thing I dont recommend is over-specializing your strings, try to reuse as many strings as possible
else you'll do more than double the work translating those
yeah I reuse alot
had to adjust my format a few times to do that
commands take the longest, buttons, modals, etc are pretty quick
so that keeps my motivation up
hopefully
Can you elaborate on this? Ive tried adding localization before and I feel I always overcomplicate it
if you narrow your strings too much, you end up having like 3-4 nearly identical strings for every entry on your locale file
try to make them as generic as possible, so you're able to reuse strings
you might also use template strings for things that only a few words change
if you want not to overcomplicate, remember that for i18n u only need 2 things: an acessor and a locale file
the acessor should only be acessing that file and reading the specified key (and storing it in a cache, with ttl)
the file should be a simple key-value structure, personally I prefer the properties structure but yaml, ini, xml, whatever also works
I dont avise using json/xml as you need to parse the whole file before being able to retrieve a single line, so you're forced to keep the full file(s) in memory all the time
well I use json because its easy to read and I need all in memory anyway
you dont, some strings are accessed much more often than others
this becomes a problem on very big locale files, not so much on smaller ones
well I would consider ~100kb (estimated end result) small
it grows when parsed
also u need to consider you'll be keeping more than 1 file in memory
yeah, compared to what else im doing its nothing
I think my dev instance with everything cached for later used is like 700mb
I have 128gb available
@wheat mesa @radiant kraken okay so I have something regarding this I want to ask. I know previously I was thinking of not letting them use their own database urls but looking at the docs for sqlx, I can theoretically create pools for multiple databases. So I can create a pool and set it to like a map/hashmap and then call upon it whenever they are making requests.
Do you think this would work in your professional rust experience?
sounds good
okay good :D
plus my rust experience aint even professional
This makes it a lot easier as all they need to do is just provide their postgres user + pass and boom
i've never made a full-stack rust app before
plus I wont need to worry about sql injection as they can only affect databases attached to them

who sql injects themselves 
you still a professional in my eyes

@radiant kraken should I use &'static or should I use something else? iirc you mentioned Arcs
send me your code for context
pub struct DatabaseState {
pool_manager: HashMap<String, Pool<Postgres>>
}
pub async fn create_pool(database_url: String, state: Data<DatabaseState>) -> Result<&'static Pool<Postgres>, actix_web::error::Error>{
let pool = state.pool_manager.get(&database_url);
if pool.is_some() {
Ok(pool.unwrap())
} else {
state.pool_manager.insert(&database_url, PgPoolOptions::new().connect(&database_url).await.expect("Failed to connect to the database, please check your "))
}
}
nope that's invalid

well I have yet to implement returning an error but what is invalid
and what should I do instead
remove 'static
it requires a lifetime
do you really have to return a reference?
Okay so ik the function says create_pool but it is meant to get the pool if it exists or create one then return it
What else should I return?
Option<&Pool<Postgres>>
ah
Should I do pool.unwrap().clone()?
hm
try this perhaps?
use core::marker::PhantomData;
pub struct DatabaseState<'a> {
pool_manager: HashMap<String, Pool<Postgres>>,
phantom: PhantomData<&'a ()>,
}
pub async fn create_pool<'a>(database_url: String, state: Data<DatabaseState<'a>>) -> Result<&'a Pool<Postgres>, actix_web::error::Error>{
let pool = state.pool_manager.get(&database_url);
if pool.is_some() {
Ok(pool.unwrap())
} else {
state.pool_manager.insert(&database_url, PgPoolOptions::new().connect(&database_url).await.expect("Failed to connect to the database, please check your "))
}
}
me no understand what that is
PhantomData is a value without a size that let's you explicitly add a lifetime generic to a struct without references in it
hence, marker
to declare it in a struct initiation you just do ```rs
StructName {
phantom: PhantomData,
}
it's 0 bytes in memory so it has no overhead
Yeah itβs just to make the compiler happy
I donβt understand thoughβ¦ why do you need multiple different connections?
So that way I can handle multiple databases?
And me happy, too
But why do you need to handle multiple databases at the same time?
I also donβt really know what youβre making, I forgor
Because I am making a service for roblox devs to store data externally rather than use datastores.
Each roblox dev when signing up gets their own pg user that they can use to make new databases and in turn tables on those dbs
Sounds like devops hell ngl π
The querying/mutation of those databases has to be done over rest api though as roblox is limited on what you can do
i dont think roblox devs know what postgres even is
So youβre building a rest api for managing data
Essentially yes.
I still donβt really understand why that requires multiple pools
Well because the rest api needs to know what database to query?
What database to use to make new tables?
Hmmmm maybe I understand what youβre saying now
I can't simply use a pg user with root access
that is dumb
so I am using their already made pg user accounts
so they can only manipulate dbs they made
I see
Also if anyone tries and sql inject they are fucking themselves over

But yea, thats why I am creating multiple pools.
I mean ideally you just use prepared statements to prevent injection in the first place but idk how youβre structuring it
You can't use prepared statements with sqlx on table names and columns
Since this sounds like something that beginner devs would use more than advanced devs, why bother letting them query the database themselves? Why not just mimic a datastore-esque API and expose it to endpoints
Seems like it would be a little safer and simpler to implement
How so?
Like I get what you mean but I am also not sure I am understanding
I am pretty sure I am going for what you are talking about either way.
Idk how datastores work in roblox but I assume that itβs not super complex, probably supports loading, mutating, and saving data
Sounds like supporting SQL is a nightmare for devs that likely donβt know how to use it
Unless Iβm misunderstanding what youβre doing
Well I am trying to mimic roblox datastores but use a relational database instead
Whyβs that
Honestly, no idea just thought it'd be fun 
Though I do admit that I dislike how unfamiliar datastores are in roblox
it feels more restrictive
With a relational database I can create one-to-one, one-to-many and even many-to-many table relations where tables rely on each other and make fetching data easier
if I fetch a user, I can get any inventory data associated to that user as well
instead of how roblox right now you have to make multiple datastores
or you could save stringified json, but that requires you to have to use something to decode/encode the data as well
its a whole extra step
@sharp geyser did the phantomdata work?
Oh no idea I got sidetracked by how ima make the module for this so it seems similar to Roblox DataStores lol
Iβll test it here in a second after my shower
So it did fix some of the lifetime issues
I have thes errors now: https://hatebin.com/qwtmqtshkh
As far as the first error goes, I don't really understand what I should do to fix it, the second one is also a bit confusing on what it wants me to do as I don't see how it is borrowing anything. The third one I get it says to use .clone but you've said to stay away from it as much as possible so idk if I should listen to the compiler
Okay so my shitty solution to some of these problems
pub async fn get_or_create_pool<'a>(database_url: String, state: &'a mut Data<DatabaseState<'a>>) -> Result<&'a Pool<Postgres>, actix_web::error::Error>{
if let Some(pool) = state.pool_manager.get(&database_url) {
Ok(pool)
} else {
let pool = PgPoolOptions::new().connect(&database_url).await;
match pool {
Ok(pg_pool) => {
state.pool_manager.insert(database_url.clone(), pg_pool.clone());
Ok(&pg_pool)
},
Err(err) => {
Err(ErrorBadRequest(
DatabaseError {
reason: String::from(err.to_string())
}
))
}
}
}
}
Still facing issues regarding the match statement's Ok block
error[E0596]: cannot borrow data in an `Arc` as mutable
--> src/database.rs:43:17
|
43 | state.pool_manager.insert(database_url.clone(), pg_pool.clone());
| ^^^^^^^^^^^^^^^^^^ cannot borrow as mutable
|
= help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `Arc<DatabaseState<'_>>`
error[E0515]: cannot return value referencing local variable `pg_pool`
--> src/database.rs:44:17
|
44 | Ok(&pg_pool)
| ^^^--------^
| | |
| | `pg_pool` is borrowed here
| returns a value referencing data owned by the current function
error[E0425]: cannot find function `sanitize_input` in this scope
--> src/tables/create_table.rs:66:9
|
66 | sanitize_input(&table.table_name)?,
| ^^^^^^^^^^^^^^ not found in this scope
ugh no matter what I try I don't get why it isn't working
Hey @earnest phoenix, the link to your Will of Steel support server on top.gg is expired.
https://willofsteel.vercel.app/ -> Community
Hi
finally, the last content tag in my game's content is implemented π
saved the least common tag type till last
basically is a way for the user to input some information they know, from things theyve seen in-game, basically solving riddles and stuff
location gating based on previous knowledge
if you want to modify a value inside an Arc, it needs to be in a Mutex
so Arc<Mutex<T>>
i've seen alot of people use prisma nowadays, i know it's a database client
is it any good?
its a database ORM
idk how to describe it
but it works with many database types without having to adjust the code much
is it sql based?
i see, is it like a client that connects your code to the database model?
what's the point of that if many databases offer standalone usage?
duckdb for example, othre SQL based databases etc
basically the same as create table i see
but what is the benefit of using prisma?
Why can't i just use a standalone sql based database
honestly not sure
but i know its very easy to migrate databases without having to rewrite queries
this might help
i see it being used a lot tbf
tldr
orm should stand for objective restrictive mess
i find prisma too complicated for what it does
they lost me at "thinking in objects"
which is why i just use a regular db client / package
i see, but let's be real if you have created a SQL based model you only need to change the way the client queries to the database which makes this prisma nullable, sql remains sql 
yes
i'll stick to how i do it, and avoid preprocessor nonesense or similar reflection voodoo to map objects->db or db->objects.
if it's an integration between sql and sql as well as sql and nosql then it's pretty sick for sure
void autocomplete(dpp::cluster& bot, const dpp::autocomplete_t& event, const std::string& uservalue) {
auto rs = db::query("SELECT lower(name) AS name FROM game_users WHERE name LIKE ?", {uservalue + "%"});
dpp::interaction_response ir(dpp::ir_autocomplete_reply);
for (const auto& r : rs) {
ir.add_autocomplete_choice(dpp::command_option_choice(r.at("name"), r.at("name")));
}
bot.interaction_response_create(event.command.id, event.command.token, ir);
}
i mean really, is understanding SQL that hard?
π
if your framework or lib protects you properly from sql injection and keeps little bobby tables away from your database, and it properly handles type safety, you dont need an ORM
still havent decided if i want or need to also use redis for some stuff though, i have some things that arent important enough to put in db, but i want to persist over restarts, redis seems a good plan for that
reminds me of mongo
mangodb
amungos
prisma is akin to java's jpa
if u used it before
hmmm
seems the only way to force this first embed to be as wide as the 2nd is to add an icon to it
can anyone else think of a way?
this has been bugging me for some time now
as soon as you add an image to an embed it restricts its width
add an invisible thumbnail
oh thanks for letting me know, is the bots link or server link?
support server
idk, just repeated what they said
ohlol ok
they prolly tried to access it
Omehhw1
well, it used to be worse when IE was still alive
now you just need to support 2 different browsers
what's upp peeps
UTTP
Are we able to send voice message using bot?
Yes
no
that only documents what a voice message is
Ohh
Sadly we cant π₯²
Even they dont show mp3 as playable on mobile
I heard someone got it working before :3
Probably even a few days after they introduced it
I don't know if it was some undocumented endpoint or something, but I remember there was a conversation about it here
It was an undoc'd endpoint
here's an example i got working: https://gist.github.com/flazepe/b8deffbc728ce917deff5549b5be7a1d
Can I use this code in SnowTransfer?
@pale vessel can the id be the same always?
Lmao that's funny
Also, why not just readFileSync and then use the Buffer.byteLength
yea you can do that
i just did whatever i thought of
i just thought statSync would be 100% accurate
Okay cool didn't know if statSync also included like file headers which was important

it should be ogg (the file extension) anyway
i haven't tested any other audio file type other than mp3/ogg
but anything commonly supported should work? or similar containers to ogg at least
no clue how discord checks the audio files
Discord is saying it's supposed to be ogg opus. When was the last time you checked this?
the uploaded file i used was an mp3 and it worked. i tested like 30 minutes ago
Oh okay sweet
it's just the extension that needs to be ogg, i believe. you could try to change the extension to be the same as the uploaded file, it might just work
I'm not really gonna fuck with it tbh
bruh?
if you do non-audio file types, it'll fail
this is for both attachments and messages endpoint
so like... Literally any audio file type?
this prob
i think on the docs, discord meant that as in the audio message you send
we're sending it manually directly to the API so
Ah. The client only sends ogg
would probably recommend ogg as well to users since other formats have their own quirks
file size as well :(
oh, interesting
aac does work, but it doesn't embed
let me try with an actual aac file
okay so it embeds only on mobile
this is similar to the webp situation where it doesn't embed on ios
so you're spot on xD
just stick with ogg or mp3 and you'll be fine
one thing to note is that the mp3 file that i renamed to .aac stopped embedding as well on desktop
so file extension does matter, not just the audio type itself
okay for fuck's sake, the aac file also does embed if you rename it to a .mp3
jeez
lmao
Does only ogg and mp3 embed?
Also, isn't the max audio length like 60 seconds?
(another note, the file extension does not matter for the attachments endpoint)
desktop and mobile:
ogg
mp3
m4a
wav
flac
only on mobile:
aac
aiff
opus
wma
nope
Weird okay then
already tried and it refused to upload at all
Oh you mean only clients marked as mobile can upload those attachments
never mind it works xD
only on mobile though. on PC, it'll be marked as a normal attachment
wait..
i'm so dumb xD
i already tested it. i thought you were asking a question
i have severe brain damage when i said this
You're doing great
and nope, i just looked through google for common audio file types
This is what I thought you meant #development message
ah
when i said it only works on mobile i meant that it only embeds properly as a voice message on mobile
Alright. I'll just leave it up to the user to figure this crap out
Not about to write out a bunch of file types the user can choose from
it's not really a problem. why can't you just hardcode it to be ogg/mp3?
I could
50% done π https://fs.rjns.dev/v/XqZwkKbTWIGDEIggUi
is it possible to lock voice channels such that people can't join anymore?
Yes, but if any roles or overrides explicitly allow CONNECT, then you cannot deny it as allow always overrides deny
i see, how would i lcok it then?
When users are timed out they also cannot join VCs and will be disconnected from them
seems pretty straight forwrad
remove all overrides and permissions that allow CONNECT for channel(s) and then explicitly deny on an override for "this" channel
CONNECT is on even when flipped off iirc for global role settings
just not overridden
so literally just deny the CONNECT intent for the interaction.guild.id for example
you mean permission? Yes. Intents are a different key word
though, would people within the vc automatically get disconnect? No right?
No you'd have to disconnect users already in a channel
yeah sorry
sounds good! Thank you
i am just looking to close the party w/o disconectting people so this sounds awesome
people with the CONNECT, MANAGE_MEMBERS and VIEW_CHANNEL permissions for that channel can still move members to it
i see, but nomal people w/o an overriden CONNECT cannot join righ?
Correct
an alternative is to deny everyone and only allow specific people through overrides
If this is a guild you manage
hmm
how would that work? How can i deny everyone
and suppose i would deny each member, wouldn't it first of all take a lot of time and kick the current members
override channel permission for everyone (guild ID for role ID) to deny CONNECT and then for each user you want to allow in, allow
But if a user is already in the vc it's not needed to allow them, right?
if they leave, well their problem lmao
Correct. They wont be kicked, but they wont be able to join back
That last approach only works if you manage the guild and your permissions dont explicitly allow anyone or a role
asides from mods/admins of course
yeah i have that thankfully
im having a problem hosting my bot:
whenever i host bot in vps the slash commands are not loading, but they are loading locally
Try to Ask in official developer server
One message removed from a suspended account.
discord developer server
okay, thanks!
what do you guys use to install nodejs in linux?
i use nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm```
then sh nvm install 20.9.0
etc
I'm not finding anywhere else to ask for suggestions on bots, so posting here.
I'd like an automessage feature that will randomly choose from a number of messages. For example: a daily announcement for a pictures theme but it will post a random option from 10 different choices so it's a surprise for everyone. Embed options would be bonus.
so lemme see if I understood what you mean:
the bot fetches N messages from a channel, then choose one of them randomly and send in another (specified) channel
is that it?
could be from a channel or from a dashboard, but yes
that's too specific for an existing bot, but doesn't sound too complicated to make one, you could probably find someone willing to do it (not free, likely)
the dashboard part cranks the difficulty from 1 to 10 tho
since it'd require an entire site + api to achieve it
is there any code for yt sub count ?
Yeah I just want something like Carl or Dyno to let me randomize their automessage haha
I'll reach out to a guy
Donβt forget nvm use
if its the first version it will auto use
^
how do we set the user Limit when creating channels?
voice channels right?
lottery: TypeError: Cannot read properties of null (reading 'prize')
Anyone can help? 
Say you are using it like so something.prize then something is null
log something and see if it is what you think it is
if this is the error then ofc it will log null
no need to log just properly define "something"
Only sometimes or all the time? You never know
Unknown code flow is impossible to predict :(
Hello can anyone help me setting up a killfeed bot for rust console ?
react native & password hashing through bcrypt
const bcrypt = require('bcryptjs');
import isaac from "isaac";
bcrypt.setRandomFallback((len) => {
const buf = new Uint8Array(len);
return buf.map(() => Math.floor(isaac.random() * 256));
});
var hashedPassword = bcrypt.hashSync(password,10);
console.log(hashedPassword);
first i get some error telling me to setRandomFallback and so i did but now i get
ERROR Error: Requiring unknown module "undefined". If you are sure the module exists, try restarting Metro. You may also want to run yarn or npm install., js engine: hermes
I am positive that its from this code as i dont get error if i comment it out
obviously tried doing npm install already
i tried pretty much everything, like using just bcrypt instead of bcryptjs but i run into errors
please, anyone good in vercel & nextjs
take a look at this please π π
https://github.com/orgs/vercel/discussions/5585
call stack size is when functions are called recursively too much without pushing processing to the next ticks
If it's trying to compile your code and following too deep, then that would happen :(
processing should be deferred with setImmediate if possible
mate
it happens with vercel
i next build
it works just fine
but when vercel does it
that error.
and?
If it's a vercel issue doing exactly what I described then there's probably nothing you can do until they ask for your code and are able to decide if it's your fault or their fault
It's a general suggestion anyways. Defer processing to next ticks if you call recursively
Make sure that you indeed have the module installed and you are requiring it in the project where its in node_modules.
If that doesn't work delete node_modules and your lock file and run npm install or yarn again to re-download those modules from your package.json
Worth a try, but did you try changing all vars to lets?
Unless you reuse names, shouldn't make a difference
block scoping variables is a better idea always though
I suppose so, but vars are always involved when something weird happens
legacy code support
Stuff like the GH arctic code vault exists for a reason lol
js: "we must protect old code at all costs, nothing can break"
npm: "stupid old code, get out of my way you pleb so I can update this package from 2.0.1 to 2.0.1b"
lmao
@sharp geyser how's that rust app been going btw
Oh uh about that
Well actually
I scrapped the pool idea cause yknow after some thought and messages in the rust discord realized I dont need pools
I can just make a connection and close it each request.
No one will be accessing their data that often, it'd be in a cache logically
After I figured that out it actually became smooth sailing
Only thing I am worried about now is querying.
ah icic
i decided to make my admin section on-theme as far as its messages goes.... what do you think?
looks good, the image on the center just seems a bit too small tho
the guard?
cheeseburger bicmac whopper
im thinking if an unauthorised user does log in, it will first warn them "i dont know you, stranger, don't come back or we won't be so merciful"
then 2nd attempt, they actually kill your in-game character forcing you to respawn
it DID warn you
very creative
i love it when games go meta

though how can it know the user's in-game characeter?
IP and/or cookies if any
or probably by idk, the fact they login through discord?
I can only assume it will see if they have the proper permission by querying when they login
which you could easily get their character as well
when they log in, it knows who they are via oauth
and can look up their in game character by user id
ah, what if the user is logged out tho
i dont think he has access to user IPs from discord
as in, not playing?
logged out of the website
i know
i mean what if you try to access the admin thing in the website while you're not logged in
and there are only two login parts of the website: admin panel, and premium sales page (not made yet)
One message removed from a suspended account.
oh, if youre not logged in you get that page i pasted earlier
"stop, who goes there"
its pretty unlikely that anyone will find the page anyhow
not like i'll put a link to it anywhere on the site
the kill thing is more for nosey people who probe around at subdomains
icic
insane, thanks
hey guys i need some website design help. I am sadly not a designer, only a programmer... i got this so far, and the test that reads test should be a list of specications of the product. I am using bootstrap, how would you guys go about designing the specifications list
you might ask why the fuck i went with such a strange background, the product is named to a city in turkey so i figured to set a theme of that city as a background
if you scroll down you actually see the city lmao
let me set the object position to center, one sec
Yea thatβs too much. Background images are fine if used correctly but I personally hate when they take up the entire background
Especially when thereβs so much open space that content isnβt taking
i mean what else can i do in this case
i wanted to incorporate istanbul a bit more as that's what my product basically is inspired from
it could be a nice like header kinda thing or something
but idk once again i am not a designer hahah
Again asking for design help will get you subjective answers so mine wonβt always be correct for you
any subjective answer is better than mine, i don't have a lot of web experience to go against it.
Iβd try and either make the content take up a larger space or shorten that image to be like what Brady said
That image is overpowering and distracting
what i figured to do, is to have the product image in the upper left corner, the rhs contains a list of descriptions and then under the product image i wanted to incorporate a drop down menu with specifications of the product
though i am not sure
i see alright let me try it out
don;t worry about the unreadable text on the top for now. Suppose we went like this, what else could i use to make it look more appealing. At the moment, i feel like there's just a too harsh of a border between the image and the white bg below it
i might completely change the design cuz idk this shit looks ugly af
Hm
Working with background images is always hard to get right
Is there a reason it needs to be so prominent?
could just lower the opacity on it/put a dark overlay
okay it's. getting better
i have 3 products basically. Each product has it's own settings tailored to a certain city across the world
i want to show the customers the differences between them, as each product brings it's own ambiance
i moved the button away from the image as well, it seemed out of place
idk i think it looks good! What do you guys think?
hey
wow
i thought winscp was good
but no
only 9 concurrent transfers
transfers suddenly just stop
disappear
I use bitvise, it works pretty well
is it just me
or does 'Blackbox.AI' seem unreal
as in sell-your-data unreal
no account required
there is no contact page
the "issues" on their vsc extension goes to their site
there it's Blackbox, here BlackboxAI, over there BLACKBOX
ima ask it to draw an anime girl


Anyone knows a good rich text editor for React? I want something like I select the text and it appears a menu when select is hover
Something youβve used
its funny how employers/recruiters commonly refer to js as java and not knowing the different
"Java Back End Developer with Node JS"
i've used tinymce for a php project before, but they also have a package for react https://www.npmjs.com/package/@tinymce/tinymce-react
you can also try ckeditor, i heard it's good
is it possible to already work as a junior developer while still being in year 3 of uni bachelor?
every fucking job offer i see requires 5+ years of work experience
and even their junior positions need 2+
@eternal osprey You can still try
If you have actually coded projects
Proof of concepts
etc
Then imo (and hopefully the employer's) you can be a good fit
@slim heart didnβt you get a job out of high school?
@slim heart ^ if you did, how π₯Ί
which is most demanding bot type
the rare / niche ones (game helpers, music, etc.)
the ones you thought were the most demanding - are frankly, quite saturated
i'd say most demanding bots are the ones that are interactive or security related
an apprenticeship program got me into the company, i proved i wasnβt just an apprentice and they hired me full time
probably object depth related
thats a good way to get in
companies cant really vet everyone because theyd run out of time if they tried everyone that said they could do it
is it front-end or front end
frontend
Fend
but people still use them
people still crave for multipurpose - especially fun discord bots
but not by much
since multipurpose bots often peak at around 200 to a few thousand servers
end
@dense flame?
Hi @half laurel we dont allow advertisements here
hello there

someone please explain what the fuck this error is
google it as afirst check
also what were you doing to cause that error
are you on a school wifi or a wifi which uses a login / auth system? i get that sort of errror at school when i haven't logged into the wifi
im at school im already authed into the wifi
You can not use your school WiFi for that
its likely school wifi blocking it
i've done it before
It's possible it's been blocked since
It's scary how much a schools IT will watch what you do and stop from happening.
yup
my school TI is scared of me
at my college, IT comes to me for last resort if they can't fix something
my school IT sucked
I bypassed their search filters by unchecking a box
they couldn't think of a smarter way to do it
π
my old school's IT was ddossed by a student and had a ransomware attack
I also put 1.1.1.1 on a thumbdrive and ran that on my school laptop to access blocked sites
oh yeah i forgot someone zip bombed the computers in the tech lab
someone data breached my school's servers once
that's what i also use here to access Reddit 
my school is unblocking discord
it got blocked on accident during an outage
Oop
Fortnite
const Discord = require('discord.js');
const token = there is a token here dont worry;
const channelId = "1174021581710823444";
const client = new Discord.Client({intents: 32767});
client.on('ready', async () => {
console.log(`Logged in as ${client.user.tag}!`);
const channel = await client.channels.fetch(channelId);
client.on('message', (msg) => {
if (msg.content === '!start') {
let intervalId = setInterval(() => {
channel.send('Sending message every 1 second');
}, 1000);
} else if (msg.content === '!stop') {
if (intervalId) {
clearInterval(intervalId);
}
}
});
});
client.login(token);```
bot is not sending msg when i am doing !start
can someone help?
Why are you listening to message event inside of ready event?
You can paste this message event in a similar way to the ready event, plus depending on your discord.js version it may be a message or messageCreate event, so keep this in mind
Yep
how do i fix the message event thing
You should do it this way
client.on("ready", async () => {
// your ready event
})
client.on("messageCreate", async (msg) => {
// your message create event
})
const Discord = require('discord.js');
const token = token is here
const channelId = "1174021581710823444";
const client = new Discord.Client({intents: 32767});
let intervalId;
client.on('ready', async () => {
console.log(`Logged in as ${client.user.tag}!`);
const channel = await client.channels.fetch(channelId);
});
client.on('messageCreate', (msg) => {
if (msg.content === '!start') {
intervalId = setInterval(() => {
channel.send('Sending message every 1 second');
}, 1000);
} else if (msg.content === '!stop') {
if (intervalId) {
clearInterval(intervalId);
}
}
});
client.login(token);```
like this??
Should work
u both just contradicted each other?
he said "you should do it this way"
and you did the opposite
and a lot of other very bad things
lmao
actually nvm, its not that bad
just your indentation is fucked up
so at first look the person who sees your code thinks the messageCreate event is inside the ready event
but it isnt actually, its just hard to read
ohk?
but code still not working
const Discord = require('discord.js');
const token = cant show this
const channelId = "1174021581710823444";
const client = new Discord.Client({intents: 32767});
let intervalId;
client.on('ready', async () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('messageCreate', async(msg) => {
const channel = await client.channels.fetch(channelId);
if (msg.content === '!start') {
intervalId = setInterval(() => {
channel.send('Sending message every 1 second');
}, 1000);
} else if (msg.content === '!stop') {
if (intervalId) {
clearInterval(intervalId);
}
}
});
client.login(token);```
this good?
permissions are all given btw
@quartz kindle so.. whats wrong ?
your intents are wrong
Remind me what version of discordjs youβre using?
intents: 32767 does not include the MESSAGE_CONTENT intent
14.14
which is required to access msg.content
32767 is all intents, except message content, scheduled events and auto moderation
65535 is all intents except scheduled events and auto moderation
meaning 32767 + message_content = 65535
give the one for all ig?
all intents possible = 3276799
although you should just use what you actually need
otherwise your bot is wasting internet, ram and cpu for no reason
more intents = more events = more internet/ram/cpu used
this piece of code only really needs GUILDS, GUILD_MESSAGES and MESSAGE_CONTENT, which is 33281
how do u calculate these codes?
btw code works now
thanks a lot
your code only works for 1 channel at a time
if you do it in 2 channels, you will break it
ok
just tell him to never do it in 2 channels at once then
if he does, he will not be able so stop one of them
until you restart the bot
yea sure,or mayb will develop a system of db where i will ask owner to set up a channel in server



