#development

1 messages Β· Page 1749 of 1

boreal iron
#

But as long as the client is part of the guild?

earnest phoenix
#

yeah

boreal iron
#

Even if he’s offline?

earnest phoenix
#

FFMPeg takes too long to install cuz it has too many dependencies

pale vessel
#

What do you mean by "locally"?

spare badger
#

@boreal iron It will work exactly like how a user can set its nickname in a guild. It will stay untill the user or the bot leaves the server.

#

Even when its offline

boreal iron
#

Alright

#

Thanks

earnest phoenix
spare badger
#

@earnest phoenix It's loading.

earnest phoenix
#

npm install @discordjs/opus all errorrs

spare badger
#

Try running npm install -g windows-build-tools first and then re-run the install command for @discordjs/opus

earnest phoenix
spare badger
signal estuary
#

Is there a fast way to give the user the possibility to use slash commands or normal commands with the prefix.
Because I dont want to rewrite all commands because its a lot of work:

client.on("ready", async () => {
    const creditCommand = await createCommand({
        name: "credits",
        description: "Zeigt die Credits des Botes"
    }, "808771611070038046")
});

async function createCommand(data, guildID){
    return await client.api.applications(client.user.id).guilds(guildID).commands.post({
        data: data
    })
}

client.ws.on("INTERACTION_CREATE", async (interaction) => {
    console.log(interaction)
    switch (interaction.data.name){
        case "command":
            await sendWaiting(interaction)
            await new discordjs.WebhookClient(client.user.id, interaction.token).send("outout")
            break
    }
})

function sendWaiting(interaction){
    client.api.interactions(interaction.id, interaction.token).callback.post({
        data: {
            type: 5
        }
    })
}
woeful pike
#

why are you guys installing ffmpeg through npm lmaoo

latent heron
#

ara

earnest phoenix
#

yt search done

latent heron
#

that's the investment you have to make with slash commands

earnest phoenix
#

ytdl core are done

honest garnet
#

hello

earnest phoenix
#

npm install @discordjs/opus
npm install ffmpeg-static

those 2 are the one has problems

signal estuary
earnest phoenix
spare badger
#

@earnest phoenix Have you tried the solution I send you for the @discordjs/opus package?

latent heron
#

i mean if its really that hard to rewrite the way commands are processed and not the actual command logic

earnest phoenix
#

yeah

latent heron
#

then don't bother looking into slash commands at all

spare badger
#

@earnest phoenix How did that work?

latent heron
#

it's not like a majority of writing code is you having to constantly modify things as you go

earnest phoenix
spare badger
#

@earnest phoenix Please start sending the entire error instead of a small part. I can't help you otherwise.

#

Okay so you are going to have to open the terminal with admin privileges and then run that command again.

vivid fulcrum
#

it literally tells you what to do

#

lol

spare badger
#

Yea it might also be smart to start reading the error messages yourself πŸ˜‚

earnest phoenix
#

ight

earnest phoenix
#

then run cmds

#

Or if on mac ios do sudo

#

and enter username password of mac then do

vivid fulcrum
#

can we get one more person to tell them to run as admin

earnest phoenix
#

LMAO

solemn latch
#

run as admin /s

weary crypt
#

Make sure to uncompress 😎

fringe fractal
#

Hello, someone crashed my discord bot using a math command.. He or she don't want to tell me how. Is there any way to fix it? Or any package to use math commands?

earnest phoenix
earnest phoenix
#

and here's a way to crash bots that do that: /math process.exit();

solemn latch
#

dont think it was eval, probably was the math package

fringe fractal
solemn latch
#

oh heck its an eval

solemn latch
#

yeah, tons of ways to crash an eval math command. probably best not to use it.

fringe fractal
#

Hmm yes. But is there any way to use a math command without crashing my bot? If not, I'll delete the command xd

fringe fractal
#

Okay, I'll try it. Thanks for the help c:

earnest phoenix
#

||or expression.replace(/[^0123456789+-/*]/g, "")||

fringe fractal
#

uhm ok

solemn latch
#

just a heads up, there are some math packages which also are crash able.
make sure to look at the issues listed.

fringe fractal
#

hmm I think I'll delete just the command. Everyone can use google for Math xD

pale vessel
#

This

solemn latch
#

i dont think ive ever seen someone use a math command because they really needed it.

lusty quest
#

if i would use a math command, there is some fancy code execution engine api that i would use for it

#

0 risk to kill your system with a bad entry

earnest phoenix
#

Hi

lament rock
#

or just don't include arbitrary expression evaluation unless your bot is specifically dedicated to mathematics somehow

#

Don't be general purpose

#

specialize

vivid fulcrum
#

my weeb bot is going to make it amongst other 100,000 weeb bots that do the same thing!

lament rock
#

fr

earnest phoenix
#

or

function math(expr: string): number | Error {
  if (!expr) return new Error("no expression provided bruh");
  let e = [];
  expr = expr.trim();
  for (let w of expr.split(/(<=[0-9])\+(>=[0-9])/g)) {
    e.push(w);
    e = e.join("+");
  }
for (let w of expr.split(/(<=[0-9])\-(>=[0-9])/g)) {
    e.push(w);
    e = e.join("-");
  }
for (let w of expr.split(/(<=[0-9])\/(>=[0-9])/g)) {
    e.push(w);
    e = e.join("/");
  }
for (let w of expr.split(/(<=[0-9])\*(>=[0-9])/g)) {
    e.push(w);
    e = e.join("*");
  }
e = e.replace(/^[+/*-]/g, "")
     .replace(/[+/*-]$/g, "");
return eval(e);
}
#

wait you also have to remove extra symbols at the end

lament rock
#

too much iteration over the string. You can just capture the operand

umbral zealot
earnest phoenix
#

why in hell would you use a ! prefix

umbral zealot
#

It's an example, idc

woeful pike
#

when will people stop trying to parse math expressions with regex

solemn latch
#

the 1:99999999 thing is the most common crash for math commands

vivid fulcrum
lament rock
earnest phoenix
#

well in that case
function math() {
return 0;
}

pale vessel
#

That's what I use for my bot's command

lament rock
#

I bet people love it when people crash the api

umbral zealot
#

I bet they blocked out that particular flaw in their own API

pale vessel
#

Ahahaha

#

They didn't

lament rock
#

lol its on heroku

pale vessel
#

But that's better than crashing your own bot

earnest phoenix
#

ahahahhahah

umbral zealot
#

wow

solemn latch
earnest phoenix
#

more expensive than a better vps

umbral zealot
#

so if someone were to make a system that just keep pinging that endpoint...

#

Β―_(ツ)_/Β―

solemn latch
earnest phoenix
#

wait can jsfuck crash them

#

bruh it cant

lusty quest
#

this is why using a code execution engine works.

earnest phoenix
#

i think google has a math api

pale vessel
#

Piston bae

#

That's their official bot, right?

lusty quest
#

ye

#

you cant really kill the bot

#

even a fork bomb wont work

lament rock
#

fill an array then fork

earnest phoenix
#

whats a fork

lusty quest
#

if the process takes longer than 5 seconds it sends a kill signal to the Container running the code

#

if the code tries to delete the container it stops the container

lament rock
#

forking the process is to create an identical instance of the process

lusty quest
#

will get a kill signal

#

they had smart people trying to get the service down, but it is quite robust now

lament rock
#

cool

boreal quest
#

Does anyone have experience in discord.js unit testing and could help me with some references or something to get started with optimizing code.

lavish bramble
#

Can anyone suggest me best anime reaction gifs api

#

For free

lament rock
long crow
#

For the math, slash command option is not a bad idea. Though only integer options can be used

pale vessel
#

I wouldn't recommend it

#

There's always going to be vulnerabilities

#

Of course, if you use eval

#

I assume you don't, like a sane person would

long crow
#
const { SlashCommand, CommandOptionType } = require('slash-create');
const c = [{name:'add',value:'addition'},{name:'sub',value:'subtract'},{name:'multiply',value:'multiplication'},{name:'div',value:'division'}];

module.exports = class Math extends SlashCommand {
  constructor(creator) {
    super(creator, {
      name: 'math',
      description: 'Do some math function',
      throttling: {duration:5,usages:1},
      options: [
        {
          type: CommandOptionType.STRING,
          name: 'op',
          description: 'What operand of math you using',
          choices:c
        },
        {
          type: CommandOptionType.INTEGER,
          name: 'x',
          description: 'x quantity'
        },
        {
          type: CommandOptionType.INTEGER,
          name: 'y',
          description: 'y quantity'
        }
      ]
    });

    // Not required initially, but required for reloading with a fresh file.
    this.filePath = __filename;
  }

  async run(ctx) {
    try {
      if (ctx.options.op =="addition") {
        ctx.send(`${(ctx.options.x + ctx.options.y).toLocaleString('en-US')}`);
      }

      else if (ctx.options.op == "subtract") {
        ctx.send(`${(ctx.options.x - ctx.options.y).toLocaleString('en-US')}`);
      }

      else if (ctx.options.op == "multiplication") {
        ctx.send(`${(ctx.options.x * ctx.options.y).toLocaleString('en-US')}`);
      }

      else if (ctx.options.op == "division") {
        ctx.send(`${(ctx.options.x / ctx.options.y).toLocaleString('en-US')}`);
      }
    } 
    catch (err) {ctx.send('There is an error running the command');}
  }

};``` Well, yeah no eval involved
lament rock
#

The problem with that is that it doesn't allow complex statements to be made

#

but it is safe

lavish bramble
lament rock
#

but it's really good

pale vessel
#

1k guilds or above only by the way

snow urchin
warped ravine
#

When I Try To Start My Bot Gets An Error Like This

earnest phoenix
vivid fulcrum
#

update to djs v12

warped ravine
vivid fulcrum
#

They're Telling You To Stop Typing Like This

warped ravine
vivid fulcrum
#

nah it's just annoying when people type like that

earnest phoenix
#

ok so it's another indian

lavish bramble
earnest phoenix
#

@warped ravine apna discordjs ko v12 me update karo: npm i discord.js@^12

warped ravine
earnest phoenix
warped ravine
#

@earnest phoenix How do I migrate to discord.js v12

snow urchin
#

npm i discord.js@^12

warped ravine
#

Thanks

#

I really thank you all

#

gave a very long error

marble juniper
#

client.emojis.get doesn't work

marble juniper
#

you have to use client.emojis.cache.get

marble juniper
solemn latch
#

πŸ‘€ pretty sure only a few people use TS here

earnest phoenix
#

sortof

marble juniper
#

lol

#

my bot is full typescript

lavish bramble
#

Is there is any other port then 3000

earnest phoenix
lavish bramble
#

Working

earnest phoenix
#

wdym working

#

soo i created a new bot and started from a new scratch and it was worth trying

rocky hearth
#

I'm confused how Not a Number is a number?

vivid fulcrum
#

it's really an object

latent heron
#

@drifting shell join bot dev vc

vivid fulcrum
#

but its type is a number

#

because the value (NaN) can only derive from numbers

#

i.e. 0/0

pale vessel
#

Zero Division error

drifting shell
latent heron
#

now

near stratus
#

Sorry I went offline.
You can do ipconfig in windows and
ifconfig on Mac and Linux

quiet pawn
#

lit vc

snow urchin
latent heron
#

@drifting shell undeafen

earnest phoenix
#

is this good?

earnest phoenix
#

are you using nextjs

#

if so then pages is the cwd

#

Try ../src/stuff

tired panther
#

How can you remove a undefined value from a array without looping through?

snow urchin
#

first one, 2 dots as you suggested
second one, 1 dot
@earnest phoenix

earnest phoenix
#

I cant find the src directory

snow urchin
rocky hearth
#

in ts I have a variable const VAL = 10, How do I make a type from it like,
type Val = -10 | 10

rocky hearth
#

I want the type to be dynamic

#

I guess to use typeof VAL, but how do get the negative part?

earnest phoenix
sudden geyser
#

So VAL can either be positive or negative 10 (and no number in between)?

rocky hearth
#

Like, VAL would be a positive number.
I want to create a type from it, like
const VAL = 10;
type Sign = -10 | 10;

#

if VAL changes, Sign should also change

cinder patio
#

Val can't change cause it's const

#

and even if it could, Typescript is a static transpiler

#

there'a no such things as dynamic types. You'll have to settle with a specific number or just number

woeful pike
#

what are you trying to do exactly?

woeful pike
#

gotta get into type level arithmetic with peano numbers and shit monkaSHAKE

cinder patio
#

lol

woeful pike
#

oh actually it doesn't work because it's a negative number yeah ok

#

and it's only supported for very small numbers because of typescript's recursion limit

lament stump
#

Does anyone know how to align a block of text like this with an image? I've been trying for hours now

#

this is what i currently have

woeful pike
#

flexbox with align-items and justify-content center

cinder patio
#

Why would you need that anyways... VAL changes during runtime, typechecker can't do nothing about it

woeful pike
#

I think what he wants is to infer the type of literal values for type safety

lament stump
woeful pike
#

I use something similar for top.gg but not with numbers

lament stump
#

what

#

that is my code for that

#
            display: flex;
            align-items: center;
            justify-content: center;
        }```
vocal trellis
#

somehow my bot is insane slow idk where it is coming from! does anyone knows if there is something wrong with dc api

broken matrix
#

when my bot turns on is its status online for a few ms then goes to dnd?

olive rune
broken matrix
solemn latch
#

there has been some issues with a few vps hosts reaching cloudflare/discord

#

oh, they are setting it to dnd and you're setting it to online?

broken matrix
#

nope, their bot is on dnd

#

im making mine track its outages

olive rune
#

What language is your bot in?

broken matrix
#

js

#

theirs is py

#
client.on('presenceUpdate', (oldPresence, newPresence) => {
    let member = newPresence.member;

    if (member.id === '454323110569574422') {
        if (oldPresence !== newPresence.status) {

            let channel = member.guild.channels.cache.get('841514123547508736');
         
            if (newPresence.status === "online") {
                text = `@foggy crown is back online, The issue is resolved.`;
            } 
             if (newPresence.status === "offline") {
                text = `@foggy crown is experiancing an outage. Keep up with this bot for more information on this outage.`;
            }
            
            channel.send(text);
        }
    }
});
solemn latch
#

if your just trying to determine if the bots online, any status(online, dnd, idle) should be considered online status's.

broken matrix
#

ill brb let me ask them a question

#

wait i just answered my question

stray birch
#
          let ServerEmbed = new Discord.MessageEmbed();
          ServerEmbed.setTitle("I'm Currently in ${client.guilds.cache.size} servers);
          ServerEmbed.setDescription("Make sure to invite me to your server, My goal is to be in 100 servers!")
          message.channel.send(ServerEmbed);``` giving me an error
sudden geyser
#

well why is it

main trench
#

@stray birch why do you do ServerEmbed.setTitle?

mental raven
#
@client.command()
async def meme(ctx):
  async with ctx.typing():
      time.sleep(0.1)
      subreddit = reddit.subreddit('memes')
      top = subreddit.top(limit=100)
      sub_list = []


      for submission in top:
        sub_list.append(submission)

      subChosen = random.choice(sub_list)

      subTitle = subChosen.title
      subUrl = subChosen.url

      embedVar = discord.Embed(title=subTitle, color=0xffa300)
      embedVar.set_image(url=subUrl)
      embedVar.set_footer(text=f"Result from r/{subreddit} || By {subChosen.author} || {subChosen.score}β–² || {subChosen.num_comments}πŸ’¬")

This works but it is very very slow.. How to make it faster?

#

It's python btw

stray birch
deep mantle
slender thistle
#

Yes PRAW isn't async

mental raven
main trench
mental raven
#

idk how to use async praw

stray birch
#

i tried it didnt work

slender thistle
#

Wdym you don't know

mental raven
slender thistle
#

What's the difference that you're stuck on

mental raven
#

Isn't there a difference between praw and async praw?

slender thistle
#

Isn't it like almost the same crap but with awaited methods? 02derp

mental raven
#

where do i put them tho?

stray birch
slender thistle
#

Wdym put

#

Do you understand what methods are

mental raven
#

yeah

#

nvm

main trench
#

Guess your code is set up strange

#

Anyways what's the error you ran into?

stray birch
main trench
#

Holy those colors do not go well together

stray birch
#

im not on visual studio code lol

main trench
#

Gonna remind myself never to use repl

stray birch
#

lol

main trench
#

Unexpected token interesting

#

The only thing i can think of is to check your bots token

stray birch
#

ok

stray birch
main trench
#

I don't see any out of place "."

#

What line is the error happening on?

stray birch
#

i found the mistake now

main trench
#

Where was it?

stray birch
#

forgot to put }

main trench
#

Ah

stray birch
#

lol

main trench
#

Wow repl does not give great errors then

wheat mesa
#

@stray birch ```js
var cfPossible = ['Heads!', 'Tails!']
var cfResult = cfPossible[Math.floor(Math.random()*cfPossible.length)]
const cfembed = new Discord.MessageEmbed()
.setColor('#0099ff')
.setDescription(:coin: **You flipped a ${cfResult}**)
message.channel.send({ embed:cfembed })

This is the code that works for my embeds, try something more like this instead of doing `ServerEmbed.setTitle`
stray birch
#

wait i got a cmd error

#

the ${client.guilds.cache.size} isnt working

#

for the embed

main trench
#

What does the error say about it

stray birch
wheat mesa
#

You're not preparing the compiler for string interpolation in your string

stray birch
#

idk how serverEmbed not defined

wheat mesa
#

You have to use backticks

main trench
#

Check that it's defined

stray birch
#

ok

wheat mesa
#

ffs

#

discord is being weird

main trench
#

You trying to make a code block @wheat mesa?

wheat mesa
#

Nah, I was trying to escape backticks within a code block

#

Not sure how to do that

main trench
#

\

#

I think

wheat mesa
#

yeah, wasn't working

stray birch
#

ok now my code is working

main trench
#

Nice

sudden geyser
#

Does anyone know if there's a difference between a surname and a family name? I tried searching on Google, but all I got were answers suggesting it was for formality

pale vessel
#

πŸ€”

#

no difference?

sudden geyser
#

seems so, ty

mental raven
#

How can I turn this from PRAW to Async PRAW?

subreddit = reddit.subreddit('memes')
      top = subreddit.top(limit=100)
      sub_list = []


      for submission in top:
        sub_list.append(submission)

      subChosen = random.choice(sub_list)

      subTitle = subChosen.title
      subUrl = subChosen.url

      embedVar = discord.Embed(title=subTitle, color=0xffa300)
      embedVar.set_image(url=subUrl)
      embedVar.set_footer(text=f"Result from r/{subreddit} || By {subChosen.author} || {subChosen.score}β–² || {subChosen.num_comments}πŸ’¬")

You'll say it's easy but i am kinda new to coding and I am not that smart
so sorry if this is easy to do
Just call me stupid

#

I am just stupid

worn grove
#

I was wondering about shards. My bot isn't completely huge, but what is the benefit of shards, and what are they used for?

sudden geyser
#

You should shard when Discord requires you to.

worn grove
#

oh, alright

eager scarab
#

How can I do that, when I click the power button, a command is executed (the one I want)

#

like

#

html file: ```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Discord bot!</title>
<script src="./index.js"></script>
</head>
<body>

<button id="start">Power on</button>
<button id="off">Power off</button>

</body>
</html>

#

js file: ```js
const startsScript = document.getElementById('start')

const TEST = console.log('test works')

startsScript.addEventListener('click', TEST)

#

what I want is to execute the command node bin/index.js

#

this is the bin/index.js file: ```js
const Discord = require('discord.js');
const bot = new Discord.Client();
const token = require('./token');
bot.ready('ready', () => {
console.log('bot is connected')
});

bot.login(token)

mental raven
solemn latch
left escarp
#

Sad

sage bobcat
#

One message removed from a suspended account.

#

One message removed from a suspended account.

gray bronze
#

Does anyone know how to put a video of 1.30 min (by link) in an embed cuz i cant figure it out

pale vessel
#

you can only put images

gray bronze
#

Fuck

boreal iron
#

Can I actually remove the bot's nickname again
Which would restore it's username automatically.

vivid fulcrum
#

you should be able to just pass null

boreal iron
#

Hmm well then I need to try it I guess oldEyes

weary crypt
#

If not, I believe that the nickname is a different field(or whatever they might call it on JS) and you can just pass in their username instead

placid iron
#

@pale vessel can you share your embed to text with me please TsubameGrin

quaint wasp
#

guys

#

yall kept telling me to use github

#

now that I go on it

#

MHMMM

#

how useful is it?

placid iron
#

tf this

quaint wasp
#

I refresed it lots of times.

#

IDK

weary crypt
#

bruh huh

quaint wasp
#

there was a button with github on it and I pressed it

stiff lynx
#

Hi everyone, How can I check if the mentioned user is a bot?

#

because I did a rob command

#

And I want to avoid that people try to rob a bot

weary crypt
#

What language are you using and api?

stiff lynx
#

discord.js

#

message.author.bot this is for the message

craggy inlet
#

I've made a bot and added Slash commands and added a String option to add text but it won't show when I run the slash commandI'm using it for an 8ball command and I want it to show what you askedBut it's not working for Slash commands

#

Can anyone help

weary crypt
weary crypt
craggy inlet
#

Default I think DB

#

No BD

#

BD script

weary crypt
#

Not really too sure on that, can you send me the docs on slash commands for BD

craggy inlet
#

I did the instructions but it still didnt work

weary crypt
#

I know, can you send the docs to me?

placid iron
#

thank

weary crypt
#

thanks

craggy inlet
#

its not by discord but its from the app i use to make the bot

weary crypt
#

I see that now

craggy inlet
#

and its how to make slash commands on BD script

eternal osprey
#
const therest = test.substring(test[0][1].length)```test.substring is not a function
#

how is that?

weary crypt
#

The only thing I can think of, make sure that your invite scope is correct(this way your bot can actually use em) Also make sure that you are saving properly @craggy inlet

#

Not too much else I can say since I cannot see the code they are using etc...

craggy inlet
#

it is on the right scope and im saving it properly. ig the options dont work on BD script

boreal iron
vivid fulcrum
#

it's crazy how neither the api or the lib docs mention it lol

sage bobcat
#

One message removed from a suspended account.

vivid fulcrum
#

it's kind of intuitive but considering you're working with discord, nothing is intuitive

sage bobcat
#

One message removed from a suspended account.

vivid fulcrum
#

hello

sage bobcat
#

One message removed from a suspended account.

vivid fulcrum
#

πŸ€—

sage bobcat
#

One message removed from a suspended account.

#

One message removed from a suspended account.

pale vessel
sage bobcat
#

One message removed from a suspended account.

fiery stream
#

feel free to teach me C#

cosmic forum
vivid fulcrum
#

i love c# so much but it stinks in the UI department

#

this is where js is king

vivid fulcrum
fiery stream
#

china

#

arnt*

vivid fulcrum
#

πŸ€·β€β™‚οΈ

fiery stream
#

pretty sure they are but k

weary crypt
placid iron
#

either way, yes

earnest phoenix
#

has discord finally released a version that supports stage channels?

boreal iron
quaint wasp
#
``` Umm... wtf does it not know what user is?
craggy pine
#

Not if you don’t tell it what user is..?

sage bobcat
#

One message removed from a suspended account.

errant hornet
#

How would the bot get the ID of a role it just created?

sudden geyser
#

What library are you using?

eternal osprey
#

how do i use .push to add a number to a []?

#

so for example [20], I want to add 40 more:

summer torrent
#

add 20 to 40?

#

so [60] ? or

sudden geyser
#

You could call .push 40 times, but this depends on what you really want to do.

  • Do you want to add the number 20 40 times to the array?
  • Do you want to add 40 more numbers to the array?
#

The former is easy to implement:

Array(20).fill(40);
harsh blade
#

Can any1 help me rq

#

How would i use the "displayname" in console.log?

#

I Dont really know if u can even do that lol

#

Nvm i sorted that out

#

Is there a way to make this message colored?

weary crypt
#

console foreground color?

harsh blade
#

The message color

#

like in console.log

weary crypt
#

Yea there maybe something in the class console to change the color

#

In C# it is Console.ForegroundColor =

sudden geyser
#

It depends on the environment.

#

If you're in your browser console (e.g. Chrome) you can use CSS.

harsh blade
#

Figured it out

#

i used this list

#

if anyone else is wondering :p

sudden geyser
#

Great. I recommend you use constants or a library to store them (since I see a lot of users include the raw color in the string).

harsh blade
#

Ohh

#

so its easier to use ig?

sudden geyser
#

Yeah

#

and less ambiguous

#

You probably can't tell what \x1b[1m Hello, World! means up front.

harsh blade
#

haha

#

Alright, thanks for the help :p

rocky hearth
#

Does this library discord.js , is also managed and created by microsoft itself?

#

or it is a open source project?

earnest phoenix
#

It is a library created by the devil himself to cache everything and make the memory suffer mmLol

rocky hearth
#

who's devil

long marsh
#

Anyone know why a shard would randomly go down without any caught errors?

#

Happens from time to time on my bot. I have seen shard disconnect & restart before, but I get all the logs for those.

rocky hearth
#

because u might be not handling them properly

long marsh
#
const manager = new ShardingManager('./src/bot.js', {
  token: Config.Bot.token,
});
manager.on('shardCreate', (shard) => console.log(`Launched shard ${shard.id}`));
manager.spawn();
#

Is there a manager.on('shardException') or anything?

rocky hearth
#

idk, what does the error says

long marsh
#

There isn't an error, lol

#
client.on('error', (code) => {
  console.error(code);
});

process.on('exit', (code) => {
  console.log(code);
});

process.on('uncaughtException', (error) => {
  console.error(error);
});

process.on('unhandledRejection', (error) => {
  console.error(error);
});
#

I catch everything from the client itself.

#

I don't get anything from the shard.

#

It was just a shot in the dark - I really don't know what it could be doing. I suspect it's low ram.

#

But, I'm not reaching ram limits πŸ€”

lament rock
#

there might be a manager error event

#

makes the most sense if there was one

long marsh
#

Do you have documentation for that?

#

I legit could not find it

#

Wow

lament rock
#

Looks like shardCreate is the only event in the docs

long marsh
#

Just found it

#

Well, that should help πŸ˜„

lament rock
#

that's a ClientShard event

#

not manager

long marsh
#

OH!

#

Duh.

#

Yeah, I believe there's only 1 event "shardCreate"

lament rock
#

for the manager, yes

long marsh
#

Right - so how do we catch errors from the shard manager standpoint?

#

In an idea world, I would assume there shouldn't be errors πŸ€·β€β™‚οΈ

lament rock
#

You could listen to the error event in the shard and then post the message to the manager

#

arbitrarily emit an event through the ShardManager

#

but that's not type safe

long marsh
#
client.on('error', (code) => {
  console.error(code);
});

process.on('exit', (code) => {
  console.log(code);
});

process.on('uncaughtException', (error) => {
  console.error(error);
});

process.on('unhandledRejection', (error) => {
  console.error(error);
});
#

Would none of those already catch the shard error?

#

I was assuming I was catching everything by those standards.

#

I could throw in the shardError event as well.

lament rock
#

shardError would

#

since shardError is for socket errors

rocky hearth
#

y can't I require all the files in ./events?

#

it is not giving any errors, and also not logging anything

earnest phoenix
#

Btw you're not invoking the console.error method, other than, if it doesn't log anything then have you tried logging something before reading the files?

rocky hearth
#

yes, than it works

rocky hearth
#

this time I also got the error, no such file or directory "events"

earnest phoenix
#

Because fs targets the root path

lament rock
#

does fs default to cwd?

earnest phoenix
#

./src/events

lament rock
#

@earnest phoenix on the topic of relative paths, check out what I made. npm backtracker

earnest phoenix
lament rock
#

pain

lament rock
#

tldr; you can use that module to have native like file resolution using relative paths based on the previous frame in code execution

#

aka, the current func

earnest phoenix
#

Looks kinda really pog and useful actually, imma see what optimizations I can apply by contributing

lament rock
earnest phoenix
#

I think the first() and last() methods of the Stack class can take a parameter to return the required amount of elements just like the collections in discord.js

#

Imma PR that real quick

delicate shore
#

This code isn't working

#
let res = await fetch(`https://api.pgamerx.com/ai/response?message=${okbrooo}&type=stable&unique_id=${msg.author.id}`, {
            method: 'GET',
            headers: { 'x-api-key': 'MY API KEY' },
        })
        let json = await res.json()
        let reply = json[0]["message"]

#

If I fetch the api using my wrapper it works, but like this it returns 504

#

even tho everything is correct

#

oh wait

#

I am dumb

#

I was using the wrong endpoint smh

boreal iron
#

Hey @earnest phoenix how would you create an embed with 4 fields - only 2 in one line (each).
Discord is forcing as much inline fields as will fit in the embed.

lament rock
delicate shore
#

encoded string

lament rock
#

ok cool

delicate shore
#

couldn't find a better name bruh

#

i am very bad at naming things

lament rock
#

const a = enc(b)

delicate shore
#

Imagine what I will name my child

earnest phoenix
delicate shore
#

well that's not gonna happen anyway

lament rock
#

NodeRequire.cache: { [id: string]: Module | undefined }

Module.children

rocky hearth
#

I'm trying use slash command. But my client events are not working
Is this is wrong?
const bot = new Client({ intents: 9 })

#

what is a intents, actually?

prisma locust
#

Hi, can you help me know how to get the server icon via the discord server's invite link? I think he will know the forehead with a request, but I couldn't. anyone who wants to help knows how to tag me.

trail finch
#

how to make my discord.js bot prefix work on lowercase and uppercase?

#

I tried some basic stuffs but didnt work

thorny arch
#

hey how does a bot detect someone voted

rocky hearth
#

always, convert the command name to lowercase, and check only for lowercased string

trail finch
#

um for commands I used command handler and made it both lower and upper case

boreal iron
earnest phoenix
#

yes, but the gap is not that huge

boreal iron
#

Alright, thanks I will test it out if I’m back at my PC

near stratus
trail finch
distant bramble
#

hmmm

near stratus
pale vessel
#

What if I put A!ping

trail finch
#

OH THATS TRUE! ok I got the idea

#

thank you @near stratus

lament rock
# rocky hearth what is a intents, actually?

gateway intents are sent as a bitfield which can be logic'd down to specific numbers which represent specific settings corresponding to events the client is asking Discord to send instead of sending every event. Most events are grouped together under specific intents. If the client doesn't want to receive VOICE_STATE_UPDATE events, then the client shouldn't identify with that intent in the bitfield. As a consequence, Discord won't send that event

near stratus
#

@trail finch

if(message.content.slice(0, (PREFIX.length-1)).toLowerCase() === PREFIX.toLowerCase() ){
    //The rest
}
earnest phoenix
#

What Is The Error @near stratus

#

??

rocky hearth
near stratus
earnest phoenix
#

Mhm

near stratus
pale vessel
#

message.content.toLowerCase().startsWith(PREFIX.toLowerCase()) would suffice, no?

earnest phoenix
#

@near stratus Btw Why Would Put js if(message.content.slice()) That should not be correct syntax

lament rock
#

Network I/O may become cluttered with events which would not be processed at all by the library or the client. Would also consume more CPU time decoding the messages from the gateway

fathom pivot
#

Fuck

trail finch
#

nvm my idea didnt work

near stratus
trail finch
#

btw I was talking about prefix to be both cases so that if I use YK help, yk help and Yk help it will work

#

because many mobile player's first letter when typed the first letter is upper case so..

near stratus
#

*should

trail finch
#

but isnt it only for lower case?

near stratus
trail finch
#

ok

rocky hearth
#

for slash commands, we can't give alias names yet, right?

near stratus
olive roost
#

How do i add servercount

boreal iron
#

Using a library doing it for you or just POST the server count to the topgg endpoint

#

Repeatedly of course

lament rock
#

I'd just post every 10 minutes

boreal iron
#
  • 1 hour
near stratus
#

I post once every hour
Also every time my bot is added or removed to a server

pale vessel
#

It won't matter as long as it's not once every one millisecond

errant perch
#

is it against tos to use a user bot to repeatedly use a command on a bot?

near stratus
pale vessel
near stratus
errant perch
#

theyve been doing this every 30 seconds for 5 days

pale vessel
#

Just blacklist them or add cooldowns

errant perch
#

ok thanks, just wondering if there are any other repercussions to this

copper cradle
#

your bot should ignore other bots by default

errant perch
long crow
#

Just ignore bot user

near stratus
copper cradle
#

^

errant perch
#

Β―_(ツ)_/Β―

#

ok

boreal iron
#

But who knows...

errant perch
#

what's this mean

#

oh

#

server count

near stratus
trail finch
errant perch
#

it makes the content of the message lowercase which i assume will make it case insensitive

#

same with prefix

trail finch
#

oh

#
if (!message.content.toLowerCase().startsWith(prefix.toLowerCase())) return;```

this is the way I added it in my code and it works fine!
boreal iron
#

But who actually cares... if you’re below the rate limit everything is fine

pale vessel
#

A!AaaA (content) to lowercase = a!aaaa
A! (prefix) to lowercase = a!
a!aaaa starts with a! = true

#

🧠

boreal iron
#

You forgot to mention B!BbbB to lowercase = a!aaaa too

near stratus
boreal iron
#

Huh what?

near stratus
#

@kindred lava

#

It has that command

#

It'll give a server count graph

boreal iron
#

Nope... can’t imagine something more useless tbh KEKW

long crow
#

isEven npm

near stratus
errant perch
#

anyone know how to write a privacy policy?

#

and terms of conditions?

errant perch
pale vessel
errant perch
#

oh lol

#

whoops

#

hm

#

didnt work

#

i use dblapi.js

#

do i need to use the up to date one?

thorny arch
#

can someone explain how im supposed to integrate webhooks to a bot

soft glade
#

im trying to make a roleplay bot for my friend for her server and im making a punch command so you can do _punch and it will send Wow you punched this user and a gif but its not sending the gif

@client.command()
async def punch(ctx, member: discord.Member):
  embed=discord.Embed(title=f"Wow! You Punched {member}")
  embed.set_image(url='https://images.app.goo.gl/KS7fzgAe5PmvXUHP8')
  await ctx.send(embed=embed)
soft glade
#

i dont want it to show the link to the gif and i found thats the easiest way

soft glade
thorny arch
#

ye i got it

soft glade
#

ok

thorny arch
#

@soft glade just copy the link of the gif i sent above

soft glade
#

ok

thorny arch
#

goo.gl links for images dont work

#

its just like that

soft glade
#

Oh 1sec

#

Nvm

thorny arch
pale vessel
thorny arch
#

hmmm

soft glade
#

https://cdn.discordapp.com/attachments/272764566411149314/843349780787888148/g91XPGA.gif @thorny arch this is the link that i sent

soft glade
#

ok

latent heron
soft glade
#

lol

thorny arch
woeful pike
#

aoba best girl

sudden knoll
thorny arch
#

hmmm ayt

thorny arch
sudden knoll
#

wdym, ports are how your computer connects to the outside world

#

you can put any port between the given range, most ppl use 5000

thorny arch
#

oh ok

#

and how do i get my bot's token

sudden knoll
#

your bot's webhook page on top.gg

thorny arch
#

hmmmk

sudden knoll
#

the token is for posting your server count

thorny arch
#

mhm

thorny arch
sudden knoll
#

it's not necessary for webhooks, but using this lib is ez and gives you some extra functionality so might as well

thorny arch
#

mmmk

earnest phoenix
#

somehow it detects something

pale vessel
#

What's the error?

earnest phoenix
#

if (cmd === 'play'){

#

The error is below that

#

idk why it detects that thing

#

somewhere in that group

#
if (cmd === 'play'){
^

// The error is here```
#

What's the error

craggy pine
#

Mine being "Messages" of null

earnest phoenix
craggy pine
#

Yabe, you're not listening.

earnest phoenix
#

I know but what's the error you're getting

earnest phoenix
craggy pine
#

Screen shot the ENTIRE error.

#

Not just the if (cmd === 'play'){ ^

#

part

earnest phoenix
craggy pine
#

ty

#

cmd is not defined

earnest phoenix
#

Define cmd then

craggy pine
#

That's your error.

earnest phoenix
#

command then

rocky hearth
#

in ts is it possible to define a abstract method's parameter, such that all the child classes has same method signature?
So I dont have to redeclare the parameters in each child methods.

earnest phoenix
#

ight

craggy pine
#

Ah you got offline. KEKW

earnest phoenix
earnest phoenix
craggy pine
# earnest phoenix Lmao, btw I don't mind pings lyt <3

Well I suppose I can ask just incase. So my project is a little price tracking thing designed for me and a friend to use when we're "Flipping" and the bot is basically only 100ish lines long. Specifically I transitioned to an API to get more accurate prices instead of scrapping a certain website. After doing so, a peice of code (Which was unmodified) now cause major issues and ultimately killing the bot. I don't think providing the code itself that's erroring will be much use but I was wondering if I sent you the bot itself or I could even share screens idc it could be potentially an easy fix that I'm just overlooking.
The line that's dying is

async function updateChannelMessage(priceDelta, data, bot) {
  console.log(data);

  let channel = await bot.channels.fetch(data.channelId, true)
  let message = await channel.messages.fetch(data.messageId, true); // <-- messages being null
  await message.edit(getEmbedByDelta(priceDelta)).catch(console.log);
}

But I doubt that's much context for you correct

#

It works fine if I revert code which is why I'm like What

earnest phoenix
#

hmm, that's kinda strange; when you log the data at the start of the function after calling it, does it contain the correct channelId property with a valid channel ID?

craggy pine
#

Well here's the thing.

#

The bot itself is designed to like "Start the process" on boot so I don't have to re-run code. So when I begin the bot for the first time it's 100% fine.

#

If i close console then start the bot up again, the error appears.

#

I do keep the data in a .json it's suppose to look at.

#
{"currentPrice":550993000,"usersToNotify":["160679942319767552"],"messagesToEdit":[{"messageId":"843330564508876820","channelId":"720571224777949205"}],"scrapeURL":[]}
#

So the msgID and channelID are indeed there.

earnest phoenix
#

So is that what it exactly logs when you log data?

craggy pine
#

sec.

#

the log is above the error

#

I wonder if it's related to the fact the API uses data aswell as it's formatting. but it's in its own function and should not see it.

earnest phoenix
#

That is really weird, you said it runs fine on the startup and after restarting; that error starts to appear? Literally the only reason I would think of why this happens is that the bot is logging in to a different application with a token instead of the main one

#

Or the channel ID is incorrect which I presume is not the case if not changed

craggy pine
#

Correct. As mentioned in the original message above, I'd be happy to kind of, demonstate it? A gif would take too long to make if you're willing to watch KEKW

earnest phoenix
#

I would like to hear you demonstrate it, a gif might also be helpful but nah; that would take too long

prime mist
#

Is messages actually a property on the channel instance? https://discord.js.org/#/docs/main/stable/class/Channel

earnest phoenix
#

no

#

Its a property on the TextChannel class

prime mist
#

Maybe log the channel variable and see what is going on?

craggy pine
#

Well again this line that causing trouble was never changed in the first place. I yeeted puppeteer code to use request since API instead of scrapping. Puppeteer code works fine.

#

no issues what so ever.

earnest phoenix
#

The channel variable entirely returns null

#

it joined and it plays but it needs more commands sadKEK

craggy pine
#

I'll lower my rate it checks the price to make a gif.

#

sec

earnest phoenix
craggy pine
#

20 sec gif oh well.

#

here goes nothing

#

Notice that b4 I close the console, it does indeed check the price, returns "Data" and it works. I close console, reopen it and error.

earnest phoenix
#

Oh wait, are you those object logs the message ID and the channel ID of the messages the users sent to invoke the command?

craggy pine
#

No it's the bot embed. It just updates it as prices change

#

botembed = messageID, channel ID = channel command was ran in to start the process

earnest phoenix
#

Oh, lemme check the code you sent me real quick

craggy pine
#

Sure.

earnest phoenix
# craggy pine Sure.

I'm starting to see a pattern here, you're pushing the message the bot sends to an array to edit them later, but in the gif you showed; it logs 4 objects when the bot only sent one message? Am I missing something here? Or maybe the channel ID being pushed there was deleted? I'm as confused as you're

craggy pine
#

It's on a timer, so what it does is I'm able to create multiples of these if I wish hense the array but generally I only have one message running.
What the bot does is it opens the API stores the data after x time (I usually set it to a minute per check) it will compair old value to new and alert the users "Subscribed" to get a DM on the change. If I close the bot and wish to resume this later, it would since the messageID and channelID both would exsist since I wouldn't delete the message itself.

#

It logs the objects each rotation because I did that for debugging purposes really.

#
{"currentPrice":552000000,
"usersToNotify":[],
"messagesToEdit":[{"messageId":"843373934221066250","channelId":"720571224777949205"}],
"scrapeURL":[]}

This is what it's storing and it will only ever overwrite "current price" since it changes. usersToNotify is a push and same goes to messagesToEdit, URL is a overwrite but never really used

earnest phoenix
#

I literally have no clue at all, all of it seems fine to me as I don't see anything wrong except that you're not resolving the promise of doing a request with request() which I presume is not the one causing the issue, this is really strange

craggy pine
#

KEKW no worries. I'll post litterally what was changed so u can see old code aswell just incase that may help but if it doesn't I appreciate your assistance nontheless.

#
async function scrapeItemPage(url) {
  try {
  const browser = await puppeteer.launch();
  console.log("\nStarting virtual browser...")
  const page = await browser.newPage();
  console.log("Opening a new page...")
  await page.setDefaultNavigationTimeout(0);
  await page.goto(url);
  console.log("Going to GE-Tracker.com")

  //get price
  const [el] = await page.$x('/html/body/div[2]/div/div[3]/div[4]/div[2]/div[1]/div/div[2]/div[2]/table/tbody/tr[1]/td[1]/div/span')
  inqPrice = await el.getProperty('textContent')
  inqPrice2 = await inqPrice.jsonValue();

  //get ID
  const [el2] = await page.$x('/html/body/div[2]/div/div[3]/div[3]/div/div/div[2]/h1/small')
  if (el2 == null ) {
    return
  } else {
    itemID = await el2.getProperty('textContent')
    itemID2 = await itemID.jsonValue();
    console.log("ID of item is: " + itemID2.slice(4))
  }


  //get item Title
  const [el3] = await page.$x('/html/body/div[2]/div/div[3]/div[3]/div/div/div[2]/h1')
  itemTitle = await el3.getProperty('textContent')
  itemTitle2 = await itemTitle.jsonValue();
  console.log("Name of item is: " + itemTitle2)

  //finished
  await browser.close();
  console.log("Closed Virtual Browser...")
  
  //save everything
  currentPrice = inqPrice2.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, '').trim();
  setImage = ('https://secure.runescape.com/m=itemdb_oldschool/1619001006055_obj_big.gif?id=' + itemID2.slice(4));
  getTitle = itemTitle2;
  console.log(setImage)
  saveCurrentPrice();

  console.log("Price of " + itemTitle2 + "is " + currentPrice);
  return currentPrice;

  } catch (error) {
    console.log(error)
    saveCurrentPrice()
  }
}
#

old ^

#
async function scrapeItemPage(url) {
  try {

    let options = {
      'method': 'GET',
      'url': url
    };

    //get json data
    request(options, function (error, response) {
      if (error) throw new Error(error);
      let pretty = JSON.parse(response.body);
  
    //save everything
    currentPrice = pretty.data[22486].high;
    setImage = ('https://oldschool.runescape.wiki/images/e/ee/Scythe_of_vitur_detail.png?33aa5');
    getTitle = "Scythe of Vitur";
    saveCurrentPrice();

    console.log("Price of " + getTitle + " is " + currentPrice);
    return currentPrice;

  })} catch (error) {
    console.log(error)
    saveCurrentPrice()
  }
}

new ^

#

I was kinda hoping discord would just you know. make that code-block an expandable thing but nvm. Sorry for spam KEKW

#

That was all that was changed

earnest phoenix
#

Yea I don't think that's the issue though, the only things I can suggest trying is to resolve the promise of request() AND try to return as soon as the channel is unavailable for testing to see if it helps at all yk?

craggy pine
#

I'll take the advice thumbsup

rapid wharf
#

How much ram should be good for a bot in multiple servers??

earnest phoenix
#

Depends on what the bot does

rapid wharf
earnest phoenix
#

If the commands do some complex processing and shit, it would require quite a lot, but if it doesn't then at least 300MB just to be sure would be enough for now if the bot is currently small, if it gets bigger you would have to get some more or even at least 2GB or 3GB depending on how many guilds it operates on

rapid wharf
#

reallllyyyy

#

for now the bot is under dev

#

and the free hosting i m using it provides 100 mb of ram

#

and 1.14 gb of ssd

#

so should i shift @earnest phoenix ??

earnest phoenix
#

The amount of ram you would could also depend on what lib you're using, for example if you're using discord.js; 100MB is a no no since it caches heavy objects which is costly for memory allocation

#

You should get a VPS instead of free hosting, but if you're only testing on the free hosting for now its fine

lusty quest
#

wtf 100MB ram, this requires some insane amount of optimisation to be able to run stable

earnest phoenix
#

yea

lusty quest
#

its possible with js, but requires stuff like using better memory allocators

rapid wharf
lusty quest
#

not sure with py, but its not the most efficent language out there, even with py you probably have to do a lot of stuff like tuning your cache and using a better memory allocator

#

its less headache to just use a vps with more ram

woeful pike
earnest phoenix
#

I'm not sure if discord.py caches heavy objects but don't go on about using 100MB for a Discord bot

rapid wharf
#

okie thanks

earnest phoenix
#

Very unstable

craggy pine
earnest phoenix
#

You can tho

pale vessel
#

doesn't it use the error event was thinking of http(s) module

woeful pike
#

by the time the callback runs and you throw Error the try/catch block is no longer in the stack and can't catch the error you throw

craggy pine
#

Ah, that makes sense. This was me just copy pasting working code that I made in place of puppeteer code which used try/catch. Thanks for the heads up.

woeful pike
#

you might find axios easier to use since it's built on promises and isn't deprecated

craggy pine
#

funny enough I'm working with that now seeing how it works

#
const Discord = require("discord.js");
const axios = require('axios');

module.exports.run = async (bot, message, args) => {

    axios.get('https://prices.runescape.wiki/api/v1/osrs/latest?id=22486/5m')
    .then(response => {
      console.log(response.data.url);
      console.log(response.data.explanation);
    })
    .catch(error => {
      console.log(error);
    });

}

module.exports.help = {
    name: "test2"
}
#

just testing it nothing being built really.

woeful pike
craggy pine
#

I heard some people talking about Axios so why not try it out ^_^

pale vessel
#

Fetch gang rise up

near stratus
pale vessel
#

I heard centra is good

lusty quest
#

axios is nice, but heavier than node-fetch

near stratus
craggy pine
#

ty tho thumbsup

#

Reading docs b4 I really do anything.

prime mist
craggy pine
#

Likely will πŸ™‚

#

Ya I figured it out pretty quickly. It's pretty nice ngl

lusty quest
#

isnt request deprecated

pale vessel
#

It is

craggy pine
#

Never knew tbh KEKW

#

I made this stupid project quite a bit ago and recently decided to work with it again

lusty quest
#

yea its deprecated since 2020

craggy pine
#

Welp the more you know.

earnest phoenix
#

Welp kids, this is why you don't use deprecated packages KEKW

craggy pine
#

it do be like that sometimes.

thorny arch
#

ye

earnest phoenix
#

Was gonna suggest using node-fetch but axios is also nice

craggy pine
#

welp time to test code out once more with axios but with actual project.

craggy pine
earnest phoenix
#

Wait wtf

#

How?

craggy pine
#

idk tbh but I'll take it

earnest phoenix
#

what does that mean that was an issue from the Node.js's interpreter

craggy pine
earnest phoenix
#

What Node.js version are you currently using?

craggy pine
#

good question KEKW

#

sec

#

13.12.0

earnest phoenix
#

hm, you should try updating to v14 as it's the current LTS

craggy pine
#

I can ya.

#

and again funny enough I put await back in the code and it's still working. Fuck coding KEKW I am updating tho regardless.

earnest phoenix
#

Lmfao wtf

#

Gotta love how a piece of code can fuck with you and you remove and place it back to where it exactly was, it works

#

KEKW wtf is coding anymore

craggy pine
# earnest phoenix <:KEKW:727825308404940800> wtf is coding anymore

Ah you know what, it wasn't the async or anything that caused the issue. The error returned. But I did figure it out. The reason why Puppeteer worked with the current code is because it took a decent chunk of time to open a virtual browser, save data, and do whatever. It did this while the bot booted up. So the bot would boot up fully before puppeteer completed. Since API is faster, the api stuff would try to resolve before the bot came fully online so "messages" would be indeed null since it isn't online to see them. Changed some index.js stuff and well, we're good.

earnest phoenix
#

Damn, its always the smallest issues that causes all of this

craggy pine
#

I noticed it when flip flopping between old and new code and console.logged extra shit. But it was the "I'm online!" message that cought my attention. With puppeteer it would always come before the prices. With API it will come up after the error.

earnest phoenix
#

Btw you can also assign the wait variable to Discord.Util.delayFor instead lol

craggy pine
craggy pine
earnest phoenix
#

HmmKay glad that you found out what was causing your issue and fixing it; I thought of telling you to check to see if the client is fully logged in but then I thought nah that wouldn't be the case

#

Seems like it was KEKW

craggy pine
#

Ya major facepalm moment

hearty kernel
#

why the bot dont send massge when someone join

eternal osprey
#

hey

 const points = database[name].points
  const d = levels[message.author.id].completed
  const c = levels[message.author.id].points
  levels[message.author.id].points.fill(Number(points) + Number(c))
  levels[message.author.id].completed.fill(Number(d) + 1);

why does this return me: 2020 and 11?
While it should be 40 and 2

gaunt stag
#
module.exports = {
    name: 'coinflip',
    description: 'Flip a coin',

    execute: async(client, message, args) => {
        const heads = ("./Images/heads.png")
        message.channel.send(`You got heads, ${heads}`)
    }
}``` should work right?
lusty quest
gaunt stag
lusty quest
gaunt stag
#

no it does not

lusty quest
#

also you cant send images like this

gaunt stag
#

You got heads, ./Images/heads.png

#

comes

lusty quest
#

you have to send them as a attachment

lusty quest
# eternal osprey wot

check with typeOf() what type your numbers are, if they are strings you have to make sure you pass in numbers.

gaunt stag
#

const heads = new Discord.MessageAttachment("./Images/heads.png")

#

like that?

lusty quest
eternal osprey
#

they are an object

#

all 3

lusty quest
#

so you try to use an object and use math on them?

eternal osprey
earnest phoenix
lusty quest
earnest phoenix
#

hi

#

help me

client.on('message', (message) => {
    const low = require('lowdb')
    const FileSync = require('lowdb/adapters/FileSync')
    const adapter = new FileSync('./db.json')
        const d = low(adapter)


        const gguild = message.guild
        if (d.get("antispam").find({ guild_id: gguild.id }).value()) {

    antiSpam.message(message)
        }
}); ```

Error:
```\Bot discord (js)\booot perso\antispam.js:67
        if (d.get("antispam").find({ guild_id: gguild.id }).value()) {
                                                      ^

TypeError: Cannot read property 'id' of null
    at Client.<anonymous> (c:\Users\Vitcor\OneDrive\Bureau\Bot discord (js)\booot perso\antispam.js:67:55)
    at Client.emit (events.js:327:22)
    at MessageCreateAction.handle (c:\Users\Vitcor\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
    at Object.module.exports [as MESSAGE_CREATE] (c:\Users\Vitcor\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
    at WebSocketManager.handlePacket (c:\Users\Vitcor\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
    at WebSocketShard.onPacket (c:\Users\Vitcor\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
    at WebSocketShard.onMessage (c:\Users\Vitcor\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
    at WebSocket.onMessage (c:\Users\Vitcor\node_modules\discord.js\node_modules\ws\lib\event-target.js:132:16)
    at WebSocket.emit (events.js:315:20)
    at Receiver.receiverOnMessage (c:\Users\Vitcor\node_modules\discord.js\node_modules\ws\lib\websocket.js:835:20)```
earnest phoenix
#

it doent work

#

How you gave?

#

###Cap Has 1 of the best AntiNuke system on Discord. It has better antinuke system than Security and Wick.It also comes with Moderation, Music, Economy, Utlity and Fun commands etc.

#

Space after #

#

oh

#

alruight ty

#

Like this ### Hi

#

Thank You

#

it works

#

Yep

mental raven
#

Does anyone know how to use discord.py with pyrebase to make a leaderboard command? This is my try:

@client.command(aliases=['lb'])
async def leaderboard(ctx):
  for x in db.get().val():
    y = db.child(x).child('Wallet').get().val()
    f = int(y)
    everyonesWallet.append(y)
    everyonesWallet.sort(reverse=True)
  
  top1user = everyonesWallet[0].parent()
  top2user = everyonesWallet[1].parent()
  top3user = everyonesWallet[2].parent()
  top4user = everyonesWallet[3].parent()
  top5user = everyonesWallet[4].parent()

But it has this error:

Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: '<' not supported between instances of 'str' and 'int'

Can you help me?

#

Please?

low river
#

i have a totally different lb from u

mental raven
low river
#

no-

mental raven
#

sad

low river
#

welp imma show u my lb

#

irrespective that i left that bot

#
@client.command(aliases = ["lb"])
async def leaderboard(ctx,x = 1):
    users = await get_bank_data()
    leader_board = {}
    total = []
    for user in users:
        name = int(user)
        total_amount = users[user]["wallet"] + users[user]["bank"]
        leader_board[total_amount] = name
        total.append(total_amount)

    total = sorted(total,reverse=True)    

    em = discord.Embed(title = f"Top {x} Richest People πŸ’΅" , description = "This is decided on the basis of raw money in the bank and wallet",color = discord.Color(0xfa43ee))
    index = 1
    for amt in total:
        id_ = leader_board[amt]
        member = client.get_user(id_)
        name = member.name
        em.add_field(name = f"{index}. {name}" , value = f"{amt}",  inline = False)
        if index == x:
            break
        else:
            index += 1

    await ctx.send(embed = em)

async def open_account(user):
    
    users = await get_bank_data()

    if str(user.id) in users:
        return False
    else:
        users[str(user.id)] = {}
        users[str(user.id)]["wallet"] = 0
        users[str(user.id)]["bank"] = 0

    with open("mainbank.json", "w") as f:
        json.dump(users,f)

    return True

async def get_bank_data():
    with open("mainbank.json", "r") as f:
        users = json.load(f)

    return users

async def update_bank(user,change = 0,mode = "wallet"):
    users = await get_bank_data()

    users[str(user.id)][mode] += change

    with open("mainbank.json", "w") as f:
        json.dump(users,f)

    bal = [users[str(user.id)]["wallet"],users[str(user.id)]["bank"]]

    return bal```
#

will be different for u as i am storing my bank info in mainbank.json file

mental raven
#

oh ok

#

That's alot of code

hearty perch
#

Excuse me, what?

marble juniper
hearty perch
#

No

marble juniper
#

those intents will soon be required to be set in discord.js v13

hearty perch
#

that's not my point

marble juniper
#

when the new discord.js update comes out intents will be required lol

hearty perch
#

They said a video is outdated because intents

marble juniper
#

yes

#

that video doesn't have intents in the code

#

thats the thing

#

that i just said

#

bruh

hearty perch
#

But

#

you know

#

Nevermind

#

I don't feel like it's worth arguing

marble juniper
#

I don't get what you don't get

opal plank
#

replying to a 2 month old message. bold move

marble juniper
#

also yes that message is ancient

#

more ancient than IBM computers

sudden geyser
#

What does IBM even do today

sudden geyser
mental raven
#

How do I find that

sudden geyser
#

requirements.txt?

mental raven
#

the latest

marble juniper
#

do u even know python first of all

#

lol

mental raven
marble juniper
#

a little bit or experienced

mental raven
#

a little bit

marble juniper
#

ic

sudden geyser
#

The error you're getting means you're trying to compare a str with an int (not allowed in Python; must be the same type). It's ambiguous since I don't see you doing comparison in your source code and the traceback only points towards files in the internal library.

sudden geyser
#

I'm not saying you did. I'm saying the error did:

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: '<' not supported between instances of 'str' and 'int'

mental raven
sudden geyser
#

Maybe. The error still says otherwise.

mental raven
#

hmm

#

I have an idea

#

i will try it

#

it didn't work ._.

#

I am trying to get 5 values from Firebase then sort them from the bigger to the lower and then i am trying to get their parent to say that he has the more money..

slender thistle
#

It's outdated because intents are not mentioned. If I recall correctly, Discord enforces intents since API v8/v9, so even if it works now doesn't mean it should be recommended as a guide

#

Feel free to share your POV if you think it's worth being discussed, I don't mind

green kestrel
#

hi there shiv!

#

people are going to WANT to update to API v9 soon

#

which means code lacking intents simply will. not. work.

#

because v9 got threads

#

and if discord.js don't pull their finger out and release a stable version with slash commands and threads they're gonna get left behind

#

all their good stuff seems to be on their beta

slender thistle
marble juniper
#

I wont use beta in my bot yet

#

obviously

#

but I will try it out ig using a new bot account

#

just to play around with it

#

slash commands support looked really nice to me

#

easy to use

earnest phoenix
#

Vortex hackban is ip ban how

#

Someone telling me

sudden geyser
#

When you ban a user from a guild/server, it's by IP.

zenith terrace
#

every bot does. It is the same as using the ban buttons on discord

rocky hearth
#

how could I stop nodemon from restarting on new file creation

sudden geyser
rocky hearth
#

naah, I think its not possible, what i want

rocky hearth
#

runOnChangeOnly didnt work, but what it actually do

opal plank
#

@rocky hearththats almost the whole purpose of nodemon, why not use forever, pm2 or bash to startup/maintain scripts?

rocky hearth
#

thanks for mentioning, I'll look up them

#

hey can u mention what is ur development environment in ts to make bots?
I do yarn watch:dev, to start testing the bot locally

#

idk, if it is proper dev env. I've heard of using ts-node, but the package require-all doesn't seem to work with it (as it requires js files)

opal plank
#

@rocky hearth gimme 5,in the bathroom rn

rocky hearth
#

πŸ˜† , no worries

pale vessel
#

Have a good shitting session Erwin

opal plank
slender thistle
#

Shitty situation

opal plank
# rocky hearth hey can u mention what is ur development environment in ts to make bots? I do `y...
{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Launch Bot Directly",
      "program": "${workspaceFolder}/out/index.js",
      "skipFiles": ["<node_internals>/**"]
    },
    {
      "type": "node",
      "request": "launch",
      "name": "Launch Program",
      "program": "${workspaceFolder}/out/index.js",
      "preLaunchTask": "tsc: build - tsconfig.json",
      "outFiles": ["${workspaceFolder}/out/**/*.js"]
    },
    {
      "type": "pwa-node",
      "request": "launch",
      "name": "Explorer Enabled",
      "skipFiles": ["<node_internals>/**"],
      "program": "${workspaceFolder}/src/index.ts",
      "outFiles": ["${workspaceFolder}/out/**/*.ts"],
      "runtimeArgs": ["-r", "ts-node/register", "--inspect=4765"]
    },
    {
      "type": "node",
      "request": "attach",
      "name": "Attach Program",
      "port": 5880,
      "restart": false,
      "skipFiles": ["<node_internals>/**"],
      "outFiles": ["${workspaceFolder}/out/**/*.js"],
      "showAsyncStacks": true,
      "smartStep": true,
      "sourceMaps": true
    }
  ]
}
#
{
  "compilerOptions": {
    "allowJs": true,
    "baseUrl": ".",
    "declaration": true,
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "inlineSources": true,
    "lib": ["ES2019", "DOM"],
    "module": "commonjs",
    "moduleResolution": "node",
    "noImplicitAny": true,
    "noImplicitReturns": true,
    "outDir": "out",
    "sourceMap": true,
    "strict": true,
    "strictNullChecks": true,
    "target": "ESNext",
    "watch": true,
    "paths": {
      "@/*": ["src/types/*"],
      "~/*": ["src/*"]
    }
  },
  "files": ["src/types/genshin.d.ts"],
  "include": ["src/**/*.ts", "src/commandssrc/globalsbals"],
  "exclude": ["node_modules", ".vscode", "emotes"]
}
#

those are my settings

pale vessel
#

dist gang

rocky hearth
#

hmm, y u hv added DOM in lib?

#

isn't it used on frontend frameworks?

opal plank
#

cuz i have a local http server built in with it

rocky hearth
#

ooh ok

opal plank
#

my local website/admin panel runs off inside the bot cuz i was too lazy to create a decent token gen for a public api

rocky hearth
#

in paths does ~/* have special semantic meaning?

opal plank
#

it does

#

allows me to dynamically import everything in there, regardless of pathing

#

cuz it makes it available everywhere

sudden geyser
#

is that intentionally spelt wrong

opal plank
#

shush

#

i just typed it to show it off

#

as hinted by the shadowed font

#

@rocky hearth

#

this is a good example

#

both of them work exactly the same

rocky hearth
#

what about ~/*

opal plank
#

same deal

#

that just makes everything in /src accesible for me if i type in ~/

rocky hearth
#

oh, so we can use any symbol?

opal plank
#

doesnt need to be a symbol

rocky hearth
#

ok so they dont have any special meaning

opal plank