#development

1 messages ยท Page 1835 of 1

quartz kindle
#

i mean the library

fresh bluff
#

oh

#

idk

#

im new to coding

modest maple
quartz kindle
#

py / python is the language. discord.py is the name of the python library to interact with discord

lunar cove
fresh bluff
#

im just using python

modest maple
fresh bluff
#

Nope thats a scam

lunar cove
lunar cove
fresh bluff
lunar cove
#

Learn how to code a Discord bot using Python and host it for free in the cloud using Repl.it. Along the way, you will learn to use Repl.it's built-in database and create a Discord bot that uses webhooks to connect with GitHub.

Need help with this tutorial? You can ask questions here: https://forum.freecodecamp.org/

This course was developed by...

โ–ถ Play video
#

take this and watch some similar stuff

fresh bluff
#

in run the bot in replit\

lunar cove
#

this guy is using reptil

rose warren
#

Imma go cry in a corner now

quartz kindle
#

or similar

lunar cove
fresh bluff
lunar cove
rose warren
#

No. There are no dumb questions. Just at least you listened to the answers we gave you.

quartz kindle
modest maple
#

that tutorial

modest maple
#

is almost

#

the worst tutorial

#

on youtube

rose warren
modest maple
#

and it amazes me how badly its done

quartz kindle
lunar cove
#

Ohh well I learnt from choochoo train guy so dunno abt this

#

I avoid python

quartz kindle
#

god

fresh bluff
#

I CANT DO THIS

#

Its to hard

split hazel
#

does anyone here know how deletes in interactions work

#

does delete delete the latest reply

#

since you can apparently post multiple replies

#

in 15 mins

lunar cove
#

Umm, so I have now been able to fetch the webhook and confirm whenever someone votes and send thier id in console. Now I want to send a message to specific channel, I read the docs and googled and found out that client.channels.cache.get('CHANNEL ID').send('Hello here!') sends the message, but I don't have client declared in my server.js, so my doubt is do I need to write ```const Discord = require('discord.js');

const client = new Discord.Client();``` once again in server.js or there is some other way ?

What I have written in server.js -->

const server = express();
//for top.gg
const Topgg = require('@top-gg/sdk');
const webhook = new Topgg.Webhook("4N8eXCvZHjpfwt");

server.all('/', (req, res)=>{
    res.send('Your bot is alive!')
})

function keepAlive(){
    server.listen(3000, ()=>{console.log("Server is Ready!")});
}

server.post("/dblwebhook", webhook.listener(vote => {
  // vote will be your vote object, e.g
  console.log(vote.user) // 395526710101278721 < user who voted\
  user=client.users.cache.get(vote.user);
  client.channels.cache.get('766908428411994134').send('Thank you ${user} for voting!!');
  // You can also throw an error to the listener callback in order to resend the webhook after a few seconds
}));

module.exports = keepAlive;```

Is other things right beside that client thing ?
quartz kindle
split hazel
#

discord js says no

#

unless theres some other method to do it

#

man fuck djs lol

#

im just doing it to test out interactions

quartz kindle
split hazel
#

how would you get a reply id

#

the interaction reply method returns void

quartz kindle
#

reply is the original message

#

so you use @original as the message id

#

for followups you use CommandInteraction#followUp

split hazel
#

oh i see

quartz kindle
#

they return message objects

split hazel
#

thats interesting

#

follow ups last 15 minutes right

quartz kindle
#

the token lasts 15 mins

#

you can do whatever with the token in that time

split hazel
#

so yes

quartz kindle
#

be it following up, editing or deleting

split hazel
#

i saw it in api docs

quartz kindle
#

offtopic: rate my code

#
this.properties = options.properties && typeof options.properties === "object" && [options.properties.$os, options.properties.$browser, options.properties.$device].every(x => typeof x === "string") ? options.properties : {
    $os: process.platform,
    $browser: "test",
    $device: "test"
};
#

:^)

split hazel
#

maybe if you indented properly i'd give it a 10

quartz kindle
#

its just the first line is super long

split hazel
#

thats your queue to press enter

quartz kindle
#

xD

split hazel
#

if it does the job it does the job

fresh bluff
#

Ok im getting a error

split hazel
#

though as an easter egg the os, device and browser should be "amogus"

fresh bluff
#

File "main.py", line 7
print('we have logged in as {0.user}
^
SyntaxError: EOL while scanning string literal

quartz kindle
#

for example

earnest phoenix
quartz kindle
#

```js
console.log("lol")
```

fresh bluff
#

hey Guys i need help

split hazel
#

```rs
wait i dont know rust
```

fresh bluff
#

im getting a error

#

File "main.py", line 7
print('we have logged in as {0.user}
^
SyntaxError: EOL while scanning string literal

#

what does that mean?

earnest phoenix
#

```detritus
type djs = dumb

split hazel
quartz kindle
#

do you know what a string it?

fresh bluff
split hazel
#

man

fresh bluff
#

@quartz kindle this is the line im getting the error at
print('we have logged in as {0.user}
'.format(client)')

split hazel
#

just use f strings they're a lot easier to use for beginners

quartz kindle
#

the string is malformed

fresh bluff
#

im getting a error bc of }

#

that

quartz kindle
#

no you arent

earnest phoenix
quartz kindle
#

lmao

earnest phoenix
#

since it's the protoype object the ref should be same

#

the json is unnecessary

fresh bluff
#

Oh wait im dumb

earnest phoenix
#

which is why ill make it worse

fresh bluff
#

File "main.py", line 7
print('we have logged in as {0.user}
^
SyntaxError: EOL while scanning string literal
but i still get this after fixing the error

quartz kindle
#

again, do you know what a string is?

fresh bluff
#

Idk what to do

#

no

quartz kindle
#

then learn what a string is

fresh bluff
#

im so confused

quartz kindle
#

because you dont know how programming works

sudden geyser
#

You may want to start with learning python.

quartz kindle
#

learn some basics

fresh bluff
#

ima keep this bot on hold and learn more about python

quartz kindle
#

good idea

lunar cove
#

I'm planning to add a very basic command handler too

earnest phoenix
#
// bot.js

//do your bot stuff here
//DONT run client.login

module.exports = client;

// server.js
const client = require("./server.js");

// do your webhook stuff and send messages with the bot

client.login(token);
long crow
#

manga search and anime search done, now need to fine tune, then my bot is finished? lol

#

process.memoryUsage()

cinder patio
#

process.memoryUsage.rss()

lunar cove
earnest phoenix
#

uh no

#

you are requiring server in which file?

lunar cove
#

main one, index.js

earnest phoenix
#

and where is your bot code?

lunar cove
#

Well I'm plannning to use command handler(did in previous code of a basic bot) so in commands folder

#

command.js and server.js are in root

earnest phoenix
#

ok cool

lyric mountain
#

damn, didn't expect flashbang

earnest phoenix
#

lmfao

lunar cove
earnest phoenix
#

anyways does your server.js file need to access the client variable?

lyric mountain
#

reptil has dark

earnest phoenix
lyric mountain
earnest phoenix
#

me and the bois reading the article on light mode

lunar cove
#

now this white patch feels more weird and badsmile1

earnest phoenix
#

Lol

#

So does your server.js file need anything that requires the client variable?

lunar cove
#

Well I tried sending message of vote confirmation from server file, is that wrong way to go ?

lyric mountain
earnest phoenix
#

It will stop your bot

lyric mountain
#

really?

lunar cove
#

yeah

earnest phoenix
#

Is there any official date when v12 will be depreciated ?

lyric mountain
#

dat sucks

earnest phoenix
#

And it'll reopen when you run the app again because it reopens if the app is listening on a server

lyric mountain
#

just create a css file then and add body { background-color: black }

lunar cove
# lunar cove Well I tried sending message of vote confirmation from server file, is that wron...

like this

const express = require('express');
const server = express();
//for top.gg
const Topgg = require('@top-gg/sdk');
const webhook = new Topgg.Webhook("4N8eXCvZHjpfwt");

server.all('/', (req, res)=>{
    res.send('Your bot is alive!')
})

function keepAlive(){
    server.listen(3000, ()=>{console.log("Server is Ready!")});
}

server.post("/dblwebhook", webhook.listener(vote => {
  // vote will be your vote object, e.g
  console.log(vote.user) // 395526710101278721 < user who voted\
  user=client.users.cache.get(vote.user);
  client.channels.cache.get('766908428411994134').send('Thank you ${user} for voting!!');
  // You can also throw an error to the listener callback in order to resend the webhook after a few seconds
}));

module.exports = keepAlive;
lyric mountain
#

uh oh

earnest phoenix
#

the error should be client is undefined

lyric mountain
#

keep your webhook auth secret

wheat mesa
#

Gotta regen that now!

lunar cove
#

no error ๐Ÿ™‚

earnest phoenix
#

The error will only happen when a user votes

lunar cove
earnest phoenix
#

Because it will try to send a message to vote.user

lunar cove
lyric mountain
lunar cove
earnest phoenix
#

You need to pass the client variable to server.js

#

lazy approach:

module.exports = client => {
keepAlive();
the rest of your code in server.js
}

// index.js
keepAlive(client);
#

Hmm

#

Will do rn

#

Ll

#

sussy baka above

lunar cove
earnest phoenix
#

i meant put all the code in server.js there

#

except the last line

lunar cove
#
user=client.users.cache.get(vote.user);
  client.channels.cache.get('766908428411994134').send('Thank you ${user} for voting!!');```
this, right ? or whole ?
earnest phoenix
#

whole

#

except the last line where you put your old module.export

lunar cove
#

won't it make server.js useless ?

earnest phoenix
#

It wont

#

You're just going to run the file but after giving it access to client

lunar cove
#

Well the basic intention of server.js was to reduce the clutter in index.js but it's opposite now๐Ÿ˜…

earnest phoenix
#

ikr

#

code splitting with module.exports makes it easier to read and debug but it adds two extra lines to every file

lyric mountain
#

if the cost for easier debugging is 124192804 extra lines it's still worth it

earnest phoenix
#

and then we have this:

const thing = require("./../../../../../components/path/to/smth/aaaaa/got_the_file.js");
#

i still dont know how to use absolute imports in esbuild

fresh bluff
#

LETS GO!

lyric mountain
#

just put the full path

earnest phoenix
#

bruh

#

that's 3 more folders

lyric mountain
#

like C:/files/more files/da files/file.txt

lunar cove
#

So

index.js

console.log('Beep beep! ๐Ÿ‘‹');

const keepAlive = require('./server');
const Discord = require('discord.js');
const client = new Discord.Client();
module.exports = client => {
keepAlive();
const express = require('express');
const server = express();
//for top.gg
const Topgg = require('@top-gg/sdk');
const webhook = new Topgg.Webhook(process.env['WEBHOOKAUTH']);

server.all('/', (req, res)=>{
    res.send('Your bot is alive!')
})

function keepAlive(){
    server.listen(3000, ()=>{console.log("Server is Ready!")});
}

server.post("/dblwebhook", webhook.listener(vote => {
  // vote will be your vote object, e.g
  console.log(vote.user) // 395526710101278721 < user who voted\
  // You can also throw an error to the listener callback in order to resend the webhook after a few seconds
}));
}

keepAlive(client);
client.login(process.env['BOTTOKEN']);

client.on('ready', () =>{
    console.log("Bot is ready !!");
    client.user.setActivity('Tracking Votes', { type: "LISTENING" }).catch(console.error)
})

const commandHandler = require('./commands');

client.on('message', commandHandler);```
> server.js
```module.exports = keepAlive;```
lyric mountain
lunar cove
lunar cove
#

bottom

earnest phoenix
earnest phoenix
lunar cove
#

That's what I have, cut pasted whole there as u said, I misunderstood ?

earnest phoenix
#

oh i got it

#

you placed server.js in the wrong place lmao

lunar cove
#

what

earnest phoenix
#

anyways i think that should be good

lunar cove
#

I have always used it in root

earnest phoenix
#

just put the keepAlive(); after function keepAlive() {}

#

also keepAlive functions dont work anymore

#

try uptimerobot

lunar cove
earnest phoenix
#

ig it should work

#

try to test your bot with a test vote

lunar cove
#

It feels wierd server.js is empty and index.js is cluttered

earnest phoenix
#

(the top.gg test one not the replit)

lunar cove
earnest phoenix
#

server.js is empty

lunar cove
lunar cove
#

nearly empty

earnest phoenix
#

lmfao

#

this was what your code was supposed to be

server.js

module.exports = client => {
anything and EVERYTHING server.js does and is supposed to do pls put it here i beg you
}
#

im off to sleep rn bye

lunar cove
#

index.js

console.log('Beep beep! ๐Ÿ‘‹');

const keepAlive = require('./server');
const Discord = require('discord.js');
const client = new Discord.Client();


keepAlive(client);
client.login(process.env['BOTTOKEN']);

client.on('ready', () =>{
    console.log("Bot is ready !!");
    client.user.setActivity('Tracking Votes', { type: "LISTENING" }).catch(console.error)
})

const commandHandler = require('./commands');

client.on('message', commandHandler);```

> server.js
```javascript
module.exports = client => {
  const express = require('express');
  const server = express();
  //for top.gg
  const Topgg = require('@top-gg/sdk');
  const webhook = new Topgg.Webhook(process.env['WEBHOOKAUTH']);

  server.all('/', (req, res)=>{
      res.send('Your bot is alive!')
  })

  function keepAlive(){
      server.listen(3000, ()=>{console.log("Server is Ready!")});
  }

  server.post("/dblwebhook", webhook.listener(vote => {
    // vote will be your vote object, e.g
    console.log(vote.user) // 395526710101278721 < user who voted\
    // You can also throw an error to the listener callback in order to resend the webhook after a few seconds
  }));
}

module.exports = keepAlive;```

Final, right ?
#

imo depends on how proficient are you in discord.py

stable nimbus
#

I've gotten to where I am pulling my commands, but I am only trying to pull certain ones, should I be filtering my commands instead of immediately mapping? Or is there a way I can do this? I am working on pulling certain commands from one category or location, which is administration commands, but instead I get all commands, and I am pretty sure I am just doing it wrong.

const response = [...client.commands].map(
                            (value) => value[0].toString().toUpperCase() + value.slice(1).toString().toLowerCase()[
                                client.commands.filter(
                                    (cmd) => cmd.location == 'Administration'
                                ).size
                            ]+`\n===\n ${client.commands
                            .filter((cmd) => cmd.location == 'Administration')
                            .map((value) => value.name)
                            .join(', \n')
                            }`
                        );

Thanks in advance.

fresh bluff
#

I MADE A WORKING BOT

solemn latch
#

djs is typically known for being behind tbh

fresh bluff
stable nimbus
fresh bluff
#

AND I DON'T NEED TO BE ON REPLIT THE WHOLE TIME TO KEEP THE BOT UP

#

Oh wait i do

lyric mountain
#

6 remaining

boreal iron
stable nimbus
lunar cove
lunar cove
stable nimbus
#

Paid hosting will always be better, I personally recommend Contabo but that is up to you who you go with, if you're just starting out try IcedHostLLC, very professional team and very very cheap.

lyric mountain
#

code being public is not an issue

#

less resource is

#

5 remaining

earnest phoenix
stable nimbus
wheat mesa
#

Free host scavenger hunt

fresh bluff
#

How do i make my bot stay on always

lyric mountain
wheat mesa
#

pay for a host

fresh bluff
#

I don't have money ๐Ÿ˜ฆ

wheat mesa
stable nimbus
#

Get job

fresh bluff
#

can't

stable nimbus
#

This ain't for you without money

wheat mesa
#

personally I use Oracle as a free host

lyric mountain
#

Oracle zoomeyeszoomeyeszoomeyeszoomeyeszoomeyes

fresh bluff
stable nimbus
wheat mesa
#

Granted it's not a lot of resources

boreal iron
#

๐Ÿคฆโ€โ™‚๏ธ

lunar cove
#

Well for starting out free ones are great

wheat mesa
#

Oracle works fine for a small bot

lunar cove
#

try gcs or heroku, free but good

lyric mountain
#

oracle is the total inverse of "customer friendly"

#

if with contabo you can call em for a pizza party

wheat mesa
#

I chose Oracle because it was a host with 24/7 uptime and I won't get charged unless I upgrade my account

stable nimbus
#

The opposite actually for oracle

earnest phoenix
wheat mesa
#

Whereas with AWS and stuff they might slap you with a bill if you have overages

lyric mountain
#

oracle is that guy who'll take the whole pizza box, throw into ur face and run to the street freaking out

stable nimbus
lunar cove
# earnest phoenix THAT'S more like it Just one line to change Remove the second module.exports = k...

New error coming now

    at checkListener (events.js:110:11)
    at _addListener (events.js:347:3)
    at Client.addListener (events.js:405:10)
    at /home/runner/AS-bot/index.js:18:8
    at Script.runInContext (vm.js:130:18)
    at Object.<anonymous> (/run_dir/interp.js:209:20)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)```
earnest phoenix
lunar cove
wheat mesa
#

I'll eventually upgrade to a paid host once I need to

earnest phoenix
stable nimbus
wheat mesa
#

What

lyric mountain
#

hm what?

stable nimbus
#

Legit.

wheat mesa
lyric mountain
#

all sites have all 3 elements

stable nimbus
#

That message yeh

#

Sorry

lyric mountain
#

it's like the holy trinity of webdevving

wheat mesa
#

js handles the backend logic, CSS and HTML are for frontend development

lyric mountain
#

js also for frontend logic

lunar cove
earnest phoenix
stable nimbus
#

Yeah, mine is literally written in js, since I made it with EJS and I'm having so many issues with it.

earnest phoenix
#

that's a you problem

lyric mountain
#

the site can be made with anything, but will be presented to the user as a html/css/js site

earnest phoenix
#

i haven't done a command handler for 4 months

stable nimbus
#

I had to learn how to make mine, and I had to make it better because I wanted everything organized because OCD

#

Which I still need help on my problem

#

Obsessive Compulsive Disorder,

fresh bluff
#

HOW DO I HOST MY BOT 24/7

lunar cove
#

ohh ok

lyric mountain
fresh bluff
#

๐Ÿ˜ฆ

earnest phoenix
#

pwnfunction on youtube found an http header that can serve as an equivalent of the link tag in html but there is no html served in the response body
dude used some nasty css to rickroll people
here's the header name: ||never gonna give you Link||

wheat mesa
#

Pay for a host!

#

Paid hosts are always gonna be better than free hosts

#

Free hosts have strings attached

quaint wasp
#

is there a simple way to detect if there is "Missing permission" error in your code in your index and then simply make it do something like return; ?

stable nimbus
quaint wasp
#

(Discord.js v12.5.6)

lunar cove
#

@earnest phoenix it's stopped working now, earlier it was registering userid on console but that too ain't happening Kanna_Cry

lyric mountain
#

contabo is like 6.99

earnest phoenix
#

Ah yes Discord.js v125.6 the version we finally get slash command support

lyric mountain
#

what's that? a starbucks coffee?

#

once a month

quaint wasp
#

lol

earnest phoenix
lunar cove
earnest phoenix
#

alr

stable nimbus
earnest phoenix
#

well did you try to use a test vote

split hazel
wheat mesa
#

From what I've heard, hetzner gives the most raw specs for the price, never used it though.

lunar cove
#

test vote is down so i tried with alt account

earnest phoenix
#

it should log smth on test vote

wheat mesa
stable nimbus
split hazel
#

i can make a one time investment and buy a small express and get some coffee beans and cream and im all set

quaint wasp
#

like client.on('MISSINGPERMISSIONS', () => {

}) ?

stable nimbus
lunar cove
#

index.js

console.log('Beep beep! ๐Ÿ‘‹');

const keepAlive = require('./server');
const Discord = require('discord.js');
const client = new Discord.Client();


keepAlive(client);
client.login(process.env['BOTTOKEN']);

client.on('ready', () =>{
    console.log("Bot is ready !!");
    client.user.setActivity('Tracking Votes', { type: "LISTENING" }).catch(console.error)
})```

> server.js
```javascript
  module.exports = client => {
  const express = require('express');
  const server = express();
  //for top.gg
  const Topgg = require('@top-gg/sdk');
  const webhook = new Topgg.Webhook(process.env['WEBHOOKAUTH']);

  server.all('/', (req, res)=>{
      res.send('Your bot is alive!')
  })

  function keepAlive(){
      server.listen(3000, ()=>{console.log("Server is Ready!")});
  }

  server.post("/dblwebhook", webhook.listener(vote => {
    // vote will be your vote object, e.g
    console.log(vote.user) // 395526710101278721 < user who voted\
    client.channels.cache.get('766908428411994134').send('Thank you');
    // You can also throw an error to the listener callback in order to resend the webhook after a few seconds
  }));
}```
earnest phoenix
stable nimbus
split hazel
#

though in the uk its a little cheaper

earnest phoenix
stable nimbus
# quaint wasp alr

Keep the following in mind, just because you have those two things does NOT mean that you will be able to figure out the permission instantly, figure out what permissions your bot needs, and tailor error messages to such, I will give you an example from my code.

lunar cove
wheat mesa
#

detritus moment mmulu ts onPermissionsFailClient(context: Command.Context, failed: bigint[]) {}

fresh bluff
#

Hey guys I need some help again

#

Where do i put this code in

@bot.event
async def on_ready():
change_status.start()
print("Your bot is ready.")

rose warren
#

Wait i thought you went to learn python about an hour ago?

stable nimbus
# lunar cove It is meant to be run in index.js , right ? That's what I learned from tutorial...

From Message.JS for The RP Bot

//If the permission for sending messages is denied for the bot, alert the owner, if can't alert owner, leave
if(!message.guild.me.hasPermission('SEND_MESSAGES')) {
            const owner = await client.users.cache.get(message.guild.ownerID);
            return owner.send(`Hey <@${message.guild.ownerID}>! I am missing permissions in \`${message.guild.name}\`! I need the "Send Messages" permission please!`).catch(() => message.guild.leave());
        };
//If the bot is requested to embed things but can't due to 'EMBED_LINKS' being denied
if(!message.guild.me.hasPermission(`EMBED_LINKS`)) {
            if (embeds == 'no') {
                //
            }
            else {
                return message.channel.send(`Hey! Embeds are enabled for this server, but I can't \`Embed Links\`!`);
            };
        };
//If the bot is requested to delete commands after running them but can't 'MANAGE_MESSAGES'
        if(!message.guild.me.hasPermission(`MANAGE_MESSAGES`)) {
            if(messagedel == 'no') {
                //
            }
            else {
                await message.channel.send(`Hey! Message Deletion is enabled in this server! But I can't \`Manage Messages\`!`);
            };
        };

Just as an example.

fresh bluff
#

i did but i need my bot link

valid frigate
#

this is a golang question

i have a set list of structs that follow a specific interface as follows:

type A interface {
  ...
  Configuration() B
}

type B struct {
  ...
  Configuration T
}

type StructOne struct {
  Configuration B
  ...
}

(s *StructOne) Configuration() {
  return s.Configuration
}

the problem is that the configuration is set as a config value, and if left empty, the Configuration field on StructOne will be nil, and i don't think i have to check for a nil value every time, so is there a better way to do this? (essentially StructN all have the same field, Configuration, but they each have their own unique fields as well)

lunar cove
stable nimbus
#

Replied to the wrong person. Sorry Rimuru.

quaint wasp
#

alright

#

lol

stable nimbus
#

But yeah thats just some of my error catchers for the server itself on the message, that's what I can handle.

lyric mountain
#

missing )

tame wraith
#

hello everyone

stray seal
#

What is my Error? I am trying to get .ping .

rose warren
#

You're not passing db to your command

stray seal
rose warren
#

In index.js where you have the execute() call

#

You're not passing the db to the command

pale vessel
#

it's not that they didn't pass it, they didn't define it in the index file

stray seal
#

OK Thanks

#

Let me do it now

#

What is this File:
json.sqlite
I ran my code for my tenth time and just got that

quartz kindle
#

that file is created by quick.db

#

its where all the data you save with quick.db is stored

stray seal
#

alr

#

What is my Error for this Clear Command?

#
Promise { <pending> }
Hint: hit control+c anytime to enter REPL.
MythicalBot is online
/home/runner/MythicalDreams-Bot/index.js:35
            client.command.get('clear').execute(message, args);
                           ^

TypeError: Cannot read property 'get' of undefined
    at Client.<anonymous> (/home/runner/MythicalDreams-Bot/index.js:35:19)
    at Client.emit (events.js:314:20)
    at Client.EventEmitter.emit (domain.js:483:12)
    at MessageCreateAction.handle (/home/runner/MythicalDreams-Bot/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
    at Object.module.exports [as MESSAGE_CREATE] (/home/runner/MythicalDreams-Bot/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
    at WebSocketManager.handlePacket (/home/runner/MythicalDreams-Bot/node_modules/discord.js/src/client/websocket/WebSocketManager.js:384:31)
    at WebSocketShard.onPacket (/home/runner/MythicalDreams-Bot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
    at WebSocketShard.onMessage (/home/runner/MythicalDreams-Bot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10)
    at WebSocket.onMessage (/home/runner/MythicalDreams-Bot/node_modules/ws/lib/event-target.js:132:16)
    at WebSocket.emit (events.js:314:20)
repl process died unexpectedly: exit status 1
๎บง ```
rose warren
#

index.js line 35

stray seal
#

I will

#

i am

#

can someone help with this error tho?

quaint wasp
#

umm

stray seal
#

BREH

quaint wasp
#

I forgot how to turn json thing "[object Object]" to string ๐Ÿ˜….. I tried .toSting() but no work

rose warren
#

It's better than cloning a GitHub repo

quaint wasp
#

ooooo

#

right

stray seal
quaint wasp
#

thanks

stray seal
rose warren
#

It says your clear command isn't defined in commands

stray seal
quartz kindle
#

i mean

#

most of those errors should be pretty easy to understand

stray seal
#

. . .

quartz kindle
#

do you have to ask about every single error you get?

#

if something is undefined, it means it doesnt exist or your code cant find it. so look for typos, then look for mistakes

stray seal
#

@quartz kindle where the Error Here? I dont see it.

#

I am confused

#

I have a line there tho

#
await message.channel.messages.fetch({limit: args[0]}).then(messages =>{
                message.channel.bulkDelete(messages);

So go from that to this?

message.channel.messages.fetch({limit: args[0]}).then(messages =>{
                message.channel.bulkDelete(messages); ```
#

New Error:

Promise { <pending> }
/home/runner/MythicalDreams-Bot/commands/clear.js:11
        await message.channel.messages.fetch({limit: a
Promise { <pending> }
Hint: hit control+c anytime to enter REPL.
MythicalBot is online
#

@swift umbra

#

No it is not lol

#

I copied the Con

#

I just got that Error

#

I dont

#

ReRunning ^

#

@swift umbra ^^

#

Yeah

#

I reran it too

#

After a while it says it is online.

#

It is online but the code is broke LOL

#

Let me test

#

yes LOL.

#

I need this fixed with the error

#

Because it will Confuse me

#

I did.

#

After i run it, it is taking a minute to show that it is online.

severe pike
#

how can i put images into my top.gg description?

quartz kindle
#

markdown or html?

rose warren
#
<img src="" />
quartz kindle
#

^ for html

#

![IMAGE_NAME](https://FULL_DIRECT_URL_TO_IMAGE.png)
^ for markdown

wheat mesa
#

How do I edit the script args for a pm2 process?

#

And/or get rid of the script args entirely

quartz kindle
#

cli or ecosystem file?

wheat mesa
#

cli

quartz kindle
#

wait, what cli args exactly?

wheat mesa
#

I accidentally put some extra args on the pm2 script earlier, all I'd like it to run is npm start but I accidentally added args after that

quartz kindle
#

well you can always delete + start again

wheat mesa
#

I suppose

quartz kindle
#

besides that, it should be --node-args=

#

or something

#

--interpreter-args <arguments> interpreter options (alias of --node-args)

#

--node-args <node_args> space delimited arguments to pass to node in cluster mode - e.g. --node-args=โ€--debug=7001 --trace-deprecationโ€

wheat mesa
#

Just got it

severe pike
#

thanks guys!

wheat mesa
#

111mb of RES usage upon startup (using top). Does that seem about right for 17 cached guilds with ~40 members and users cached?

errant flax
#

how do i make a request in html inside
<script> tag

#
const express = require("express")
const app = express()

//app.use(express.json())
app.use("view engine","ejs")

app.get("/",(req,res)=>{
  res.render("home")
})

app.listen(2000,()=>{
  console.log(`Listening to port 2000`)
})

?

winged juniper
#

How

split hazel
#

you replace it

winged juniper
#

Ok i well dot it naw

boreal iron
quartz kindle
#

or the native fetch api

split hazel
#

or by selling your soul to the devil

errant flax
wheat mesa
boreal iron
#

thanks Waffle

#

was about to say it

wheat mesa
#

lol

stable nimbus
quartz kindle
#

what are you trying to do?

stable nimbus
#

I am trying to pull literally only 2 commands from one folder and I can't for the life of me.

#

I pull them from the cache so I have to use the collection.

#

But I am also updating my DJS so until then I'm not looking for help atm.

wheat mesa
#

Just to make sure, these intents aren't privileged, right?

      GatewayIntents.GUILDS,
      GatewayIntents.GUILD_MESSAGES,
      GatewayIntents.GUILD_MESSAGE_REACTIONS,
      GatewayIntents.DIRECT_MESSAGES,
      GatewayIntents.DIRECT_MESSAGE_REACTIONS,
quartz kindle
#

if client.commands is a collection of commands, you can directly filter it

#

client.commands.filter(something)

wheat mesa
#

Alright, time to disable those switches on the prod bot then mmLol

stable nimbus
stable nimbus
long crow
#

${details.description ??= 'Not Available'}`.replace(/<br>|<b>|<i>|<\/b>|<\/br>|<i>|<\/i>/gm, ' ').slice(0, 1600) Any idea how can I make it instead of cut of because of the length, and become hanging, I want it like (...more) at the end of sentence. I can see padEnd, but not sure how to implement it

boreal iron
#

Can you provide a screenshot to see what you mean by "become hanging"?

long crow
boreal iron
#

2 possibilities:

  • cutting of the last sentence (match ". ")
  • splitting your already cutted text by / +/g
    to replace the last item of the array (in your case "Worki) by a โ€ฆ for example
earnest phoenix
#

Anyone now how; When the bot would restart, it would check if the user has a role, in a preset embed, if a user was removed from a role, it would update the pre-sent embed?

#

if that makes sense

long crow
earnest phoenix
#

how to fix dis

latent heron
#

Question for Namecheap domain owners:

#

do I need to buy the Web Hosting package in order to get access to FTP?

split hazel
#

why else would you need ftp

#

if you're not gonna host

latent heron
#

some domain web host providers offer it for free

#

that's why

split hazel
#

in namecheap you need to pay extra for hosting

wheat mesa
#

(Index.js at line 187)

earnest phoenix
#

sure

#

@wheat mesa

waxen bough
#

let's see how further this goes

long crow
#

why es5, why not es6 ๐Ÿ‘€

waxen bough
#

idk how to set babeljs

#

i just started using it

split hazel
#

@waxen bough install my packages and config above

#

you have to install the plugins too

waxen bough
#

ahh thanks i will install it

#

nodejs 12 is es6 right?

long crow
mild agate
#

what are context menus?

#

anyone got a screenshot?

long crow
waxen bough
#

optional chaining is not used in djs

#

i guess the plugin is not necessary

waxen bough
#

damn

long crow
#

The few last thing I need to clean up my codes I guess. @ts-expect-error go brrrr

pale vessel
#

Inconsistent casing go brrrrrrr

long crow
#

Hahaha

#

it named CustomCasing

rocky hearth
#

Can I change order of keys in an js object?
So that when I do Object.values() it gives different result

pale vessel
#

Sort them

#

Use Object.entries(obj), sort the entries and turn it back to an object by using Object.fromEntries(entries)

arctic notch
#

Can anyone knows about it

earnest phoenix
# arctic notch

EnmapPathError: The Key "86550994630193664" does not exist in enmap "settings" at Map.get

arctic notch
#

How to solve

long crow
#

https://sourceb.in/rHcJdOhE5b Anyone can redirect me how I can get the commandName and customId without resorting the use of ts-expect-error in this code?

wheat mesa
#

Whatโ€™s the warning itโ€™s producing without ts-expect-error?

long crow
#

property commandName does not exist on interaction, well because it exist when the interaction is interaction.isCommand()

arctic notch
#

anyone knows about enmap database

cinder patio
long crow
cinder patio
#

then you can't

long crow
#

oh, just leave it be then, aight

cinder patio
#

You can also just use ts

long crow
#

Evie, the creator of the lib is there too

arctic notch
#

thanks

earnest phoenix
#

How would I display all the users in a role?

errant python
#

Perhaps I am truly an idiot, but discord.js doesn't seem to be sending my command options properly (slash)

#

Is there some sort of bizzaro reason that it does this? I don't handle my commands via their "command register" garbage, so if I am being forced to get the options by using their system I will be angry

#

It should just send me the websocket data- but it isn't, I tested it myself, I can get the command options data without the library just fine

long crow
#

I register from message command last time, and now registering via slash command itself

errant python
#

Not too sure what you mean by that

#

I don't use message based commands at all and don't plan to

long crow
#

I only used it once to register my deploy command

#
module.exports = {
    name:'deploy',
    description: 'Deploy global slash command(s)',
    guildOnly:true,
    owner:true,
    /**
   * @param {import('discord.js').Message} message
   */
    async run(message) {
        // @ts-expect-error
        const { SlashCommands } = message.client;
        const guildCommand = await SlashCommands.get('deploy');
        await message.client.application.commands.create(guildCommand, guildCommand.guildId);
        message.channel.send({ content:'Done' });

    },
};```
#

then the rest, I register from the slash command deploy

errant python
#

Yes but I already have slash commands registered with the api, I did it myself without the library- that's not my issue

long crow
#

no idea then

errant flax
#

how to check which subcommand group was used?

errant python
#

Update: Found out my answer

#

2 things: discord.js is stupid, and if you want to get command options you must use their command registry system mmLol

light gorge
#

With upcoming api changes how are we supposed to the server owners to re invite the bots to support the new interactions

#

i know some bots automatically got the permissions, like groovy and dank memer

long crow
#

The server owner don't really need to reinvite, just need to reauthorize with relevant scope

light gorge
#

yeah but how am i supposed to get hem to do that

#

i wouldn't trust server owners to actually do it

errant flax
#

how to check which subcommand group was used?
anyone?

light gorge
#

they'd kick the bot and forget about it

earnest phoenix
#

How would I display all the users in a role?

long crow
#

On your command handler, attach button link with the relevant scope you needed

light gorge
#

well good thing my bot is already verified, because I am deffinitly going to drop below the 75 server mark

long crow
light gorge
#

speaking of suspicious links

long crow
#

haha, lmao

waxen bough
#

perfect timing

light gorge
#

wait how did he at everyone

waxen bough
#

you can type @ everyone but they cannot be pinged

light gorge
#

or did a user name themselves everyone

errant flax
#

how to check which subcommand group was used?

earnest phoenix
#

Code:
let owners = message.guild.roles.cache.get('871584074937028648ID').members.map(m=>m.user.id);

Error:

(node:3419) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'members' of undefined
errant flax
earnest phoenix
#

Same lmao

earnest phoenix
#

Wym?

long crow
#

No love for appleduck

errant flax
#

remove the members part

#

like
let owners = msg.guild.roles.cache.get("id")

errant flax
earnest phoenix
wheat mesa
errant flax
#

just checking if the role exist

wheat mesa
#
let owners = message.guild.roles.cache.get('871584074937028648ID').members.map(m=>m.user.id);
                                                              ^^
#

Why is there an ID at the end?

#

That's why it doesn't work

earnest phoenix
#

ITs trying to @ the user .

errant flax
errant flax
#

numbersID

#

remove the ID part from .get()

earnest phoenix
#

Its trying to do this.

errant flax
#

remove the ID at the end of the role id

wheat mesa
errant flax
#

i thought u were pointing at the map misosface

wheat mesa
#

formats differently on our screens ig

errant flax
wheat mesa
#

Yeah, you're on mobile so it's different

earnest phoenix
#

So remove .user.id?

wheat mesa
#

No...

earnest phoenix
#

or just members.map()?

#

๐Ÿ˜•

wheat mesa
#

Neither...

errant flax
earnest phoenix
#

I haven't made a Staff List in like a year now.

wheat mesa
#

You're not passing in a valid id as your role

earnest phoenix
#

The Role ID is not valid?

wheat mesa
#

You're passing in '871584074937028648ID'

errant flax
#

remove the the ID part at the end of the role id

wheat mesa
#

The 'ID' at the end makes it invalid

earnest phoenix
#

PFFFT

earnest phoenix
#

@wheat mesa It does not error no more, but it doesn't display the Users in the role...

#
 
      let owners = message.guild.roles.cache.get('871584074937028648').members.map(m=>m.user.id);

      const embed = new Discord.MessageEmbed()
      .setAuthor(message.author.tag, message.author.displayAvatarURL({ dynamic:true }))
      .setDescription(`**Top Brass** - <@&871584074937028648>\n> - ${owners}`)
      message.channel.send(embed)
      ```
wheat mesa
#

owners is an array of user IDs

earnest phoenix
#

So its a map within a map is what I am doing O_O

wheat mesa
#

Log owners and see what shows up

earnest phoenix
#

[]

wheat mesa
#

Does anyone have the role?

earnest phoenix
#

Yes

#

4 People

#

I tried this: ```
.setAuthor(message.author.tag, message.author.displayAvatarURL({ dynamic:true }))
.setDescription(**Top Brass** - <@&871584074937028648>\n> - ${message.guild.roles.cache.get('871584074937028648').members.map(m=>m.user.id)})

#

Doesnt work

wheat mesa
#

Well, you have nothing in your array of members to begin with

earnest phoenix
#

eh?

wheat mesa
earnest phoenix
#

mhm

#

What do I do to fix that? ๐Ÿคฃ

wheat mesa
#

Try logging the value of message.guild.roles.cache.get('roleid')

earnest phoenix
#
  },
  id: '871584074937028648',
  name: 'Alena Black Ops',
  color: 1315860,
  hoist: true,
  rawPosition: 144,
  permissions: Permissions { bitfield: 2146959359 },
  managed: false,
  mentionable: false,
  deleted: false
}```
wheat mesa
#

I don't see any members property there

earnest phoenix
wheat mesa
#

I'm not sure if you need a certain intent to access the roles or not, but what intents do you have enabled?

earnest phoenix
#

0

wheat mesa
#

Actually I don't think you need intents for that

#

Hold on lemme test something

errant flax
#

its not showing the member bc probably there rnt cached

wheat mesa
#

^^

earnest phoenix
#

Whats da fix to that then?

errant flax
#

use MEMBER partial/fetch the member

earnest phoenix
#

When I log it, it says it got 0 people with the role

#

When I do other roles, its says it got 1 person with them.

#

How can I fix this?

light gorge
#

for the user to re auth the bot they need to kick it right?

earnest phoenix
#

no

#

you can invite a bot again without kicking and it doesn't matter

light gorge
#

ok ty

winged juniper
#
		let messages = await message.channel.messages.fetch({limit:100});
		messages = messages.values();
		messages = messages.filter((m) => !m.pinned);

Why i have a error in messages.filter discord.js v13

errant flax
#

console log messages

winged juniper
#

Ok

winged juniper
errant flax
#

log messages

winged juniper
#

Ok 1 sec

winged juniper
lunar cove
#

I am trying to export the client constant from my index.js to server.js to be able to use client.channels.cache.get('766908428411994134').send('Thank you'); but my keepalive(); function is giving error TypeError: keepAlive is not a function , these are my files AA_Gab_Bow

index.js

console.log('Beep beep! ๐Ÿ‘‹');

const keepAlive = require('./server');
const Discord = require('discord.js');
const client = new Discord.Client();
module.exports.Gclient = client; // Exporting client

keepAlive();
client.login(process.env['BOTTOKEN']);

client.on('ready', () =>{
    console.log("Bot is ready !!");
    client.user.setActivity('Tracking Votes', { type: "LISTENING" }).catch(console.error)
});```
> server.js
```javascript
//Importing client
const index = require("./index.js");
const client = index.Gclient ;
//Importing express and making express
const express = require('express');
const server = express();
//for top.gg
const Topgg = require('@top-gg/sdk');
const webhook = new Topgg.Webhook("4N8eXCvZHjpfwt");
//Keeping bot always on
server.all('/', (req, res)=>{
    res.send('Your bot is alive!')
})

function keepAlive(){
    server.listen(3000, ()=>{console.log("Server is Ready!")});
}
//Vote confirmation
server.post("/dblwebhook", webhook.listener(vote => {
  // vote will be your vote object, e.g
  console.log(vote.user) // 395526710101278721 < user who voted\
  client.channels.cache.get('766908428411994134').send('Thank you');
  // You can also throw an error to the listener callback in order to resend the webhook after a few seconds
}));

module.exports = keepAlive;

When I wasn't using the client it was working fine, happened only when I imported client , can I get some pointers ?

winged juniper
lunar cove
#

in index.js ?

winged juniper
#

Yes

lunar cove
#

Getting this as error TypeError: keepAlive.execute is not a function

winged juniper
#

Do you use discord.js v13?

lunar cove
#

Also one more thing the top console.log('Beep beep! :wave:'); is logging in console twice, I dunno why superhappy

lunar cove
#

It's 12.2.1, checked rn

winged juniper
#

You need to use this const { keepAlive } = require('./server.js')

#

Replace this back keepAlive()

lunar cove
#

still TypeError: keepAlive is not a function

#

I have another bot which I made after learning the tutorial it has this code

index.js

console.log('Beep beep! ๐Ÿ‘‹');

const keepAlive = require('./server');
const fetch = require('node-fetch');
const Discord = require('discord.js');
const client = new Discord.Client();

keepAlive();
client.login(process.env['BOTTOKEN']);

client.on('ready', () =>{
    console.log("Bot is ready !!");
    client.user.setActivity('Prefix is: `&`', { type: "LISTENING" }).catch(console.error)
})

const commandHandler = require('./commands');

client.on('message', commandHandler);```
> server.js
```javascript
const express = require('express');
const server = express();

server.all('/', (req, res)=>{
    res.send('Your bot is alive!')
})

function keepAlive(){
    server.listen(3000, ()=>{console.log("Server is Ready!")});
}

module.exports = keepAlive;```

Here keepalive is working fine, I guess in the new bot there is some issue with importing client, I think I messsed up there but can't figure it out .
#

@winged juniper

latent heron
#

@errant forge

#

fuck wrong one

#

@slender thistle

#

i hope you liek my code

#

because "organization"

slender thistle
#

That's

#

Acceptable

earnest phoenix
#

Hello shiv

slender thistle
#

Hello Mist

lunar cove
earnest phoenix
lunar cove
#

keepAlive.keepAlive is not a function

earnest phoenix
#

then console log keepalive

lunar cove
earnest phoenix
#

just do it and tell me what did it log

lunar cove
earnest phoenix
#

weird

lunar cove
near stratus
lunar cove
lunar cove
#

TypeError: keepAlive is not a function

woeful pike
lunar cove
#

Well since you told I'm changing the name

woeful pike
#

I don't see anything with the exports that could be wrong but you never want to import from index.js

#

you have server.js importing from index.js importing from server.js importing from index.js..... etc

lunar cove
#

So how could I use client.user.setActivity('Tracking Votes', { type: "LISTENING" } in server.js ?

woeful pike
#

why not move all client stuff inside client.js and export a function that does that

#

and import client.js from index.js and server.js so you don't have circular dependencies

near stratus
#

so it should look like

function keepAlive(client){
  server.post("dbl", (req, res) => { 
    /* Some code */
    client.blah.blah.blah()
   }
  server.listen(3000, () => console.log("Server is on"))
}
module.exports = keepAlive
#

don't mind my code formatting

#

and in index.js

client.on("ready", () => {
  keepAlive(client)
  // The rest of your code
})
lunar cove
#

ok lemme try

lunar cove
woeful pike
#

have you tried to console.log what keepAlive is lol

lunar cove
# woeful pike have you tried to console.log what `keepAlive` is lol

Actually I am now trying what u said before to create a new client.js
did this in index.js and server.js

const dis = require('./client.js');
const client = dis.Gclient;```

and in client.js
```javascript
const Discord = require('discord.js');
const client = new Discord.Client();

module.exports.GClient = client;```
woeful pike
#

it's most likely because of a circular import problem. You're running the contents of index.js from server.js before actually exporting the function you need

lunar cove
woeful pike
#

as a golden rule of thumb, never import index.js

lunar cove
near stratus
near stratus
near stratus
#

Like you have the client
so why import ?

near stratus
lethal trout
#

code

const {
    Client,
    Message,
    MessageEmbed,
    MessageButton,
    MessageActionRow
} = require('discord.js');

module.exports = {
    name: 'tic',
    aliases: [''],
    description: '',
    usage: '',
    /** 
     * @param {Client} client 
     * @param {Message} message 
     * @param {String[]} args 
     */
    run: async (client, message, args, Discord) => {
        const embed = new MessageEmbed()
            .setColor('')
            .setTitle('ticket');

        const bt = new MessageActionRow()
            .addComponents(
                new MessageButton()
                .setCustomId('tic')
                .setLabel('Primary')
                .setStyle('PRIMARY'),
            );

        message.channel.send({
            embeds: [embed],
            components: [bt]
        });
    }
}```
index
```js
client.on('interactionCreate', async (interaction) => {
    await interaction.deferUpdate();
    if (!interaction.isButton()) {
        if (interaction.customID === 'tic') {
            interaction.editReply({
                content: 'hi'
            })
        }
    }
});```
err: wont send the message
near stratus
#

and don't import client

lunar cove
#

ohh ok

#

server.js

module.exports = (server) => {const express = require('express');
const server = express();
//for top.gg
const Topgg = require('@top-gg/sdk');
const webhook = new Topgg.Webhook("4N8eXCvZHjpfwt");
//Keeping bot always on
server.all('/', (req, res)=>{
    res.send('Your bot is alive!')
})

function keepAlive(server){
  server.post("/dblwebhook", webhook.listener(vote => {
  console.log(vote.user)
  client.channels.cache.get('766908428411994134').send('Thank you');
}))
  server.listen(3000, () => console.log("Server is on"))
}
}```
This is correct right ?
near stratus
near stratus
#

I told you just to replace the keepAlive line

near stratus
# lunar cove but this <:superhappy:854959390389174282>

server.js

const express = require('express');
const server = express();
//for top.gg
const Topgg = require('@top-gg/sdk');
const webhook = new Topgg.Webhook("4N8eXCvZHjpfwt");
//Keeping bot always on
server.all('/', (req, res)=>{
    res.send('Your bot is alive!')
})

module.exports = (server) => {
  server.post("/dblwebhook", webhook.listener(vote => {
  console.log(vote.user)
  client.channels.cache.get('766908428411994134').send('Thank you');
}))
  server.listen(3000, () => console.log("Server is on"))
}
}โ€Š
#

and please do
console.log(typeof keepAlive) in index.js

azure ore
#

Hey guys, i don't really know if this is something i could ask here but in case i'd be happy to get help ๐Ÿ˜…
I've added the ytdl core and all to my .js bot to make it play music, but sometimes it bugs and stops
All is left to do is to either clear the queue or stop him again, as it thinks it's still playing..
I'm pretty sure that this is a Server issue but if not might there be a solution for the bot not to freeze?
I don't think the code is needed, since it's a pretty standard music code, if im wrong i can just send it :)

lunar cove
#

index.js

console.log('Beep beep! ๐Ÿ‘‹');

const keepAlive = require('./server');
const Discord = require('discord.js');
const client = new Discord.Client();

keepAlive();
console.log(typeof keepAlive);
client.login(process.env['BOTTOKEN']);

client.on('ready', () =>{
    console.log("Bot is ready !!");
     keepAlive(client);
    client.user.setActivity('Tracking Votes', { type: "LISTENING" }).catch(console.error)
});```
like this , right ?
#

error

    at module.exports (/home/runner/AS-bot/server.js:12:10)
    at /home/runner/AS-bot/index.js:7:1
    at Script.runInContext (vm.js:130:18)
    at Object.<anonymous> (/run_dir/interp.js:209:20)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)
    at internal/main/run_main_module.js:17:47```![miosad](https://cdn.discordapp.com/emojis/855029779995951104.webp?size=128 "miosad")
near stratus
# lunar cove > error ```Cannot read property 'post' of undefined at module.exports (/hom...

aaaaaagggggghhhhhhhhhhhh fuck

module.exports = (server) => {
  const express = require('express');
  const server = new express();
  const Topgg = require('@top-gg/sdk');
  const webhook = new Topgg.Webhook("4N8eXCvZHjpfwt");
  server.all('/', (req, res)=>{
    res.send('Your bot is alive!')
  })
  server.post("/dblwebhook", webhook.listener(vote => {
  console.log(vote.user)
  client.channels.cache.get('766908428411994134').send('Thank you');
}))
  server.listen(3000, () => console.log("Server is on"))
}
}โ€Šโ€Š
lunar cove
near stratus
#

index.js

console.log('Beep beep! ๐Ÿ‘‹');

const keepAlive = require('./server');
const Discord = require('discord.js');
const client = new Discord.Client();

console.log(typeof keepAlive);
client.login(process.env['BOTTOKEN']);

client.on('ready', () =>{
    console.log("Bot is ready !!");
     keepAlive(client);
    client.user.setActivity('Tracking Votes', { type: "LISTENING" }).catch(console.error)
});โ€Š
near stratus
lunar cove
#

works but with this

    at module.exports (/home/runner/AS-bot/server.js:12:10)
    at /home/runner/AS-bot/index.js:7:1
    at Script.runInContext (vm.js:130:18)
    at Object.<anonymous> (/run_dir/interp.js:209:20)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)
    at internal/main/run_main_module.js:17:47```
lunar cove
crimson kindle
#

Hello! Im making a command that send random emojis when u say ;randomemoji. Can anyone help please?

lunar cove
#

Ohh well there was an extra } in server.js I removed it too and it has started working , let's test it

near stratus
#

okay
I define server : Server is already defined
I don't define server: can't read property of undefined

near stratus
#

random emoji

crimson kindle
near stratus
lunar cove
#
    at /home/runner/AS-bot/server.js:11:3
    at /home/runner/AS-bot/node_modules/@top-gg/sdk/dist/structs/Webhook.js:99:23
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
767320732686352415
ReferenceError: client is not defined
    at /home/runner/AS-bot/server.js:11:3
    at /home/runner/AS-bot/node_modules/@top-gg/sdk/dist/structs/Webhook.js:99:23
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
767320732686352415
ReferenceError: client is not defined
    at /home/runner/AS-bot/server.js:11:3
    at /home/runner/AS-bot/node_modules/@top-gg/sdk/dist/structs/Webhook.js:99:23
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
767320732686352415
ReferenceError: client is not defined
    at /home/runner/AS-bot/server.js:11:3
    at /home/runner/AS-bot/node_modules/@top-gg/sdk/dist/structs/Webhook.js:99:23
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
767320732686352415
ReferenceError: client is not defined
    at /home/runner/AS-bot/server.js:11:3
    at /home/runner/AS-bot/node_modules/@top-gg/sdk/dist/structs/Webhook.js:99:23
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
767320732686352415
ReferenceError: client is not defined
    at /home/runner/AS-bot/server.js:11:3
    at /home/runner/AS-bot/node_modules/@top-gg/sdk/dist/structs/Webhook.js:99:23
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
767320732686352415
ReferenceError: client is not defined
    at /home/runner/AS-bot/server.js:11:3
    at /home/runner/AS-bot/node_modules/@top-gg/sdk/dist/structs/Webhook.js:99:23
    at processTicksAndRejections (internal/process/task_queues.js:97:5)```

So well it started working and is logging the userid in console but still it is not sending message in channel as client ain't working ![Kanna_Cry](https://cdn.discordapp.com/emojis/866718561853636649.webp?size=128 "Kanna_Cry")
near stratus
#

oh fuck

#

It's a typo

#

sorry

#

server.js

module.exports = (client) => {
  const express = require('express');
  const server = new express();
  const Topgg = require('@top-gg/sdk');
  const webhook = new Topgg.Webhook("4N8eXCvZHjpfwt");
  server.all('/', (req, res)=>{
    res.send('Your bot is alive!')
  })
  server.post("/dblwebhook", webhook.listener(vote => {
  console.log(vote.user)
  client.channels.cache.get('766908428411994134').send('Thank you');
}))
  server.listen(3000, () => console.log("Server is on"))
}
}โ€Šโ€Šโ€Š
#

I misspelled client for server

earnest phoenix
#

why is there a new in express

#

looks sus

nova basin
#

Help me please zerotwocry

earnest phoenix
#

We can't help you by magic
Show your code

near stratus
earnest phoenix
#

i can read your mind
Your mood is horny

woeful pike
#

you should really work on your mind reading skills if you want to get clients as a developer

lunar cove
pale vessel
#

`<@${vote.user}>`

lunar cove
#
client.channels.cache.get('766908428411994134').send('Thank you <@${vote.user}>');```this, right ?
woeful pike
#

getting pinged for every vote must be annoying

long crow
#

Immediately kick bot after getting pinged

umbral lake
#

Hey, its my code:

client.on("presenceUpdate", async (oldPresence, newPresence) => {
    if (!newPresence.activities[0]) return
    if (!newPresence.activities[0].state) return
    const guild = client.guilds.cache.get("848100598908846110")
    const role = guild.roles.cache.get("851390008086626314")
    if(newPresence.activities[0].state.includes(".gg/axd")) {
        if(!oldPresence.activities[0].state.includes(".gg/axd")) {
            newPresence.member.roles.add(role)
            guild.channels.cache.get("873487634377363486").send(`Merci <@${newPresence.user.id}> pour ton soutien !`)
        }
    } else if(oldPresence.activities[0].state.includes(".gg/axd")) {
        if(!newPresence.activities[0].state.includes(".gg/axd")) {
            newPresence.member.roles.remove(role)
        }
    }
});

when someone has the .gg
the bot spam the message :/

lunar cove
#

Well it's to for confirmation, I will try to add it in embed so pings won't work

waxen bough
#

i'd use user#tag

lunar cove
#

Well, for embeds what do you guys do, it must be tiring to write whole 10-15 lines for each embed, so do you like create an object or something else to use them ?

rose warren
#

I just wrote an embed. It doesn't take that long and looks better in the channel.

lunar cove
#

for every .send option ?

rose warren
#

What do you mean every send option?

lunar cove
#

Like if i use message.channel.send() multiple times in a file with if/else conditions , so would you write javascript {embed: { //Send a new embed title: "Embed 1", fields: [{ name: "Description", value: "The Description" }] }} this is every message.channel.send() ?

eternal elbow
#
  const { code } = req.query;
  const body = {
    client_id: process.env.CLIENT_ID,
    client_secret: process.env.CLIENT_SECRET,
    grant_type: "authorization_code",
    code: code,
    redirect_uri: process.env.CALLBACK_URL
  }
  fetch("https://discord.com/api/oauth2/token", {
    method: "POST",
    body: JSON.stringify(body),
    headers: {
      "Content-Type": "application/x-www-form-urlencoded"
    }
  }).then(res => {
    console.log(res)
  }).catch(e => {
    console.log(e)
  });

{
error: 'unsupported_grant_type',
error_description: 'Grant type None is not supported'
}

I do the exact same thing with Discord developers. What is wrong with this code?

summer acorn
#

I have a function where I can optionally pass a number (timestamp) to add another number to that instead of adding it to Date.now(), I am experiencing a little bit of an issue when I set it to 0 though, the ternary just takes 0 as false, how would I solve this and make the ternary ignore 0 as a binary value? preferably without adding more lines. also for reference, here is the line of code I am talking about

#

and it works when I make timestamp anything other than 0

#

I also know that adding another parameter for the ternary would work, but I would not prefer doing that

pale vessel
#

typeof timestamp === "number"?

summer acorn
#

ah yes actually good point, I didn't think of that

#

I just woke up and can't think code very well for another like half an hour kekw

#

thank you, flaze

modest maple
#

pepehmm Vote time, what's your preferred server less host?

rocky hearth
#

Hi, I am working on a react project. I hv a situation where i want the user to let download a txt file, which has some content copied from a textarea.

So how can I create a file and let user download it, on click of a button?

cinder patio
#

data URIs

quartz kindle
#

you have to send body like this

#

client_id=XXX&client_secret=XXX&grant_type=authorization_code

#

not like json

lunar cove
#

Umm, has anyone used repl.it database ?

eternal elbow
quartz kindle
#

the fetch api in js doesnt

#

other js libs might do

eternal elbow
#
 body: new URLSearchParams({
        'client_id': process.env.CLIENT_ID,
        'client_secret': process.env.CLIENT_SECRET,
        'grant_type': 'refresh_token',
        'refresh_token': userData.session.refreshToken
}),
``` By the way I solved it like this
quartz kindle
#

๐Ÿ‘

eternal elbow
#

Thanks

quartz kindle
#

fetch is considered a fairly low level api i believe, otherwise we wouldnt have a billion different http libs in js lmao

long crow
#

Ho ho ho, no more @ts-expect-error

quartz kindle
#

there is no best, just depends on what features you need

#

using fetch is fine, just a bit more "manual", which also makes it faster

#

another awesome lib tho is undici

#

undici is being developed by the node.js devs themselves and is a faster/better alternative to node's raw http

eternal elbow
quartz kindle
#

nope

eternal elbow
#

Or should I switch to undici?

quartz kindle
#

the more manual, the faster it is (usually)

#

you dont need to switch anything

#

fetch is fine

#

unless you want to

eternal elbow
#

Okay thanks

long crow
#

Tim, gimme some motivation to make the web page of my bot.. Ha ha ha

quartz kindle
#

lel

pale vessel
#

imagine a webpage for your bot

nocturne grove
#

lmao

#

can anybody explain the difference between those two things?

const channel = await client.channels.fetch(channelId);

const channel = client.channels.resolve(channelId);```
pale vessel
#

resolve only accesses the cache

earnest phoenix
#

That'll throw an error
Don't redeclare the same variable angeryBOYE

pale vessel
#

fetch tries to access the cache or fetch it if unavailable

earnest phoenix
#

what's the difference between cache.get and resolve then

nocturne grove
#

okay thanks, so .resolve() is the same as .cache.get() actually?

pale vessel
#

resolve can take a class

#

cache.gay() only accepts IDs

nocturne grove
#

is that spelling intended? lol

earnest phoenix
#

flazepe.gay() === !0

nocturne grove
#

okay but thanks
now I know resolve uses cache, the real thing I wanted to know:
how can I get all roles of a member, as
member.roles.fetch() doesn't exist,
member.roles.resolve() uses cache and
member.roles.cache.get() uses cache (obviously)

#

or should I not worry about that and just use .cache.get()?

pale vessel
#

discord.js caches all guild roles by default

#

cache is fine

nocturne grove
#

okay thank you!

#

so guild.roles.fetch() is also unnecessary?

pale vessel
#

yeah

nocturne grove
#

๐Ÿ‘

umbral lake
#

Hey, its my code:

const Discord = require('discord.js');
const client = new Discord.Client({
    fetchAllMembers: true
});

const disbut = require('discord-buttons');
require('discord-buttons')(client)

client.on('ready', () => {
    console.log(`Logged in as ${client.user.tag}!`);
});

but nothing in the console log :/

#

note: the bot is in a server with 50000 membres, its the problem?

pale vessel
#

fetchAllMembers option is deprecated

umbral lake
#

oh okay

pale vessel
#

You have to use await guild.members.fetch()

umbral lake
#

okay

#

how I added this:

client.on("presenceUpdate", (oldPresence, newPresence) => {
    if (!newPresence.activities[0]) return
    if (!newPresence.activities[0].state) return
    const guild = client.guilds.cache.get("827851345078779945")
    const role = guild.roles.cache.get("873493998004740166")
    if(newPresence.activities[0].state.includes(".gg/axd")) {
        if(!oldPresence.activities[0].state.includes(".gg/axd")) {
            newPresence.member.roles.add(role)
            const channel = guild.channels.cache.get("873503609982169108")
            const embed = new Discord.MessageEmbed()
            .setTitle(`Merci !`)
            .setColor("RANDOM")
            .setDescription(`Merci <@${newPresence.user.id}> pour ton soutien !`);
            channel.send(embed)
        }
    } else if(oldPresence.activities[0].state.includes(".gg/axd")) {
        if(!newPresence.activities[0].state.includes(".gg/axd")) {
            newPresence.member.roles.remove(role)
        }
    }
});
#

so when a user has the .gg... in the bio, the user has a role and a message was send

#

the bot does nothing :/

brave tendon
#

Hey! I am kinda lost... I am currently doing a permission handler for user and bot permissions in a command.. the thing is that even if the bot has all permissions except the ADMINISTRATOR if I try to run the command I only get the error log inside the console .. normally the bot should send a message in which it states that it is missing a permission

#

This is the flag in the command botPermissions: ['ADMINISTRATOR']
And the error I get in the console is the DiscordAPIError: Missing Permissions

#

But why is it that way? What did I do wrong

earnest phoenix
#

Are you sure the bot has the Administrator permission

#

or the permission to even do what you are doing

brave tendon
#

That is what I am testing.. to see if the bot would respond with a message saying that it does not have the Administrator permission

#

The bot itself has every other permission but just won't reply

hollow depot
hollow depot
#

prob then the problem is the deprecated option, but they already said it so i didnt want to repeat

#

if you already fixed the option and it still does not work idk

wicked skiff
#

Hi

nocturne grove
#

@umbral lake maybe a very stupid question, but do you have a client.login(<token>) somewhere?

#

because I don't know if that's the full index.js that you were sending

nocturne grove
#

okay xd

umbral lake
#

its the full index but I removed the login line

nocturne grove
#

okay
understandable that you did that

umbral lake
#

but the ready works in console.log but

#

but system for presence update dosen't work

earnest phoenix
nocturne grove
#

yes that for sure ^

nocturne grove
umbral lake
#

okay oof

nocturne grove
#

so it's not doing anything? No embed or error?

umbral lake
#

nop

#

but

#

I think the server is big

#

50k members

nocturne grove
#

also, try to log for example newPresence.activities[0] so you can see if that is what you expected. So if that state indeed contains '.gg/axd' etc.

umbral lake
#

when the event is on I console.log(no) and nothing lol

nocturne grove
#

or at least log to see if the event is fired

umbral lake
#

event fired?

nocturne grove
#

if the event is activated when someone's presences update

umbral lake
#

nothing in the console

novel snow
#

Playing with some sourcecode I found, But;

nocturne grove
#

hmm, do you have the presences intent enabled?

earnest phoenix
#

Do you have the presence intent enabled

novel snow
#

SyntaxError: Unexpected token '?'

#

Does anyone know what that is?

nocturne grove
#

I feel like it's meant to be ||

novel snow
#

Should I try going to that module and changing it?

quartz kindle
umbral lake
novel snow
quartz kindle
#

update your node.js

novel snow
#

Yeah uh how lmfao

quartz kindle
#

download a new version and install it?

novel snow
#

Thought there was a command for it

nocturne grove
#

oh oops, I just didn't know ?? existed
Now I learnt what it is :)

waxen bough
#

what do i put there

earnest phoenix
#

What?

waxen bough
#

type arguments

nocturne grove
#

should probably be new Discord.Collection()

earnest phoenix
#

That looks like typescript code

waxen bough
waxen bough
earnest phoenix
#

What is the error you are getting

nocturne grove
#

oh sry

earnest phoenix
#

Its red for a reason

quartz kindle
waxen bough
earnest phoenix
#

What?

#

Well

waxen bough
earnest phoenix
#

If you are defining a collection you need to tell it what it will hold

waxen bough
#

it holds commands

earnest phoenix
#

Collection<string, string> for example

#

Means the collection key will be a string and the value of that key will also be a string

#

Do you have a command class?

#

If so you can set the value to be of type Command (or whatever you called the command class)

nocturne grove
#

@quartz kindle btw, you advised me to look into js classes
I did, but I wonder why I should use that if I can also do this:
Can you explain that to me?

class car {
    constructor(name) {
        this.name = name;
    }
}

function car2(name) {
    return { name };
}

new car('Volvo');
// car { name: 'Volvo' }

car2('Audi');
// { name: 'Audi' }```
#

probably a faq lol

earnest phoenix
#

Well because yo u can create a new instance of a class

nocturne grove
#

someone else can also answer of course ๐Ÿ™‚

earnest phoenix
#

With a class you can create an instance of it and use the methods inside it freely

#

or make them static ofc

#

That probably isn't the best reason but its my reason

nocturne grove
#

methods are functions right?

waxen bough
#

i am trying to do the same thing in the guide but i'm coding in typescript so i need typedefs do i just put import('discord.js').ApplicationCommand?

quartz kindle
#

classes are a better way to create relationships and inheritance

earnest phoenix
#

that is a much better reason lol

quartz kindle
#

before es6, it was possible to create class-like structures with functions and objects

#

now with the class syntax its easier to use and to understand

#

and cleaner in general

earnest phoenix
quartz kindle
#

essentially you want to use classes if you are creating multiple copies of an object, and the object contains functions that access the objects own properties

earnest phoenix
#

Tim always gives better explanations

#

Does someone know how i update my codes to djs v13 easily?

#

Follow the change log

#

It tells you everything different from v12 to v13

waxen bough
#

it's so much easier in v12

quartz kindle
boreal iron
quartz kindle
#

it was the same thing when v11 went to v12

nocturne grove
#

okay thanks both. So in the example I sent it doesn't really matter, but then it's just cleaner?
Then I think that answers my question

quartz kindle
#

everyone complaining about it lmao

#

and now everyone use v12 like its normal

nocturne grove
#

yeah lol

#

before you had stuff like channel.sendMessage() iirc
never used that myself tho

earnest phoenix
#

that was v9 or 10 I think

earnest phoenix
nocturne grove
#

hm can't remember I was using d.js with v10

#
let count = 5;
- embed.addField('Count', count);
+ embed.addField('Count', count.toString());```
This is especially useful
marsh bluff
#

Since structure extensions are not allowed, and discord.js-commando does exactly that, is there a way to easily switch from discord.js-commando to slash commands or at least make Commando work?

brave tendon
#

Why am I getting api error: Can not send empty message

marsh bluff
#

are you using the new API?

brave tendon
#

Oh not yet.. my version is still the ^12.5.3

#

Ima update

eternal elbow
#

Does anyone know the exact name of the algorithm used in the refresh token, access token and code?

#

OAuth2 or something else

split hazel
#

well you just said it

eternal elbow
split hazel
#

yes

#

the whole process is called oauth2

eternal elbow
#

Ookay one more question

#

Does it make sense if I just use it for my own site without being tied to another site?

nocturne grove
#

general question: do you (in general) keep a help command when having converted all commands to slash commands?

eternal elbow
glass barn
#

i did not yet completed my bot! is it possible to submit my bot ? as top.gg takes some times to check and verify the bot...

shrewd hazel
#

@glass barn Yes

#

Im waiting 2,9 days to get verified

#

And now im get verified so just wait

split hazel
glass barn
shrewd hazel
split hazel
#

if you really want to you can set the access token in cookies but it'd be best if you do it through the server

glass barn
shrewd hazel
#

How do i use webhook, my bot dont hosted on cloud

eternal elbow
split hazel
#

jwt would probably be the best and most secure for storing them

#

since you can pretty much verify it hasn't been tampered with

#

just make sure to set a strong secret for jwt

eternal elbow
#

Alrgihtt thanks

earnest phoenix
#

if i added a automatic status changing into my bot what is the limit of seconds i could do to avoid rate limites

hollow depot
nocturne grove
#

to everyone arguing about their verification time: I waited 3 months ๐Ÿ˜„

nocturne grove
lyric mountain