#development

1 messages · Page 120 of 1

peak drum
#

Works both ways

neon leaf
#

is it possible to make a class that defines a generic not trough the constructor?

eternal osprey
#

anyone who knows how to use tensorflow for py? I need some help with my epoch, batch, layer configs as my mean absolute error is pretty high

earnest phoenix
eternal osprey
#

i am not asking to ask, this literally was my question

quartz kindle
#

when i work with typescript i try to make everything as simple as possible, because once it starts getting too complicated it quickly becomes an ungodly mess

neon leaf
#

the problem is that it just is quite a complex project

quartz kindle
#

meaning i dont work too hard to make every single millimetre of code correctly typed down to every single possible combination

earnest phoenix
quartz kindle
#

its fine to sometimes work with a few any's here and there and manually inject type coercions here and there

earnest phoenix
#

Especially the first few paragraphs, even though reading the website in its entirety is definitely worth it

eternal osprey
earnest phoenix
#

Sounds great, don't expect any replies then ^-^

eternal osprey
#

okay 👍

earnest phoenix
#

Your message is 1 to 1 the described behavior of the website

eternal osprey
#

Really?

#

Wow*

#

I recently used tensorflow to create a model for predicting. I started with 50 units in each layer (except for the dense layer) and also added a batch size of 32, eventually 50 epochs as well. For linear predicting, would anyone know any good values for these variables as i currently get a mean error of around 57%
i know it's a matter of trial and error but is there any ballpark so that it makes the setting up part of my model a bit easier..

#

is this better for you Moderator Krypton?

quartz kindle
# neon leaf do you know about this, tim?

directly with generics i dont think so, unless you create a class builder that returns different classes based on options.
you can however use narrowing to filter unions inside classes

earnest phoenix
#

See, with some effort it's doable

#

Though don't expect anyone to answer as the active people don't use py or tensorflow PES_Smart

neon leaf
neon leaf
#

yup that works. Thank you so much!!!! I was struggling with this quite long

prime quest
#

bot dev, nice

rigid maple
#

?

surreal sage
#

I want Main to Renderer

#

Not Renderer to Main to Renderer

peak drum
#

You can use ipcRenderer.on if I remember correctly

surreal sage
#

And where do I emit?

#

Cause ipcRenderer's unavailable on Main and vise versa

peak drum
#

ipcMain.send

#

Or sendSync

earnest phoenix
#

good idea ?

peak drum
#

I guess

deft wolf
#

I don't know

#

I hate ads on discord

peak drum
#

I guess it could be nice for a ads discord

earnest phoenix
# deft wolf I hate ads on discord

"PromotionBot is a Discord bot designed to help server owners and administrators promote their servers based on the number of invites users have generated. The bot rewards active users who invite new members to the server by allowing them to promote their own servers once they reach a certain threshold of invites. It also provides an easy-to-use interface for checking the number of invites a user."

#

its cool for you'r server !

peak drum
#

You mean “your server”

deft wolf
rustic nova
#

promotions for invites

#

j4j essentially imo

earnest phoenix
quartz kindle
#

j4j is cringe

earnest phoenix
deft wolf
earnest phoenix
earnest phoenix
grand crest
#

guys sorry but i have stupid question

#

how to make that

#

Sunday, August 13, 2017 3:21 PM

deft wolf
#

<t:123>

grand crest
#

exacly

#

how?

#

Sunday, August 13, 2017 3:21 PM

deft wolf
#

<t:timestamp>

grand crest
#

<t:99999>

deft wolf
#

Google what timestamp is

grand crest
#

ok

grand crest
#

thanks <3\

deft wolf
#

Also this

#

Or not, that's the same

grand crest
earnest phoenix
#

Or just the official documentation lmfao

#

Creating a gist that straight up is a copy of the docs gigachad

earnest phoenix
#

anyone have a bot idea ?

deft wolf
#

You already have a bot, why do you need another one?

earnest phoenix
#

I'd have 272 bots tbh

#

With each a single command

#

Shouldn't be too hard

earnest phoenix
peak drum
#

the hosting costs tho

rigid maple
#

I'm trying to make a TwitchPlayer using SvelteKit, but when I change pages in a "Layout" the iframe reloads and I don't want that. For example, TwitchPlayer will show up in /dashboard/channel but not in /dashboard/videos and if I go from /dashboard/videos to /dashboard/channel the iframe will not load from the beginning.

I solved the iframes not being reloaded by putting them directly in the +layout.svelte file, but how can I make them appear where I want on the page I want?

civic scroll
#

use routers mayhaps, if you do have access to the path

fiery stream
#

can anybody help me solve this issue pls

earnest phoenix
fiery stream
#

…?

earnest phoenix
#

Await it...?

#

If you mark is a async

fiery stream
#

everything is awaited tho

earnest phoenix
#

Then you can't do

s = Something()

but have to do

s = await Something()
fiery stream
#

what am i supposed to await it tho ion get that

earnest phoenix
#

Because you declared __init__ as an async function

#

Welcome to asynchronous programming

fiery stream
fiery stream
earnest phoenix
#

Or as said, await it.

#

Though looking at that madnesss

#

Makes more sense to remove the async

fiery stream
#

7 it is awaited

earnest phoenix
#

???????

#

You're awaiting the init call of super

#

Not YOUR init function

#

Where do you await it in this line?

fiery stream
#

makesss sense kinda

#

ye it does

fiery stream
earnest phoenix
#

What you definitely can't do is make magic methods as async

#

Make your init function non async and don't call await super().__init__()

#
Starlette.__init__(self, routes=[
  Route('/', self.home),
])

is a thing, as shown in their documentation

#

Or I guess don't await the init call on super, as magic methods are not made to be async either way, so I doubt they made their init method async

#

Not sure why you decided to await that if it can't be awaited in the first place

fiery stream
#

concurrency is a pain in the ass in python

#

or all languages

earnest phoenix
#

If you don't use it correctly or don't understand the fundamentals, obviously

#

Can't just slap await or async anywhere

fiery stream
#

anyways can you help me explain another error

silent folio
#

Collar blue

spark flint
#

ok

earnest phoenix
# fiery stream

This function cannot be called when another asyncio event loop is running in the same thread.

#

Don't have 2 event loops running on the same thread

fiery stream
#

well i read that but idk what cases that error

#

i get it

#

i think

#

i have to use this right

celest swan
#

Do you guys know how to host a bot or develop it through iphone

#

@fiery stream could you tell me which application do u use?

earnest phoenix
#

Host? Use a VPS
Code? Use a PC

fiery stream
#

i use it for coding tho

celest swan
fiery stream
#

not hosting

celest swan
fiery stream
celest swan
fiery stream
#

ofcc

#

runs almost every language

celest swan
#

Can you help me install discord.js?

#

@fiery stream

deft wolf
#

npm i discord.js poggythumbsup

celest swan
deft wolf
#

Yes, read the message

fiery stream
#

open new page n click packages n search it

celest swan
fiery stream
#

then im not sure mate i dont really code in javascript been a while

sage heart
#

how verify bot

celest swan
sage heart
#

@celest swan bot join 100 server

earnest phoenix
celest swan
#

So I installed discord js v13 version and it dont recgonize it

peak drum
#

npm install discord.js@14.something

lyric mountain
rigid maple
#

I'm trying to make a TwitchPlayer using SvelteKit, but when I change pages in a "Layout" the iframe reloads and I don't want that. For example, TwitchPlayer will show up in /dashboard/channel but not in /dashboard/videos and if I go from /dashboard/videos to /dashboard/channel the iframe will not load from the beginning.

I solved the iframes not being reloaded by putting them directly in the +layout.svelte file, but how can I make them appear where I want on the page I want?

green kestrel
#

why do racists make bad databases?

because they hate foreign keys.

#

...i'll get my coat

rustic nova
#

Go away

quartz kindle
#

thats more xenophobia than race but yeah lmao

real rose
#

dear god

lavish ibex
#

hello

#

my bot is not sending messages in the server channels

#

but it sends in dm

solemn latch
#

is the issue sending messages, or is it not receiving commands?

#

slash commands or prefix?
or something else

lavish ibex
spark flint
lavish ibex
solemn latch
#

do you have the message intent enabled?

spark flint
#

^

lavish ibex
solemn latch
#

in your bot and on the dash?

spark flint
#

do you have it enabled in your code

lavish ibex
#
import discord
from discord.ext import commands
import random
import json

# Load Pokemon names from file
with open('pokes.txt', 'r') as f:
  pokemon_names = f.read().splitlines()

# Load Pokemon info from file
with open('pokemon.json', 'r') as f:
  pokemon_info = json.load(f)

# Load user data from file
with open('user.json', 'r') as f:
  user_data = json.load(f)

intents = discord.Intents.default()
intents.members = True  # Enable the privileged gateway intent

bot = commands.Bot(command_prefix='!', intents=intents)


@bot.event
async def on_message(message):
  # Ignore messages sent by the bot itself
  if message.author == bot.user:
    return

  await bot.process_commands(message)


@bot.event
async def on_ready():
  print('Bot is ready.')


@bot.command(name='hunt')
async def hunt_command(ctx):
  pokemon = random.choice(pokemon_names)
  # Check if user exists in user_data
  if str(ctx.author.id) not in user_data:
    user_data[str(ctx.author.id)] = {'hunted_pokemon': []}
  hunted_pokemon = user_data[str(ctx.author.id)]['hunted_pokemon']
  # Check if the pokemon is already hunted
  if pokemon in hunted_pokemon:
    await ctx.send(f"You hunted {pokemon}!")
  else:
    hunted_pokemon.append(pokemon)
    # Save user data to file
    with open('user.json', 'w') as f:
      json.dump(user_data, f)
    # Check if the pokemon is hunted for the first time
    if hunted_pokemon.count(pokemon) == 1:
      await ctx.send(f"A wild {pokemon} appeared! Registered to Dex!")
    else:
      await ctx.send(f"A wild {pokemon} appeared!")


@bot.command(name='pokemon', aliases=['poks'])
async def pokemon_command(ctx):

  # Check if user exists in user_data
  if str(ctx.author.id) not in user_data:
    await ctx.send('You have not hunted any Pokemon yet!')
  else:
    hunted_pokemon = user_data[str(ctx.author.id)]['hunted_pokemon']
    if not hunted_pokemon:
      await ctx.send('You have not hunted any Pokemon yet!')
    else:
      embed = discord.Embed(title="Your Hunted Pokemon", color=0xff0000)
      for i, pokemon in enumerate(hunted_pokemon, start=1):
        embed.add_field(name=f'#{i} {pokemon}', value='', inline=False)
      await ctx.send(embed=embed)


@bot.command(name='info')
async def info_command(ctx, pokemon_number: int):
  # Check if user exists in user_data
  if str(ctx.author.id) not in user_data:
    await ctx.send('You have not hunted any Pokemon yet!')
    return

  hunted_pokemon = user_data[str(ctx.author.id)]['hunted_pokemon']
  if not hunted_pokemon:
    await ctx.send('You have not hunted any Pokemon yet!')
    return

  if pokemon_number < 1 or pokemon_number > len(hunted_pokemon):
    await ctx.send(
      f'Invalid Pokemon number. You have hunted {len(hunted_pokemon)} Pokemon.'
    )
    return

  pokemon_name = hunted_pokemon[pokemon_number - 1]
  pokemon_info_data = pokemon_info[pokemon_name.lower()]

  # Check if user has hunted this Pokemon before
  user_hunted_pokemon = [p.lower() for p in hunted_pokemon]
  if pokemon_name.lower() in user_hunted_pokemon:
    num_hunted = user_hunted_pokemon.count(pokemon_name.lower())
    message = f'You have hunted {num_hunted} {pokemon_name}!'
  else:
    message = 'You haven\'t hunted this Pokemon yet!'

  embed = discord.Embed(title=pokemon_name.capitalize(), color=0xff0000)
  embed.set_image(url=pokemon_info_data['image'])
  embed.add_field(name='Type', value=pokemon_info_data['type'], inline=True)

  embed.set_footer(text=message)

  await ctx.send(embed=embed)

#

is it there in the code?

#

@spark flint

lavish ibex
lyric mountain
#

you don't have the intent enabled

spark flint
#

you have not given the bot the correct intents

#

in the code

lavish ibex
#
intents = discord.Intents.default()
intents.members = True  # Enable the privileged gateway intent

bot = commands.Bot(command_prefix='!', intents=intents)
#

this

lyric mountain
#

nope

#

you're enabling members intent

#

you need messages intent

lavish ibex
#

oh

#

💀

solemn latch
#

the docs go over it

lavish ibex
#

ok

lyric mountain
#

btw, don't use json as a database

lavish ibex
#

json

lyric mountain
#

?

lavish ibex
#

i need to learn about database

#

i am newbie

solemn latch
#

json is still extremely relevant. its just not meant to be used as a database

#

never was

lyric mountain
#

you can use it for pokemons, as they wont be changed

lavish ibex
#

is database easy to learn

lyric mountain
#

but definitely not for user data

#

depends

#

I think it's fairly easy, but it's "different"

lavish ibex
#

oh

lyric mountain
#

do a quick crashcourse on codecademy

#

or mozilla, whatever

lavish ibex
#

ohk

#

oh sry

#

i forgot to say Thanks!

#

:)

lyric mountain
#

yw

lavish ibex
#
intents = discord.Intents.default()
intents.members = True  # Enable the privileged gateway intent
intents.messages = True
bot = commands.Bot(command_prefix='!', intents=intents)
#

still not replying 💀

earnest phoenix
#

Still not reading the docs

#

It's message_content

lavish ibex
#

sry i read it quickly

#

scrolling down using my new mouse lol

#

working

#

If i use images of pokemon from different sites will it be a issue in future?

#

like copyright or something?

#

ok

#

pokeapi is free right?

#

ty :)

lyric mountain
#

ESPECIALLY if you have any sort of monetization

#

nintendo doesnt have a good track record of supporting fan apps (especially discord bots)

grim aspen
# lavish ibex If i use images of pokemon from different sites will it be a issue in future?

that depends, if you're doing something nintendo related then there will be issues like the second you do something with those images. there's a creative commons law where you pay to use stock images. now pokemon is protected by trademark law so you can't use anything they have that is trademarked without having the chance of being sued. also pokemon company has answered this question. they said that nobody should use their images because they are unable to review requests relating to pokemon intellectual property

#

tldr: copyright laws, short answer; no

lyric mountain
#

it's a "using pokemon at all" issue, not what api u use

grim aspen
#

don't think it's an issue with the api

#

it's the issue of using images

lyric mountain
#

you'll probably fly under the radar for a while, they wont bother with an unknown bot

#

but the moment you get some popularity, expect a C&D email

grim aspen
#

if they do happen to notice you using images without permission you will get a cease and desist

lyric mountain
#

lul

grim aspen
proven lantern
#

can 403 errors like this be cause by a lack of permissions or is there a special character that's not allowed?

earnest phoenix
#

403 is forbidden

proven lantern
#

like no permission forbidden?

lyric mountain
#

"you cant access this" forbidden

earnest phoenix
#

403 (FORBIDDEN) The Authorization token you passed did not have permission to the resource.

lyric mountain
#

nope, ssi is 5xx

grim aspen
#

sounds like it's trying to find a permission that doesn't exist, related to API

proven lantern
#
{
  "components": [
    {
      "type": 1,
      "components": [
        {
          "type": 2,
          "label": "Join Lobby",
          "style": "3",
          "custom_id": "join_lobby_btn.[REMOVED]",
          "disabled": true
        },
        {
          "type": 2,
          "label": "Leave Lobby",
          "style": "2",
          "custom_id": "leave_lobby_btn.[REMOVED]"
        }
      ]
    },
    {
      "type": 1,
      "components": [
        {
          "type": 2,
          "label": "Start Lobby",
          "style": "1",
          "custom_id": "start_lobby_btn.[REMOVED]",
          "disabled": false
        },
        {
          "type": 2,
          "label": "Close Lobby",
          "style": "4",
          "custom_id": "close_lobby_btn.[REMOVED]"
        }
      ]
    },
    {
      "type": 1,
      "components": [
        {
          "type": 5,
          "custom_id": "kick_player_btn.[REMOVED]",
          "placeholder": "Kick a player"
        }
      ]
    }
  ],
  "embeds": [
    {
      "title": "zzzAlex-DigimonTCGSP's Hosting a **!A pelear¡** Lobby",
      "description": "\n**Lobby is ready to start!**                \n\n**Players**\n<@[REMOVED]>\n<@[REMOVED]>\n\n**Lobby Info**\n*Players*: 2 players\n*Team Size*: Free for all\n**Host your own Lobby**\nhttps://discord.com/channels/[REMOVED]/[REMOVED]/[REMOVED]",
      "color": 16730441,
      "footer": {
        "text": "\nA voice channel will be created for everyone to share when the match starts."
      }
    }
  ]
}

here's the request body with all IDs replaced with [REMOVED]

earnest phoenix
#

Not necessarily wrong token

earnest phoenix
pale vessel
#

shouldn't style be a number?

proven lantern
grim aspen
#

it's trying to make a PATCH request but it isn't allowed to make that request

earnest phoenix
#

400 Bad Request (Invalid Form Body)

#

As it says

The Authorization token you passed did not have permission to the resource.

#

Your code may be perfectly correct, if your bot doesn't have access to whatever you're trying to do - it won't go far

grim aspen
#

it's trying to find the channel but it doesn't have access to the channel

earnest phoenix
#

Not necessarily either

proven lantern
earnest phoenix
#

Could very well be trying to edit a message it cannot edit

proven lantern
#

so they'd need send message perms?

earnest phoenix
#

That for sure

grim aspen
#

it is the api issue

#

related to permissions

proven lantern
#

mmkay, i'll ask them what perms they gave the bot

earnest phoenix
# proven lantern

Unrelated to your issue but may I ask why you're using Axios over the built-in global fetch() function? (Or just Undici, which is where that function comes from), or Node-Fetch

proven lantern
earnest phoenix
#

You don't have to, that header is specified by default when possible

lyric mountain
#

u can make a wrapper for fetch

proven lantern
#

also dont like doing the res.json thing

lyric mountain
#

sometimes I wonder if I'm the only weirdo that make wrappers when I don't want to specify the same properties everytime

earnest phoenix
#

If you're using Node.js v18 or higher, use the built-in global fetch() function, otherwise use Undici

#

The Fetch API is a standard

#

fetch diez

earnest phoenix
# proven lantern it should be

It is, but not everything expects the same content-type so you'd have to specify it yourself, besides you can make a wrapper as said if you really need it to be passed in every request you make

earnest phoenix
proven lantern
earnest phoenix
#

Fetch also does that

proven lantern
#
    .then(res => res.json())
    .then((json) => {
        // do something with JSON
    });```
#

.then(res => res.json())

pale vessel
#

you could easily make a small wrapper around that though

earnest phoenix
#

Oh I was talking about the header, what you're showing is a body consumer, not everyone wants to consume a body and look at it, which can also take a long time depending on the body type and size

lyric mountain
#

btw, you don't always want the body json

earnest phoenix
#

And yeah

lyric mountain
#

it'd be better for large payloads not to call res.json()

proven lantern
lyric mountain
#

and check status beforehand

grim aspen
#

i thought axios doesn't automatically do that

lyric mountain
#

you'd not need to get the body json, just the status

#

this is a weak example tbh, but there are scenarios where not getting the json is preferrable

#

cough cough like when working with patreon cough

proven lantern
#

the content-type is set to json when the request body is json. the response is parsed json if the response has a json header content type

lyric mountain
#

the response wont be parsed until you use res.json()

#

before that it'll be plain text

pale vessel
#

they're talking about axios?

lyric mountain
#

fetch

pale vessel
#

I'm sure they mean axios

proven lantern
#

axois looks at the headers and sees it's json for me

#

i just tested fetch and it looks like it add the content type headers now

#

on requests

earnest phoenix
proven lantern
#

just look at the content type. if it's json then parse it to json

lyric mountain
#

we don't mean different headers

#

we mean that sometimes it's preferrable not to call res.json() if what you want is other data

#

as that'll parse the text into a json object

#

thus allocating more resources

proven lantern
lyric mountain
#

it doesn't matter

proven lantern
#

server could be messed up sending the wrong content type

lyric mountain
#

you could have content-type: Shrek Video an still call res.json()

#

content type doesn't define what's being sent through the body, it just tells the receiver what to expect

proven lantern
#

if the receiver expects json then why not just call res.json() for me internally?

lyric mountain
#

imagine you have a huge payload, with millions of entries

proven lantern
#

unless the server is lying about the content type

#

multipart

earnest phoenix
#

The API doesn't know if you actually want the body of the request to be consumed, and shouldn't assume that as the receiver may just be looking simply for the status, header data, or similar, or for the body to be consumed as a different type rather than just the specified content-type

proven lantern
lyric mountain
proven lantern
lyric mountain
#

the server returns all the info about anime XYZ

proven lantern
#

in my case i am the server and the consumer

#

except for the discord api stuff

#

but they give the right content-type

lyric mountain
#

yes, but forget abt ur current case, we're explaining why res.json() isn't required everytime

#

for some transactions you simply don't care about the body, you just want the headers or other metadata

#

it is if you need the body

#

you could also use the raw body, but it'd be hard to work with

#

res is the request itself

#

to get the plaintext you'd use res.body

proven lantern
#

you'd want to work with a data stream instead of putting the entire res.body into memory

earnest phoenix
#

Res is the response, it contains status code, headers, and other metadata sent by the server, if you want to get the text response you would call res.text()

lyric mountain
#

the latter is official

#

fetch was a browser-only api, but they integrated into node in the newest versions

grim aspen
#

nodefetch is third party for nodejs

proven lantern
lyric mountain
#

json must be parsed all-or-nothing, if you want to use streams you need to use another format

#

multipart is just to tell the receiver that there'll be more data to come

proven lantern
lyric mountain
#

I mean, as long as the json starts and ends in the same request

earnest phoenix
grim aspen
#

misread, nodefetch and fetch use different environments. like kuu said, fetch is browser only, while node-fetch is used in server-side javascript

proven lantern
lyric mountain
#

there's fetch for node now, node-fetch was a third-party surrogate while node didn't get it oficially

earnest phoenix
#

Node-Fetch implements the Fetch API, and so does Undici (the Fetch API Node.js uses as built-in), Undici does it better and is more standard compliant

proven lantern
#

nice, i wonder if it's easier with axios

quartz kindle
#

Undici does it better
lies

#

well tbf its been a while since i used it, hopefully its much better now

thorn spruce
#

Hey! how can I check that sometimes the server takes more than 3 seconds to answer?

#

Because sometimes i'm getting unknown interaction from nowhere with Discordjs

lyric mountain
#

by rule of thumb, anything that involves additional processing should have the interaction deferred as the very first thing

#

before starting anything else

thorn spruce
#

in fact it seems happening not on the slash commands but in components

lyric mountain
#

any interaction

#

never do any processing before you defer the interaction

thorn spruce
#

i'm doing that

await event.reply(content).then(e => {
            const filter = async i => i.user.id === this.author && await i.deferUpdate()
            const collector = e.createMessageComponentCollector({ filter, time: 250000})
            collector.on("collect", async r => {
                switch(r.customId) {
                    case "profileDisplay":
                        if(AllowedPage.includes(r.values[0]) && this.Page[r.values[0]] != undefined)  {
                            const content = {embeds:[this.Page[r.values[0]]]}
                                r.editReply(content)
                        }
                    break;
                }
            })
        })
lyric mountain
#

are you 100% sure that code works?

thorn spruce
#

yep it does

lyric mountain
#

as I see it, you're replying/deferring more than once

#

oh wait, nvm

#

that's a collector

thorn spruce
#

at each click?

#

yep

lyric mountain
#

but well, see this:

#

const filter = async i => i.user.id === this.author && await i.deferUpdate()

#

you're not deferring as the first operation

#

if the user that clicks is not the author, it wont defer

thorn spruce
#

ah you think it may come from that?

lyric mountain
#

very likely

thorn spruce
#

i'll try

lyric mountain
#

also please use multiline

#

instead of an AND chain

thorn spruce
#

I tried with my secondary acc

#

and it doesn't send error

#

it may come from networks issues too no?

lyric mountain
#

unlikely, unless your host is shit

#

discord has its own internal pooler, so the requests wont come fast enough to cause lost requests

#

not to mention libraries also have their own poolers

thorn spruce
#

i'll also try to replace my filter by that

        const collectorFilter = async i => {
            await i.deferUpdate();
            return i.user.id === this.author;
        };
lyric mountain
#

u don't need to await btw

#

let defer happen parallel to the filter

thorn spruce
#

i can do that too

#

Alright

#

I'll try these things and let's see what happen

lyric mountain
#

another tip (not related to the original issue), store the array values in a constant

#

const page = this.Page[r.values[0]]

rigid maple
#

How can I make the iframe not reload even if the pages in a route change in ReactJS

#

but the iframe will appear on a single page

thorn spruce
lyric mountain
#

gl

proven lantern
#

guess what this evaluates to without running it.
const title = document.title || typeof document.title === 'undefined' ? "No Title" : "Empty String Title"

#

i think i broke javascript

boreal iron
#

Should be !document.title

quartz kindle
#

|| is evaluated before ternary

boreal iron
#

If title exists OR title undefined = no title doesn't make sense

quartz kindle
#

so your code is basically (document.title || typeof document.title === 'undefined') ? "No Title" : "Empty String Title"

proven lantern
#

they messed up the order of operations when making js

#

and all languages

boreal iron
quartz kindle
#

lmao

#

ternary has one of the lowest priorities

#

since its basically a glorified if

#

look at it like this, and it will make more sense
if(document.title || typeof document.title === 'undefined') { "No Title" } else { "Empty String Title" }

proven lantern
#

i just need to remind myself that logical OR and ternary aren't at the same level

#

ternary's always seem more like a glorified logical or statement

sharp saddle
#

damn

wooden ocean
#
const { Permissions, EmbedBuilder } = require('discord.js');

module.exports = {
  name: 'lockdown',
  description: 'Locks down all channels',
  category: 'moderation',
  usage: '<reason>',
  permissions: ['MANAGE_CHANNELS'],
  async run(client, message, args) {
    // Check if a reason was provided
    const reason = args.join(' ');
    if (!reason) {
      return message.channel.send('Please provide a reason for the lockdown!');
    }

    // Lock all channels and send embed message
    const channels = message.guild.channels.cache.filter(channel => channel.type === 'GUILD_TEXT');
    const lockdownEmbed = new EmbedBuilder()
      .setColor('#ff0000')
      .setTitle(':lock: Server Lockdown')
      .setDescription(`The server has been locked down due to the following reason: **${reason}**.\nWe apologize for the inconvenience and we will fix the issue as soon as possible.`);

    channels.forEach(channel => {
      channel.permissionOverwrites.edit(message.guild.roles.everyone, { SEND_MESSAGES: false });
      channel.send({ embeds: [lockdownEmbed] }).catch(console.error);
    });

    // Create and log the timeout role
    const timeoutRole = await message.guild.roles.create({
      name: 'Timeout',
      color: '#ff0000',
      permissions: [],
      reason: `Server lockdown: ${reason}`,
    });
    message.guild.channels.cache.forEach(channel => {
      channel.permissionOverwrites.edit(timeoutRole, { SEND_MESSAGES: false });
    });
    const modLogChannel = message.guild.channels.cache.find(channel => channel.name === 'mod-logs');
    if (modLogChannel) {
      modLogChannel.send(`🔒 Server locked down by ${message.author.tag} for the following reason: **${reason}**.`).catch(console.error);
    }
  },
};

error:

RangeError [BitFieldInvalid]: Invalid bitfield flag or number: SEND_MESSAGES.
vague monolith
#

Hello guys. I am new to bot development and I've seen that there are multiple libraries and frameworks, I've been using discord.py Discord.Client but it is being difficult to integrate slash commands, maybe it would be better to use the interactions framework?

vague monolith
#

I'm saying that what library is better: Discord.client or interactions.client.

lyric mountain
#

neither are libraries, they're modules of d.py

earnest phoenix
lyric mountain
#

the difficulty will be arguably the same as you'll be using interaction events

earnest phoenix
#

No need to get an additional library whatsoever

lyric mountain
#

just make a decent command structure (d.py has a command manager iirc) and call them inside a single event handler

earnest phoenix
#

No need to have an event handler at all

lyric mountain
#

d.py does it all automatically?

earnest phoenix
#

correct

lyric mountain
#

damn

earnest phoenix
#
@app_commands.command(name="monke")
async def monke(self, interaction: discord.Interaction) -> None:
  await interaction.response.send_message("yes")
#

All you need

vague monolith
#

ok thank you!

nocturne dagger
#

Is there a easy way to prevent a bot from tagging users as <@id> instead of their name

lyric mountain
#

wdym?

nocturne dagger
#

Like @daring fjord

#

Instead of actually tagging the user, its in discord.js

#

I have it as a string <@${id}>

#

But sometimes it doesn't actually tag the user.

lyric mountain
#

is id a string or a number?

nocturne dagger
#

string

#

I think its a cache issue because if I mention the user and then redo the command it works fine

lyric mountain
#

likely discord issue then

#

ik

nocturne dagger
#

No way to have the bot pull from cache?

lyric mountain
#

it's not the bot that pings, it's discord itself

nocturne dagger
#

Okay, thanks for the info.

north cairn
#
const { SlashCommandBuilder } = require("@discordjs/builders");
const { MessageActionRow, MessageButton, MessageComponent, MessageEmbed } = require("discord.js")
let x = Math.floor((Math.random() * 6) + 1);
module.exports = {
  data: new SlashCommandBuilder()
.setName( "bat")
  .setDescription("bat a random bowl"),
 async execute (client, interaction)  {
  const row = new MessageActionRow()
  .addComponents(
  new MessageButton()
  .setStyle("PRIMARY")
    .setCustomId("coverdrive")
  .setLabel (" Drive "),
   
  new MessageButton()
  .setStyle("SECONDARY")
    .setCustomId("defend")
  .setLabel ("Defend  "),
    

  new MessageButton()
  .setStyle("DANGER")
    .setCustomId("loft")
  .setLabel ("Loft  "),
    )
    
    return interaction.reply({ content: `An Inswing Delivery Is Coming.<@${interaction.user.id}>`, components: [row] }); 
   client.on("interactionCreate", async (ButtonInteraction) => {
     if(ButtonInteraction.isButton()) return
     if(ButtonInteraction.customId === "loft") {
       await ButtonInteraction.reply({content : `${x}`})
     }
   })
     
  
 }
}```
it sends message (inswing delivery) but when i am pressing buton,it isn't replying 
can u say like how do i make button reply
deft wolf
#

With interaction collector

#

Yes, you can, but the minus or plus is that such a button will always work. The one from the collector for a limited time only

quartz kindle
north cairn
quartz kindle
#

if you already have an interactionCreate file, then you already have a client.on for that file

#

so remove the client.on part

#

do you have a command handler?

#

or is the code you showed your interactionCreate file?

thorn spruce
# lyric mountain gl

Update :( It doesn't fix the problem tbh i'm going to just handle them as random error

thorn spruce
#

i just remove defer from the filter and put it after the collector on

#
            const collector = right.createMessageComponentCollector({ filter: (i) => i.user.id === this.author, time: 250000});
            collector.on('collect', async r  => {
                await r.deferUpdate(),
                this.message = r;
                await this[r.values[0]]();
            })
#

Oh wait maybe i just remind myself somethings do you think it could come from that?

    static async send(event:any, msgTypeInteraction:any, msgTypeMessage:any):Promise<any> {
        msgTypeInteraction["fetchReply"] = true
        msgTypeMessage["fetchReply"] = true
        return event.type == 2 ? await event.editReply(msgTypeMessage) : event.type == 3 ? await event.editReply(msgTypeInteraction)  : event.channel.send(msgTypeMessage)
    }

I'm doing this weird things to not have two time the same code for Interaction and Message event

#

Yeah iknow too i should drop the message support

lyric mountain
#

idk how interaction collector works, does it automatically defer if an invalid click is done?

thorn spruce
#

Wdym by invalid click

lyric mountain
#

for example, if someone that's not the author clicks on the button

thorn spruce
#

Tbh i dont think i'll try

#

With the filter it send nothing

copper lion
peak drum
#

i got it working you want an example?

thorn spruce
#

me?

thorn spruce
peak drum
#

yes you KEKMEGAROLL

#
 const filter = (interaction) =>
              interaction.user.id === interaction.user.id;
            const collector = interaction.channel.createMessageComponentCollector({
              filter,
              time: ms("30s")
            });

collector.on("collect", (interaction) => {
(interaction.customId == "customId") {

//do stuff
}

});
collector.on("end", (collected) => {
              interaction.editReply({ components: [] });
            //  console.log(`Collected ${collected.size} interactions.`);
              return;
            });``` this is the code i use
thorn spruce
#

let's go bro show me xD

#

ahh i understand

#

but it is because you can only do it one time

#

mine can be press more than one

peak drum
#

you can change it to this hang on

hasty rampart
#

Hi who knows any free ai generation api for discord.js bot?

peak drum
#

now it will fire everytime the user clicks on the button for 30s

peak drum
peak drum
thorn spruce
#

in fact

#

I was almost doing the same thing?

            const collector = e.createMessageComponentCollector({ filter:  (i:any)  => i.user.id == this.author, max:1, time: 300000 });
            collector.on('collect', async r  => {
                await r.deferUpdate();
                const NotificationIn = new NotificationReminder(this.playerLang, this.author);
                switch(r.customId) {
                    case "hourlyNotification":
                        NotificationIn.buildHourlyNotification(currentDate)
                        NotificationIn.bulkAddNotification();
                        r.followUp({
                            content:this.langWriter.writer("notification.remindAdded"),
                            ephemeral:true
                        })
                        collector.stop();
                    break;
                }
            })
#

no?

#

Do you think say channel change somethings?

#

like event.channel.createMessageComponentCollector

peak drum
#

well in my example it listens for every button click in said channel

#

may i ask what the customId is you're listening for

#

because if you do it like this js if (r.customId == "<your customId>") {} maybe it'll work

#

what do you want to know xD i made a play command that can play and search a song on youtube xD

hasty rampart
peak drum
#
proven lantern
#

is there any way to see which permissions are set for my bot in someone's server? do i need to find my bot's role on a server and then look at the permissions of that role?

pale vessel
#

if you use slash commands it's just app_permissions property in the payload

proven lantern
#

so how do i figure out what this is?
app_permissions: '112150186033143'

pale vessel
#

deserialize it

#

or use bitwise and operator

proven lantern
#

this is the error im getting from this server. u will look at how to do that now

pale vessel
#

what's this

proven lantern
#

a Create Guild Channel api call that is failing on a server with app_permissions: '112150186033143'

#

MANAGE_CHANNELS and possible MANAGE_ROLES is needed

pale vessel
#

I know the code says 403 but the error says bad request

#

could it be the data is invalid?

proven lantern
#
{
   "name":"Shared Voice Channel",
   "type":2,
   "parent_id":"946027446073966645",
   "permission_overwrites":[
      {
         "id":"782212633255870466",
         "type":0,
         "deny":"3146752"
      },
      {
         "id":"1081014782435537009",
         "type":1,
         "allow":"3146768"
      },
      {
         "id":"782211758315012128",
         "type":1,
         "allow":"3146752"
      },
      {
         "id":"219390252064702464",
         "type":1,
         "allow":"3146752"
      }
   ]
}
#

i think discord gives 403 errors when it doesn't have perms

#

perhaps

pale vessel
#

could be

#

now that I think of it, newer discord API versions should provide an error with a specific field if there's anything wrong with any

#

so it could be permissions

proven lantern
pale vessel
#

how are you sending the request?

proven lantern
#

post request using my bot token for authorization

proven lantern
# proven lantern

left side is app permissions. right side is manage roles permission. does this mean the app has manage roles permission?

#

16 is manage channels permission

proven lantern
pale vessel
#

no, permission hierarchy is only for managing members

#

you figure that out, I'm sleeping Bedge

proven lantern
#

the permission_overwrites are trying to create the channel with these permission given to some members and denied for the everyone role
CONNECT, VIEW_CHANNELS, SPEAK
It also give the bot MANAGE_CHANNELS permission in addition to the other 3.

#

i think i need to give my bot CONNECT and SPEAK perms so it can make a channel with those perms

pale vessel
#

ahhh

proven lantern
#

it works on my server just fine, but not other peoples servers

#

so idk how to verify

#

but we will see

pale vessel
#

make sure your bot has those permissions before creating the channel with the overwrites?

proven lantern
#

i'll ask them to test it out with those perms to see if works

#

actually i can test the app_perms thingy

pale vessel
#

you can test it yourself too

proven lantern
#

it has perms!

#

idk

#

i think discord made a mistake

lyric mountain
#

dont use numbers

proven lantern
#

i like numbers

lyric mountain
#

but js doesn't

proven lantern
#

true

pale vessel
#

try bigint

proven lantern
#

how about this?

pale vessel
#

add n after all three numbers

proven lantern
#

is it hex?

pale vessel
#

112150186033143n & 3146768n === 3146768n

proven lantern
#

they are all still true

pale vessel
#

yea since the number doesn't overflow

#

I dunno what the issue is

#

maybe don't use axios /s

proven lantern
#

that will fix it

#

i already use a wrapper function so i'd just need to update one file to get ride of axios

proven lantern
#

946027446073966645 is the parent channel and my bot doesn't have access to that channel. that's probably the issue

#
{
   "name":"Shared Voice Channel",
   "type":2,
   "parent_id":"946027446073966645",
   "permission_overwrites":[...]
}```
hushed robin
#

guys

#

can i use emojis in select menu

#

options

#

custom emojis

#

dead development

hazy raptor
#

!setwelcome title

hushed robin
hushed robin
#

why don't this work

wheat mesa
#

shows random code snippet with no context whatsoever
“why doesn’t this work”
gives no information on what doesn’t work about it

hushed robin
#

discord keep doing this error

wheat mesa
#

Something is too long

#

Read the error

hushed robin
#

nothing is long

#

why does this return empty array

#

this is so rigged

wheat mesa
#

Man almost as if we have no info on what any of that is 🤪🤪

hushed robin
#

it's a component

wheat mesa
#

Well yeah, but the other 15 variables in there

hushed robin
#

when i click Request the code above should enable offer and disable request

wheat mesa
#

I’m not going to bother anyways

hushed robin
#

bruh

wheat mesa
#

✌️

hushed robin
#

someone else help pls

wheat mesa
#

Was just trying to get some more info for the future people trying to help

hushed robin
#

why is development dead

hushed robin
#

nvm i fixed it myself

pale vessel
#

save this to your favorites, you'll need it whenever somebody mentions discord.js

topaz terrace
#

why is it showing appeal-server:undefined even tho on the help menu it shows the command?

#

logged client.slashId in interactionCreate of the help menu

#

it showed the slash ids

#

but when i logged client in the imports

#

it showed nothing.

#

prob when the imports was registered

#

slash register havent runned yet

supple quail
#

yo rarely use this but

#

which one of you yahoos knows about sharding

#

i need help with it LOL

#

i launched it but i need more info i guess, so how does it work and would i need to rewrite my entire file structure to utilize it? I currently use a command handler so not sure if id need to change that to make sharding work

#

also, can i still use like interaction.reply or would i need to use something else

#

discord.js btw

#

tbh i just learn better being taught things but the docs are so confusing 😭

sharp geyser
#

Essentially all sharding does is "split" the bot into multiple processes so it can handle processing server information more effectively. You can do a thing called auto sharding which will automatically spawn shards as it needs or tell it how many shards it needs. With DJS I think the recommended is 1 shard per 2500 servers. The thing with sharding is that not every shard will have access to every guild your bot is in as it will only have access to the guilds the shard manages so you will have to fetch all guilds if you ever need to do that. (there might be a better way I don't really remember off the top of my head).

#

Really the major thing to look out for is guilds and members when sharding as I said, each shard only covers so many guilds and has no access to other guilds in other shards right off the bat.

earnest phoenix
#

Doesn't matter what djs believes is the right amount of guilds per shards

#

It's discord telling you how many you should use

sharp geyser
#

Indeed

#

Some people dont listen though

#

unless they use auto which uses the recommended shards from discord

earnest phoenix
#

Would definitely use autosharding tbh

sharp geyser
#

but was it not every 2500 shards a shard should be spawned?

#

Back when discordjs didn't have auto sharding

earnest phoenix
#

Yeah that's the max guilds per shard

#

Though it's recommend ~1 - 1.5k per shard

wheat mesa
#

(sometimes even less if you're running a processing intensive bot like a music bot)

sharp geyser
#

Ima spawn a shard for my bot in 5 servers

earnest phoenix
#

Well you have one my default either way

#

What I hate about discord is that they're inconsistent, sometimes their retry_after is in milliseconds and sometimes in seconds krThisIsFine

sharp geyser
#

not anything new

#

discord always be inconsistent

earnest phoenix
#

Just annoying because then you may end up waiting for nothing

echo summit
#

does anyone know how to work with 2 mongodb databases in 1 project?

peak drum
#

Use 2 connections

echo summit
#

i got that, my main issue is the models

torn robin
#

does editing my bot's page before verification effect it's place in the queue at all?

rustic nova
#

No

torn robin
#

cool thanks

north cairn
#

hey i am trying to make buttons reply,but they aren't replying.can someone help me?

const { SlashCommandBuilder } = require("@discordjs/builders");
const { MessageActionRow, MessageButton, MessageComponent, MessageEmbed } = require("discord.js")
let x = Math.floor((Math.random() * 6) + 1);
module.exports = {
  data: new SlashCommandBuilder()
.setName( "bat")
  .setDescription("bat a random bowl"),
 async execute (client, interaction)  {
  const row = new MessageActionRow()
  .addComponents(
  new MessageButton()
  .setStyle("PRIMARY")
    .setCustomId("coverdrive")
  .setLabel (" Drive "),
   
  new MessageButton()
  .setStyle("SECONDARY")
    .setCustomId("defend")
  .setLabel ("Defend  "),
    

  new MessageButton()
  .setStyle("DANGER")
    .setCustomId("loft")
  .setLabel ("Loft  "),
    )
    
    return interaction.reply({ content: `An Inswing Delivery Is Coming.<@${interaction.user.id}>`, components: [row] }); 
   client.on("interactionCreate", async (ButtonInteraction) => {
     if(ButtonInteraction.isButton()) return
     if(ButtonInteraction.customId === "loft") {
       await ButtonInteraction.reply({content : `${x}`})
     }
   })
     
  
 }
}```
peak drum
north cairn
#

i made slashCommand in a bot,the problem is only owner is able to use it

#

idk how

#

nothing error in code

viral mason
#

whats the code

north cairn
#

application.command is on

#
const { SlashCommandBuilder } = require("@discordjs/builders");
module.exports = {
    data: new SlashCommandBuilder()
        .setName('ping')
        .setDescription('Shows latency/ms from the B0T'),
    async execute(client,interaction) {
  await  interaction.reply({content: `**The bot ms = ${client.ws.ping}ms**`})
  }
}```
#

only the owner is able to use it

viral mason
north cairn
#

not others

deft wolf
#

The problem is probably in the command handler

north cairn
#

what could be the possible reason behind this

#

giving

#

dc is lagging or what today

deft wolf
#

No

north cairn
#
const { readdirSync } = require("fs");

const Discord = require("discord.js")

const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { token } = process.env.token;


const ascii = require("ascii-table");
const client = require("discord.js");
const { clientId }  =  process.env['applicationid'];
let table = new ascii("SlashCommands");
table.setHeading("SlashCommand Name", "Loaded Status");
const slashCommands = []



module.exports = (client) => { 
   
  
  readdirSync("./slashCommands/").forEach(dir => { 
    const commands = readdirSync(`./slashCommands/${dir}/`).filter((file) =>
      file.endsWith(".js")
    );
    for (const file of commands) {
      const pull = require(`../slashCommands/${dir}/${file}`);
      slashCommands.push(pull.data.toJSON());
         if (pull.data.name) {
        client.slashCommands.set(pull.data.name, pull)
        table.addRow(pull.data.name, "✅");
      } else {
        table.addRow(
          pull.data.name,
          `❌`
        );
       
      } 
    }
  
  console.log(table.toString());
  });
  client.on('ready', async () => {
  const rest = new REST({ version: '9' }).setToken(process.env.token);

 
    
try {
        console.log('Started refreshing application (/) commands.')
        await rest.put(
            Routes.applicationCommands(process.env.applicationid),
            { body:slashCommands },
    );
  
    console.log('Successfully reloaded application (/) commands.')
  } catch(error) {
    console.log(error) 
}
 });
  }```
viral mason
#

How does this code help?

deft wolf
#

This is where you register commands. We are interested in where you receive them

north cairn
#

what is the point of receiving when u cant run

#
const {MessageEmbed, Collection } =  require("discord.js");
const { readdirSync } = require("fs");
const Discord = require("discord.js")
const client = require("../../index")
const fetch = require("node-fetch");

 



client.on("interactionCreate", async interaction => {
  const { commandName } = interaction;
    if (!interaction.isCommand()) return;
  
    const slashCommand = 
    client.slashCommands.get(interaction.commandName);
  const slash =  client.slashCommands.get(slashCommand)
  

        try {
await slashCommand.execute(client, interaction);
} catch(err) {
            console.log(err)
await interaction.reply({content: "An Error Occured!", ephemeral: true})
        }
    ```
#

here

viral mason
deft wolf
#

Not at all

viral mason
#

Rip

north cairn
#

what else do i show now

#

i showed u interactionCreate,showed u handler,showed u command

viral mason
north cairn
#

and they never did like this

#

that owner can only access

#

so its strange for me

deft wolf
#

There is absolutely nothing in any of these codes that would limit the use of the command to only one specific user

viral mason
#

💀

north cairn
#

ah

#

guys

#

i posted index.js file

#

and it says

#

content blocked content...

#

contains*

viral mason
#

show full code + traceback

north cairn
earnest phoenix
#

where the traceback tells you the error comes from duh

viral mason
deft wolf
#

I'm wondering in what sense "command can only be used by the owner". If there is nothing in the code itself, it is possible that it is set in the interaction tab. Of course, it depends on how you checked whether someone else can use it

viral mason
#

My bot is having a meltdown

lavish ibex
#

how to add images to top.gg description

deft wolf
#

Use html or markdown

lavish ibex
#

ty

#

can you send me a link to convert image to html url?

earnest phoenix
#

Host your image somewhere, e.g. imgur, and use that link

deft wolf
#

You can even host them on discord and use the discord attachment url

#

But yes, imgur is a safer option

winter pasture
winter pasture
viral mason
viral mason
lavish ibex
earnest phoenix
#

Right click

#

Open image url

deft wolf
#

^

earnest phoenix
#

or copy link or whatever it's named

slender wagon
#

whats the best lib for telegram bots in nodejs

deft wolf
#

Telegraf?

slender wagon
#

if you guys have experience with telegram bots

pale vessel
#

telegram.js

#

I made that up but it's probably real

slender wagon
#

this seems like the top option

deft wolf
#

It's very popular and the documentation is pretty clear too

lavish ibex
deft wolf
#

No

earnest phoenix
#

Right click an image

lavish ibex
#

oh ty

#

i cant see copy link

deft wolf
#

Click on image

#

Not message

lavish ibex
deft wolf
#

Yea, copy image adress

nocturne dagger
#

Anyone know why a bot may not be getting the guildMemberAdd event

#

for (const file of eventFiles) {
    const event = require(`./events/${file}`);
    if (event.once) {
        client.once(event.name, (...args: any) =>
            event.execute(...args, client, prisma)
        );
    } else {
        client.on(event.name, (...args: any) => {
            console.log(event.name), event.execute(...args, client, prisma);
        });
    }
}
earnest phoenix
#

it doesn't have the intent

nocturne dagger
pale vessel
#

: any GIGACHAD ts dev

nocturne dagger
pale vessel
#

isn't that like the only way anyway

nocturne dagger
#

It is actually any because idk what it is

#

yea

winter pasture
nocturne dagger
#

All 3 enabled yea

winter pasture
#

Are any other events triggering?

nocturne dagger
#

It logs events like interactionCreate

#

and messageCreate

lavish ibex
#

image is not coming

#

💀

lyric mountain
#

ur bot is not yet approved

nocturne dagger
lyric mountain
#

so the page is not public

lavish ibex
#

see

#

images are not coming 💀

lyric mountain
#

u need to use either markdown or html

#

not simply put the link there

#

also, don't use discord as an image host

#

if the messages are ever deleted, you'll lose the images

lavish ibex
#

but should i convert this link to html?

#

or markdown?

pale vessel
#

markdown is easier ![alt text](link)

winter pasture
# nocturne dagger

Try toggeling it on and off in discord.dev? Maybe its out of sync or something

lyric mountain
#

markdown is simpler, html allows more styling freedom

#

so it boils down to what u need

nocturne dagger
winter pasture
#

Could it be because it’s a partial?

#

See if it’s logging then

nocturne dagger
#

Figured it out

#

I have and international keyboard which makes one of the characters is guildMemberAdd not the english one

#

but it looks identical

winter pasture
#

Happy you figured it out in the end lol

lyric mountain
#

does it happen to be cyrilic keyboard? KEKW

#

idk why ascii has an exact replica of the english alphabet instead of simply using a single table

winter pasture
#

VSCode Contextual Unicode highlighting saves me every so often xD

earnest phoenix
#
cönsolę.løg("Hēllº wõrld!")
lavish ibex
pale vessel
#

did you forget the exclamation mark

north cairn
# viral mason ^
const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('YOU REALLY THINK THAT THERE WILL BE A WEBSITE HAA LOL. \n Please let me know in my DevelopingWorld Discord Server if you want the bot public! \n Discord invite: ')
});

app.listen(3000, () => {
 console.log("Well done soldier, your project is now running!");
});

const Discord = require('discord.js');
const client = new Discord.Client({intents: [
  "GUILDS", 
"GUILD_MEMBERS", 
"GUILD_INTEGRATIONS" , 
"GUILD_BANS" ,
"GUILD_EMOJIS_AND_STICKERS", 
  "GUILD_MESSAGES" , 
  "GUILD_INVITES" ,
  "GUILD_PRESENCES" ,
  "GUILD_MESSAGE_REACTIONS" ,
  "DIRECT_MESSAGES" ,
  "DIRECT_MESSAGE_TYPING" ,
  "DIRECT_MESSAGE_REACTIONS" , 
  
], allowedMentions: ["users"]
 });
client.commands = new Discord.Collection();

client.aliases = new Discord.Collection();
client.events = new Discord.Collection();
client.slashCommands = new Discord.Collection();
client.config = require("./config.json");



module.exports = client;

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

client.once("ready", async () => {
  console.log(`[READY] ${client.user.tag} has logged in.`);
  const servers = await client.guilds.cache.size
  const servercount = await client.guilds.cache.reduce((a,b) => a+b.memberCount, 0)
  let activities = [
    `| In ${servers} servers`,
    `| ${servercount} members`
  ]
  
  setInterval(() => {
    const presence = activities[Math.floor(Math.random()*activities.length)]
    client.user.setPresence({ activities:[{name: `${presence}`, type: `WATCHING`}]})
  }, 2500)
})

 client.login(process.env.token);
#

there

lyric mountain
#

for images it's <image>

lavish ibex
#

lol ty :)

#

i literally forgot everything

north cairn
#

ok nvm i got it thanks

lyric mountain
#

holy that endpoint message is cringe

earnest phoenix
#

much

lavish ibex
#

Hello

#

How many days for getting my bot verified by top.gg ?

lyric mountain
#

around a couple weeks

lavish ibex
#

Omg

#

I remember making a bot 2 yr ago it just took nearly a week or 3 days ig

earnest phoenix
#

As you said, 2 years ago

opaque acorn
#
Z:\\\\\node_modules\discord.js\src\client\actions\MessageCreate.js:13
      const message = channel.messages.add(data);
                                       ^

TypeError: Cannot read properties of undefined (reading 'add')
earnest phoenix
#

channel.messages is undefined

opaque acorn
earnest phoenix
#

Doesn't matter what it represents, it's undefined

peak drum
#

If you could provide a little more of your code someone might be able to help you

lyric mountain
#

I'm fairly sure messages need to be fetched

peak drum
#

If the bot has permissions to use the messageCreate event it doesn’t

lyric mountain
#

even then you'd access it through the cache

slender wagon
#

I will be integrating crypto payments in one of my nodejs projects does anyone have an idea how it works exactly?

grim aspen
#

idk if that's against TOS

#

sounds risky

#

it's kind of almost being on the line's edge/crossing the line

peak drum
#

Tos of what?

grim aspen
#

discord

slender wagon
#

How is crypto against the TOS

#

Or are you talking to the other person

peak drum
#

^

grim aspen
#

but still sounds risky

wheat mesa
#

That has absolutely nothing to do with what he asked

#

He never said a bot

grim aspen
#

oh

#

small brain moment

lyric mountain
#

@wheat mesa I think now I understand better why people bash at java (dealing with an "enterprise library" - not a binary, but a source code I need to copypaste into a folder)

#

boi can people write ugly code

rustic nova
#

tbf

#

depends on code age

grim aspen
#

^

rustic nova
#

because newer java code is likely better maintained from the beginning

lyric mountain
#

it was written in 2022

rustic nova
#

ok I take that back

lyric mountain
#

it's a flutter -> android compatibility layer for a tablet-like terminal I'm developing a software for

#

like, if it was legacy code I'd understand but damn

#

a lot of the code is if-else-if-else-if-else-if-else-if-else-if-else

wheat mesa
#

Yeah there’s some valid reasons to bash java

lyric mountain
#

like, there were better ways to do the same thing, like switch-case or just using model classes

#

the whole thing is a Map (no, not even Map<String, Object>) being juggled around

wheat mesa
#

Lmfao

#

And I thought my code was bad 😭

lyric mountain
#

nah ur code is preem

#

much better than most professional code I've seen

grim aspen
# slender wagon I will be integrating crypto payments in one of my nodejs projects does anyone h...

now that i can understand it properly. basically like people would already know, using a crypto payment system would involve payment monitoring an using an API

  1. there are many payment processors such as bitcoin, bitpay, coinbase commerce, etc. i suggest choosing only one.
  2. using that processor, create an account to obtain the proper credentials to use.
  3. Configure project using the API.
  4. create a payment system using the API
  5. Monitor the payments
  6. of course if it's successful, you need to make sure to update the account using the information from the step above
    since it's a complicated process i'd recommend also using the documentation provided
slender wagon
#

Okay, i will try and find a platform that supports most of the cryptos

grim aspen
#

also one thing to note: make sure the whole process is secure, any breaches, hacks, need to be solved asap or the whole business will be destroyed

lyric mountain
#

odds of someone donating (i suppose) are already low enough, crypto even less

wheat mesa
#

Yeah if you’re looking for donations I’d just use like buymeacoffee

#

Probably much easier

grim aspen
#

oh yeah value of crypto currencies are currently low

#

idk if patreon would be a good idea

lyric mountain
#

not after you peek at their api

peak drum
slender wagon
lyric mountain
#

ah

slender wagon
lyric mountain
#

likely regional issue

slender wagon
#

Yup i was about to say that

hushed robin
#

how can i turn a map into an array easily

#

right now i'm doing this but takes so long to type 💔

const items = Array.from(itemCache, (item => { return { name: item[1].name, emoji: item[1].emoji }}));
neon leaf
#

I mean, you could do

const items = Array.from(itemCache, item => ({ name: item[1].name, emoji: item[1].emoji }) );

would be slightly smaller

#

but I dont really understand what exactly you want to do? like you cant just magically turn a map / object into an array, like do you want it to be an array of keys? a 2d array with key-value? ...

hushed robin
#

to become an array

#

so i can loop through it

neon leaf
#

you should probably show an example because there are many ways of turning objects into maps and all do different stuff

#

your code that you sent doesnt really make sense

hushed robin
neon leaf
#

I mean im kinda tired rn but that looks like its just assigning elements to a static value, aka it probably doesnt do what its intended to

hushed robin
#

what

neon leaf
#

ah no

#

what exactly is item cache?

hushed robin
#

cache of items

neon leaf
boreal iron
#

Just loop over your map and assign the items to your array

#

Take the map size as loop maximum

neon leaf
#

if its an actual Map instance you could just do

for (const [key, value] of Map.entries()) {
  console.log(key, value)
}```
#

for a normal object it would be

for (const [key, value] of Object.entries(object)) {
  console.log(key, value)
}```
hushed robin
#

literally the first thing i said

neon leaf
#

so its an actual map instance (new Map())? then just do what I said above to loop over or keep using your version

hushed robin
hushed robin
#

how can i do it for less writing

neon leaf
#

cant really, you could make a function that takes care of it

hushed robin
#

l javascript

lyric mountain
#

worthy to note maps dont keep order

hushed robin
#

is that important

neon leaf
#

depends on what you use the map / array for, probably not

grim aspen
#

^

hushed robin
#

why does this not work

#

oh wait

#

nvm

#

i'm stupid

neon leaf
#

you can also just do
offer.get(item).amount = 1
afaik even though it looks weird

quartz kindle
#

objects dont

lyric mountain
#

huh? for me it was always the opposite

#

objects always kept their keys in the correct order

quartz kindle
#

maps are ordered by insertion

#

objects are unordered, but most implementations use some form of ordering these days

hushed robin
quartz kindle
#

for example symbols first, then keys in alphabetic order and what not

hushed robin
#

the bot is functional now

quartz kindle
#

The iteration order for objects follows a certain set of rules since ES2015, but it does not (always) follow the insertion order. Simply put, the iteration order is a combination of the insertion order for strings keys, and ascending order for number-like keys:

lyric mountain
#

aight, now it kept the order on both

quartz kindle
#

The keys in Map are ordered while keys added to object are not. Thus, when iterating over it, a Map object returns keys in order of insertion. (Note that in the ECMAScript 2015 spec objects do preserve creation order for string and Symbol keys, so traversal of an object with ie only string keys would yield keys in order of insertion)

hushed robin
#

why dis happening

#

offer should be disabled but it's enabled somehow scream

#

(on the second embed)

hushed robin
#

does anyone know

#

i'm very stumped on this

#

this is the code for the components

#

idk how offer is enabled and request is disabled

#

makes no sense

lament rock
#

The library probably assumes that in the presence of explicit enabled calls, the others without explicit calls should be inferred as disabled

grim aspen
#

they're saying it might be turned off by default by the library itself

grim aspen
#

simplified like explaining to a 5 year old: imagine if you asked for asked for a toy, and your toy box could understand what you want. if you asked for specific toys, the other toys you didn't ask for won't appear

hushed robin
#

thats a much worse explanation

#

i understand what your saying but it makes no sense

hushed robin
#

it works on the first embed

#

buttons are correct

#

but on second one it doesn't

grim aspen
#

bro i swear i'm going to dim it down to an explanation for a toddler

hushed robin
#

are you slow

#

i just said i understood what you said

#

someone help

#

pls

#

😭

grim aspen
#

just remove the setdisabled

hushed robin
#

???

#

why would i remove the disable

#

how is offer enabled and request disabled

grim aspen
#

are you sure it's not the third one

lament rock
#

because you don't explicitly set it as enabled

hushed robin
#

why would i need to?

lament rock
hushed robin
#

i explicitly set offer as disabled and it's not disabled

#

i don't think it has anything to do with that

grim aspen
#

because by default it doesn't have to be added

#

it will already be disabled

#

LIKE I SAID EARLIER

hushed robin
#

what?

hushed robin
#

in discord.js if you don't specify .setDisabled it will set it as enabled

rustic nova
#

why not just

#

try it and see

hushed robin
#

cus

rustic nova
#

try it and see

hushed robin
#

try what and see

rustic nova
#

bru

grim aspen
#

by that second button it's already disabled like i said before

hushed robin
#

what second line

grim aspen
#

button i mean

hushed robin
#

i don't understand what you mean

rustic nova
# hushed robin

on the buttonBuilder of the request button, set this specifically as setDisabled(false) and see if that does something

#

and try if that works

hushed robin
#

ok

past nymph
#

I'm trying to apply for verification but I'm getting this

Your app is missing an invite link. Add one so users can easily add your bot to their server.

Not sure how to continue

hushed robin
grim aspen
hushed robin
past nymph
hushed robin
#

ok

#

i think i know why

deft wolf
#

Why?

hushed robin
#

ok i know issue but i don't know how to resolve

#

this code is modifying my code

#

but how can i do this without it modifying my code

rustic nova
grim aspen
#

wdym

#

how is it modifying the code? what code is being modified?

hushed robin
#

idk

hushed robin
rustic nova
#

just remove it?

hushed robin
#

no

#

i need it

#

bruh

grim aspen
#

what is the purpose of that block of code?

rustic nova
#

"i want the mode button enabled"

"no i want to keep the code that always sets the mode button disabled"

hushed robin
#

so if i click on request

neon leaf
#

so I have an array of listeners, now I often add and remove listeners dynamically, whats the most logical way of removing? It should not cause a leak in the end, currently for testing I just assign a listener to null and when executing them check if its truthy but that wont scale well, should I just slice the array or is that too slow / takes too much memory with alot of items?

hushed robin
#

it should disable request and enable offer

grim aspen
#

i don't honestly think that block of code is modifying the button

hushed robin
#

it is

#

it's modifying code

hushed robin
quartz kindle
neon leaf
#

im using a custom one

quartz kindle
#

look into what the native one does then

#

but if you have multiple events in an array, you will have to match the function you want to remove, likely using a loop or .find()

#

then you can use splice

neon leaf
#

I had the idea of just returning the index when adding one and being able to remove by index, its just an internal emitter

quartz kindle
#

thats a good idea yes

neon leaf
#

currently I have this