#development

1 messages · Page 260 of 1

eternal osprey
#

hey guys i am trying to create an image classification model.
It's a model that basically should classify images into a few categories:

  1. Adults, 2. Children, 3. All, 4. Inappropriate
    What do you guys suggest, shall i create it from scratch? This will need a hella big dataset... and well there's gonna be some sketchy ahh images in there as well to test the innapropriate label.

May there instead be a pre-defined model that i could download and use online?

lament rock
eternal osprey
#

mmhmm yeah exactly thats true.

#

i don't necessarily need anything that's gonna be 100% accurate

#

The thing i need is also very specific, so i dont even think i can use pre-built models

#

as well, they are all trained for a specific set of labels.

#

so i MIGHT have to do it myself anyways..

next storm
#

how to get started with creating a custom RPC with 2 buttons using js?

warm surge
#

@next storm

#

oh i miss read it

warm surge
# next storm how to get started with creating a custom RPC with 2 buttons using js?

this is my old code for RPC (pulled out of my friend dm) ```const RPC = require('discord-rpc'); // npm i discord-rpc
const rpc = new RPC.Client({ transport: 'ipc' });

rpc.on('ready', () => {

    rpc.setActivity({
        details: '',
        state: ``,
        largeImageKey: '',
        largeImageText: 'Invite Virsa',
        buttons: [
            {
                label: `Invite`, url: ''
            },
            {
              label: `Support`, url: ''
          }
            ] // you can remove buttons, yes but you cant add more than two
    })
console.log('Authed for user', rpc.user.username);

});

rpc.login({clientId: '' })
.catch((err) => {
console.error("An error has occurred:", err);
})```

#

just change stuff

next storm
# warm surge this is my old code for RPC (pulled out of my friend dm) ```const RPC = require...

it shows this:

An error has occurred: Error: Could not connect
    at Socket.onerror (D:\dr\node_modules\discord-rpc\src\transports\ipc.js:32:16)
    at Object.onceWrapper (node:events:634:26)
    at Socket.emit (node:events:519:28)
    at emitErrorNT (node:internal/streams/destroy:169:8)
    at emitErrorCloseNT (node:internal/streams/destroy:128:3)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21)```
#

ah damn, working now, didn't use desktop version smh

#

btw, how to make this automated? @warm surge

warm surge
#

wdym

next storm
#

like if I want to use this then I've to always run this code so that the Rich Presence is visible'

#

can't this be automated

warm surge
#

yes

next storm
#

can it be?

warm surge
#

use pm2

next storm
#

if I restart my pc then

#

again I've to run

#

;-;

warm surge
#

or even restarting discord

next storm
#

what do you use personally?

#

for the RPC

warm surge
#

like code or?

next storm
#

not code, for automation

warm surge
#

i dont, you have to start it when you want use it but use pm2 so you dont have keep vscode running in the background

next storm
#

umm okay

next storm
#

like what happening is that on opening the bat file, it opens the command prompt, and closes it instantly, though the RPC works, but the problem is it gets stuck in a loop where it opens and closes command prompt continuously

warm surge
#

open your cmd

#

Cd whatever you have it at

#

and type

#

pm2 start index.js

next storm
#

@warm surge this is happening

#

Idk why a separate terminal is opening and closing in a loop

warm surge
#

pm2 log 0

next storm
#

ah wait

#

@warm surge

warm surge
#

its working

next storm
#

yeah but why the terminal is behaving like that

warm surge
#

idk

next storm
#

;-;

#

any fix for that?

warm surge
#

it doesnt do that with me so idk

next storm
#

like is it because of any config of pm2 or something

warm surge
#

nope

next storm
#

ugh

delicate zephyr
#

if you want raw logs with out the 0/index |

next storm
#

I want to fix that opening and closing loop of terminal

delicate zephyr
#

thats powershell and pm2

#

maximize it then going into logs

next storm
warm surge
#

maximize your cmd and log it

delicate zephyr
#

^

next storm
#

you want to me to maximize the command prompt, and then run the above cmd?

delicate zephyr
#

yes

#

wait, are you trying to build a rich presence that stays on all the time for your discord?

delicate zephyr
#

you know that you're reinventing the wheel right

next storm
#

wdym

delicate zephyr
#

this literally exists

next storm
#

is it safe?

delicate zephyr
#

it's open source and used by plenty of people, scan it with your anti-virus and slam it in virus total if you're that worried

warm surge
#

oh yea

#

probably on window safe mode

delicate zephyr
#

nah they just havent signed the exe

warm surge
#

ik

next storm
#

ah damn, my code was ready lol

#

nvm

#

will use this app instead

feral aspen
split owl
#

guys how do I fix 429 rate limit error
discord.errors.HTTPException: 429 Too Many Requests (error code: 0)

i've changed my code like adding timeouts on commands and cooldowns between api requests but this error still keeps popping up

edit: i have a vps and dont host it on a common IP so the error shouldnt be because of that

#

on the most recent error it literally rate limited my bot because of my /help command that has 0 api requests

harsh nova
#

I think there's some program where you pay windows to be listed as a trusted certifier but the process is likely involved and they have ur legal name

feral aspen
harsh nova
raven nexus
#

how could i make it work? it still like this i want to add it everything

quartz kindle
#

is this the file you are showing?

raven nexus
quartz kindle
#

if you dont need it anymore, remove that line

raven nexus
#

ok

#

i want to know is distube run by lavalink

#

or no?

quartz kindle
#

i dont know, you can check their npm page or github page

raven nexus
#

after i restart i keep getting this

lyric mountain
#

index is supposed to be just the entrypoint, alas why it's called index

thorn torrent
#

Hello, I have a question. How can I have a reward for voting like the rest of the bots?

digital swan
#

Use the webhook

crystal wigeon
#

anyone here build microservices? topggThink

solemn latch
#

I've microserviced one thing to make it easier to do high availability.
Still never deployed it, still finalizing stuff.

crystal wigeon
#

wait are you the same woo who got married

solemn latch
#

No, unless I married maggie and didn't know

crystal wigeon
#

lmao nvm it was another guy

wheat mesa
#

confusing the W’s

crystal wigeon
#

yess

#

it was waffle

#

lol

solemn latch
#

You're married waffle?

crystal wigeon
#

anyway @wheat mesa last we spoke you were working on your own startup no? just wondering, what are all the services you are building

#

yea recently

solemn latch
#

Why wasn't I invited topggAngry

crystal wigeon
#

so i been working on this idea - marketplace for microservices. where you could find production ready backend services that you could plug-n-play. It helps people ship their products faster.
You also own the code so its fully customizable.

#

And for devs you can build your own service and sell it on the marketplace

wheat mesa
wheat mesa
crystal wigeon
#

i wanted some feedback and tryna figure out what backend stuff people usually re-build. so i can offer it to them saving a lotta time. like oauth servcie for example

#

and payments

wheat mesa
#

Payments are something you outsource to another company

#

If you tried to handle transactions by yourself that’s already a startup in itself

crystal wigeon
#

yeah but like if you were to integrate with paypal,. or stripe

#

you build a backend

#

no no, its a backend service with all the integrations basically

#

that gets you setup quick so you can focus on business logic

wheat mesa
#

Personally I have never made a microservice. I have not done a lot of deployment or anything like that, still have a lot to learn there

crystal wigeon
#

so you dont waste time setting the usual things. like oauth, payments, file management. code deployment

#

mhm

#

but you get the idea no? you have everything tailored and ready to use.

#

And if you are a dev you can build and sell your backend service that many people would use. if its robust enough

wheat mesa
#

I get the idea but this really sounds more like a software contracting company

crystal wigeon
#

its more like rapid api

#

but here you get full access to code. and can customize

#

you own everything

#

like a boilerplate

#

once we have a landing page ready it might shed more clarity. but yeah. tryna see what services people are using in their projects. some might be useful to others as well

solemn latch
#

I like the idea, I just don't know how valuable it is for most people.

I feel like some polls on public forums to figure out of there's an audience for it may help. Make a poll on a few reddit forums and twitter.

crystal wigeon
#

right, can you share your email with me, so i can get you on the waitlist?

#

i mean people have bought ship fast boilerplate

#

which is not secure at all

#

so im sure people would use it to help them build faster

#

but yea. do you have any reddit channel recommendations?

#

dropped you a dm

#

sent you both a dm

crystal wigeon
#

dont htink too hard, just throw what comes to mind 😂

solemn latch
#

One of the things that takes me awhile is secure internal database API calls.

IE, have a microservice that has an API that has the sole purpose of doing database calls.

#

I just have a boilerplate that I use these days.

crystal wigeon
#

A backend service for secure internal DB calls. hmm not sure how that works

#

btw its also not just limited to js

solemn latch
#

Mines written in GO these days, yeah.

solemn latch
#

Assuming you want this to be a marketplace you'll want tags for different deployment enviorments.

crystal wigeon
#

mhm

crystal wigeon
#

the deployment im writing will like support different platforms like gcp, aws, flyio

tidal pendant
#

Can someone explain to me what the decorators in python actually are ?

solemn latch
solemn latch
#

Looks like at the most simple level, its a function in a function.

sharp geyser
#

Functions basically the same in typescript as well

#

the outer function takes in arguments, the inner one is supposed to modify what its used on while having access to these outer arguments

solemn latch
sharp geyser
#

yuh

#

decorators if used properly are very handy

#

that debug decorator is a bit more on the complex side

eternal osprey
#

hmmmm???

cobalt tinsel
#

bro

#

how to get our bot online 24 hours?

deft wolf
#

Rent a VPS and host your bot there

earnest phoenix
frosty gale
quasi hinge
#

My bot was declined for not having features or commands... But it does. Who can I talk to?

small tangle
deft wolf
earnest phoenix
primal fog
#

Hey fellow developers. Do you think a discord bot can still be profitable in 2024?
I am not building another moderation, all-in-one, AI or anime bot so I believe its sort of unique

#

Question is do bots make money nowadays

bitter granite
wheat mesa
#

A job will make you more money than a discord bot will

warm surge
#

indeed

#

i got no job beside school paying me

sage bobcat
warm surge
#

^

deft wolf
#

Discord bot is more like a hobby, in 99% of cases you just pay extra for it or you are even

sage bobcat
#

One message removed from a suspended account.

#

One message removed from a suspended account.

warm surge
#

plus

#

discord payments rates are shit

bitter granite
deft wolf
warm surge
bitter granite
#

and you have to deal with dumb support

warm surge
#

discord takes half or even more of money you earned

primal fog
bitter granite
primal fog
#

But I guess 2021 covid was the time to do it

bitter granite
warm surge
#

thats would be worse

bitter granite
#

would be better precovid

primal fog
#

I thought that everyone being at home would increase discord traffic no?

bitter granite
primal fog
#

True

bitter granite
#

the thing is from me reviewing bot

#

i rarely see bot being online after like 2month of testing

primal fog
#

well in case you review mine let me know

primal fog
#

I am gonna submit it try it out for lie 4-5 months and see what I can do

#

Hetzner vps is cheap anyways

deft wolf
#

Mine will be online for the second year next month YESSSSSS

bitter granite
primal fog
primal fog
deft wolf
#

I don't even know

primal fog
deft wolf
#

3k

primal fog
#

what's the name?

bitter granite
deft wolf
bitter granite
digital swan
primal fog
#

So I guess fair

bitter granite
real rose
#

vps > shared

bitter granite
primal fog
#

Depends what the bot does

real rose
#

more access to stuff

bitter granite
real rose
#

hetz starts at like 4eur for 4gb anyway

warm surge
#

novonode vps are the goat

bitter granite
real rose
#

wym

#

donation place

bitter granite
real rose
#

oh

#

affiliate

#

you mean

#

yeah hetz doesnt iirc

bitter granite
warm surge
bitter granite
warm surge
real rose
#

cringe

warm surge
real rose
warm surge
bitter granite
#

i have it on my wa bot as a cmd e!donation

warm surge
primal fog
#

Nah whatever is moneized day 1

#

will be all

digital swan
primal fog
#

And its a mini-game not a moderation bot so no weird paywalls

warm surge
#

share that with me

digital swan
#

but you cant withdraw that

warm surge
#

pleaseee

bitter granite
#

since i wont need to deal with payment

warm surge
#

i need pay my rent i already paid for like week ago

bitter granite
digital swan
#

fr?

primal fog
bitter granite
#

onlu 5$ fee
minimum 30 i think

digital swan
#

still a fee though

#

just seems better to use kofi and receive the money yourself

bitter granite
warm surge
#

my school pays me more anyways

#

but is monthly

primal fog
#

tbh it takes courage to builda moderation bot

#

into the existing ones

bitter granite
primal fog
#

like dyno mee6 etc

digital swan
primal fog
warm surge
digital swan
primal fog
#

THey chaned the policy. Whatever you sell on a 3rd party (coffee, ko-fi, patreon, pernsonal-site) must be on discord as well

digital swan
#

if youre not selling any bonus and its just a donation

bitter granite
primal fog
#

Good luck getting a donation on a discord bot

digital swan
primal fog
#

Without any benefits

bitter granite
primal fog
#

Good luck scaling nonetheless

bitter granite
#

my bot is in low ammount of server
but the server quality is good

warm surge
bitter granite
#

i dont use novonode for a reason

primal fog
#

if i submit now am i still eligible?

#

or you guys already voted

bitter granite
primal fog
#

Wait last post mentioned Q2 picks and thought q3 was coming up

bitter granite
#

my brain isnt working

bitter granite
primal fog
#

okay so i better wrap up development then

#

and call it

bitter granite
#

@warm surge am i in the correct site?

warm surge
#

novocode

#

noice

raven nexus
#

anyone know php well?
i want to know how to make it allign same line

digital swan
#

I’m not sure that’s php specific but could you not just use grid?

proven lantern
raven nexus
#

this is my first time

digital swan
earnest phoenix
#

me when windows slow

pearl trail
#

chat is this real

quartz kindle
#

you just have to use using use

harsh nova
surreal sage
coarse turtle
#

why does my server count say 123?

lyric mountain
#

u probably sent that value to topgg

coarse turtle
lyric mountain
#

Well, topgg only shows what you give them

wheat mesa
#

CORS is going to be the death of me god

lyric mountain
#

You probably left some debug code to upload that specific number

lyric mountain
#

At this point it's basically an initiation rite

wheat mesa
#

Does anyone know why my ASP.NET backend is having issues with CORS? I'm trying to make a POST request from a Vue SPA running on http://localhost:5173 to my ASP.NET backend running on http://localhost:5063 with a CORS policy like so:

      builder.Services.AddCors(options =>
        {
            options.AddPolicy("AllowSpecificOrigin", policy =>
            {
                policy.WithOrigins("http://localhost:5173")
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials();
            });
        });
      // ...
      var app = builder.Build();
        
      app.UseCors("AllowSpecificOrigin");
``` and a request that looks like this: ```ts
const res = await fetch("http://localhost:5063/api/auth/callback", {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({
        code: authCode
    })
});
#

It seems my browser is making a preflight request that fails, but it won't tell me any errors since it is not available to scripts, so I don't specifically know what's wrong

lyric mountain
#

Did you try 127 instead of localhost?

wheat mesa
#

I have not but I don't think it would make a difference

lyric mountain
#

Oh also, in port might not be the same as out port

#

Check if the calling address is 5173

wheat mesa
#

Wdym

#

The network request?

lyric mountain
#

Hm, actually nvm, it'd be the same as it's a site

#

Well, first of all try to allow * just to check if the setup is right

wheat mesa
#

Here's the headers for the preflight req btw

OPTIONS /api/auth/callback undefined
Host: localhost:5063
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:132.0) Gecko/20100101 Firefox/132.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br, zstd
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Referer: http://localhost:5173/
Origin: http://localhost:5173
Connection: keep-alive
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
lyric mountain
#

If it allows passing then you can narrow down to the specific address

#

Try with 127 to check

#

Some things refuse to work with localhost alias for some reason

wheat mesa
#

Still fails with .AllowAnyOrigins()

lyric mountain
#

Then the api part is wrong, not the address specifically

wheat mesa
#

Still fails using 127 address too

lyric mountain
#

If * failed then it's not an address issue

#

Idk how asp works tbh, but the issue is in how you're setting the policy

#

It's annoying to get right always

wheat mesa
#

agh

#

I gtg for now but I asked in the C# server too, hopefully they know what's wrong

#

ASP is finicky sometimes

lyric mountain
#

gl

wheat mesa
#

Yeah no it turned out I'm a moron and I mistyped one number in the port

sharp geyser
raven nexus
civic scroll
#

is this cursed

small tangle
#

i smell apache spark

solemn latch
#

does the identify scope provide email addresses?

I purged my database, logged in with just the identify scope and it still provided an email address.

#

Odd

#

NVM, its caching somewhere that I'm unaware of

#

Oh, its actually inside of authorized apps. Since I authorized email once it always provides my email. Weird.

civic scroll
#

there is no data stream 😔

sharp geyser
#

email is only provided with the email scope when doing oauth2

#

Assuming you mean discord

frosty gale
green kestrel
earnest phoenix
#

@harsh nova is interested

harsh nova
#

-b 1305163978854498364 crypto scam

gilded plankBOT
#

upvote jerry002009#0 was successfully banned.

bitter granite
bitter granite
harsh nova
bitter granite
#

all location is there

harsh nova
#

Luca sucks so bad

harsh nova
earnest phoenix
#

read to massage them?

harsh nova
#

Sure wish Luca had a nuke command

harsh nova
bitter granite
deft wolf
harsh nova
#

Always forget to use in app ban

bitter granite
#

Atleast its inst like 10+ message spam per channel

dusky idol
#

How good of an idea it is to host multiple MongoDB clusters for one single high traffic Discord Bot in order reduce lag/delay in commands?

#

Would love to hear pros and cons of it pray_zc

lyric mountain
#

mongo was already supposed to be used in high traffic environments

#

if you're feeling a delay then something is wrong with your flow

#

but well, the pro is that you scale horizontally, so you can have 2 medium specs servers instead of 1 top spec

#

the con is that you double the resource consumption

dusky idol
lyric mountain
#

sounds like a leak

#

what language are we talking about btw?

dusky idol
lyric mountain
#

those threads that you see going up, are they being properly disposed of?

#

afaik python doesn't have threads, it uses sub processes to mimic them

dusky idol
#

For some additional information, I'm self hosting the bot through my other device as I found it more reliable method to resort to

lyric mountain
#

shouldn't matter much

#

just take note if the threads are piling up, and keep an eye on htop for high cpu usage

dusky idol
lyric mountain
#

what is your bot about?

#

wait you're using windows to host?

#

but well, from what I see your bot is goin into swap memory, which will be much slower than phys memory

#

your websocket latency is also very high, so it might be compounding into the delay you're feeling, perhaps your bandwidth isn't enough for the demand

dusky idol
lyric mountain
#

and at last, if your threads are separate processes and not virtual threads (threads that are created within the runtime not OS) then you might be suffocating your cpu

dusky idol
#

Popular genre

lyric mountain
#

yes, but high latency will affect all requests

#

every transaction made with discord will have that latency added into it

dusky idol
#

I had a conversation with a dude facing similar problem, he said that it was the case for him too but he switched from mongodb to sql and it fixed, now I'm sure there must be a better way than just switching database

lyric mountain
#

also for a gacha bot you could disable message cache, unless you're fetching messages very frequently

lyric mountain
#

mongo excels at being thrown random stuff to later fetch by id

dusky idol
lyric mountain
#

while sql excels at data organized into tables and relationships

#

also another thing to note is that mongo will take as much memory it's allowed to

#

sql databases usually refrain from taking memory preemptively

lyric mountain
lyric mountain
dusky idol
dusky idol
lyric mountain
#

that'd be 7 threads per core, the recommended is around 2

dusky idol
lyric mountain
#

I'm back

lyric mountain
#

in my bot I use cores - 2 for my pool

#

the leftover 2 cores I leave free for the OS to use, my bot is quite cpu intensive so I dont want to starve the system itself

#

and then I have an unbounded virtual thread pool for the commands themselves, those are created and managed akin to JS promises (created and managed by the runtime)

#

but a way to check if this might be the issue is to look at your CPU usage

#

if it's maxed nearly all time then it's suffocated

#

also reduce your maximum allowed mongo cache to about 40% of your total physical memory, so it doesn't push your bot into swap zone

#

fine tune that percentage based on your taste, the more cache you give to it the faster the database will perform, but the less physical memory your bot will be allowed to use

stark abyss
sage bobcat
#

One message removed from a suspended account.

proven lantern
#

are discord quests going to be like steam achievements?

#
This event cannot be received by apps at this time. It's documented because it appears on the Webhooks settings page.
QUEST_USER_ENROLLMENT is sent when a user is added to a Quest on Discord.```
bitter granite
earnest phoenix
quartz kindle
#

lmfao

frosty gale
#

big companies try not to pretend that a massive data breach has never happened to them challenge (impossible)

pine willow
#

idk if I should make that a public bot or not

digital swan
#

could get expensive

#

those flames are definitely not coming out the exhaust

sage bobcat
#

One message removed from a suspended account.

pine willow
#

Running on h100 GPUs

#
  • low-performance
pine willow
spark flint
#

thats not bugged thats just AI being AI

#

lol

sage bobcat
#

One message removed from a suspended account.

#

One message removed from a suspended account.

deft wolf
pine willow
lyric mountain
#

Nah it looks sedan

sage bobcat
pine willow
pearl trail
#

95% it does

eternal osprey
#

hey guys

#

these are basic input spinners

#

for the input type number, but it only shows on pc. It does not show on the mobile interface, while i actually need that

raven nexus
#

is there a way to do a command that required to /vote before able to run the command?

lyric mountain
#

also why is that input so big

eternal osprey
#

nooooo

#

are you fr

#

oh my days

#

i ned that fucking spinner as i am using step increment type shit

reef relic
#

What do I do?

digital swan
#

Type something

reef relic
#

Doesn’t work

#

Well I can type

digital swan
#

Then it could possibly be broken

reef relic
#

Nvm

#

I did it

#

Thanks for helping me

proven lantern
#

i have the initial work done for my private wow server bot. does this break any Top.gg rules?

#

these are the two commands. they dont enter a password or username

pine willow
#

Its creating Accounts on a non Offical Server right?

#

I don't see a Problem tbh

#

Because these aren't real information?

proven lantern
#

the username and password work when their WoW client points to my private server

pine willow
#

Shouldnt be a Problem tbh

#

But I can be wrong lol

#

Why do you make it a Public bot?

proven lantern
crystal wigeon
#

Kuu, Chitty

#

remember the idea i told you guys last time?

#

@quartz kindle @lyric mountain @eternal osprey about the marketplace for microservices

#

we just launched our landing page. can you guys give some feedback?

#

this will maybe also help you understand better what i was talking about

#

dont ban me kekcry im just asking for feedback. https://tryamnesia.com/

reef relic
#

import discord
from discord.ext import commands, tasks
import datetime
import asyncio

intents = discord.Intents.default()
intents.members = True # Enable member-related events
intents.message_content = True # For reading messages

client = commands.Bot(command_prefix="!", intents=intents)

List to track suspicious accounts

suspicious_users = set()

Configuration

ACCOUNT_AGE_LIMIT = 60 # Minimum age of account in days to join (can be adjusted)
RAID_THRESHOLD = 5 # Number of messages sent in a short period for it to be considered a raid
MESSAGE_THRESHOLD_TIME = 5 # Time window in seconds to consider raid

Function to check account age

def check_account_age(user):
account_creation = user.created_at
age_in_days = (datetime.datetime.utcnow() - account_creation).days
return age_in_days >= ACCOUNT_AGE_LIMIT

Anti-Alt Account: Check account age when a user joins

@client.event
async def on_member_join(member):
if not check_account_age(member):
suspicious_users.add(member.id)
await member.kick(reason="Account too new.")
await member.send(f"Your account is too new to join the server. Please create an account that's at least {ACCOUNT_AGE_LIMIT} days old.")
print(f"Kicked {member.name} for having a new account.")
else:
print(f"{member.name} joined. Account age is valid.")

bitter granite
#

is it python?

reef relic
#

Anti-Raid: Track message activity to detect raids

recent_messages = []

@client.event
async def on_message(message):
if message.author.bot:
return

# Record the time and user of the message
recent_messages.append((message.author.id, message.created_at))

# Remove messages older than the threshold time window
recent_messages[:] = [(user_id, timestamp) for user_id, timestamp in recent_messages if (datetime.datetime.utcnow() - timestamp).seconds <= MESSAGE_THRESHOLD_TIME]
#

Check if there's a raid

user_message_count = sum(1 for user_id, _ in recent_messages if user_id == message.author.id)

if user_message_count >= RAID_THRESHOLD:
    # Possible raid detected, take action
    await message.delete()  # Delete the message
    await message.author.ban(reason="Detected raiding behavior.")
    print(f"Banned {message.author.name} for potential raid.")
    await message.channel.send(f"User {message.author.name} was banned for raiding behavior.")
await client.process_commands(message)

Anti-Nuke: Monitor and react to mass message deletions or role changes

@client.event
async def on_guild_role_update(before, after):
# Check for any significant changes in roles that could indicate an attempt to nuke the server
if len(before.permissions) != len(after.permissions):
# Log the event, possibly alert staff
print(f"Role change detected: {before.name} -> {after.name}")
@client.event
async def on_guild_member_update(before, after):
# If user role changes significantly or if user becomes an admin unexpectedly
if "admin" in [role.name.lower() for role in before.roles] and "admin" not in [role.name.lower() for role in after.roles]:
print(f"Suspicious role removal detected for {after.name}")

@client.event
async def on_message_delete(message):
# If a large number of messages are deleted within a short time, it's a raid attempt
print(f"Message deleted in {message.channel.name} by {message.author.name}: {message.content}")

Command for bot owner to check suspicious users manually

@client.command()
async def check_suspicious(ctx):
if suspicious_users: {', '.join([str(user) for user in suspicious_users])}")
else:
await ctx.send("No suspicious users detected.")

Command to start the bot

@client.command()
async def start(ctx):
await ctx.send("Bot is now monitoring for raids and suspicious accounts!")

Run the bot with your token

client.run('YOUR_BOT_TOKEN')

deft wolf
#

But why

bitter granite
#

idk how to dev bot on python so i sadly cant help

bitter granite
#

Also no need to send all the file
you prob just need to fix the main(or other starting file) to get it to be able to connect

reef relic
#

It’s to long to send whole thing at once

bitter granite
reef relic
#

What can you dev with?

bitter granite
reef relic
#

What bot can you make?

bitter granite
#

mostly bot on another platform

reef relic
bitter granite
#

You can wait untill someone does

reef relic
bitter granite
#

like i said You can wait untill someone does

reef relic
#

So you don’t

mortal ginkgo
#

Hey, when u starting the robot what the error in console?

sage bobcat
#

One message removed from a suspended account.

#

One message removed from a suspended account.

mortal ginkgo
bitter granite
mortal ginkgo
bitter granite
#

Thats not bot token

mortal ginkgo
#

Thats not your bot token

bitter granite
#

thats bot id

mortal ginkgo
#

And dont share the real one

reef relic
#

Ok

sage bobcat
mortal ginkgo
#

The token u can get in discord developer portal

#

I think is the main problem? U dont put the real one token, thats why the bot not go onKEKW KEKW KEKW

#

Because if u share bot token anyone can connect with them

bitter granite
#

ops wrong reply

mortal ginkgo
#

Thats okey

lyric mountain
#

If a bot is able to nuke then you won't be able to stop it cuz it has higher perms than u

#

Also things will happen way too fast for people to remove the bot in time

pearl trail
#

1st function: what if an admin wanted to change role permission
2nd function: what if owner want to demote admin
3rd function: it just logs all deleted message
KEK

lyric mountain
#

Yeah, it's basically just taking the role of audit log

bitter granite
#

I just relized there is alot of print

crystal wigeon
sage bobcat
#

One message removed from a suspended account.

#

One message removed from a suspended account.

lyric mountain
#

There's a broken comment there

sage bobcat
#

One message removed from a suspended account.

#

One message removed from a suspended account.

lyric mountain
#

Yeah, that's why it's not running most likely

#

A bunch of comments are just freeform text

#

No prefix

sage bobcat
#

One message removed from a suspended account.

bitter granite
#
Anti-Raid: Track message activity to detect raids
recent_messages = []

@client.event
async def on_message(message):
    if message.author.bot:
        return

    # Record the time and user of the message
    recent_messages.append((message.author.id, message.created_at))

    # Remove messages older than the threshold time window
    recent_messages[:] = [(user_id, timestamp) for user_id, timestamp in recent_messages if (datetime.datetime.utcnow() - timestamp).seconds <= MESSAGE_THRESHOLD_TIME]
# Check if there's a raid
    usermessage_count = sum(1 for user_id,  in recent_messages if user_id == message.author.id)

    if user_message_count >= RAID_THRESHOLD:
        # Possible raid detected, take action
        await message.delete()  # Delete the message
        await message.author.ban(reason="Detected raiding behavior.")
        print(f"Banned {message.author.name} for potential raid.")
        await message.channel.send(f"User {message.author.name} was banned for raiding behavior.")
    await client.process_commands(message)
# Anti-Nuke: Monitor and react to mass message deletions or role changes
@client.event
async def on_guild_role_update(before, after):
    # Check for any significant changes in roles that could indicate an attempt to nuke the server
    if len(before.permissions) != len(after.permissions):
        # Log the event, possibly alert staff
        print(f"Role change detected: {before.name} -> {after.name}")
@client.event
async def on_guild_member_update(before, after):
    # If user role changes significantly or if user becomes an admin unexpectedly
   if "admin" in [role.name.lower() for role in before.roles] and "admin" not in [role.name.lower() for role in after.roles]:
        print(f"Suspicious role removal detected for {after.name}")

@client.event
async def on_message_delete(message):
    # If a large number of messages are deleted within a short time, it's a raid attempt
    print(f"Message deleted in {message.channel.name} by {message.author.name}: {message.content}")

# Command for bot owner to check suspicious users manually
@client.command()
async def check_suspicious(ctx):
    if suspicious_users: {', '.join([str(user) for user in suspicious_users])})
    else:
        await ctx.send("No suspicious users detected.")

#Command to start the bot
@client.command()
  async def start(ctx):
     await ctx.send("Bot is now monitoring for raids and suspicious accounts!")

#Run the bot with your token
client.run('YOUR_BOT_TOKEN') ```
#

had to fix the broken comment

#

wierd why is there "

bitter granite
pearl trail
#

the reason i say python hard is wth is this 💀 if "admin" in [role.name.lower() for role in before.roles] and "admin" not in [role.name.lower() for role in after.roles]

bitter granite
#

Wouldnt it be better to just check the roles perms

#

Or am i just dumb

pearl trail
#

i mean its AI code

#

never meant to have 0 issue

lyric mountain
random kettle
#

python is one of the easier languages to learn imo

lyric mountain
#

it is, but the low entry barrier also makes larger complex codebases nigh unreadable if not taken into account way earlier at project design

random kettle
#

both python and javascript make a lot of good coding habits "optional" with how flexible they are

lament rock
#

now isnt it just lovely eslint exists

warm surge
#

question how to get accurate rating with cpu and ram usages on node.js with process?

pearl trail
#

process.memoryUsage / 1024 / 1024

warm surge
#

e

#

process.memoryUsage().heapUsed / 1024 / 1024

#

@pearl trail

pearl trail
#

yes thats just bare code

#

you do that on each property

warm surge
#

@pearl trail is discord breaking for you

#

??

#

nvm

pearl trail
#

ye

crystal wigeon
#

Yeah apparently discord had hiccups this morning

frosty gale
warm surge
quartz kindle
quartz kindle
warm surge
#

@quartz kindle

warm surge
#

For each process

quartz kindle
#

unless your system swaps it out (windows mostly), thats gonna be the more accurate number, including the node process itself and whatever else it reserves

#

also, for cpu you cant really use it like that, its more complicated

#

cpu usage is calculated by measuring time of cpu activity

#

so you need to measure it over time

warm surge
#

thanks tim @quartz kindle

frosty gale
#

do you want what the process has physically allocated, do you want to know how much virtual memory it has, do you want to include shared memory, do you want to include swap memory as well, etc etc

deft wolf
#

I need Discord but better

spark flint
#

@solemn latch might be interested

#

:^)

solemn latch
#

@hollow blade no ads please

dapper quarry
#

Rate my organization skills.........

spark flint
#

horrible

#

imo move the commands into a diff folder

#

move dbs out of that folder

#

sort nicer

lyric mountain
#

Why...why are there so many dbs?

civic scroll
earnest phoenix
#

And just have one bot db with all the tables you need

muted harness
warm surge
#

And that’s deal breaker

bitter granite
small tangle
#

sheer loc isnt bad

dapper quarry
civic scroll
sharp geyser
#

@prime cliff when it comes to state management with blazor, what is the recommended way? I know there is several methods for it, and I have tried out one such method which is to use dependency injection, the problem with that method seems to be it does not differentiate between the client, so two people can end up seeing the same state.

prime cliff
#

So you want 2 people to view the same state i guess?

sharp geyser
#

No not at all

#

Thats the exact opposite

#

That's what is currently happening

#

State is being shared globally, when in fact it shouldn't be

#

Right now im trying to do it so that the state is user dependent

prime cliff
#

That depends on how you inject using the specific type there is Singleton

#

Singleton is basically shared between everyone so you can inject a shared service or you can do a scoped type which will create an instance for that user so like a scoped database service connection for each user

sharp geyser
#

hm

#

but scoped acts like singleton with blazor no?

prime cliff
#

No you need to register it first like builder.Services.AddSingleton<IDataAccess, DataAccess>();

#

Then in your components/pages you can do @inject DataAccess Data

#

You can also do a session state component instead of dependency inject

sharp geyser
#

Well I know about how to use DI in blazor, my problem is using Singleton it is accessible to everyone, so everyone would see the same state data

#

I am trying to keep user specific information in state, so it persists across sessions

#

I think I found what I need though

prime cliff
#

I do something a little more customized

@if (Ready)
{
    @switch (SessionError)
    {
        case SessionErrorType.AuthenticationError:
            {
<MudText Typo="Typo.h6">Authentication Error</MudText>
            }
            break;
        default:
            {
                    <CascadingValue Value="@this">
                        @ChildContent
                    </CascadingValue>
            }
            break;
    }
}

protected override async Task OnInitializedAsync()
    {
        State = await AuthenticationStateProvider.GetAuthenticationStateAsync();
        UserDateOffset = await JS.InvokeAsync<int>("GetUserTimezoneOffset");


        if (State == null)
        {
            Console.WriteLine("Auth Error");
            SessionError = SessionErrorType.AuthenticationError;
        }
        else if (!State.User.Identity.IsAuthenticated)
        {
            Console.WriteLine("Auth Required");
            SessionError = SessionErrorType.AuthenticationRequired;
        }
        else
        {
            Console.WriteLine("Trigger Ready");

        }
        Ready = true;
}```
#

This is for blazor server-side though

#

It basically creates a session component for that user as the main component and then loads the pages after it with CascadingValue.

#

Then any component/pages you want to use it in can be referenced with

[CascadingParameter]
private SessionProvider Session { get; set; }```
#

This way i can use the Session.UserDateOffset value to show date/time for that user 🙂 like what Discord does

sharp geyser
#

Interesting

#

For now ima just do something stupidly simple

#

I can always make it better later

neat mauve
# dapper quarry Rate my organization skills.........

loool mine looks similar because I'm just lazy and am totally fine with my structure, which i dev by myself only xd so no one to bother with

Although I haven't got so many databases... wtf? I got postgresql database on a second server of mine, so traffic goes over the internet. but one Database for all data with tables there, that reference each other (Although I only got two tables yet and the player table is made in a horrible, but for me nice/easy to work/change/extend stuff on).

lyric mountain
#

One for the cache, two for the optimization

#

And ofc relationships, which is the main thing about sql

neat mauve
neat mauve
# lyric mountain One for the cache, two for the optimization

wdym one db for cache and two for optimization?

I keep a copy of recent user data in ram as objects to omite a database connection over the network to my other server; Also regularly cleaning that data if not used for (currently) 5 minutes, then I just go through it quickly and save it in a cache list, which i then save; so all other threads potentially waiting can proceed as soon as possible.

lyric mountain
#

Not db one db two

#
  • for the cache
  • for the optimization
#

Bullet points

neat mauve
# lyric mountain - for the cache - for the optimization

thats a listing. for cache and optimization you need a single db. thats what u wanted to say? Instead of 'one' and 'two' just reworking it so there will be an 'and' between the two listings, like this:

One for the cache, two for the optimization -- reworkd-->For cache and for optimization.

lyric mountain
#

Lmao, I don't think you get what I meant

#

Ok ill reword

#

You should have a single db for two reasons - one for the cache, two for the optimization

neat mauve
small tangle
#

Benefit 1) Cache
Benefit 2) Optimization

lyric mountain
#

That

neat mauve
#

Though the use of 'one' and 'two' feels unintuitively for me. maybe using 'firstly' and 'secondly' would have helped me understand it better 🙂

lyric mountain
#

Fair

earnest phoenix
#

@harsh nova is interested

bitter granite
#

welp

earnest phoenix
#

@radiant kraken what's some more common usage?

println!("{}{}", indent, node);

or

println!("{indent}{node}");
sharp geyser
#

Depends

#

2nd one if its a raw value / not something with nested properties

#

1st one if you want to access a nested property

#

main difference between the two is you can't do

println!("{indent.something}");```
earnest phoenix
#

indent is just a string and node implements fmt::Display, so doesn't matter that much

#

But I feel like being consistent and always use the "{}", stuff format everywhere, even when you can "{stuff}", is one good way of going, especially to keep consistency

surreal sage
#

question mark

#

"malware" (file ends in .infected, no shit)

#

and a lot of google chrome user data

#

pups

radiant kraken
radiant kraken
bitter granite
radiant kraken
hollow blade
surreal sage
#

holy fucking shit dependabot just keeps throwing prs at me

sage bobcat
#

One message removed from a suspended account.

#

One message removed from a suspended account.

neat mauve
earnest phoenix
#

not only should, it is

quartz kindle
#

pr = pull request
prs = pull requests

#

:^)

neon leaf
#

@quartz kindle switched back from worker to nodejs again btw

quartz kindle
#

you mean from worker_thread to child_process?

neon leaf
#

No, cloudflare workers

quartz kindle
#

ah

neon leaf
#

The performance has been getting worse and worse

quartz kindle
#

like proper vps hosted nodejs?

neon leaf
#

Now it's on 4 ha vms with 2 load balancers

#

Ye

#

Like 2400% faster on some endpoints

quartz kindle
#

xD

#

cf workers have the whole on-demand thingy, with cold starts and shit

neon leaf
#

That isn't even the main problem, workers are pretty fast themselves

#

However the included database, D1 is incredibly slow

#

300ms for a select * for 10 rows

quartz kindle
#

rip

neon leaf
#

Like the entire table is 16 rows

quartz kindle
#

thats basically the same for any remote database i guess

neon leaf
#

Could be

#

But I'm happy to be on postgres again

quartz kindle
#

its incredibly hard to do edge computing and centralized db at the same time

neon leaf
#

Yeah

#

D1 being a single sqlite file ran by a nodejs process may also be the reason

quartz kindle
#

somewhere in the world

#

and simultaneously attempting to replicate itself across the edge

neon leaf
#

Afaik they don't do replication

quartz kindle
#

their cache thingy does right?

#

i dont remember

neon leaf
#

Nope

quartz kindle
#

oh its now a separate thingy

#
Cloudflare Docs

Hyperdrive is a service that accelerates queries you make to existing databases, making it faster to access your data from across the globe, irrespective of your users' location. Hyperdrive supports any Postgres database, including those hosted on AWS, Google Cloud and Neon, as well as Postgres-compatible databases like CockroachDB and Timescale...

prime cliff
#

🙂 fully working now

pale geyser
#

Hi

#

Hi

eternal osprey
#

Hey, anyone any insights on how to create my own mail server?

sharp geyser
#

don't

hearty cargo
#

hello all, where can i get Yoshimia commads list?

agile belfry
#

how can I know which server is I'm using my botv

sage bobcat
#

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.

warm surge
#

@agile belfry

agile belfry
#

yeah I meant the list of servers that are using my bot

#

@sage bobcat

bitter granite
sage bobcat
#

One message removed from a suspended account.

#

One message removed from a suspended account.

sharp geyser
#

@prime cliff I was messing about with that component lib you recommneded, and stuck on the first step.
InvalidOperationException: A component of type 'Radzen.Blazor.RadzenTheme' has render mode 'InteractiveAutoRenderMode', but the required endpoints are not mapped on the server.

#

Not entirely sure what this means, as I am calling both AddRazorComponents and MapRazorComponents

prime cliff
#

Did you see the install guide on how to setup the service and also add the main components?

sharp geyser
#

Im following the .Net 8/9

prime cliff
#

Are you using render mode auto or server too

sharp geyser
#

No idea what any of this stuff does tbf

#

My exact Program.cs file

prime cliff
#

Ah there server render mode

#

In your MainLayout file you should have added <RadzenComponents @rendermode="InteractiveServer" />

sharp geyser
#

That worked ty

#

This blazor stuff is insane man, learning a new thing comfyPanic

prime cliff
#

Basically the render mode is either webassembly, serverside render or the new auto mode which is hybrid client and serverside

sharp geyser
#

hm

#

Clicking a button and listening to the event seems to do nothing

prime cliff
#

Yea blazor is quite insane with interactivity and hooking up a bunch of stuff to C# took time to learn and still learning new things

#

You need to set the event like so

<RadzenButton Click="@Submit"

@code {
   async Task Submit()
   {
   }
}```
sharp geyser
#

Yea I did that

#
<RadzenLayout>
    <RadzenHeader>
        <RadzenStack Orientation="Orientation.Horizontal" AlignItems="AlignItems.Center" Gap="0">
            <RadzenSidebarToggle Click="@(() => _sidebarExpanded = !_sidebarExpanded)" />
            <RadzenLabel Text="Mercatus" />
        </RadzenStack>
    </RadzenHeader>
    <RadzenSidebar @bind-Expanded="@_sidebarExpanded">
        <RadzenPanelMenu>
            <RadzenPanelMenuItem Text="About" Path="/about" />
        </RadzenPanelMenu>
    </RadzenSidebar>
    <RadzenBody>
        <div>
            @Body
        </div>
    </RadzenBody>
</RadzenLayout>

@code
{
    bool _sidebarExpanded;
}
prime cliff
#

Radzen components uses Click="" as a custom name but other html elements use @onclick=""

sharp geyser
#

So should I use @onclick ?

#

Because it seems the event isnt firing

prime cliff
#

Really no errors on terminal console or browser console?

sharp geyser
#

Some but they seem to be related to an extension

prime cliff
#

Wait are you testing local http or https

sharp geyser
#

local

prime cliff
#

With http?

sharp geyser
#

yea

prime cliff
#

The http to https might be breaking it then, this is more for production usage

sharp geyser
#

I just removed that and same issue

#

Event isnt firing and or, its doing nothing

prime cliff
#

Does the browser network tab show websocket working?

sharp geyser
#

Status 101

prime cliff
#

In your App.razor you should have <RadzenTheme Theme="standard-dark" @rendermode next your css links

sharp geyser
#
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <base href="/"/>
    <link rel="stylesheet" href="@Assets["lib/bootstrap/dist/css/bootstrap.min.css"]"/>
    <link rel="stylesheet" href="@Assets["app.css"]"/>
    <link rel="stylesheet" href="@Assets["MercatusWeb.styles.css"]"/>
    <ImportMap/>
    <link rel="icon" type="image/png" href="favicon.png"/>
    <HeadOutlet/>
    <RadzenTheme Theme="material-dark" @rendermode="InteractiveServer" />
</head>

<body>
<Routes/>
<script src="_framework/blazor.web.js"></script>
<script src="_content/Radzen.Blazor/Radzen.Blazor.js?v=@(typeof(Radzen.Colors).Assembly.GetName().Version)"></script>
</body>

</html>
prime cliff
#

Hmm something weird is happening but i can't really tell

sharp geyser
#

Seems like they dont work in layouts

#

Events at least

prime cliff
#

It should work fine i have it too

sharp geyser
#

shrug Seems like its an issue with buttons specifically

#

At least from the 2 or so posts I saw

prime cliff
#

You could maybe zip archive the project folder and DM me i can take a look

sharp geyser
#

Sure

prime cliff
#

@sharp geyser found the issue for some reason the main blazor render mode itself is being confused with no warnings either never seen that before.

Fix it in App.razor with <Routes @rendermode="InteractiveServer"/>

#

You'll see the sidebar works too now

sharp geyser
#

Interesting

#

Thanks a lot for that aha

prime cliff
#

That really should not be happening either because by default it's interactive server and the other modes throw an exception

sharp geyser
#

I always run into the weird

#

Maybe its cuz im using .net 9

#

it might be a bug with it

wheat mesa
#

I’d highly recommend a SPA with ASP.NET instead of using razor, I fucking hate razor

#

It’s what I have to use at work and the amount of times I wish we used Vue is insane

#

I find that razor gets really messy because you’ll have a ViewModel with an ever-expanding amount of properties

sharp geyser
#

Eh, blazor to me just seems the most ideal

#

Since I can re-use code to turn that web app into a mobile app, or even other platforms

#

my biggest selling point is having everything essentially on the same code base

prime cliff
prime cliff
#

Blazor is the new stuff that combines html and C# code together with C# events, asp.net mvc is the older one that dosen't let you have interactivity or complex component views and code.

wheat mesa
#

Ah, I’ve been using MVC then

#

Still not a fan of the blazor syntax in general though

prime cliff
#

I mean it's a straight up upgrade from mvc and you can layout a bunch of components to reuse in multiple pages and also have a session state with a lot more functionality

#

There's also a lot of open source development for it on awesome-blazor github with components, themes, markdown integration, WYSIWYG editor and a bunch of examples

#

It also lets you bind component variables two-way for back and forward usage and events (including regular javascript events) like on click and on hover straight to C# code for whatever you need

wheat mesa
#

I still prefer to completely de-couple my frontend and backend with an SPA and separate ASP.NET backend

#

(Plus if I have to write javascript, I’d rather just make my entire frontend in a javascript-based frontend)

prime cliff
#

Fair that depends on how you want to work with it

surreal sage
#
new Promise()
  .then(() => new Promise((resolveTimeout) => {
    setTimeout(resolveTimeout, 1_000)
  })
  .catch(() => {
    // will this error block catch the initial promise's error, or the resolveTimeout's?
  })
  .finally(() => {
    // will this final block run after the resolveTimeout?
  })```
#

or should I instead get rid of the finally {} block of the initial promise and wrap the contents of then and catch in a try {} finally {}

wheat mesa
#

Finally will run after the promise either resolves or rejects

surreal sage
wheat mesa
#

The first one

surreal sage
wheat mesa
#

Afaik at least

surreal sage
#

if it errors, catch and finally

#

otherwise it just logs gambling

#

not finally

#

sigh

surreal sage
#

wait

pearl trail
#

yes it'll wait for the setTimeout inside .then

surreal sage
#

.then will start a new promise chain

#

and the .catch after would be apart of the .then

#

instead of the first promise

pearl trail
#

won't it be for both promises?

#

hmm

#

yes the catch will catch errors from either promise

surreal sage
pearl trail
surreal sage
#

.then doesnt run unless you call resolve

#

kinda weird ngl

pearl trail
#

ye

#

imo it's not weird tbh

#

otherwise, why would you need to create a Promise in the first place

neat mauve
#

Hello there! I got an important question:
Will user_id's stay valid under any circumstances? or can it happen that a user_id changes for a certain user?

earnest phoenix
#

discord user ids?

#

Because "user_id" is pretty generic in a dev channel

lyric mountain
#

it's the only thing you can use to link to a specific user

surreal sage
#

promises are truthy sad

#

(i got hit with a 24h ratelimit ban)

earnest phoenix
#

horrible async

surreal sage
#

i think

#

no idea actually

#

i forgot to remove something else

#

maybe that was it

#

im schizo

surreal sage
earnest phoenix
#

also what is up with the requirement to add "use client"; at the top of every file to be able to use useState()

#

literally every file now the first line is that

neat mauve
#

😭 🔫

pine willow
#

Hello! I added user installs a few hours ago and suddently my bot stopped working on my Servers, but when I start it on my PC it works?
Its just stuck in "thinking..." forever

#

:(

earnest phoenix
#

look through your logs

pine willow
#

Everything is running fine

#

It randomly stopped working

#

after 1 hour or so

earnest phoenix
#

then we can't help

pine willow
#

uh ok

pine willow
#

Wasnt a Issue on my end

earnest phoenix
#

some bot interactions

pine willow
#

but thats the exact Issue I have

earnest phoenix
#

it was on buttons only, message update and when including a components field in the new data

#

it failed with error 500 and threw "Interaction failed"

#

and not the "is thinking" state

earnest phoenix
#

best comment so far

sharp geyser
#

Must be a discord snippet

warm surge
pearl trail
#

wait wha we can do this in js??

lyric mountain
#

unicode value be like

pearl trail
#

sorry, i meant the “races” “sorted_races” without const let var etc

neon leaf
sage bobcat
#

One message removed from a suspended account.

pearl trail
#

isoke

surreal sage
#

what's our opinion on an api ratelimit banning you for (sum) 24 hours after it responds with 429 for 20 requests

earnest phoenix
#

fair enough

sage bobcat
#

One message removed from a suspended account.

lyric mountain
#

better yet, ban if too many 4xx statuses are returned

quaint yarrow
#
await guildModel.aggregate({ $match: { public: true, banned: false } });

does anyone know why this mongoose query is taking 26s? (using console.time)
theres only 2.1k documents in the collection

i've also tried using find instead of aggregate which took 27 seconds, however i need to perform operations which i removed from the query to see if they were causing the significant query times which evidently not

spark flint
#
await guildModel.countDocuments({ public: true, banned: false});
#

wait does that return results or the count

#

might be ```js
await guildModel.find({ public: true, banned: false}).toArray()

#

oh wait i just read what you said FacePalm

#

are you using mongo cloud?

quaint yarrow
#

im using atlas, not sure if thats the same

spark flint
#

yeah thats the same

#

make sure the db is in the same region as you

#

or a close region

quaint yarrow
#

its in the same

spark flint
#

ah

quaint yarrow
#

it's only just started overnight

lyric mountain
#

atlas free tier?

quaint yarrow
lyric mountain
#

I'm pretty sure it has low performance, tho not low enough to make a query take 27 seconds

#

all in all if you have a remote database you need to consider getting a local cache of some sort

#

it also depends on how much data you have

quaint yarrow
quaint yarrow
#

my other bot has a collection with 46k documents and it takes less than 20 seconds

lyric mountain
#

like, when you fetch document A keep it in cache (with an expiration criteria), then when attempting to fetch it again first check if it's already cached

quaint yarrow
#

for context, this is the collection for the guilds

lyric mountain
#

a properly optimized db shouldn't take much more than 2-3 seconds for the worst cases

quaint yarrow
#

right now caching shouldn't be in the picture because it shouldn't take longer than 2 seconds, im not sure why it is

lyric mountain
#

does mongo have anything akin to EXPLAIN from sql?

quaint yarrow
#

it has explain, but thats for find

queen needle
#

I would cache when I had like 5 documents..

lyric mountain
#

nosql somehow manages to be more complicated than sql

#

EXPLAIN would be able to give detailed metrics for query performance that'd help solve this much faster

lyric mountain
quaint yarrow
# lyric mountain well, does find take 20s too?

okay this is weird:

console.time('FindAll')

console.log(await guildModel.find({
    public: true,
    banned: false
}).explain())

console.timeEnd('FindAll') // FindAll: 37.597ms


console.time('getAllGuilds');

const guilds = await getAllGuilds({ sort: parsedSort === 'most_relevant' ? undefined : parsedSort });

console.timeEnd('getAllGuilds'); // getAllGuilds: 26.529s


export async function getAllGuilds(options: { sort?: SortBy }) {
    console.log(options);
    return guildModel.find/*<GuildQuery<'averageRating' | 'monthVotes'>>*/({
        public: true,
        banned: false
    });
}```
lyric mountain
#

run explain on that find

#

to see if it's a database issue or latency issue

quaint yarrow
#

im doing it on the top one

lyric mountain
#

ah

#

well, what's the result of it?

#

oh wait, nvm

#

it's likely a network issue then, too much data being transferred

#

try to limit the getAllGuilds return to 1

#

to check

quaint yarrow
#

how could that be possible when i have a db with 46k documents (returning html transcripts) in a single go

lyric mountain
#

is your guildModel a fat document?

#

like, many fields or large fields

quaint yarrow
lyric mountain
#

I meant structure

quaint yarrow
#

34 properties
1 property which has a long value (2k chars), the rest is either booleans, numbers, or object id's

lyric mountain
#

well, I cant say much for mongo cuz I never worked with it, but this would be the only explanation

#

check the return of that explain, to see if any action takes too much time to complete compared to the rest

#

if you have too many booleans it'd be better to compress into an int field btw

quaint yarrow
#

though that shouldn't matter, this is my other db used on my other bot and it returns an entire HTML document for all 33k documents and it does it in a couple seconds

lyric mountain
#

sometimes large amounts of fields take longer to assemble than a single large field

quaint yarrow
#

33k at 11kb whereas the one in question is 2.1k at 1.5kb

lyric mountain
#

dont measure by storage size

quaint yarrow
#

okay, that took 1 second

#

however when using aggregate i use $project which should only return 14 properties

lyric mountain
#

cant help much on the internals of how those ops work sadly

#

what did your explain say on the log btw?

#

it should contain data on every operation done

quaint yarrow
lyric mountain
#

hm, 2s so indeed not an issue on database's side

#

I'm clueless on this case, could be throttling on atlas' side

#

guess you'll need someone more experienced to help on this

quaint yarrow
lament rock
pearl trail
#

oh, interesting

#

thanks for the explanation

lyric mountain
#

the hoops js will jump through to avoid throwing errors

frosty gale
#

js users wondering why their app full of .catch(err => null) and try {} catch {} isnt working

solemn latch
#

😄

#

The usual

warm surge
wheat mesa
#

Genius

#

Promise rejection roulette

lament rock
#

Some linters will complain about some .catch(...) calls, so I just do .catch(e => void e)

Some complaints involve not using the callback param, or that an expression was expected. Luckily void is an expression statement and using the variable works

earnest phoenix
#

god i love html

return (
    <div className="container">
      <div className="row">
        <div className="col col--12">
          <div className="row">
            <div className="col col--3">Label:</div>
            <div className="col col--9">{label}</div>
          </div>
        </div>
        <div className="col col--12">
          <div className="row">
            <div className="col col--3">Expired:</div>
            <div className="col col--9">{expired}</div>
          </div>
        </div>
        <div className="col col--12">
          <div className="row">
            <div className="col col--3">Recent:</div>
            <div className="col col--9">{recent}</div>
          </div>
        </div>
      </div>
    </div>
  );

div everywhere