#development

1 messages · Page 177 of 1

sharp geyser
#

See

wheat mesa
#

I need more code than what u sent

sharp geyser
pale vessel
#

since you're using request, it expects a sync http client, not async

#

use request_async if you want to provide an async http client

sharp geyser
#

😭

compact pier
#

I have a blob data of an image, how can I check, if that blob is jpg?

#

to prevent xss

sharp geyser
#

What language are you using here?

compact pier
#

typescript

#

or javascript

sharp geyser
#

so long as you have the blob you can use .type to get the MIME type

compact pier
#

yeah, but is there somehow that you can fake it?

sharp geyser
#

Not unless you let them pass in their own blob data

#

or have any access to what the data is

compact pier
#

what do you mean?

sharp geyser
#

Well

compact pier
#

I have a service worker, that allow to upload blob data via request

lament rock
#

I'm working on a set of Unity3D player controllers and this shit is a nightmare

sharp geyser
#

the easiest way to get the type is to just pass in the raw blob data to js' Blob constructor like let blob = new Blob(blobData) then blob.type.

#

you have to somehow control what blobData is in this case though if you are worried about them mutating it themselves

compact pier
#

ohhh

#

understood

#

thank you

sharp geyser
#

But why unity?

lament rock
#

It's very fun!

#

VRChat

sharp geyser
#

gotcha

#

I am not surprised if games will soon be swapping away from unity ngl. Unless unity has fixed their little problem mmLol

lament rock
#

They did come up with something a lot more pallatable for devs

sharp geyser
#

Nice

#

So now they aren't completely screwed

#

I know before they were doing some outrageous pricing schemes

lament rock
#

Well. All of the trust people had in them for years is kinda out the window. Rather, they're skeptical

sharp geyser
#

charging per install

lament rock
#

I'm personally gonna keep using Unity. The changes are more than enough for me to continue

sharp geyser
#

Yea

lament rock
#

for my own game that is

sharp geyser
#

Me personally I wont be using Unity

lament rock
#

VRChat doesnt have to worry since they're free

sharp geyser
#

Don't they still do it anyway?

lament rock
#

Iirc, no

sharp geyser
#

I thought they charged 5 cent per install no matter what

lament rock
#

If you dont make money off your app, then you dont have to pay

#

is what I heard

sharp geyser
#

I mean doesn't VRChat still have IAPs?

lament rock
#

Well, yes, but I'm pretty sure Unity already gets a royalty from that. Them double dipping would be horrendous and I think was part of the problem initially

sharp geyser
#

Yea, I think Unity was trying to sneak that in there. Then again never saw the original report myself

#

Just went based off hearsay

digital swan
#

im having the weirdest issue with breejs. on my production server (vultr) everything works fine no issue

but on a test server (digitalocean) im running the same code just different database and bot, and randomly whenever a certain bree job ends, the main process is exited without any error or message.
bree is ran from main process while using discord-hybrid-sharding for clustering

bree scheduler: https://github.com/tekoh/nypsi/blob/main/src/scheduled/scheduler.ts
the job that causes it to exit: https://github.com/tekoh/nypsi/blob/main/src/scheduled/jobs/votereminders.ts

this happens randomly after a seemingly random amount of hours of the bot being online

hidden gorge
#

bot refuses to say im not a developer and crashes when shutdown is ran but prints no error

Code:

const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');


module.exports = {
    data: new SlashCommandBuilder()
    .setName('shutdown')
    .setDescription("DEVELOPER COMMAND"),

    async execute(interaction) {

        const shutdownEmbed = new EmbedBuilder()
        .setTitle("RoSearcher Has Shutdown")
        .setColor("Green")

        const notadevEmbed = new EmbedBuilder()
        .setTitle("You are not a developer")
        .setColor("Red")


        if (interaction.user.id == "919674489581731842") {
            await interaction.reply({ embeds: [shutdownEmbed] });
            process.exit(0)

            
        }

        if (!interaction.user.id == "919674489581731842") {
            await interaction.reply({ embeds: [notadevEmbed]});
        }
    }
}

digital swan
#

use !=

or you could just use else

vivid fulcrum
#

or structure your logic so you don't need an else 🙃

digital swan
#

more readable imo

craggy pine
#
if(!thing) {
whatever
return
}

shutdownEmbed
processExit

No else needed.

hidden gorge
tulip ledge
lyric mountain
#

btw just expanding on why it worked, when u do if (!something == thing) you're converting the first value to boolean, which will make == compare both sides as booleans, meaning it'll always end up being if (false == true) if the both values are non-empty strings

stark abyss
#

how would I get this to be in RREF?
let matrix = [
[1, 1, 1, 0, 0, 0, 0, 0, 15],
[0, 0, 0, 1, 1, 1, 0, 0, 15],
[0, 0, 0, 0, 0, 0, 1, 1, 15],
[1, 0, 0, 0, 1, 0, 0, 1, 15],
[0, 0, 1, 0, 1, 0, 1, 0, 15],
[1, 0, 0, 1, 0, 0, 1, 0, 15],
[0, 1, 0, 0, 1, 0, 0, 1, 15],
[0, 0, 1, 0, 0, 1, 0, 0, 15]
];
you can assume the matrix is going to only contain 1s because matrix comes from the magic square

scenic kelp
#

In mathematics, Gaussian elimination, also known as row reduction, is an algorithm for solving systems of linear equations. It consists of a sequence of operations performed on the corresponding matrix of coefficients. This method can also be used to compute the rank of a matrix, the determinant of a square matrix, and the inverse of an invertib...

stark abyss
#

ok

hidden gorge
#

instantly goes to Confirmation not received instead of waiting 1 minute for a response or no response

Code:

     
try {
    const confirmation = await response.awaitMessageComponent({time: 60_000 });

    if (confirmation.customId === 'shutdownconfirm') {
        await confirmation.update({ embeds: [offEmbed], components: [] });
        process.exit(0);
    } else if (confirmation.customId === 'shutdowncancel') {
        await confirmation.update({ content: 'Action cancelled', components: [] });
    }
} catch (e) {
    await interaction.editReply({ content: 'Confirmation not received within 1 minute, cancelling', components: [] });
}
    }
}
    async execute(interaction) {

        const shutdownEmbed = new EmbedBuilder()
        .setTitle("Confirm Shutdown RoSearcher")
        .setColor("Yellow")

        const notadevEmbed = new EmbedBuilder()
        .setTitle("You are not a developer")
        .setColor("Red")

        const offEmbed = new EmbedBuilder()
        .setTitle("RoSearcher Shutdown")
        .setColor("Green")

        const Confirm = new ButtonBuilder()
        .setCustomId('shutdownconfirm')
        .setLabel('Confirm')
        .setStyle(ButtonStyle.Danger)

        const Cancel = new ButtonBuilder()
        .setCustomId('shutdowncancel')
        .setLabel('Cancel')
        .setStyle(ButtonStyle.Success)

        const row = new ActionRowBuilder()
        .addComponents(Confirm, Cancel)

        if (interaction.user.id == "919674489581731842") {
            await interaction.reply({ embeds: [shutdownEmbed], components: [row], });
wheat mesa
#

Well something is causing an error, log e in your catch block instead of ignoring it

hidden gorge
#

ok i'll do that

#

ooo

hidden gorge
#

this is the full code:

const { ButtonBuilder, ActionRowBuilder, ButtonStyle, SlashCommandBuilder, EmbedBuilder } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
    .setName('shutdown')
    .setDescription("DEVELOPER COMMAND"),

    async execute(interaction) {

        const shutdownEmbed = new EmbedBuilder()
        .setTitle("Confirm Shutdown RoSearcher")
        .setColor("Yellow")

        const notadevEmbed = new EmbedBuilder()
        .setTitle("You are not a developer")
        .setColor("Red")

        const offEmbed = new EmbedBuilder()
        .setTitle("RoSearcher Shutdown")
        .setColor("Green")

        const ConfirmButton = new ButtonBuilder()
        .setCustomId('shutdownconfirm')
        .setLabel('Confirm')
        .setStyle(ButtonStyle.Danger)

        const CancelButton = new ButtonBuilder()
        .setCustomId('shutdowncancel')
        .setLabel('Cancel')
        .setStyle(ButtonStyle.Success)

        const row = new ActionRowBuilder()
        .addComponents(ConfirmButton, CancelButton)

        if (interaction.user.id == "919674489581731842") {
            const response =  interaction.reply({ embeds: [shutdownEmbed], components: [row], });
            const collectorFilter = i => i.user.id === interaction.user.id;
            try {
                const confirmation =  response.awaitMessageComponent({ filter: collectorFilter, time: 60_000 });
            
                if (confirmation.customId === 'shutdownconfirm') {
                     confirmation.update({ embeds: [offEmbed], components: [] });
                    process.exit(0);
                } else if (confirmation.customId === 'shutdowncancel') {
                     confirmation.update({ content: 'Action cancelled', components: [] });
                }
            } catch (e) {
                console.log(e)
                 interaction.editReply({ content: 'Confirmation not received within 1 minute, cancelling', components: [] });
            }
                }
            
            
    
        if (interaction.user.id != "919674489581731842") {
             interaction.reply({ embeds: [notadevEmbed]});
        }

    }

    }

wheat mesa
#

you did not await the interaction.reply in your const response = ... line

hidden gorge
#

oh

#

i did that same error

wheat mesa
#

show me

hidden gorge
#

i fixed it...

#

im so stupid

hidden gorge
#

Once again i'm sorry to ask but my Error handler refuses to dm me when i get an error:

client.on('error', (error) => {
  console.error('Discord.js error:', error);

  const userId = 919674489581731842;
  const user = client.users.cache.get(userId);

  console.log('User ID:', userId);

  if (user) {
    user.send(`An error occurred:\n\`\`\`${error.message}\`\`\``)
      .then(() => console.log('Error message sent successfully.'))
      .catch((sendError) => console.error('Error sending message:', sendError));
  } else {
    console.error(`User with ID ${userId} not found.`);
  }
});
pale vessel
hidden gorge
deft wolf
#

Change it to "919674489581731842"

hidden gorge
#

oh

digital swan
#

im having the weirdest issue with breejs. on my production server (vultr) everything works fine no issue

but on a test server (digitalocean) im running the same code just different database and bot, and randomly whenever a certain bree job ends, the main process is exited without any error or message.
bree is ran from main process while using discord-hybrid-sharding for clustering

bree scheduler: https://github.com/tekoh/nypsi/blob/main/src/scheduled/scheduler.ts
the job that causes it to exit: https://github.com/tekoh/nypsi/blob/main/src/scheduled/jobs/votereminders.ts

this happens randomly after a seemingly random amount of hours of the bot being online

GitHub

the best discord bot. Contribute to tekoh/nypsi development by creating an account on GitHub.

GitHub

the best discord bot. Contribute to tekoh/nypsi development by creating an account on GitHub.

hidden gorge
deft wolf
#

What error do you have then?

hidden gorge
#

i dont have one exept for the command error im using for testing

pale vessel
#

are you sure the user is cached? use const user = await client.users.fetch(userId); to make sure it's fetched

hidden gorge
# pale vessel are you sure the user is cached? use `const user = await client.users.fetch(user...

did that and added async but still fails

client.on('error', async (error) => {
  console.error('Discord.js error:', error);

  const userId = "919674489581731842";
  const user = await client.users.fetch(userId);
  console.log('User ID:', userId);

  if (user) {
    user.send(`An error occurred:\n\`\`\`${error.message}\`\`\``)
      .then(() => console.log('Error message sent successfully.'))
      .catch((sendError) => console.error('Error sending message:', sendError));
  } else {
    console.error(`User with ID ${userId} not found.`);
  }
});
pale vessel
#

it didn't log anything?

hidden gorge
pale vessel
#

then the event isn't being triggered at all

#

unless that first console.error() did log something

hidden gorge
#

i wonder if its getting cancelled out by the slash command error handler

pale vessel
#

client's error event is only for gateway errors i believe

#

a command handler's error won't go there

hidden gorge
#

added it to the built in error handler for slash commands and it semi works

pale vessel
#

least vague error

hidden gorge
#

yeah idk why it said that and not the full error

limpid hatch
#

Oi

hidden gorge
pale vessel
hidden gorge
wheat mesa
#

this formatting hurts me

#

Also mixing await with .then

hidden gorge
pale vessel
#

there's nothing wrong with that. it's less confusing than a nest of await (await func()) func()

cursive sand
#

Gm

hidden gorge
#

is it a good idea that im updating the bots status when i get an error?

spark flint
#

error isn't an event afaik

hidden gorge
#

it works tho

#

but my code is still a mess

spark flint
#

thats for connection errors not for bot code errors

pale vessel
#

that'll only confuse users and it's not a good reason to change your bot's presence every time an error occurs

#

it makes zero sense

hidden gorge
#

gonna remove the error status when its done

real rose
#

-b @cursive sand silly twitter ads, not the place for it

gilded plankBOT
#

upvote wiisnu17#0 was successfully banned.

hidden gorge
#

oh

spark flint
hidden gorge
#

InteractionAlreadyReplied on interaction.showModal(modal)

  const modal = new ModalBuilder()
            .setCustomId('BanModal')
            .setTitle('Ban Modal');

            const Reason = new TextInputBuilder()
            .setCustomId("BanReason")
            .setLabel("Reason")
            .setStyle(TextInputStyle.Short)
            const firstActionRow = new ActionRowBuilder().addComponents(Reason);

            modal.addComponents(firstActionRow)

        if (interaction.user.id === "919674489581731842") {

            const response = await interaction.reply({ embeds: [BanPanel], components: [row]})
            const collectorFilter = i => i.user.id === interaction.user.id;

            try {
                const confirmation  = await response.awaitMessageComponent({ filter: collectorFilter, time: 60_000});
                if (confirmation.customId === "OpenBanPanelButton") {
                     interaction.showModal(modal);
                }
            } catch (e) {
                console.log(e)
            }

        }
deft wolf
#

You are trying to display the modal by replying to interaction which in this case is the slash command that you have already replied to

deft wolf
#

Think about whether you should respond to a slash command or a button

hidden gorge
deft wolf
#

When should the modal appear?

hidden gorge
deft wolf
#

Okay, so what is the button click event in your code?

hidden gorge
# deft wolf Okay, so what is the button click event in your code?

its this code here:

  const response = await interaction.reply({ embeds: [BanPanel], components: [row]})
            const collectorFilter = i => i.user.id === interaction.user.id;

            try {
                const confirmation  = await response.awaitMessageComponent({ filter: collectorFilter, time: 60_000});
                if (confirmation.customId === "OpenBanPanelButton") {
                     interaction.showModal(modal);
                }
            } catch (e) {
                console.log(e)
            }
deft wolf
#

Still don't see where the problem is?

hidden gorge
#

i need to find a way for the modal to show

deft wolf
#

You need to display it when someone clicks the button

hidden gorge
#

yes

deft wolf
#

You can't respond to the same interaction twice

hidden gorge
#

bro then how tf do i do this???

deft wolf
#

Assign the modal display to a button, not an interaction

hidden gorge
#

bro ur not helping at all

craggy pine
#

Buttons create their own "Intereactions" when clicked. Not the main interaction.

deft wolf
hidden gorge
#

no ur not helping

deft wolf
#

Okey

#

Good luck

fierce orbit
# hidden gorge bro ur not helping at all

When you click the button that is 1 interaction. When you try and open a modal that is another interaction. You need to assign when the button is clicked, a different interaction is going to be sent. That is best I can explain it

hidden gorge
#

i fixed it

fierce orbit
hidden gorge
#

i just got mad enough i removed the button in general

fierce orbit
#

💀

deft wolf
#

XD

craggy pine
#

Lololol

#

It really isn't that complicated. A simple google search found the answer pretty quickly for me.

fierce orbit
#

Interactions I see like functions in math, x are interactions, can never have more then 1 x or the function is false

hidden gorge
#

now i need to learn how to Read and write to JSON files

deft wolf
#

Are you gonna make json database?

hidden gorge
#

blacklist json file

hidden gorge
#

if the users id is the JSON file and they run a slash command it returns an embed saying you have been blacklisted from the bot

#

wouldnt i use fs for that?

fierce orbit
#

I probably should make a blacklist command, the amount of homophobes that have used my bot negatively 😭

hidden gorge
#

my bot interacts with apis so i thats why im adding a blacklist

craggy pine
#

I would just learn to use a database, which is also a really simple process and much better imo than using a JSON file.

#

ESPECIALLY if this bot is public

hidden gorge
#

i tried MongoDB i hate it

craggy pine
#

There are other DBs than Mongo

#

I use MariaDB

hidden gorge
#

ehhh

fierce orbit
#

I use mongo bc I am too lazy to switch

real rose
#

ok

lyric mountain
#

if you want to keep it simple, there's sqlite

#

it's a good beginner database because there's almost literally no setup to it

#

also it's very barebones - no triggers, users, procedures, functions, nothing

#

just you, types and tables

#

and switching to another database later on is easier due to this too

wheat mesa
earnest phoenix
# hidden gorge i tried MongoDB i hate it

Postgres is nice & comfy, but if you really want bare bones, SQLite is braindead. Although, you might want to read into its tendency to lock its DB on writes. Postgres doesn't suffer from the same thing.

wheat mesa
#

It is going to be slow

#

And chances are you’re going to fuck something up unless you know what you’re doing with reads and writes

#

Postgres is an awesome option, mongo is easier to get into

earnest phoenix
#

I mean, ig that's basically what Waffle said, kek.

lyric mountain
earnest phoenix
#

Oh? SQLite no longer suffers from DB locking?

lyric mountain
#

I mean, i does, but it now manages concurrent writes such that you don't need to worry about it anymore

#

at the end of the day any file-based db is subject to file locking

#

still wont match postgres performance, but as a starter it's a good option

#

especially because postgres has all types sqlite has, so migrating is seamless

earnest phoenix
#

Yeah, for now.

hidden gorge
#

i should really make myself immune to that

wheat mesa
#

JSON “databases” are duct tape solutions to a bigger problem of not knowing how to use a real database

grim aspen
#

i have so many questions about that video

green kestrel
#

I only have two:

WTF
and
WHY

#

"boss, we can't afford to have this wreck towed..."
"ok does it still drive"
"uh yes but not legally"
"I didn't ask that I said does it drive"
"well yes but... but..."
"ok then! cya in a bit, drive it to the breakers yard!"

kekeke

surreal sage
#

okay this makes no sense

surreal sage
#

but <picture><img/></picture> does work

green kestrel
#

yay progress made 😄

crystal wigeon
#

Hey does anyone use aws with route 53?

#

I saw someone was using aws here before

#

Would be nice if someone can help me with a-b testing my product

sharp geyser
green kestrel
#

like a MUD

sharp geyser
green kestrel
#

yes I'm done on that for a bit just gotta wait for it to grow

sharp geyser
#

icic

green kestrel
#

but if it doesn't, like sporks didn't grow fast, this is my backup plan

sharp geyser
#

I was planning on trying to make a bot myself again

green kestrel
#

what you going to make

sharp geyser
#

an RPG bot probably

#

I've always wanted to make something RPG but discord was always limiting, then again I don't even have the stuff I need to make a graphical rpg so discord it is

shrewd shadow
green kestrel
#

would you play it?

#

if people want to play it, then it does the job lol

spark flint
#

how would you guys optimise PSQL

#

i have a db that is currently using over 100gb with close to 200 million entries into the table

#

using indexes but its still taking minutes to query

#
const { rows } = await client.query(`SELECT * FROM data WHERE domain LIKE '$1' OR hostname LIKE '$1' LIMIT $2 OFFSET $3`, [`%${query}%, limit, skip]);```
#

thats my currently query

#
const { rows } = await client.query(`SELECT * FROM data WHERE addresses @> $1 LIMIT $2 OFFSET $3`, [`{${ip}}`, limit, skip]);``` this is another
#

SELECT COUNT(*) FROM data also takes like 5 minutes

#

i've adjusted the db to allow higher memory usage etc (64gb ram, 8 core server), that made a difference for a day or so but is slow again now

sharp geyser
#

ask chatgpt trollface

spark flint
#

already did KEKW

#

that helped tbh

#

it told me what conf changes to make to optimise the servers resources

sharp geyser
#

I assume you are using connection pooling so its not just going through one connection right?

spark flint
#

i dont know

#

i usually use mongo but people told me to use pg

sharp geyser
#

Okay I would look into connection pooling, it will help by reusing existing connections and might improve response times. Also using LIMIT and OFFSET are very costly from what I recall

spark flint
#

so for pools, when do i use await pool.connect()

#

not per query is it KEKW

sharp geyser
#

It should be at the very start

spark flint
#

like this

#

and not like this

sharp geyser
#

if you call release it will shut the app down iirc

spark flint
#

oh lovely

sharp geyser
#

I haven't used the pg library in ages though so one sec, let me relook at the docs

sharp geyser
spark flint
#

👌

sharp geyser
#

It will create a connection and then put it in the pool and when a query is done it will just use a pre-exisiting connection in the pool

spark flint
#

ok time to test smide

sharp geyser
#

At least thats what I remember it doing

spark flint
#

i'm creating a new index

#

because apparently it uses somethign else when using LIKE

#

and i'll look at removing limit + offset and just do that myself

sharp geyser
#

Also using LIMIT and OFFSET is extremely costly as it looks through all the rows

spark flint
#

yeah

sharp geyser
#

you can use a cursor paginated system

#

its much faster

#

iirc pg also has a way to do that intuitively

spark flint
sharp geyser
#

pg-cursor I think it was

spark flint
#

what i've done is

#

made it cache the query in general

#

not reliant on skip or limit values

#

so if paginating it wont make it redo the query

#

5m cache

sharp geyser
#

Well

#

Even so using LIMIT and OFFSET will make it read all the rows of the table iirc

spark flint
#

i've rmeoved those

#

and i'm doing that myself

sharp geyser
#

noice

spark flint
#

skip and limit are always present

#

and default to 0 and 100

sharp geyser
#

fair

#

if it works doing it yourself go for it

#

if not pg-cursor is always an option

spark flint
#

love when nano takes ages to write data KEKW

#

something is inserted to pg every like 0.01s

earnest phoenix
#

100 inserts a second? Jeez.

#

Now I'm curious what you're doing w/your queries, lmao.

sharp geyser
#

bun runs a lot of stuff that is popular

#

I wouldn't be surprised

spark flint
#

its domain data

sharp geyser
#

wth

spark flint
#

basically indexing data about sites resolving to IPs / hostnames

sharp geyser
#

Oh nvm

#

I forgot you run that phish thing

spark flint
#

yeah its for prevention

#

but it also allows searching for domains based on queries

#

aka every new incoming domain gets index

#

and therefore can be searched

sharp geyser
#

Yknow people can't scam on the web if you buy every possible domain name mmLol

spark flint
#

lmfao

sharp geyser
earnest phoenix
#

Closer to reality than you think. Sorta.

green kestrel
#

lol

#

imagine if they can't revoke the sale, because they can't access their systems because the domain was sold KEKW

#

like when Facebook went down and they couldn't get in their building

radiant kraken
dusky idol
#

Anyone here who's good at image manipulation python? Pillow/easypillow library? I'm in need of some assistance, been stuck since 24 hours now

sharp geyser
#

I can make graphical games all I want but it’ll just be a shell

lament rock
#

Unity is fun

green kestrel
#

at least not nicely

#

i'd hve had to use reactions and stuff

lament rock
#

idlerpg existed for a long time

green kestrel
#

and check that the person reacting owns the message etc

#

and everyone would see everyone elses gameplay

green kestrel
lament rock
#

ik

green kestrel
#

idlerpg is boring, you just gain xp by... idling

#

and clicking

#

its cookie clicker

lament rock
#

Well. Idle games can be quite fun

green kestrel
#

the game im making is the opposite of an idle game, like trivia you have to actually engage with it

lament rock
#

Even if this wasn't Discord, sounds like a "totally fun and simple" adventure

green kestrel
#

whats that?

lament rock
#

I do wish you good luck on that is what I'm trying to get across

#

its been a long time since Ive seen a well made game on Discord

green kestrel
#

porting this to discord will be challenging still

#

the old code for the game is in such a mess

#

and it was web based

lament rock
#

js?

#

the original game that is

green kestrel
#

this is how it used to look.... and no it was C++

#

i was crazy enough to make a game in C++ that ran as CGI programs in 2001

sharp geyser
#

is that windows xp

green kestrel
#

back then it had 1500 active players

#

windows ME

lament rock
#

May god have mercy on your soul

green kestrel
#

so all that stuff you see there, i gotta port to discord

#

including the chat box!

lament rock
#

thats

#

I see

sharp geyser
#

Good luck with that

#

Doing a cross server "chat box" will be a nightmare if you manage not to spam the api

green kestrel
#

i'll just rate limit it my end

lament rock
#

Live stream it!

green kestrel
#

lol

sharp geyser
#

the best you can probably do is route all messages in a certain channel into a server "chat box" channel

lament rock
#

a twitch embed could be an option tbh

green kestrel
#

generally, in the old version of the game certain areas were busy all the time, and other areas youd be lucky to find other people

#

they all would congregate around cities

sharp geyser
#

idk anyone who would play a discord bot game and have a twitch stream open at the same time to play said game

lament rock
#

The video in the embed would show the chat

#

people can still chat through Discord

sharp geyser
#

too much work for simple minded people

lament rock
#

Its an easy solution for dealing with rate limits

green kestrel
sharp geyser
#

You could always just use websockets and post them to a webpage

lament rock
#

I guess yeah

green kestrel
#

i was actually thinking of having links in the content that caused the bot to edit the message, so i could have realtime interactivity with the content, BUT it would have to spawn a browser window and then youd have to close it and tab back to discord

#

also... editing ephemerals is very very relaxed rate limit

#

which is nice

#

and all interaction is caused by users clicking buttons and modals, which means discord rate limit it client-side for the user, and we can reply as fast as we like

eternal osprey
#

does this server allow/help with scraping related questions?

solemn latch
#

as long as you're not breaking the sites tos or rules, and if you're unsure you get permission I dont see an issue with it.

eternal osprey
#

alright thanks !

#

where the 'class="story-block story-block--sb06" are the divs containing the articles

#
   $(".stream__list .story-block--sb06").each((index, element) => {
      console.log("test");
      const category = $(element).find(".story-block__category").text().trim();
      const heading = $(element).find(".story-block__heading a").text().trim();
      const articleLink = $(element)
        .find(".story-block__heading a")
        .attr("href");
      const image = $(element).find(".story-block__image img").attr("data-src");
      const author = $(element)
        .find(".story-block__byline")
        .text()
        .trim()
        .replace("By", "")
        .trim();
    });```
seems to not even print test, hence doesn't return any elements
lament rock
#

An easy way to do this is just fetching the website then res.text().then(console.log) and then run that through an HTML prettifier if it's condensed

wheat mesa
#

Better yet yeah just use an embed

crystal wigeon
flat copper
lyric mountain
#

Are u using :id?

#

Instead of literally id

flat copper
digital swan
#

I’ve never used nextjs but surely you could make an id route, do whatever processing then redirect to the home page? If that’s what you’re asking

surreal sage
#

'kay so im learning golang

#

and the tour says

Inside a function, the := short assignment statement can be used in place of a var declaration with implicit type.

#

I don't get the implicit type

#

English isn't my mothertoung either

#

Is it like, choosing the type automatically?

slender wagon
#

Is using your own vps as a proxy ok?

surreal sage
#

i dont see why it wouldnt be

#

okyes

surreal sage
flat copper
#

ohh

queen needle
lament rock
#

explicit would mean you'd have to manually declare the type

desert kindle
#

If I lost my active dev badge can i get it back?

warm surge
hushed patrol
#

How can i show vote and guilds count in a widget of top.gg in a embed?

wheat mesa
#

Imo the way go does it is scuffed but still

surreal sage
#

first go project done i guess

eternal osprey
#

in html/js is there no enumeration for button/input actions?\

lyric mountain
#

Nope

#

Web js is quite barebones

surreal sage
#

alright mate

#

golang

#

😭.

wheat mesa
#

Probably not using it correctly

#

Maybe the function returns a status string and a status code

digital swan
#

im having the weirdest issue with breejs. on my production server (vultr) everything works fine no issue

but on a test server (digitalocean) im running the same code just different database and bot, and randomly whenever a certain bree job ends, the main process is exited without any error or message.
bree is ran from main process while using discord-hybrid-sharding for clustering

bree scheduler: https://github.com/tekoh/nypsi/blob/main/src/scheduled/scheduler.ts
the job that causes it to exit: https://github.com/tekoh/nypsi/blob/main/src/scheduled/jobs/votereminders.ts

this happens randomly after a seemingly random amount of hours of the bot being online

lament rock
#

Is that job actuallly being run in a worker_thread? If so, add lots of logging. Add a process exit handler, add an uncaughtException handler. unhandledRejection, etc

#

override process.exit to log where it came from (error stack) and then call the original process.exit

surreal sage
#

what's the api called

#

where you join a server

#

a bot tracks your presence

#

and you can api fetch/ws it

pale vessel
surreal sage
#

yess ty

hushed patrol
#

any code or ways to make a expressjs error handler?

digital swan
lament rock
#

I write my own software for this exact reason.

#

Very limited 3rd party tools

#

my npm cache is free of lodash PraiseTheGay

earnest phoenix
#

It also has a guide on setting it up on Linux.

warm surge
#

1.1.1.1

hidden nimbus
frosty gale
#

waiting until v8 feels femboy and gets rewritten in rust

sage bobcat
copper cradle
#

how did the project go tho

#

don't mind me snooping around :^)

surreal sage
#

so project done

copper cradle
#

nice

surreal sage
#

learning a programming language is kinda easy

#

you just gotta learn the syntax

#

and then the dependencies/modules

copper cradle
#

yeah pretty much

surreal sage
#

pip, 3gb

crystal wigeon
#

check your dm Prayge pls help me out

digital swan
#

anyone know of random animal image apis? (not dogs or cats)

quartz kindle
#

there was one for pigs

#

i also recall something for opossums

pale vessel
#

i'm not sure how much images there are though, so you might see repeated images

#

maybe there will be more images/endpoints added in the future

pastel hazel
#

hello

#

i'm new

#

i needed someone to make a bot for me

#

where do i find that?

deft wolf
#

Try Fiverr

#

Anywhere but here

pastel hazel
#

it's super simple

#

its like: its asks the code an and image and sends the messgae

digital swan
#

if its super simple surely you could do it yourself for free within a day

pastel hazel
#

even not knowing nothing about programing?

deft wolf
#

There are so many materials on the Internet about writing bots for Discord that it's just a matter of whether someone wants to or not

digital swan
#

^

#

if you paid good attention to a maybe 30-40 minute youtube tutorial you could do it

pastel hazel
#

ook, thx guys

#

bye

thick path
#

Hello, I want to know the IDs of the people who voted and commented on my bot. How can I do it?

quartz kindle
#

i dont think there is an api to get comments tho

lime bear
#

Huh

eternal osprey
#

Is there a way to detect who invited a user?

wheat mesa
#

Afaik there is not a "definite" way to tell for all situations, but iirc you can find who created an invite that was used to join a server

#

In fact I don't think there's a way to tell who joined using what invite, just that an invite has a certain amount of uses

deft wolf
#

You can compare invite uses before someone joined and after

prime horizon
pale vessel
candid onyx
#

after I pay for funds in auction how long until the funds show up?

hidden gorge
#

why am i getting a 401 when trying to deploy a new command

hidden gorge
wheat mesa
#

Did you use your token correctly

pale vessel
#

and make sure it's the actual bot ID

solemn latch
#

The warning at the top could be causing unexpected issues too. I doubt it, but its worth looking into fixing that.

wheat mesa
#

That seems unlikely, if that was the issue it would probably send back something about the format being incorrect rather than a 401

lament rock
#

Gotta make sure the Authorization header is the token that corresponds with the application ID and that the header is present

sharp geyser
#

I mean if they are using discord.js it doesn't matter it automatically puts it in the header for em

#

its likely the bot they are trying to post to doesn't match the token being used like flaze said

pure pier
#

Can anyone tell me how to use bots and how do I upgrade my self in discord

deft wolf
#

How do you upgrade yourself?

pure pier
#

Means sending gif in discord server

#

Upgrading profile

deft wolf
#

You need to buy discord nitro

#

For something like 10$ per month

pure pier
#

Any other way

deft wolf
#

Nope

green kestrel
#

lol my newest bot shows on invites as being created September 2019

#

because I generated the app id so long ago for it and never got around to making the bot

peak drum
#

Nice lol

arctic coyote
# green kestrel lol my newest bot shows on invites as being created September 2019

wait! InspIRCd is also by you?? Did use it for a while when hosting my IRC server and will probably use it again (to allow people who don't have discord to also communicate)

Man you are doing great stuff! Keep it up! I'm also very pleased by D++! The library i used before discontinued the maintainance and also wasn't nearly as polished!

Thanks a lot for providing these great tools for us! 💯
Really appreciated!

green kestrel
#

I really appreciate the kind words 🙂

#

also made the inspircd module for anope and one for atheme

#

speaking of... inspircd websocket code in m_websocket is very similar to dpp websocket code for obvious reasons, could probably use the two to make a discord to irc bridge module or something

#

but I don't have time to do that rn

arctic coyote
# green kestrel but I don't have time to do that rn

me probably neither 🤔 but sounds like a very interesting idea. Very low overhead bridge. in the past i did use matterbridge. Which also worked well, but saving some resources on the server is always nice ^^. Also matterbridge offers too many features that I don't need. So it feels overkill.

Anyways, glad I found you and your tools. Really nice work!

nova spindle
#

hi

jaunty basalt
#

Hi

patent onyx
#

hey I have a question

I just got my bot verified and I set up a SKU to have payments with discord for my bot

is there any way to pull the information whens omone signs up with their discordID or something so that way I can automate making them a premium member?

tulip ledge
patent onyx
tulip ledge
patent onyx
#

hahaha it has been quite dumb

tulip ledge
#

Ah then look in their docs

patent onyx
#

yea i will have to do that 😭

solemn latch
#

I assume you want the event

patent onyx
#

what event

solemn latch
#

the event for when someone uses discord monitization.

patent onyx
#

i do it manually for now 😭

solemn latch
patent onyx
#

ah ok, thank you

i might contact their support itself or do some more research

solemn latch
#

Looks like interactions contain the entitlements of each event. So for example if a user runs a command and they are subscribed it should be provided. If the guild has the entitlement it should also be in the list.

#

that should be everything you need @patent onyx

patent onyx
#

thank you @solemn latch

solemn latch
#

no problem ^-^

nova spindle
#

hi

candid shale
#

¯_(ツ)_/¯

neon leaf
pale vessel
#

goofy ahh discord icon

neon leaf
#

bruh I keep getting dms saying this 😭

#

exactly why I keep it

neon leaf
lament rock
#

Oh just $55,000

#

pocket change

terse carbon
#

hey why in

viscid furnace
#

Hello, I use Pycord but the topggpy is only compatible with discord.py how can I do that I can use pycord

drowsy lark
#

Hello

craggy pine
sharp geyser
#

Its not only compatable with that one specific python lib, that would be ludicrous

#

It is just the most commonly used so its displayed in the docs

sharp geyser
#

and it should work

radiant kraken
main trench
#

Hello

craggy pine
lament rock
radiant kraken
#

i mean yeah but it doesnt mean that you have to constantly deep dive into raw APIs whenever a wrapper is available, especially when the wrapper also does things besides just requesting to the API (e.g autoposting)

#

APIs can also change over time, and that should be left to the API wrapper developers

lament rock
#

Assuming the wrapper is maintained

radiant kraken
#

i'm sure most are maintained iaraShrug

lament rock
#

This isn't just about the top.gg api. This is about any api wrapper

#

The top.gg js wrapper doesn't support the lib I maintain, so like :(

radiant kraken
#

what

lament rock
#

what?

lyric mountain
#

Topgg api is simple enough to use it raw

odd oracle
#

hi, I would like to implement the music commands in my bot, for the moment only /play and /stop, I want the songs to be either from YouTube or Spotify or both, all of this in Python, could anyone help me?

vivid fulcrum
#

if you really need to add support for spotify links, you can gather metadata from the spotify track, search for the track name on youtube and fetch it from youtube

#

but i'd suggest trying to implement the youtube side first, and then focusing on the spotify part

lament rock
#

spotify html meta tags includes a preview mp3 link (not the full song)

lyric mountain
craggy pine
pallid obsidian
#

Bug on the "analytics" page
Disabling width "fixes" this bug

lyric mountain
slim kite
#

Hi

stark abyss
#

so liek i have this todo app and when i click on the little todo card, a modal shows up

#

like this

#

but i dont think thats a good idea, what if people wanted to just mark it as done?

#

so idk what I should do

lament rock
#

add a green checkmark button to mark it as done

earnest phoenix
#

But why are you using Pycord

#

discord.py is the go-to for Discord libraries, for Python, & is vastly more supported

red sparrow
#

can anyone help me:
``
@client.tree.command(name = "send", description = "Send a post")
async def send(inte: discord.Interaction, name: str, description: str=None, image: discord.Attachment=None):
await inte.response.send_message("Post created!", ephemeral = True)
embed = discord.Embed(title = name, description = description)

embed.set_image(url = image)
with open("postno.txt", "a") as f:
    f.write("I")
fp = open("postno.txt", "r").read()
cnt = 0
for x in range(len(fp)):
    cnt += 1
embed.set_author(name="Post No: " + str(cnt) + ". Post by: " + str(inte.user), icon_url=str(inte.user.avatar.url))
os.mkdir(str(cnt))
os.system("touch " + str(cnt) + "liked.txt")
os.system("touch " + str(cnt) + "disliked.txt")
with open("servers.txt") as fp:
    line = fp.readline()
    line = line.split("\n")
    line = line[0]
    print(line)
    while line:
        channel = client.get_channel(int(line))
        await channel.send(view=Counter(), embed=embed)
        thread = await channel.create_thread(name="Post No: " + str(cnt) + ". Post by: " + str(inte.user) + " Title: " + name,type=discord.ChannelType.public_thread)
        line = fp.readline()``

I need the buttons to not be able to clicked more than once by that one user, how would i do that?

red sparrow
# red sparrow can anyone help me: `` @client.tree.command(name = "send", description = "Send ...

Here is the view: ``class Counter(discord.ui.View):
@discord.ui.button(label='👍 ', style=discord.ButtonStyle.green)
async def counter(self, interaction: discord.Interaction, button: discord.ui.Button):

    number1 = button.label
    number2 = number1.split("👍")
    if number2[1] == " ":
        number2[1] = 0
    print(number2)
    number = int(number2[1])
    button.label = str("👍 ") + str(number + 1)
    await interaction.response.send_message("Sucessfully liked", ephemeral=True)
    await interaction.message.edit(view=self)
@discord.ui.button(label='👎 ', style=discord.ButtonStyle.red)
async def counter2(self, interaction: discord.Interaction, button: discord.ui.Button):
    number1 = button.label
    number2 = number1.split("👎")
    if number2[1] == " " or number2[1] == "":
        number2[1] = 0
    print(number2)
    number = int(number2[1])
    button.label = str("👎 ") + str(number + 1)
    await interaction.response.send_message("Sucessfully disliked", ephemeral=True)
    await interaction.message.edit(view=self)
``

This is in discord.py

tropic lagoon
#

ya

#

just got it from the dashborad

red sparrow
#

ok

tropic lagoon
#

still getting it

#

i even made a new token

digital lotus
tropic lagoon
#

alr so its not just only me

radiant kraken
pseudo grotto
#

Hey, i've setup a warning system but im kind of confused on one idea. see bots like dyno have it setup so you can determine the punishments given for reaching a thersehold by editing it on their dashboard but for a bot like mine which has no dashboard how can i get admins to set a punishment for a thersehold? what do you guys think would be a good idea for something like this on a command only scale with no web based dashboard?

deft wolf
#

Everything you can do using a dashboard can also be done using a command, the only difference is that the dashboard is simply easier and more accessible to use

#

At the very end, you still have to make a request to the API that will do what it is supposed to do, just like you would use a regular command in the bot

pseudo grotto
pseudo grotto
#

my setup command is already cluttered with 13 options

deft wolf
#

That's... probably too many options for the average user

#

It's probably better to use buttons or select menus for such a number of options

deft wolf
pseudo grotto
lament rock
#

Why does it take 2 seconds what

surreal sage
#

im doing stuff in nextjs

#

and this hmr is just breaking for some reason

#

im making changes

#

server recompiles

#

but client changes nothing

#

and i have to restart the dev server to see the changes

wheat mesa
#

Is there a way to host a GitHub pages without it being open source?

#

Or for that matter is there any static site host that’s free and easy to work with

digital swan
wheat mesa
#

Sounds good

#

To that matter is there a way to have a login (just with a standard username and password, I don’t need to update it dynamically or anything, this is an admin board) that doesn’t require a backend API?

vivid fulcrum
#

nope

wheat mesa
#

Or is there a service that makes that easy or anything

vivid fulcrum
#

a service maybe

wheat mesa
#

Since I’d rather not be showing the public where I work and have this be employee only access lol

vivid fulcrum
#

maybe 0auth suits your case

#

auth0*

wheat mesa
#

Yeah maybe but that’s a lot of work to set up in the middle of a shift, this is meant to be like a virtual recipe book for my job

#

OAuth is a hassle, I’d rather just have like a 8 digit code they enter

vivid fulcrum
#

yeah, github pages aren't meant to host something like that so you'll have to do weird solutions either way

wheat mesa
#

I’ll have to figure it out later I suppose

vivid fulcrum
#

I’d rather just have like a 8 digit code they enter
OTP seems to suit perfectly, but i have no idea which provider to recommend

wheat mesa
#

I suppose I could host it on some junk throwaway account so I don’t have to worry about anonymity

#

Only issue being that I probably don’t want to give away the recipes we use to random people in case they found it somehow

vivid fulcrum
#

what kind of content are you hosting

wheat mesa
#

Maybe I’ll just end up building an API, I really have no problem writing the code for it, I just have a feeling hosting everything is gonna be a rabbit hole

#

It’s meant to be like an admin panel for my workplace to help with training new employees, stuff like notes about closing, opening, how to make certain items, etc

vivid fulcrum
#

does it only host documentation then

wheat mesa
#

Pretty much, there will be no dynamically loaded content or html or anything

#

But I also don’t want anyone to just find that page and look at all of our notes publicly yknow

#

Which means I’m probably going to need an API

vivid fulcrum
#

this is what you're looking for

wheat mesa
#

Ah this is good

#

Thank you

#

I’ll look into how to set this up later

#

Is this a free service?

vivid fulcrum
#

for up to 10 users

wheat mesa
#

Perfect

#

We only have about 5 people that need it

eternal osprey
#

hey guys

#

i recently implemented a dijkstra algorithm in c++ to solve a distance based problem

#

however, my code seems to have a particularly high runtime (namely 1.137 which is deemed to be on the high side). Is there any way that i could dm someone my code for some help and tipes regarding the runtime complexity?

harsh nova
eternal osprey
#

awesome! I will send you a message 🙂

green kestrel
#

just finished cooking up some awesome in C++ actually

#

i wanted to pass state in components but i didnt want the user interfering with the state

#

the state is a great place to stash transient stuff under the custom_id field, but it means that youre leaving it to being tampered with... you would expect the user cant, via the standard discord client. but they can, either via selfbots, modded clients, or developer tools or postman.

#

basically, you can do like ```cpp
component.set_id(security::encrypt("some critical state info"))

#

then use security::decrypt() to decrypt the received ID

#

it uses zlib to compress the string so we get more out of the 100 char limit, then AES256 to encrypt it and then wraps it with base64 (because the field is 7 bit ascii only)

radiant kraken
#

it's nice to see a game concept with such a long history breathed back into life in the form of a discord bot

#

the game itself is older than 99% of people here onesieKEKW

green kestrel
#

im not looking forward to porting the website to laravel

#

tbh might not need to, could just update the wordpress content

#

for now anyway, so I can launch

slender wagon
#

Do you guys use your own smtp server usually or a third party?

green kestrel
#

I'm very much in the minority these days

#

however I only use my own for receiving, I use mailgun for sending

green kestrel
eternal osprey
#

hey, i was bored so i started to practice some of my algorithm skills. I created a way to assign colors to each single vertex, where adjacent vertices have different colors. I just thought that bfs would be fine, as we are just interest in A path, not necessarily the most optimal or anything:

    
    public static int edges;

    public static enum state {
        UNDISCOVERED, DISCOVERED
    };

    public static enum colors {
        BLACK, RED, BLUE
    }
//graph created here -> excluded cuz it's not that special.
    public static void BFS(int[][] graph, int source) {
        state[] explored = new state[graph.length];
        int[] predecessor = new int[graph.length];
        Queue<Integer> frontier = new LinkedList<>();
        colors[] coloring = new colors[graph.length];
        coloring[source] = colors.RED;
        for (int i = source + 1; i < graph.length; i++) {
            explored[i] = state.UNDISCOVERED;
            predecessor[i] = -1;
        }
        explored[source] = state.DISCOVERED;
        predecessor[source] = -1;
        frontier.add(source);

        while (!frontier.isEmpty()) {
            int CurrentElement = frontier.remove();
            for (int i = 0; i < graph.length; i++) {
                if (graph[CurrentElement][i] != 0 && coloring[CurrentElement] != coloring[i]
                        && explored[i] != state.DISCOVERED) {
                    predecessor[i] = CurrentElement;
                    explored[i] = state.DISCOVERED;
                    frontier.add(i);
                    if (coloring[CurrentElement] == colors.RED) {
                        coloring[i] = colors.BLUE;
                    } else {
                        coloring[i] = colors.RED;
                    }

                }
            }
        }
        System.out.println("\nMatches and Chosen Colors:");
        for (int i = 0; i < edges; i++) {
            System.out.println("Vertex " + i + " Color: " + coloring[i]);
        }
    }
#

what wpuld you guys think of the algo, it's really simply but maybe there are faster and other ways to do this?

#

i also maintained a state of color for each single path. In reality this was not needed, and we could also have a for loop in the end, and for each node, we will set a different color than its predecessor but this above seemed easier

stark abyss
#

or this

#

i think last one look the best

wheat mesa
#

I feel like the smaller buttons make the app look less clean

#

They look stubby

pale vessel
#

it might be good to have a max width of the first one, because you don't want it to look too wide on a bigger device

#

but maybe that should just be applied to the modal itself

stark abyss
#

alright thanks guys appreciate the feedback

limpid compass
#

Hello,

I'm looking for a bot that can monitor various Twitter pages based on keywords. For example, whenever a Twitter page in my watchlist posts a tweet related to the keyword "music," it will automatically be posted on my discord channel. Tweets that don't contain the keyword should not be posted. Is there a bot here that can do that?

Sorry for the inconvenience. Thank you.

deft wolf
#

I doubt it, I haven't seen any bot that would offer something so personalized

#

Besides, the Twitter API is something that either costs money or is not very easy to obtain

#

At least I didn't manage to get it angeryBOYE

limpid compass
summer torrent
north cairn
#

i am trying to shift from replit to vsc... i am getting some erros,can someone help?

#
module.exports = client;

["command","events", "slashcommands"].forEach((handler)=>{ 
 require(`./handlers/${handler}`)(client); 
 });```

so this works fine in replit but in vsc it says that : require(...) is not a fucntion
digital swan
#

whatever youre importing isnt directly a function

#

probably a difference in nodejs versions

lament rock
wheat mesa
#

I have a feeling that they just straight up copy pasted files

north cairn
digital swan
north cairn
#

how to install like older versions

lament rock
#

lol you dont wanna go back to pre v14 just for only commonjs

loud wind
#

is confesion bots allowed in discord (for enterainment)

lament rock
#

likely not if you're storing messages

loud wind
#

i was gonna make for private usage but i wasnt sure is it allowed, I wont save the content and user data, I would only save the data of "did user agreed to TOS"

digital swan
loud wind
#

thats all

digital swan
#

Oh so it literally just repeats what the user says and doesn’t store anything?

loud wind
#

the embed will be like
title: A confession sent by a anonymous person
<his confession>

#

but as i mentioned earlier, its only for private usage (I have a small server filled with my real life friends)

digital swan
#

Yeah that’s obviously gonna be fine

rapid solstice
glossy spoke
#

Gm

stark abyss
#

Need Feedback

#

🙏

sage bobcat
#

One message removed from a suspended account.

stark abyss
#

the app or the picture?

#

the app is a todo app
and my friend drew that picture

stark abyss
sage bobcat
#

One message removed from a suspended account.

#

One message removed from a suspended account.

stark abyss
#

button, text, color, the fact that there is half screen not having that specil layer

#

is the text too big or small, or is it okay? the symbols, are they too small?

flat copper
#

hello, im using tailwind css with next to create a app but its classes are not working in browser

#

next app

slender wagon
#

question...
I am working with an app where frontend is made with nextjs and backend with express.
The issue is i am setting some cookes (accesstoken and refreshtoken) for some reason they work fine on localhost but on production they don't

export const sendAccessToken = (res: Response, token: string) => {
  res.cookie('accessToken', token, { httpOnly: false, sameSite: 'none', secure: true });
};

export const sendRefreshToken = (res: Response, token: string) => {
  res.cookie('refreshToken', token, { httpOnly: false, sameSite: 'none', secure: true });
};

removed the http only atribute cuz testing

solemn latch
solemn latch
#

Interesting to use express for the backend. Nextjs has a pretty decent system for a backend.

solemn latch
earnest phoenix
#

why I dont receive event payload when I send a message in a threadchannel

pale vessel
#

your bot needs to join the thread

earnest phoenix
#

I was using the default gateway version

#

I fixed it using the v10

sharp geyser
#

So I have a class method that returns aspecific type of Promise<Array<User>> and then I have a cache prop that is just a Map<User>, thing is if I do this.cache.entries() it returns an IterableIterator<User> which is not what I want

#

Oh wait

#

I can use Array.from

#

forgor

round cove
#

I've never seen how but how can I get a bot application to apply for RPC access?

radiant kraken
sharp geyser
#

But why not use Array.from

radiant kraken
green kestrel
#

im surprised that js doesnt have Array.kinda

#

may or may not be sorta arraylike

green kestrel
#

the game sdk uses it

sharp geyser
earnest phoenix
sharp geyser
#

nope

earnest phoenix
#

Btw I’ll continue working by web bye

tall shuttle
#

I am writing a Discord bot. The bot works and does not give any errors, but it does not load the commands. What do you think is the problem? I would be glad if you could help me.

deft wolf
#

It depends on the type of these commands

#

Slash commands must be registered first

green kestrel
tall shuttle
#

If you want, I can post the code from Google docs.

wheat mesa
#

You should just post it in a pastebin

#

Or a codeblock if it’s small enough

green kestrel
#

or share the github

#

you ARE using version control, right?

sharp geyser
#

Bro sharing code in google docs

#

next level shit right there

green kestrel
#

for when you want to skip a step in training google bard

clear patio
#

Can somebody help me

const { Client, Intents } = require('discord.js');
const axios = require('axios');
const cheerio = require('cheerio');

const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
const targetChannelName = 'bot'; // Replace with the actual channel name

client.on('ready', () => {
console.log(${client.user.username} has connected to Discord!);
});

client.on('messageCreate', async (message) => {
// Check if the message is in the specified channel
if (message.channel.name !== targetChannelName) {
return; // Ignore messages from other channels
}

// Check if the command is "!vacation"
if (message.content === '!vacation') {
    // Fetch vacation ideas from Check24
    const check24_url = "https://www.check24.de/reisen/";

    try {
        const response = await axios.get(check24_url);
        const $ = cheerio.load(response.data);
        const vacation_ideas = $('.reisen-hotelname a');

        if (vacation_ideas.length > 0) {
            const random_idea = vacation_ideas.eq(Math.floor(Math.random() * vacation_ideas.length)).attr('title');
            message.channel.send(`How about a vacation at ${random_idea}?`);
        } else {
            message.channel.send("Sorry, couldn't fetch vacation ideas.");
        }
    } catch (error) {
        message.channel.send("Sorry, couldn't connect to Check24.");
    }
}

// Your existing message handling
if (message.content === "ping") {
    message.channel.send("pong");
}

});

// Log in to Discord
client.login(process.env.TOKEN);

#

If yes Massage me in private

deft wolf
#

But with what

#

We have no context

#

Also it looks like chatgtp code with those comments

stark abyss
#

yeah what is the issue?

wheat mesa
#

(No offense to them, just how it is)

lament rock
round cove
solemn latch
worn flume
#
from topgg import DBLClient
import topgg
import discord
from discord.ext import commands


TOPGG_TOKEN = token
client = commands.AutoShardedBot(shard_count=1, command_prefix="*", intents=intents, message_content=True, messages=True)
dbl = DBLClient(client, TOPGG_TOKEN)

@client.event
async def on_ready():
    await dbl.post_guild_count()


client.run(token)


  File "c:\Users\FalconHH\Desktop\Alpha\main.py", line 52, in <module>
    dbl = DBLClient(client, TOPGG_TOKEN)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\FalconHH\AppData\Local\Programs\Python\Python312\Lib\site-packages\topgg\client.py", line 98, in __init__
    self.http = HTTPClient(token, loop=self.loop, session=kwargs.get("session"))
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\FalconHH\AppData\Local\Programs\Python\Python312\Lib\site-packages\topgg\http.py", line 84, in __init__  
    self.session = kwargs.get("session") or aiohttp.ClientSession(loop=self.loop)
                                            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\FalconHH\AppData\Local\Programs\Python\Python312\Lib\site-packages\aiohttp\client.py", line 242, in __init__
    loop = get_running_loop(loop)
           ^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\FalconHH\AppData\Local\Programs\Python\Python312\Lib\site-packages\aiohttp\helpers.py", line 301, in get_running_loop
    if not loop.is_running():
           ^^^^^^^^^^^^^^^
  File "C:\Users\FalconHH\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\client.py", line 140, in __getattr__
    raise AttributeError(msg)
AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook

Can someone help me about this error?

solemn latch
#

assuming you just want to program your own rpc and not use an off the shelf solution.

round cove
#

I use TS.

#

Got a solution? 👁️

spark flint
#

you can see the extension source code

#

which shows how it works smide

round cove
#

You still need a Discord application with the correct perms to change the users activity status lol.

spark flint
#

ah, didn't catch that part

#

wait

#

ah nvm, read the error message discord gives KEKW

#

idk why discord doesn't show scope errors on the auth page instead of showing it as a valid scope

#

god knows how he got intents (he does know staff tbf) but yeah you're right

vivid fulcrum
#

oauth is garbage everywhere

#

no matter what service provider you use, chances are their oauth implementation is janky xd

spark flint
#

nah how did he get it

#

👁️

round cove
#

To be fair, Advaith is like a Discord favorite I feel. I'm not surprised if they gave him some special perms. But their app is also a year old, it might be grandfathered activity perms?

spark flint
#

well looking at past commits/issues its been like this since at least 2019

#

but yeah special perms would be no suprise

round cove
#

Since 2019? Jeez lol.

round cove
#

Classic truly

solemn latch
#

so its not really rpc is it?

round cove
#

It is.

#

It gets activities.write perm, it makes a call to the @me endpoint and changes your activity.

vivid fulcrum
#

it isn't rpc

round cove
#

Hmm?

vivid fulcrum
#

rpc is has been long dead for now and implements a different set of protocols

round cove
#

For now, RPC is in a private beta. We are not currently accepting any new developers into the program at this time.

vivid fulcrum
#

that's been there for years

#

@me endpoints are just oauth endpoints

round cove
#

What do you think it is then and how does it use a RPC scoped perm

vivid fulcrum
#

it's just an oauth scope that has a whitelist

round cove
#

Alright then how do you get whitelisted :))

vivid fulcrum
# spark flint

it's a closed beta i guess, so you don't 🤷‍♂️

round cove
#

What's a closed beta?

vivid fulcrum
#

you might find more luck in the discord developers server but a quick search just led me to this:

round cove
#

Classic.

solemn latch
round cove
#

My bad. I'm equating RPC = Rich Presence

#

I didn't know RPC was an actual protocol lol.

solemn latch
#

it might not be a protocol by definition, I dont remember what it even really is.

all I really know is that rpc is typically between two processes on a computer.

Like a game to the discord client

#

Either way, hopefully this becomes public soon

round cove
#

Right.

#

The dev discord and github comments all seem conflicting just for Advaith to get the perm somehow lol.

#

Who knows anymore.

sage bobcat
proven lantern
#

if i transfer "app to team" will that reset my public key or my bot secret token?

pale vessel
#

no, it won't

eternal osprey
# solemn latch it might not be a protocol by definition, I dont remember what it even really is...

i recently got that in one of my security courses. It's basically a connection between client (caller) and server (callee). The callee basically awaits for requests, and once the caller does so (with the required security params etc) it will authenticate the process and start the procedure that the server must perform given the params of the caller. The caller process then basically gets on hold and awaits a reply of the callee, and once it's done executing it sends it to the caller. It will authenticate the origin of the reply again and then resumes where it left off before the call was made.

#

it reminds me of ssh, but now instead of just authenticating and prompting the user the ssh access, it actually executes some process for you

tulip ledge
#

Does discordjs already have any features to detect if a user is a premium subscriber of your bot?

lament rock
#

It's cool that I don't have to update my lib unless there are major API changes

pallid obsidian
#

When I try to add ## in front of text or even try to use the <h2> tag, the text still remains the same?

pallid obsidian
sterile lantern
#

anyone know why this is happening?

#

my dockerfile used to work a couple of months ago and now im putting it on a pi but it doesnt deloy

fathom kiln
sterile lantern
#

fixed it, was a old version of node

hidden gorge
#

any reason it is only showing 1 user?

client.user.setPresence({
        activities: [{ name: `${client.guilds.cache.size} Guilds | ${client.users.cache.size} Users`, type: ActivityType.Watching }],
        status: 'idle',
      });
});
spark flint
#

Because only one user is cached

warm surge
#

client.guilds.cache.reduce((acc, guild) => acc + guild.memberCount, 0).toLocaleString()

#

@hidden gorge

lament rock
#

Caching is fun.

hidden gorge
hidden gorge
#

fixed

#

i found that out

wheat mesa
#

It’s been a long time since I’ve done anything with the DAPI though so I’m not sure if guilds are guaranteed to be cached or not by default

deft wolf
#

Probably yes, guilds are guaranteed but users/channels need to be fetched

#

That's why I don't know how many users my bot has since its creation because it's too much work to check it angeryBOYE

prisma nebula
#

hey

#
Traceback (most recent call last):
  File "/home/runner/........../venv/lib/python3.10/site-packages/discord/client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "bot.py", line 285, in on_command_error
    raise error
  File "/home/runner/...................../venv/lib/python3.10/site-packages/discord/ext/commands/hybrid.py", line 438, in _invoke_with_namespace
    value = await self._do_call(ctx, ctx.kwargs)  # type: ignore
  File "/home/runner/........../venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 846, in _do_call
    raise CommandInvokeError(self, e) from e
discord.ext.commands.errors.HybridCommandError: Hybrid command raised an error: Command 'breaking' raised an exception: 
#

any idea?

deft wolf
#

But this is probably not the whole error

#

There should be an exception after the colon i guess

wicked pivot
#
const xpPerLevel = [
    { level: 0 , xpRequired: 0 },
    { level: 1 , xpRequired: 480 },
    { level: 2 , xpRequired: 1044 }, 
    { level: 3 , xpRequired: 1713 }, 
    { level: 4 , xpRequired: 2497 },
    { level: 5 , xpRequired: 3408 },
    { level: 6 , xpRequired: 4451 },
    { level: 7 , xpRequired: 5635 },
    { level: 8 , xpRequired: 6966 }, 
    { level: 9 , xpRequired: 8447 },
    { level: 10, xpRequired: 10086 }, 
    { level: 11, xpRequired: 11885 }, 
    { level: 12, xpRequired: 13850 },
    { level: 13, xpRequired: 15983 }, 
    { level: 14, xpRequired: 18290 }, 
    { level: 15, xpRequired: 20773 }, 
    { level: 16, xpRequired: 23435 },
    { level: 17, xpRequired: 26281 }, 
    { level: 18, xpRequired: 29312 }, 
    { level: 19, xpRequired: 32532 }, 
    { level: 20, xpRequired: 35943 }
];

const xpPerItemsJob = {
    "mineur": {
        "items": [
            {
                "emoji": "![PalaBot_Stone](https://cdn.discordapp.com/emojis/1189253640439988296.webp?size=128 "PalaBot_Stone")",
                "name": "Stone",
                "xp": 0.5,
                "level": 0,
                "levelMax": 10
            },
            {
                "emoji": "![PalaBot_Quartz](https://cdn.discordapp.com/emojis/1189253638586122331.webp?size=128 "PalaBot_Quartz") ",
                "name": "Nether Quartz Ore",
                "xp": 6,
                "level": 0,
                "levelMax": 10
            },
            {
                "emoji": "![PalaBot_Iron](https://cdn.discordapp.com/emojis/1189253635423600770.webp?size=128 "PalaBot_Iron")",
                "name": "Iron Ingot",
                "xp": 8,
                "level": 10,
                "levelMax": 20
            }
        ]
    }
}


function xpRequiredForLevel(currentLevel, targetLevel, BonusXP) {
    let totalXP = 0;

    for (let level = currentLevel; level <= targetLevel; level++) {
        const levelInfo = xpPerLevel.find(l => l.level === level);
        if (levelInfo) {
            totalXP += levelInfo.xpRequired;
        }
    }

    let XpRequired = (totalXP*BonusXP)/100;


    return {"totalXP": Math.ceil(totalXP - XpRequired)}
}

function xpRequiredForJob(job, currentLevel, targetLevel, BonusXP) {

    let {totalXP} = xpRequiredForLevel(currentLevel, targetLevel, BonusXP);

    let xpValue = ''


    xpPerItemsJob[job].items.forEach(item => {
        if (item.level <= currentLevel && item.levelMax >= currentLevel) {
            xpValue += `\n${item.emoji} ${(Math.ceil(totalXP / item.xp))}` + ` ${item.name}`;
        }
    });

    return xpValue
}

xpRequiredForJob('mineur', 0, 20, 0)```

I would like to modify the code so that a 'swipe' occurs when I request, for example, from level 0 to 20. It automatically swipes from stone to iron in the example. Currently, it only provides the stone.
surreal sage
#

what am i doing wrong

gray snow
surreal sage
#

my / imports

#

can Promise.resolve make the bundle size so big?

vivid fulcrum
#

no

#

your bundle size depends on how many packages you're using

surreal sage
#

yeah

vivid fulcrum
#

react bundle sizes will always be big, even if minified

#

but 500kb seems a bit much

surreal sage
#

oh

vivid fulcrum
#

it might be because of material ui's icons

surreal sage
vivid fulcrum
#

is that a dependency?

surreal sage
#

yeah.

vivid fulcrum
#

you should find an alternative, that package has been abandoned

#

explains why the bundle size is so big

surreal sage
#

dictionaries yea

vivid fulcrum
#

that seems to work

surreal sage
vivid fulcrum
#

better than the previous package, but yeah the dictionaries are the major thing taking up space

surreal sage
#

well the 'passwords' im generating dont have any words, so I don't think i will be needing them

vivid fulcrum
surreal sage
#

yeah

vivid fulcrum
#

if the final bundle size still is too large, i'd suggest either finding a more lightweight package or moving the password related logic onto a server (if you already have one)

surreal sage
#

how secure

#

also nextjs supports api endpoints without a custom server like express

#

136 kb not bad

vivid fulcrum
#

good enough

radiant kraken
#

@wheat mesa @pale vessel i haven't touched upon discord bots in over 2 years, so is this a good Discord Bot event handler for my autoposter?

  • does guildCreate come first before ready? or does guildCreate only gets fired whenever the bot gets added to a new server
  • where does the guild intent come into effect here?
wheat mesa
#

guildCreate only fires when the bot gets added to a new server

#

As for guild intent I can’t remember since it’s been so long

deft wolf
#
The Guilds intent populates and maintains the guilds, channels and guild.roles caches, plus thread-related events.
If this intent is not enabled, data for interactions and messages will include only the guild and channel id, and will not resolve to the full class.
#

From discord.js guide

#
  • you need it to receive any messages
radiant kraken
radiant kraken
deft wolf
#

So yea, it's empty

#

Strange, it's empty in both cases

lament rock
#

for raw ws, the ready event happens first and tells you how many guilds the bot is in and then GUILD_CREATE for each guild the bot is in is sent. djs sends the ready event once all of the guilds are populated or a timeout is reached to account for server issues or network instability.

Largly guild create is tied to the guilds intent and maybe some events require it for cache. I had issues where messages had to be cached for reaction add and remove. This was in v12 and I never tried the partial events

#

rather the raw ready event has an Array of guild IDs this shard will cover

radiant kraken
hidden gorge
#

Error:

-      throw new MongooseError('Can\'t call `openUri()` on an active connection with ' +
-           ^

-MongooseError: Can't call `openUri()` on an active connection with different connection strings. Make sure you aren't calling `mongoose.connect()` multiple times. See: https://mongoosejs.com/docs/connections.html#multiple_connections -  at NativeConnection.createClient (C:\Users\FRC 7722\Desktop\Projects\Bots\RoSearchBot\node_modules\mongoose\lib\drivers\node-mongodb-native\connection.js:220:13)
-    at NativeConnection.openUri (C:\Users\FRC 7722\Desktop\Projects\Bots\RoSearchBot\node_modules\mongoose\lib\connection.js:759:34)
-    at Mongoose.connect (C:\Users\FRC 7722\Desktop\Projects\Bots\RoSearchBot\node_modules\mongoose\lib\mongoose.js:403:15)
-    at Object.<anonymous> (C:\Users\FRC 7722\Desktop\Projects\Bots\RoSearchBot\commands\developer\removeblacklist.js:74:10)
-    at Module._compile (node:internal/modules/cjs/loader:1376:14)
-    at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
-    at Module.load (node:internal/modules/cjs/loader:1207:32)
-    at Module._load (node:internal/modules/cjs/loader:1023:12)
-    at Module.require (node:internal/modules/cjs/loader:1235:19)
-   at require (node:internal/modules/helpers:176:18)

-Node.js v21.1.0

Code:

const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');

const mongoose = require('mongoose');
const BlacklistModel = require('../../schemas/blacklists');


const uri = "mongodb+srv://USERChanged:PASSChanged@rosearch.frdmhyd.mongodb.net/"
mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true, dbName: `prod`, });

module.exports = {
  data: new SlashCommandBuilder()
    .setName("removeblacklist")
    .setDescription("DEVELOPER COMMAND")
    .addUserOption(option => option.setName("user").setDescription("User to remove").setRequired(true)),

  async execute(interaction) {
    const notadevEmbed = new EmbedBuilder().setTitle("You are not a developer").setColor("Red");

    if (interaction.user.id === "") {
      const user = interaction.options.getUser('user');

      try {
        const existingUser = await BlacklistModel.findOne({ UserID: user.id });

        if (existingUser) {
          await BlacklistModel.deleteOne({ UserID: user.id });

          const userRemovedEmbed = new EmbedBuilder()
            .setTitle(":white_check_mark: User Removed from the MongoDB Collection")
            .setColor("Green")
            .addFields(
              { name: "UserID", value: user.id }
            )
            .setThumbnail(user.displayAvatarURL());

          interaction.reply({ embeds: [userRemovedEmbed] });
        } else {
          const userNotFoundEmbed = new EmbedBuilder()
            .setTitle(":x: User not found in the MongoDB collection.")
            .setColor("Red")
            .setThumbnail(user.displayAvatarURL())
            .addFields(
              { name: "UserID", value: user.id }
            );

          interaction.reply({ embeds: [userNotFoundEmbed] });
        }
      } catch (error) {
        console.error('Error interacting with MongoDB:', error);
        interaction.reply('An error occurred while processing the request.');
      }
    } else {
      interaction.reply({ embeds: [notadevEmbed] });
    }
  },
};
deft wolf
#

But why are you connecting to database inside command

#

You can do this just once in index.js file

hidden gorge
#

it worked earlier..

#

oh shit webster

worn flume
#

if you didn't changed anything its prob api error

warm surge
worn flume
#

check the mongodb api's to make sure its running

hidden gorge
#

was getting this earlier before i changed the DB over to a new one

deft wolf
#

Or you can pass db into client

#

That's true

warm surge
deft wolf
#

Yea, i said that's true

warm surge
#

oh

#

Im reading everything wrong lmao

wheat mesa
#

I personally prefer to pass my database contexts to functions instead of attaching it to the client, but whatever floats your boat

hidden gorge
#

its not api

warm surge
hidden gorge
wheat mesa
#

your error has nothing to do with this

#

You called mongoose.connect more than once somewhere, literally like the error says

#

Ideally you should not have code being run outside of a function in any place except for your index.js file

hidden gorge
#

i searched all files nothing

wheat mesa
#

Change where you connect to your database to index.js instead of in that other file

hidden gorge
wheat mesa
#

That way it is guaranteed to only happen once

hidden gorge
wheat mesa
#

Well yeah, if you fail to connect to your database then your requests are going to time out

hidden gorge
#

idk why its failing

wheat mesa
#

Check your connection string

hidden gorge
#
client.on(Events.ClientReady, readyClient => {

    mongoose
    .connect("mongodb+srv://RoDB:PassRemoved@rosearch.frdmhyd.mongodb.net/", {
      dbName: `test`,
      useNewUrlParser: true,
      useUnifiedTopology: true,
    })
    .then(() => {
      console.log("🟩 Connected to Database.");
    })
    .catch(() => {
      console.log("🟪 Failed Database Connection");
    });
#

i removed the pass just for this its in the code

wheat mesa
#

You should log the actual error instead of a useless “database connection failed” message

hidden gorge
#

ok one sec

#

bruh

wheat mesa
#

tbh this is why I dislike languages that allow you to ignore error handling like this

#

Teaches bad habits

hidden gorge
#

ok data is saving

hidden gorge
#

and then it works

wheat mesa
#

that sounds like a duct tape solution and you should be looking for the root cause of said issue

spark flint
#

My api stopped working for a few hours and mongo was returning errors

hidden gorge
deft wolf
#

This is why I love selfhosting mongo on my vps instead of using a free database

warm surge
#

I will use it all day logn

#

long

surreal sage
#

i had no idea this was a thing

wheat mesa
#

Most languages have this sort of thing, it’s quite nice

#

(Except Java, why the fuck does Java not have this)

sage bobcat
wheat mesa
#

wrong but this is one of those things that makes you wonder if the Java devs are living under a rock

radiant kraken
#

or C

#

C when

CreateWindowA("lol", "lol", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hinstance, NULL);
wheat mesa
#

I feel like many aspects of rust is designed in such a way that default parameters don’t need to exist

#

C is acceptable because it’s 50 years old

#

Java is not acceptable because it’s not 50 years old and there are many times where this pattern would be useful and avoid redundant code

surreal sage
#

is my eslint stupid?

radiant kraken
#

@wheat mesa @civic scroll i've successfully made my own first rust macro :D mmLol

#

very proud of that jargon lol

radiant kraken
wheat mesa
#

fancy

radiant kraken
#

thanks ❤️

#

wasted 2 hours of my life just to reduce some mundane boilerplate code

odd nexus
#

its saying message embed is not defined?

surreal sage
#

how can i edit ts types so that when i express.js Application.use my middleware, that a new property appears

sharp geyser
#

What

quartz kindle
#

coming up with weird ideas to "pack" data is so much fun

sharp geyser
radiant kraken