#development

1 messages · Page 2017 of 1

sudden geyser
#

In TypeScript, I have a type accepting a single value of an array of said values.

type SingleOrArray<T> = T | T[];

For example, "bread", and ["baked", "bread"] are valid. What would be the most appropriate method for checking if I'm dealing with a single or array of values? I could do typeof, but wondering if there's a preferred method in TypeScript.

lyric mountain
#

In java there's isArray(), maybe there's something similar in ts

quartz kindle
#

Array.isArray(value)

lyric mountain
#

Oh well

sudden geyser
#

Yeah regular JS has that method too. Is that the preferred way in TS?

quartz kindle
#

i mean

#

if you want to detect the type at run time, you have to use js methods

#

a pure ts approach only works at compile time, if you know the type beforehand, using stuff like something as Array<T>

#

anyhow, the js method will already give you the TS intellisense you want

cinder patio
#

Yes Array.isArray is the best method

#

If T is primitive typeof is also good

ancient nova
#

I have a sqlite database, right

#
socket.on("connection", function (socket) {
  socket.on("login", function (data) {
    var insertDatabase = db.prepare(
      "INSERT INTO users_online (count) VALUES (?)"
    );
    insertDatabase.run(1);
  });

  socket.on("disconnect", function () {
  });
});
#

trying to store there currently active user count

#

I'm having an issue

#

nothing works

#

no idea how to do it

#
socket.on("connection", function (socket) {
  socket.on("login", function (data) {
    var insertDatabase = db.prepare(
      "INSERT INTO users_online (count) VALUES (?)"
    );
    insertDatabase.run(db.prepare("SELECT * FROM users_online") + 1);
  });

  socket.on("disconnect", function () {
    var insertDatabase = db.prepare(
      "DELETE FROM users_online (count) VALUES (?)"
    );
    insertDatabase.run(db.prepare("SELECT * FROM users_online") - 1);
  });
});
``` maybe????????????
#

nope having so many errorss

#

socket.on doesn't work whatsoever what

quartz kindle
#

dont ever put listeners inside listeners

#

also why are they the same name

ancient nova
#
socket.on('connection', function (socket) {
  console.log("User Connected!!!!")
});
``` it doesn't even log whenever I'm opening the website
quartz kindle
#

then fix that first

#

its not a good idea to use the same name for 2 different things

ancient nova
#

no clue how, first time using socket.io, but I'll try

quartz kindle
#

easy to get confused on which is which, and the outer one becomes inaccessible

ancient nova
#

I know, I just forgot to change them

#
/** PORT SOCKET */
const server = require('http').Server(app);
server.listen(8001, function () {
  console.log("Your server is listening on port " + listener.address().port);
});

/** GET ONLINE USER COUNT */
const socket = require('socket.io')(server);
socket.on('connection', function (socket) {
  console.log("User Connected!!!!")
});
``` why does this not work
quartz kindle
#

did you add the client side?

ancient nova
#

I was thinking it would automatically detect it if I was using fetch to call the api

#
io.on("connection", (socket) => {
  console.log("User Connected");
  io.emit("user-count-change", +1);

  socket.on("disconnect", () => {
    console.log("User Disconnected");
    io.emit("user-count-change", -1);
  });
});
``` I would create a json endpoint to get the final user count
#

also I got the user connected to pop up whenever I visited the website

quartz kindle
#

show your client side code

ancient nova
#

SqliteError: no such table: users_online

#

I keep getting this error

#

db.prepare("CREATE TABLE IF NOT EXISTS users_online (count)")

#

I'm literally creating it here

quartz kindle
#

websockets have 2 sides, a server and a client

ancient nova
#

visit the website and check the html

#

I think sqlite is at fault

civic scroll
#
{"success":true,"count":{"count":"[object Object]1"}}
ancient nova
#

it returns this {"success":true,"count":{"count":"[object Object]1"}}

#

count 2 times

#

also wtf is object object

#

supposed to return this

#

{"success":true,"count":"1"}

quartz kindle
#

you tried to convert an object to string

#

without using JSON.stringify

ancient nova
#
io.on("connection", (socket) => {
  console.log("User Connected");
  io.emit("user-count-change", +1);
  db.prepare("INSERT INTO users_online (count) VALUES (?)").run(
    db.prepare("SELECT * FROM users_online") + 1
  );

  socket.on("disconnect", () => {
    console.log("User Disconnected");
    io.emit("user-count-change", -1);
    db.prepare("INSERT INTO users_online (count) VALUES (?)").run(
      db.prepare("SELECT * FROM users_online") - 1
    );
  });
});

#

how?

quartz kindle
#

db.prepare("SELECT * FROM users_online") returns an object

ancient nova
#

I forgot to add .get() I think

quartz kindle
#

even with .get() it still returns an object

#

db.prepare("SELECT count FROM users_online").get().count + 1

ancient nova
#

ah I see

#
/** GET ONLINE USERS **/
app.get("/checkOnline", function (request, response) {
  response.setHeader("Content-Type", "application/json");

  var getOnlineUsersFromDatabase = db.prepare("SELECT * FROM users_online");
  let databaseResponse = getOnlineUsersFromDatabase.get();
  
  response.json({ success: true, count: databaseResponse });
});
``` this is server side - endpoint
quartz kindle
#

does users_online only have a single row?

ancient nova
#

let me see

#

it still returns {"success":true,"count":{"count":"[object Object]1"}}

#

do I have to clear it?

quartz kindle
#

.get() returns an object containing the database response

#

"SELECT * FROM users_online" returns all columns from that table

#

so .get() returns something like { count: 1, othercolumn: otherdata, ... }

ancient nova
#

yep

#

{"success":true,"count":"[object Object]1"}

#

it now returns this after fixing

quartz kindle
#

console.log(getOnlineUsersFromDatabase.get())

civic scroll
#

you forgot the

#

.users_online

ancient nova
quartz kindle
#

.count

quartz kindle
civic scroll
#

clearly you ignored my message

#

:)

ancient nova
civic scroll
#

you didn't specify the property

ancient nova
#

adding that returns as undefined

civic scroll
#

.count then

quartz kindle
#

his database is polluted with invalid data, because he saved it wrong

#

you need to remove that data and save it again, but correctly this time

civic scroll
#

also multiple read / writes to db like tha

#

is a bad practice

#

you should save on interval

ancient nova
#
io.on("connection", (socket) => {
  console.log("User Connected");
  io.emit("user-count-change", +1);
  db.prepare("INSERT INTO users_online (count) VALUES (?)").run(
    db.prepare("SELECT count FROM users_online").get().count + 1
  );

  socket.on("disconnect", () => {
    console.log("User Disconnected");
    io.emit("user-count-change", -1);
    db.prepare("INSERT INTO users_online (count) VALUES (?)").run(
      db.prepare("SELECT count FROM users_online").get().count - 1
    );
  });
});

``` ```js
app.get("/checkOnline", function (request, response) {
  response.setHeader("Content-Type", "application/json");

  var getOnlineUsersFromDatabase = db.prepare("SELECT * FROM users_online");
  console.log(getOnlineUsersFromDatabase.get())
  let databaseResponse = getOnlineUsersFromDatabase.get();
  
  response.json({ success: true, count: databaseResponse.count });
});
civic scroll
#
"time": "...."
"count": ""
#

save in this format

ancient nova
#

first need it to actually work

quartz kindle
#

either delete your db file, or run "DELETE from users_online"

civic scroll
#

DROP ALL DATABASES

#

:^)

quartz kindle
#

or run a the update with a fixed number

#

also, you dont need to update like that

#

you can do this

civic scroll
#

save in a track var

sage lake
#

Member A would click a drop-down button In #post-listing channel

The bot would DM Member A and collect the required info (BUY/SELL, Description, price, image). Once thats completed they would post it in #trading channel

Member B is interested in that offer so they dm Member A

Once they agree on a trade they would manually complete that trade In-game

Once thats completed Member A can mark the listing as Sold/Fulfilled through a drop down button```
#

would a bot like this be easy to make?

quartz kindle
#

wait, your db setup is wrong in so many levels lol

sage lake
#

I have no past experience

quartz kindle
#
  db.prepare("INSERT INTO users_online (count) VALUES (?)").run(
    db.prepare("SELECT count FROM users_online").get().count + 1
  );
``` this is not updating the value in the database, this is creating a new entry with the new value
ancient nova
#

how?

quartz kindle
#

you are INSERTing a new row

ancient nova
#

insert is inserting into the database

#

adding

#

I get the count and add 1

#

do I not?

civic scroll
#

you need to UPDATE

quartz kindle
#

think of it as a table

civic scroll
#

you want to update a row, not inserting new ones

ancient nova
#

TypeError: Cannot read properties of undefined (reading 'count')

#

getting an error

#

should I create a new table, now?

civic scroll
#

change th query

#

then delete the table

#

also

#

update the row

#

not insert

quartz kindle
#

sqlite is a relational database, it stores data in tables, you need to understand how the table works

civic scroll
ancient nova
#

I am about to die

#

should I send the entire code

#

I think I messed up bad

#

it keeps giving me this

#

TypeError: Cannot read properties of undefined (reading 'count')

#

I recreated the db

civic scroll
#

check if exists

#

if does not exist

#

create one

ancient nova
#

SqliteError: near "INTO": syntax error

quartz kindle
#

show all your code

civic scroll
#
call sql.Query, "GET count from table" -> dbResponse
    if count not in dbResponse then
        call sql.Query, "INSERT ..."
    else
        get count in dbResponse -> ...
    end
end
ancient nova
#

what's the website for storing large pieces of code again

civic scroll
#

pastebin

quartz kindle
#

paste/haste/hate/abc/dick/etcbin

ancient nova
quartz kindle
#

where is the CREATE TABLE for users_online?

#

nvm found it

#

so basically

#

you have a table that looks like this

#
table users_online
------------------------
|         count        |
------------------------
|                      |
|                      | 
#

when you do INSERT INTO users_online

#

it becomes like this

#
table users_online
------------------------
|         count        |
------------------------
|           0          |
|                      | 
#

if you insert count 0 for example

#

if you INSERT again

#

it becomes this

#
table users_online
------------------------
|         count        |
------------------------
|           0          |
|           0          | 
|                      | 
#

for each INSERT you do, you create a new entry

#

and when you do SELECT * from users_online using .get(), you get { count: 0 }, and since you didnt specify a WHERE, it always gets the first row

#

if you did SELECT * from users_online using .all(), you would get [ { count: 0 }, { count: 0 } ]

#

which i dont think is what you want

#

if you do like you did before

#

"INSERT INTO users_online (count) VALUES (SELECT count + 1 FROM users_online)"

#

since you didnt use a WHERE, it autoselects the first row, so its always 0

#

and since you keep inserting, it will keep creating new rows

#

in the end you will end up with a database like this

#
table users_online
------------------------
|         count        |
------------------------
|           0          |
|           1          | 
|           1          | 
|           1          | 
|           1          | 
|           1          | 
|           1          | 
|           1          | 
|           1          | 
|           1          | 
#

which makes no sense

ancient nova
#

okay so in the code I sent I changed INSERT into UPDATEwhich still gave me errors

civic scroll
#

update where

ancient nova
#

at the very bottom

#

where the socket code is

#

this is what updates the table

civic scroll
#

i mean the row in which you did the update

ancient nova
#

wdym

civic scroll
#

actually

#

tim you do this

ancient nova
#

I'm sorry to be so hard to help but

civic scroll
#

i have no expertise nor the patient for this

ancient nova
#

I really don't understand

#

it's my second time using sqlite and my first time using socket

civic scroll
#

go look at his explaination

#

this is about SQL language

#

nothing's wrong with sqlite or socketio

#

you still don't understand relational databases

ancient nova
#

never said there is something wrong, might've just coded it wrong

civic scroll
#

that's where the problem is

quartz kindle
#

you probably want something like this:

table users_online
------------------------
|         count        |
------------------------

do this only once after you create the table, then comment it out
INSERT INTO users_online (count) VALUES (0)
now you have

table users_online
------------------------
|         count        |
------------------------
|           0          | 

then you do this UPDATE users_online SET count = count + 1 and UPDATE users_online SET count = count - 1

#

since you will only ever have 1 row, you dont need to use WHERE, but it will likely improve performance and be more correct to use a primary key

#

sqlite creates a hidden rowid column when you dont have your own primary key

#

so in fact, your table actually looks like this, you just dont know it

#
table users_online
------------------------------------------------
|         rowid        |         count        |
------------------------------------------------
|           1          |           0          | 
#

so to make it more correct and also improve performance, you can add WHERE rowid = 1

#

for example UPDATE users_online SET count = count + 1 WHERE rowid = 1

ancient nova
#

okay, I've done all the above added WHERE rowid = 1 now for the endpoint I do something like: SELECT * FROM users_online WHERE rowid = 1 as well? @quartz kindle

quartz kindle
#

since you only have count it doesnt really matter, but you can also use SELECT count FROM

ancient nova
#

perfect it works

#

think

quartz kindle
#

because rowid is never automaticcally selected

ancient nova
#

I'll include that in the scripts above as well

#

also

quartz kindle
#

show code again to confirm its correct

ancient nova
ancient nova
#
io.on("connection", (socket) => {
  console.log("User Connected");
  io.emit("user-count-change", +1);
  db.prepare("UPDATE users_online SET count = count + 1 WHERE rowid = 1").run();
  
  socket.on("disconnect", () => {
    console.log("User Disconnected");
    io.emit("user-count-change", -1);
    db.prepare("UPDATE users_online SET count = count - 1 WHERE rowid = 1").run();
  });
});


``` this is for the count update
#
app.get("/checkOnline", function (request, response) {
  response.setHeader("Content-Type", "application/json");

  var getOnlineUsersFromDatabase = db.prepare("SELECT * FROM users_online WHERE rowid = 1");
  let databaseResponse = getOnlineUsersFromDatabase.get();
  
  response.json({ success: true, count: databaseResponse.count });
});
``` and this is for the endpoint
quartz kindle
#

yes its correct

ancient nova
#

perfect

#

now for the clientside

#

should I just node-fetch that?

quartz kindle
#

depends, what do you want to do in the client side?

ancient nova
#

basically

quartz kindle
#

i mean, since you already have the websocket running, it would be a waste not to use it

ancient nova
#

actually it stopped making sense in my head just now, how exactly how I make this work?

quartz kindle
#

you want to display an auto-updating count on the website right?

ancient nova
#
const processActiveUsers = function () {
    // clientside here
    Active += 1;
}
ancient nova
#

the website is just the api

quartz kindle
#

so what do you want to display on the website?

ancient nova
quartz kindle
#

that makes no sense lol

ancient nova
#

that's what I'm saying...

#

let me think

#

I have a page with statistics right

#

and I want this to take the json from the website

#

and put it in the statistics page, right?

#

and I want to update the count based on who opens my program, rather than who opens the website, so basically, I'd ping the website every couple seconds if the person is still using the program

#

I hope that makes sense

quartz kindle
#

so you only want the socket to detect when a user leaves the page and nothing else?

ancient nova
#

well he won't be opening the actual API so

#

that's why I'd rather ping it

#
const processActiveUsers = async function () {
const getOnlineUserCount = await fetch(`https://transparent-speckle-door.glitch.me/checkOnline`).then(res => res.json());
if (getOnlineUserCount.success != false) Active += getOnlineUserCount.count;
}
#

something like this @quartz kindle

quartz kindle
#

im still confused but oh well

#

because the main function of websockets is to enable the server to send stuff to the client, ie the user's browser, without the client needing to do anything, ie fetch, etc

#

for example to create auto-updating stuff on the user's browser

#

receiving notifications, messages, etc

lyric mountain
#

can't u just track who's online by using the onOpen/onClose event?

lyric mountain
#

like, there are 2 events that happen when the client connects or disconnects

#

I use that for my canvas game so join/leave gets announced on the chat

ancient nova
#

wtf why didn't I see anything about it online when I was researching

lyric mountain
#

first one is client-side, second is server-side

ancient nova
#

why doesn't it workkkk

#

it always displays as one

lyric mountain
#

like, you still need to keep track of who's connected

#

add when connecting, remove when disconnecting

quartz kindle
lyric mountain
#

oh

quartz kindle
#

not native websocket

ancient nova
#

this is weird

#

why does it not update when I have 2 clients open?

lyric mountain
#

idk if I'm biased, but my experience with socket.io was terrible

#

raw websockets feel easier

ancient nova
lyric mountain
#

so it's technically a midway between api and websocket

civic scroll
#

ws is actually better

lyric mountain
#

that's my opinion too

quartz kindle
#

dafuq

civic scroll
#

you can broadcast data and know when it disconnects

ancient nova
civic scroll
#

much more easier

lyric mountain
#

except I'd choose wss instead mmLol

ancient nova
#

since I am actually it calling it as a sort of API

lyric mountain
ancient nova
#
const processActiveUsers = async function () {
    await fetch(`https://transparent-speckle-door.glitch.me/`); //ping the website first to add your to the online user count.
    const getOnlineUserCount = await fetch(`https://transparent-speckle-door.glitch.me/checkOnline`).then(res => res.json());
    if (getOnlineUserCount.success != false) {
        Active = getOnlineUserCount.count;
        process.title = `ZERO V2 | LOGGED AS: ${Username.toUpperCase()} | ACTIVE RIGHT NOW: ${Active} |`;
    }
}
lyric mountain
#

you don't get the performance of websockets nor the flexibility of apis

civic scroll
#

just use separated http and ws

lyric mountain
#

it sends everything through http(s)

ancient nova
#

lmao so why did they name it socket.io

lyric mountain
#

who knows

civic scroll
#

an http lib that mimics ws

quartz kindle
#

it does use websocket whenever possible

#

Although Socket.IO indeed uses WebSocket as a transport when possible, it adds some metadata to each packet: the packet type, the namespace and the packet id when a message acknowledgement is needed.

ancient nova
#

can someone visit the website I wanna see if the count updates

quartz kindle
#

The connection will fall back to HTTP long-polling in case the WebSocket connection cannot be established.

civic scroll
#

socket.io prefers ws and will use http polling

#

yeah

civic scroll
ancient nova
#

it updated me to 2 after a refresh

#

hmmm

#

it's weird

civic scroll
#

but it doesn't update in real time

ancient nova
#

at least it kinda works

civic scroll
#

cring

lyric mountain
ancient nova
civic scroll
ancient nova
civic scroll
#

no

ancient nova
#

then what

civic scroll
#

implement clientside code

#

to update th count in real time

ancient nova
#

🚫

#

I'd have to

#

ping it like

#

99999 times

civic scroll
#

no

#

you don't have to

ancient nova
#

then what do you suggest

civic scroll
#

the server will broadcast the changes

#

you just need to listen to it

ancient nova
#

didn't I tell you how glitch works

civic scroll
#

i used glitch myself

ancient nova
#

well then you should know better how it works

#

it only goes up per request

civic scroll
#

no

ancient nova
#

yes

civic scroll
#

use ws

ancient nova
#

trying to keep it up is against their tos

civic scroll
#

get a website host then

#

:^)

#

like vercel

ancient nova
#

I'm not paying for a vps 😢

civic scroll
#

i'm not even paying

ancient nova
#

it's free?

civic scroll
#

yet i still have two websites running rn

ancient nova
#

wait can it treat APIs like websites?

#

glitch

#

cause I used a node

#

which isn't up 24/7

civic scroll
#

APIs runs on cloud functions

ancient nova
#

static websites are

civic scroll
#

my website is not served statically

#

you can do middleware code to intercept / alter requests

ancient nova
#

hold on cause I'm talking about glitch right now

#

you used it right

#

did you make an api using it

civic scroll
#

no

#

i don't use glitch to make apis

ancient nova
#

should I waste my time to try change the node webapp to a static website in hope that it'll actually work?

civic scroll
#

i test it locally and push to an actual remote server

ancient nova
#

there is a tiny chance that it will

civic scroll
#

depends on what you wanna do tbh

ancient nova
#

it's just an express app

civic scroll
#

there are many site serving strats

#

incremental render, isopropic, static serverside

#

etc tc

ancient nova
#

this is one of the static websites I made long ago

civic scroll
#

it worked

ancient nova
#

it's up 24/7

civic scroll
#

mine is also up 24/7

#

without http polling

ancient nova
#

but it doesn't work

#

I won't be able to install npms

civic scroll
#

install node

#

the runtime is linux

ancient nova
#

I can't install it on that

civic scroll
#

install on something else

ancient nova
#

I can't it won't work

#

they're static

#

they work only once you can't even make a dashboard or anything like that on glitch

#

I need a better host

civic scroll
#

look for one

#

eg. vercel

#

but one catch

#

your repo gotta be public

ancient nova
#

nope nope

#

not sharing this code

civic scroll
#

then invest in a vps

ancient nova
#

worked on that for too long to share it

ancient nova
civic scroll
#

how long

ancient nova
#

couple months

civic scroll
#

have you been on it

#

half a year?

ancient nova
#

more

#

like

#

6-7 months

#

maybe even more

#

I started in early 2021

civic scroll
#

same amount of time as my project then

ancient nova
#

and you'd share it?

civic scroll
#

it's public

ancient nova
#

😐

civic scroll
#

what

ancient nova
#

if you want to help people then sure

civic scroll
#

it doesn't llook like someone would fork this project of mine

ancient nova
#

I wouldn't share that

#

same with my game I worked 2 years on

#

would never

#

a program I worked 1 day for, sure

civic scroll
#

i don't think my project would help anyone

ancient nova
#

do you just not care if anyone steals it?

civic scroll
#

they can't steal the way i design and how i make it work

ancient nova
#

they can

civic scroll
#

unless thatt person is me

ancient nova
#

what if they steal all the code and just remove your name from it

civic scroll
#

they can't replicate that

ancient nova
#

and put theirs

civic scroll
ancient nova
#

would it not?

#

it's just a string

#

any exe editors can do that

civic scroll
#

i told you, the whole thing

#

you can't even maintain it

#

if you don't know the struct

ancient nova
#

so it's badly written KEKW

civic scroll
#

that's the point

ancient nova
#

or rather

civic scroll
#

it's up to you to determine

ancient nova
#

uniquely

civic scroll
#

i wouldn't even say it's poorly written

#

lighthouse return 90+ scores

ancient nova
ancient nova
#

imma try that

civic scroll
#

august

#

but then i rebased

ancient nova
#

nice

#

what's the program about

civic scroll
#

game wiki

#

i tell about it all the time in general

#

i wouldn't say it's well-designed

#

there are flaws and bad habits i detected throughout the project

ancient nova
#

it's not something you can beat easily

civic scroll
#

eventually i will beat it

ancient nova
#

I hope I can too lol

#

I keep coming here for help almost all the time

civic scroll
#

you are lucky

#

all i had were 2 ebooks back then

ancient nova
civic scroll
#

i didn't even have a laptop to begin with

#

nor a pc

ancient nova
#

that's dedication

#

I've started with mobile development

civic scroll
#

i started with a discord bot in js

ancient nova
#

moved to modding and now I also write scripts and recently made a couple games

civic scroll
#

and i regretted instantly

#

because i knew nothing

ancient nova
#

worked on it... say like 2 years

civic scroll
#

3

ancient nova
#

I lost all the files

#

and now I don't care about bots

#

also was late literally 1 day to get the dev badge which sucks lol

#

I will never forget the disappointment I felt that day

civic scroll
#

just rewrite

#

xd

ancient nova
#

and no it'll take too long

civic scroll
#

that's where you start

ancient nova
#

it was 2 years worth of work

civic scroll
#

my 2 years of work

#

done in a month

ancient nova
#

still

#

a month is a lot

civic scroll
#

nothing much

ancient nova
#

for you lol

#

I'm 17 I still have school

civic scroll
#

given how improved you have become since last time

ancient nova
#

and exams

#

lots of them

civic scroll
#

i was 17 back then

#

lmao?

#

what, excuses?

#

in fact, that happened last year

ancient nova
#

😐 what? exams are hard

civic scroll
#

ez

#

if you study enough

ancient nova
#

on my most recent exam I scored 82%

#

without studying

civic scroll
#

then why you complaining?

#

💀

ancient nova
#

well

#

because

#

some of them are hard

#

and I have a lot of them

#

like

civic scroll
#

let's go to either dms or general

ancient nova
#

there's least 1 every single day

civic scroll
#

we are offtopic for a while now

ancient nova
#

ah ye

sudden geyser
#

that's what this channel is for

ancient nova
#

dms then?

civic scroll
#

sure

civic scroll
sudden geyser
#

delete your account

sudden geyser
#

Does Node.js/npm have an equivalent to Rust cargo's feature flags?

proven lantern
#

im cleaning up my code and commenting stuff. do you think i should change this?

#

line 201

sudden geyser
#

Do you need the [] at the end

proven lantern
#

nope

#

it wants to be a reduce

sudden geyser
#

but you aren't reducing, so removing it would be better

proven lantern
#

yeah, i will crush map()s dreams

#

is the nested ternary operator fine?

#

it's inside a string template too

sudden geyser
#

Personally I don't like the nested ternary. How about expanding it?

#

would also get rid of some duplication

#

like how you do updatedSettings[settings] twice

#

actually three times

proven lantern
#

i check if it's there once and return it once and return it in bold once

sudden geyser
#

yes, but you use it in three instances

proven lantern
#

like i could put the condition around creating the **

#

perhaps

#

i will play with it

sudden geyser
#

Like, you could do this:

// Probably built into whatever library you're using
function bold(s) {
  return `**${s}**`;
}

function styleSetting(set) {
  let updated = updatedSettings[set];

  if (updated) {
    if (serverSettingOptions[set]) {
      return bold(updated);
    } else {
      return updated;
    }
  }
}

dbSettings.map((setting, index) => ({
  name: settings[index],
  value: styleSetting(setting) || "NOT SET",
  inline: true
}))
#

Which is larger, but for a good cause 🙃

proven lantern
#

that might be needed

proven lantern
#

i know someone who programmed a flying pizza in html

#

it's declarative

#

declarative programming > imperative programming

quartz kindle
proven lantern
quartz kindle
#

it even bounces back

#

like a dvd logo

proven lantern
#

html is a powerful programming language

ancient nova
sudden geyser
#

fixed

ancient nova
#

nice

slender wagon
#
 items.forEach(function(element) {

how do i use the sort function for a forEach function?

sudden geyser
#

You probably want to sort first:

items.sort(...);
items.forEach(function(element) {...});
slender wagon
#

gotchya

sudden geyser
#

Now it doesn't :)

proven lantern
#

noice

sudden geyser
#

wait what

#

js doesn't have a sorted method?

#

that's wack

proven lantern
#

yeah

slender wagon
#

hmm

proven lantern
#

but you can make one

sudden geyser
#

Okay now it works

proven lantern
#

niice

#

maybe you could write a reduce function that sorts the array

#

that would be tricky

slender wagon
#

wait

#

can i sort them out when i pull the from the db

#

mongodb

slender wagon
#

uh so basically i wanna sort them by a element that the object has

#

in this case it's the price

proven lantern
#
db.recordsWithPrice.createIndex( { "price": 1 } )

db.recordsWithPrice.find().sort( { "price": 1 } )
raven holly
#
 Discord API Error encountered.
You are being rate limited.```
wheat mesa
#

You’re sending a TON of requests somewhere

raven holly
#

Hm can i send you code to u see

earnest phoenix
#

i copied and learned a bit of a slash commands code, it seems i need a permission to enable the slash commands (i had to re-add the bot) is there a way to bypass it or maybe get the perm. Not all perms, one of them was needed for slash commands i don't remember

austere surge
#

just do the invite again with the application.commands

timber fractal
#

Why does this render the ejs files correctly, but doesn't render it with the css? ```js
const express = require('express');
const ejs = require('ejs');

const app = express();

app.set("view engine", "ejs");

app.set("views", "./ejs");

app.use(express.static('./css'));

app.get("/", (req, res) => {
res.render("index", {
req: req,
});
});

const http = require("http").createServer(app);

http.listen(80, () => {
console.log(Website is online on the Port: 80);
});```

quartz kindle
timber fractal
quartz kindle
#
<head>
<link rel="stylesheet" href="mystyle.css">
</head>
timber fractal
#

mb i made a mistake there, thanks

neat ingot
slender wagon
#

should be something like /src/public

#

depending on your directory formating

neat ingot
#

yea, its not even required. but if used should point to files the client can access

neat ingot
#

using it for your css/js files is a common use though

slender wagon
#

i would recommend such formating is much easier to work with

neat ingot
#

ahh ok my bad, i thought the css tim showed above with the mystyle.css was a copy of yours 😛

slender wagon
#

just wait

#

there is no fix to that

raven holly
split hazel
#

@quartz kindle you might've messed up on the two byte header code

#

apparently the most significant bytes are on the right not left

#

ah right i forgot my endians

#

little endian stores most significant on the right

#

why do we even have these differences in the first place

quartz kindle
#

because they exist lul

split hazel
#

is there even performance differences between them

quartz kindle
#

i think most things use big endians by default

#

not really

#

in some edge cases there are differences

split hazel
#

its a problem cpus are not standardised 💀

#

especially the troubling history

quartz kindle
#

for example when you cannot know the total length of the number or data you are writing, there are differences in how to handle it

#

for example stuff like variable ints

#

that are used in video codecs

split hazel
#

slow down speedyos doesnt have video yet

quartz kindle
#

generally it doesnt really matter

#

one concrete example i've personally faced was writing 64 bit ints in node

#

there is a native setBigUint64() method in DataView and writeBigUint in Buffer

#

and i wanted to store only the necessary bytes, not the full 8 bytes

#

using little endian, i could write the full 8 bytes, then ignore the unused bytes at the end

#

with big endian i'd need to copy all used bytes to the left instead, which is more costly

split hazel
#

yeah that is true

quartz kindle
#

but these are very edge cases, most times the endianess doesnt matter

quartz kindle
#

my bigint serializing function has 3 different ways of doing it, depending on the bigint size lel

#

bigins and strings in js suffer from various performance issues where some methods are faster as long as the data is small, other methods become faster as the data size increases

split hazel
#

basically loops in a nutshell

quartz kindle
#

yup

split hazel
#

of course there has to be 4 different ways to iterate over something in js

#

iterators, for of, for ;, foreach

quartz kindle
#

the differences are mostly pure js vs native

#

pure js is faster as long as the data is small

#

native code is faster otherwise

#

for example, looping over each character using string.charCodeAt() is faster than Buffer.from(string) if the string is smaller than around 30 characters (depending on cpu and node version)

split hazel
#

i wont even bother

#

god i hate the fact tcp has to forecefully group packets

#

the world would've been a better place if arpanet was the modern internet

quartz kindle
#

lel

split hazel
#

oh wait that uses tcp 💀

quartz kindle
#

streams are more efficient

#

packets are grouped to not overload cpu and network, makes efficient use of hardware maximum transmission units, its a nice system

split hazel
#

yeah i get that but its annoying having to handle split packets

#

i got the split system working now i need to add checks to prevent buffer overflows and incorrect formats of data

#

would not be nice if someone set the size to 65535 which would cause the array to overrun causing a possible segmentation fault and buffer underflows

split hazel
#

@quartz kindle now when i wanna test my split packet handling the packets happen to get sent seperately perfectly each time

#

there we go crisis averted

split hazel
#

@earnest phoenix just want to appreciate how in buffers the slice function actually crops the buffer instead of making a new one

#

really efficient and makes buffer a real tool for power users

idle coral
#

what is going on?

#

EOL?

#

Do I need a newer version of Py?

#

This is code/Python from late 2018 to early 2019.

dry imp
#

......you missed a quote

idle coral
#

wdym

#

oh shit

dry imp
#

"

idle coral
#

mb sorry for bothering

#

i need to go to bed

dry imp
#

you should

idle coral
#

I woke up early

#

4

#

Works starts at 7

#

I couldn't fall back to sleep

idle coral
#

I have the variable as client.

wheat mesa
#

you need to do @client.command()

#

I don't even know python but I know that :p

#

isn't it?

dry imp
#

yes it is true waffle

#

you must add "@" since it is a decorator

rocky dagger
#

if i have an object and variable like under how can i 1; see if they are in the object and 2; see what value they have```js
let x = "name";
let y = "shape";
let z = "Consistency";

let fruitObject = {"name": "Apple", "shape": "round", "taste": "sweet"};

dry imp
#

damn this would be very easy in python, sadly idk js

lament rock
rocky dagger
#

thanks

lyric mountain
lament rock
#

so. Literally what I put

lyric mountain
#

Nope

#

Yours doesn't fulfill his 2nd requirement

lament rock
#

reading is hard

hybrid cargo
#

doStuff()

#

😭

rocky dagger
#

thank you both

pearl trail
sudden geyser
#

horny

rocky dagger
#

with mongodb im trying do add a userID variable and a integer value (amountDino) to this object and i tried first without push but then it just did a overwrite but when i added $push since thats what i saw that looked closest to what i wanted but when i added it, it says i cant do that since queue is not an arrayjs await Queue.findOneAndUpdate({ guildID: guildID, dino: dino }, { $push: { queue: { [userID]: amountDino } } });

mortal snow
#

Quick question would anyone know if python would be better then node.js for my discord bot?

craggy pine
#

Isn’t pythons lib not maintained anymore besides by the community

mortal snow
#

Yeah that is true

sudden geyser
#

only difference is there are more options, which does lead to discord in the community

sudden geyser
dry imp
#

tho i still prefer its fork

sudden geyser
#

has discord.py even released the updates they proposed

#

I think they're still in development

dry imp
#

i havent really been catching up with d.py news all i know is they came back

lament rock
#

is it under the original dev or new one

dry imp
#

the original

lament rock
#

oh pog

simple stump
#

I have a complicated NodeJS script that fetches captions and stores it locally. It has a bunch of async/await functions, but the subtitle does get downloaded eventually (see the the sourceb.in link if you want to view the subtitle yourself). I mention that because for some reason the subtitle doesn't ever get loaded. Or rather it does, but it doesn't appear in the HTML player. I'm quite confused because removing the default option displays the "English Subtitles" option in which I can toggle it on/off, but nothing is shown. Adding the default option removes the "English Subtitles" option in which I can't toggle it on/off, and once again nothing is shown. TLDR, I'm having trouble with the <track> tag as none of the subtitles are shown.
Code:

<div class="video" >
  <video controls autoplay id="videoPlayer" style="background:black">
    <track default src="${path}" kind="subtitles" label="English Subtitles" srclang="en" />
    <!--
    Path is the path to the subtitle. I don't get any errors, and the path when inspecting the element is correct.
    -->
  </video>
</div>

https://sourceb.in/RkmN7FEXBC

pearl trail
#

try this ```js
await Queue.findOneAndUpdate({
guildID: guildID,
dino: dino
}, {
"queue": {
"userID": amountDino
}
}, {upsert: true});

#

i hope that's what you want

half bear
#

hello. how can i list bot counter of a guild

#

and a role's user count

#

like the guild.memberCount thing

austere surge
pearl trail
#

use .reduce

pulsar bone
#

main.py

def login():

    code = request.args.get("code")


    at = Oauth.get_access_token(code)
    session["token"] = at

    user = Oauth.get_user_json(at)
    user_name, user_id = user.get("username"), user.get("discriminator")

    return f"Success, logged in as {user_name}#{user_id}"

Oauth.py

import requests

class Oauth:
  client_id = "****************"
  client_secret = "******************"
  redirect_url="https://Giveaway-Index.korrabender.repl.co/login"
  scope="guilds%20email%20identify"
  discord_login_url="https://discord.com/api/oauth2/authorize?client_id=926073185693220954&redirect_uri=https%3A%2F%2FGiveaway-Index.korrabender.repl.co%2Flogin&response_type=code&scope=guilds%20email%20identify"
  discord_token_url="https://discord.com/api/oauth2/token"
  discord_api_url="https://discord.com/api/oauth2/api"

  @staticmethod
  def get_access_token(code):
        payload = {
            "client_id": Oauth.client_id,
            "client_secret": Oauth.client_secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_url": Oauth.redirect_url,
            "scope": Oauth.scope
        }
 
        access_token = requests.post(url = Oauth.discord_token_url, data = payload).json()
        return access_token.get("access_token")

  @staticmethod
  def get_user_json(access_token):
        url = f"{Oauth.discord_api_url}/users/@me"
        headers = {"Authorization": f"Bearer {access_token}"}
 
        user_object = requests.get(url = url, headers = headers).json()
        return user_object

i am getting none in place of user name after login

#

can someone help its urgent(school project)

near stratus
#

damn schools started to give discord oauth as assignment

lament rock
#

I mean. If schools can get with what their student actually find interesting and can incentivize them to make stuff they actually enjoy, maybe they'll find their passion

#

I wish I got into bot dev earlier

near stratus
#

keep learning C++ it'll surely help you out in the future

lament rock
#

I need to get started on cpp tbh

#

been getting into cs more as I do unity dev. Could probably fuck around and try Unreal

pulsar bone
near stratus
earnest phoenix
earnest phoenix
#

Optimizing discord.js... late April Fool's joke

lament rock
#

I mean. Yeah true. That is a monumental challenge

rocky dagger
pearl trail
#

you can't add thing that have the same variable to object, this is what i get from what you want

userID: 2,
userID: 3
``` or maybe different let me know
#

$push is only for array

#

best to give data example with from {userid: 1} and to {userid: 2} etc

pulsar bone
near stratus
neat ingot
#

~ ive spent the past few days working on a theme generator. its pretty dope imo. I'm using colormind.io's api to generate a color pallet (5 colors - bg, text, and 3 colors) that work well together, then using some basic color theory to calculate the other 3 required colors

simple stump
#

I have a complicated NodeJS script that fetches captions and stores it locally. It has a bunch of async/await functions, but the subtitle does get downloaded eventually (see the the sourceb.in link if you want to view the subtitle yourself). I mention that because for some reason the subtitle doesn't ever get loaded. Or rather it does, but it doesn't appear in the HTML player. I'm quite confused because removing the default option displays the "English Subtitles" option in which I can toggle it on/off, but nothing is shown. Adding the default option removes the "English Subtitles" option in which I can't toggle it on/off, and once again nothing is shown. TLDR, I'm having trouble with the <track> tag as none of the subtitles are shown.
Code:

<div class="video" >
  <video controls autoplay id="videoPlayer" style="background:black">
    <track default src="${path}" kind="subtitles" label="English Subtitles" srclang="en" />
    <!--
    Path is the path to the subtitle. I don't get any errors, and the path when inspecting the element is correct.
    -->
  </video>
</div>

https://sourceb.in/RkmN7FEXBC

azure lark
#

whats the UserResolvable for an interaction with djs?

solemn latch
#

I presume just .user

eager yarrow
#

Could I have some assistance in configuring topggpy webhook api for my bot? I have the webhook working on top.gg and the tests are sending the vote message to the proper channel. But, the topggpy configuration for the webhook isn't working.

solemn latch
eager yarrow
# solemn latch are you using `async def on_dbl_vote(data):`? `async def on_dbl_test(data):` is ...

Using both

@bot.event
async def on_dbl_vote(data):
    """An event that is called whenever someone votes for the bot on Top.gg."""
    if data["type"] == "test":
        # this is roughly equivalent to
        # return await on_dbl_test(data) in this case
        return bot.dispatch('dbl_test', data)

    print(f"Received a vote:\n{data}")

@bot.event
async def on_dbl_test(data):
    """An event that is called whenever someone tests the webhook system for your bot on Top.gg."""
    print(f"Received a test vote:\n{data}")

As shown in the documentation.

solemn latch
#

I'm not a py dev, but isnt this just firing an event.
return bot.dispatch('dbl_test', data)
are you doing anything with that event?

eager yarrow
#

I have my topgg_webhook configured as shown in the documentation as well

   bot.topgg_webhook = topgg.WebhookManager(bot).dbl_webhook("/dblwebhook", "authorization token from topgg")
   bot.topgg_webhook.run(5000)
#

I'm not doing anything with the event currently. I'm not seeing the print statement in the logs to validate the event is working.

timber fractal
#
 <body>
        <div class="navbar" id="navbar">
            <nav class="navbar">
                <div class="nav-left">
                    <a href="/documentation">
                        <p>Documentation</p>
                    </a>
                </div>
            </nav>
        </div>

        <div class="content">

        </div>
    </body>``` Why is `document.getElementById("navbar");` null? Using express and ejs
lyric mountain
#

also an id kekw

wheat mesa
#

Nvm ignore me I didn’t see

#

It gets split perfectly on mobile

lyric mountain
#

kekw

timber fractal
#

ok jk what's wrong with this

snow vector
#

did you figure this out yet?

sudden geyser
#

some old laptop you don't use

#

your friend

#

your friend's friend

#

your parent/guardian's credit/debit card

#

heroku

snow vector
#

its from 2017 😭

sudden geyser
#

don't worry they'll come back and be thankful for suggesting the friend's friend

snow vector
#

lol

austere surge
#

wh

idle coral
#

disregard

austere surge
#

oki

idle coral
#

lol I literally forgot a ) on the line above

austere surge
#

i saw something immediately wrong but didnt have enough time to know what christmasthink

ancient nova
#

why tf is the performance so bad

#

wait let me try using urp instead

#

last time I tried drawing many objects and many light sources urp worked better

stiff dust
#

is there any different to set avatar size 1024/2028/4096 ?? cause i see same thing in all of them (DJS)

sudden geyser
#

wdym

#

You can set from 16 to 4096

#

And it keeps multiplying, so 32 is valid but 24 is not

craggy pine
#

Probably means how Discord displays the images

#

They do rescale down, yes.

#

But I perfer to use 1024 / 2028 since it'll hold more detail the higher u go

tulip ledge
#

2028 isn't possible

warped venture
#

apart from buying a promotion on top.gg to grow my bot how else can i like advertise my bot so i can get upvotes to get those credits to buy the promotion

austere surge
#

ask your friends if they wanna see/invite your bot

slender wagon
#
  if (interaction.channel.type != 'DM') return;

this works fine when i start the interaction on a channel it returns

#

but when i start the interaction on the dms

#

Cannot read properties of null (reading 'type')

earnest phoenix
slender wagon
#

that's exactly what i am trying to not do

sudden geyser
#

could use ?.

frail cliff
#

Hi

tulip ledge
split hazel
#

@earnest phoenix just got a segmentation fault in node 😱 😱 😱 😱 😱 😱

sudden geyser
#

how did you pull that off

sudden geyser
#

or did you touch c++

split hazel
#

late april fools prank

sudden geyser
#

aw

#

boring

split hazel
#

this will never happen

tulip ledge
#

whats a segmentation fault?

earnest phoenix
#

Best April Fools joke

sudden geyser
#

it's where you did dumb stuff with pointers

split hazel
tulip ledge
#

ah

#

alright ty

split hazel
#

and in turn the OS kills the process that does it

#

dont want some pesky program reading your grandmas password from memory

simple stump
#

I'm trying to use express to pipe a response to my main server since for some reason subtitles/captions don't work if they are local (???). I have this code so far, but I get the error Error [ERR_STREAM_CANNOT_PIPE]: Cannot pipe, not readable.

app.get("/subtitle*", async(req, res) => {
    if (!req.params || !req.params[0]) {
        return;
    }
    let id = req.params[0];
    if (!id) {
        return;
    }
    id = id.split("/")[1];
    db.serialize(async function () {
        await db.get('SELECT * FROM shows WHERE id = ?', [id], async function (err, rows, fields) {
            if (err) reject(err);
            if (!rows) {
                return;
            } else {
              let path = ...; // Path is the path to the local file which works perfectly fine.
              let stream = fs.createReadStream(path);
              console.log(stream);
              res.set('Content-Type', 'text/vtt');
              res.pipe(stream);
              res.end();
            }
        });
    });
});

Then in my express page, I use HTML and jQuery to send an HTTP request and set the track src like this:
JavaScript

// API is the home page. Essentially localhost:3000
$.get(api + '/subtitle/${id}', function(data) {
  console.log(data);
  var video = api + '/subtitle/${id}';
  $('track').attr('src', video);
  $('#sublink').attr('href', video);
});

HTML

<track src="" kind="subtitle" srclang="en-US" label="English" />
tulip ledge
#

idk bout ur issue but this is pretty stupid

   if (!req.params || !req.params[0]) {
       return;
   }
   let id = req.params[0];
   if (!id) {
       return;
   }

ur already checking if req.params[0] exists no need to check again

simple stump
#

oops. mb. i fixed my issue anyways:
fs.createReadStream(path).pipe(res);

thorny flume
#

I create a message cleanup command for my bot using bulkDelete
he returns me a collector
I passed without a map
and i wanted to get the number of times it was returned
tried with .length
but it returned to me undefined
someone help?

lyric mountain
#

show the code, it's easier to understand

thorny flume
#

lol

#

I sent it all rolled up, forgive me

#

I created a command using bulkDelete, it returns the messages that were deleted, I took and passed it in a .length, but it returned me undefined

thorny flume
#
await message.channel.bulkDelete(args[0])
     .then(async (result) => {
        if (result) {
           esult.map((result) => console.log(result.length)) // return undefined
        }
     })
pearl trail
#

result.size ?

thorny flume
#

hm....

pearl trail
#

you don't need these

        if (result) {
           esult.map((result) => console.log(result.length)) // return undefined
        }
thorny flume
#

I hadn't remembered the size

eager yarrow
#

Any python devs available?

thorny flume
#

I know, just to not have an error, this command is executed multiple times, malicious users can take advantage of this, to make the bot crash

pearl trail
#

then dont make malicious users can use it, i'd assume this is for your purge command, just let user who have MANAGE_MESSAGES or even administrator can use it

#

or make a cooldown system

lament rock
#

a combination of both

wheat mesa
#

and also limit the args between 1-100

#

unless djs handles that internally

sudden geyser
#

actually 2-100

solemn latch
#

id also put a ratelimit with the cooldown.

wheat mesa
#

yeah, with bulkdeleting it's easy to hit ratelimits

livid lichen
#

Hey developers-- when is the best time to redeem your $15 vote credits?

wheat mesa
#

ok so if anyone knows how to handle this (with relatively little context, it's difficult to explain my exact project structure), I have a parser that can currently handle prefix unary operators (like -5, or -sin(3.14), etc), but I'm wondering how I should handle postfix unary operators (like 5!, or sin(3.14)!)

#
    private Expression Unary()
    {
        // TODO: make this work with factorials/postfix unary ops
        while (Match(TokenType.Minus))
        {
            var op = Previous();
            var expr = Unary();
            return new ExpressionUnary(expr, op);
        }

        return Primary();
    }
``` basically `Primary()` is where number literals and stuff like that are identified and parsed properly, but the problem is that I can't seem to get postfix operators to work
#

(Previous() gets the previous token in the list)

#

It's difficult to post all of the code since it's a very heavily linked structure, but essentially the expression -5! would be scanned into the tokens ```
Minus
Number (5)
Factorial
Eof

#

this is c# btw

#

nevermind, I made a really simple solution and I realized I was just overthinking it

#

probably not the best solution, but It works™️ ```cs
private Expression Factorial()
{
var expr = Unary();

    while (Match(TokenType.Factorial))
    {
        var op = Previous();
        expr = new ExpressionUnary(expr, op);
    }

    return expr;
}

private Expression Unary()
{
    while (Match(TokenType.Minus))
    {
        var op = Previous();
        var expr = Unary();
        return new ExpressionUnary(expr, op);
    }

    return Primary();
}
celest pagoda
#

@bright thorn

#

thats the error

bright thorn
celest pagoda
#

that works

#

but now my hosted version goes down

#

or it should

#

figured it out

bright thorn
celest pagoda
#

i put new token

#

and it works in pc

#

but not in the server

#

and i realise why

bright thorn
#

wait for some time

celest pagoda
#

i think discord made an update so people cant run 2 instances of 1 bot anymore

#

if i turn my pc one off now and turn on the one in the server it should work

celest pagoda
#

lemme check rq

bright thorn
#

yeah

#

go ahead

celest pagoda
#

nvm

#

it still doesnt work in my server

#

so its just a 1 use thing?

#

dam

#

thats annoying af

#

after 1 use you cant use it again

#

nvm

#

none of the tokens work anymore

#

wtf is going on

#

even if i use the new token that i just reset

#

it doesnt work

#

same error

pearl trail
#

ip banned most prob

wheat mesa
#

well, don't try to run 2 instances of one bot

#

if you need one instance for testing and another for prod, make a separate bot application for testing instead

#

reset your token, copy it exactly as it appears, and retry it

#

Is there a better way to get "accurate" results with trig functions than doing this?

    public static double Tangent(double radians)
    {
        switch (radians)
        {
            case Math.PI / 6:
            case Math.PI * 7 / 6: return 1 / Math.Sqrt(3);
            
            case Math.PI / 4:
            case Math.PI * 5 / 4: return 1;
            
            case Math.PI / 3:
            case Math.PI * 4 / 3: return Math.Sqrt(3);
            
            case Math.PI / 2:
            case Math.PI * 3 / 2: return double.NaN;
            
            // more special cases
        }
        return Math.Tan(radians);
    }

I'm not looking to overcomplicate it, it just seems like there has to be a better way to deal with floating point inaccuracy

celest pagoda
#

why would i be ip banned

celest pagoda
#

oh i think ik why

pearl trail
scenic kelp
#

if you need more precision than the datatype offers you shouldn't be using that datatype

pearl trail
#

having two instances or more can make ban change higher

#

chance*

wheat mesa
# scenic kelp isn't it accurate enough as it is?

the slight imprecision in pi makes it so things like Math.Tan(pi / 2) returns some large number instead of NaN, and same thing with Math.Tan(pi / 4) returning some slightly imprecise floating point instead of 1

#

It's not that I need really precise decimals, I just need to handle special cases where the exact value is known to be a certain number

#

Any other case is plenty accurate for my case

scenic kelp
#

i mean then the only issue is you can have numbers that are so close to pi/2 but aren't actually pi/2 that get treated as though they are

wheat mesa
#

I suppose I should probably just handle asymptotes and whole number values as special cases, and let the built in function handle everything else

wheat mesa
neat ingot
#

you can have a double nan? 👀

wheat mesa
#

Yeah

#

There’s not a generic NaN type so I just used the struct value of it

quartz kindle
#

NaN is actually part of the double precision spec and therefore a valid double precision value

#

same with infinity and negative infinity

neat ingot
#

i always thought NaN was like, of type NaN

#

oh, apparently in js typeof NaN;// => 'number'

#

well there ya go then 😂

stiff dust
#

how can i add something like this to my status?

neat ingot
#

click my name, click website, click download.

stiff dust
#

are u sure that mac do same thing?

neat ingot
#

no mac did not use my app, i made my app after i seen mac's status. the app will do the same thing

#

unless you mean like, on mac os?

#

😄

solemn latch
#

most people afaik write their own rpc tools

stiff dust
#

no i mean the Mac#8888

neat ingot
#

i mean, you can write your own, you can use my app, or one of the many other apps.

#

i made my app cause no other supported getting data from some server to show in status, like bot counts

stiff dust
#

btw i know how to write rpc but i have 2 problem 1 how can i get servers count of my in my rpc and what should i do that any time i become online in discord my status became that

neat ingot
# solemn latch neat idea

thanks. its basically just polling some endpoint periodically and replacing text, easy enough really, but all wrapped in a nice gui thats being updated a lot atm. quite enjoying the process of it all tbh 😄

#

learned so much releasing an open source app like this

solemn latch
#

Mine has a disconnect issue, which is why I dont use it

neat ingot
#

been working on nicer themes/generator thing for it the past few days 🙂

#

your rpc has a disconnect issue? or some tool you wrote?>

neat ingot
stiff dust
solemn latch
#

yeah my rpc tool.

for some reason it'll disconnect from rpc and not reconnect.
I just need to restart the client when that happens, but its so unclean to do it like that. so I dont lmao.

neat ingot
neat ingot
#

lmao yea, I need to fix that for my app too. i noticed if discord disconnects when it tries to update it just breaks 😄

#

but i did add auto updating for the next release, so hopefully any issues will get patched in the future easily 🙂

solemn latch
#

auto updating is always a fun one

stiff dust
#
const rpc = require("discord-rpc")
const client = new rpc.Client({ transport: 'ipc' })
client.on('ready', () => {
    client.request('SET_ACTIVITY', {
        pid: process.pid,
        activity: {
            details: "text",
            assets: {
                large_image: "Image",
                large_text: "text"
            },
            buttons: [{ label: "btn1", url: "url" }, { label: "btn2", url: "url" }]
        }
    })
})
client.login({ clientId: "bot id" }).catch(console.error);

this is my code
https://cdn.discordapp.com/attachments/860955124955480104/868074535478526012/Custom_Discord_RPC.mp4

neat ingot
#

yea, i had never implementd it before

neat ingot
#

maybe though

stiff dust
neat ingot
#

you would have to, in your bots code, create an api with an endpoint for you to contact from your rpc code

stiff dust
neat ingot
#

then you create some endpoint like /bot-stats that returns json counts of your servers etc

stiff dust
#

https:// [app name] .herokuapp.com/

neat ingot
#

and then in your rpc code, contact that api for your stats

stiff dust
neat ingot
#

that completely depends on how your api is setup

stiff dust
#

i dono ¯_(ツ)_/¯

neat ingot
#

but the basics of it is: get the count from your bot and return that information

stiff dust
#

but even i do this we have another problem

#

i need to run the code day by day

#

with your application am i need to run it everytime?

neat ingot
#

if using a node.js server powered with express, thats as simple as doing something like:

app.get('/stats', (req, res) => {
    res.json({
        some: 'property',
    })
});
neat ingot
#

there is an option for it in the app settings

#

but you would still need to create your api endpoint

stiff dust
#

okay tnx

neat ingot
#

i cant help with that part im afraid 🙂

wheat mesa
#

What I did when I was using RPC for a bit is I had a db with the stats updated every 30 seconds or so, and the RPC would grab that data from the db

#

So that I didn’t need to create an api like that

earnest phoenix
#

hello

#

i need a help

#

i want to go to the page where i have added my server to see how many votes it has got so how can i go there

eager yarrow
#

Looking for assistance with Topggpy Python lib.

The Webhook configuration in github references using @topgg.endpoint() while the topgg api document does not, and instead references bot.topgg_webhook = topgg.WebhookManager(bot).dbl_webhook().

I have configured my bot both ways to get the webhook api to work but it is not working. There are no errors in logs for this. My bot is simply not picking up the vote event

sudden geyser
#

If a client makes an HTTP GET request to a REST API and that API modifies global state that may have an effect on the request and future requests, is that really a GET request RegThink2

neat ingot
#

like, i could see some get request that stores state/data so it doesnt repeat itself for some duration

#

some some meme fetcher api or something

sudden geyser
#

Anything. Could be a map or a database. Could only affect 3 or 3 billion devices.

solemn latch
#

sounds like a patch

neat ingot
#

if a request takes input data to alter some db item or similar that would be later referenced/recalled, then it should not use get requests

sudden geyser
#

Say, if a request for an image causes the server to run a task to save and cache it, is that really a GET request? To the client, it does the same thing. But internally, it's not. OugiWave

neat ingot
#

well, that kinda is, your just cacheing it

#

your acting as a proxy with a cache for a get request - to be more specific

#

assuming you fetch the image from somewhere else

#

if you generate it, then thats just being resource conscious imo 😄

boreal iron
#

Which in your example isn’t a forced update

eager yarrow
#

To my previous posted question, I have now found a 3rd Topggpy doc using yet again completely different logic to configure the webhook.

solemn latch
eager yarrow
eager yarrow
# solemn latch https://topggpy.readthedocs.io/en/stable/webhooks.html?highlight=webhook#topgg.W...

This logic is utilized on https://docs.top.gg/libraries/python/, which is from the first time I posted the request for aid as that does not work.

Then there's the github linke https://github.com/top-gg/python-sdk/tree/master/examples/discordpy_example from my 2nd request for aid as that doesn't work, as topgg doesn't have an endpoint() attribute.

There's also https://topggpy.readthedocs.io/en/latest/api/webhook.html which is from my latest posting the request for aid as this does not work, as topgg doesn't have a WebhookEndpoint attribute.

GitHub

A simple API wrapper for top.gg written in Python. Contribute to top-gg/python-sdk development by creating an account on GitHub.

eager yarrow
#

That messaged reads incredibly pretentious and believe me that is not the case.

solemn latch
#

👀

eager yarrow
#

The latest doc you posted is what I currently have (after reverting from previous attempt) and while it is throwing no errors it s not picking up the vote event.

solemn latch
#

it was picking up the test event correct?

eager yarrow
#

No.

solemn latch
#

🤔 well that changes everything then.
You implied test events got picked up

#

I'm assuming you are hosting on a vps correct?

eager yarrow
#

Test events are picked up in my Discord server, so that validates the webhook works (auth key, webhook url, etc)

#

VPS?

#

Heroku

solemn latch
#

what do you mean picked up by your discord server?

eager yarrow
#
@bot.event
async def on_dbl_vote(ctx, data):
    if data["type"] == "test":
        # this is roughly equivalent to
        # return await on_dbl_test(data) in this case
        return bot.dispatch('dbl_test', data)

    print(f"Received a vote:\n{data}")

The vote event, when someone votes for my bot, is not being picked up by the bot.

solemn latch
#

your getting a message in your discord server when someone test votes?

eager yarrow
eager yarrow
solemn latch
#

so data is empty?

eager yarrow
#

async def on_dbl_vote(ctx, data): is not hit at all.

#

on_dbl_vote() is not being invoked.

solemn latch
#

thats really strange its sending a message, but the events not firing.

#

did you fill in your heroku url and auth on top.gg in your bots webhook section?

eager yarrow
#

My bot is not what's sending the message.

solemn latch
#

whats sending the message?

#

@pliant gorge the bot?

eager yarrow
#

Yes

solemn latch
#

👀 when did we add that

rose warren
#

We didn't

solemn latch
#

intresting

solemn latch
sage bobcat
#

One message removed from a suspended account.

eager yarrow
#

On Top.gg, when you route to your bot, click edit, click Webhooks, configure the Webhook URL & the Authorization, click Send Test it sends a voter message to the Discord channel you have the webook in.

solemn latch
#

with a discord webhook?

eager yarrow
#

The Send Test button there.

#

Yes.

solemn latch
#

thats not a topgg tool, its third party

#

the reason your event isnt firing is you have the webhook going to webhook-topgg.com not your code.

eager yarrow
#

Do I type dblwebook in the webhook url?

solemn latch
#

nope itll be your heroku public url

#

youll also need to enable a web dyno

wooden ember
#

so discord is actively tryna mandate /comands? does this mean eventually we will lose the ability to use normal comands?

#

idk how theyd do that though