#development

1 messages · Page 898 of 1

sacred mountain
#

Is there a way to get a random outcome for something. I’m trying to make a command with like 70% chance of 1 outcome and 30% chance of another outcome. How would I do this?

queen needle
#

70% chance of win

#

30% chance of lose

sacred mountain
#

Yh

#

But how would I actually make it randomise

#

i tried ``` const stealOutcomes = [
{
outcome: "caught"
},
{
outcome: "caught"
},
{
outcome: "safe"
},
{
outcome: "safe"
},
{
outcome: "safe"
}
];

        const randomOutcome = stealOutcomes[Math.floor(Math.random() * stealOutcomes.length)];

        if(randomOutcome == "safe"){
            console.log("Safe")
        }
        if(randomOutcome == "caught"){
            console.log("caught")
        }
        break;```
#

thats obviously wrong

#

but i dont know how to do it

slender thistle
#

roll = randominteger(1, 100)
if (roll > 30) win()
else lose()

#

Sounds like spoonfeeding

nocturne grove
#

Hey, did something change with reacting with multiple emoji to a message and catching an error on it, in v12?

pale vessel
#

why'd you ask?

nocturne grove
#

because my bot is randomly catching an error if nothing is wrong

#

and it doesn't fully execute what's inside the catch thing, but that is another problem (it worked before though)

#

maybe something did change with a rate limit. I'm just doing the same command with reactions multiple times, and one time it catches something and one time it doesn't

pale vessel
#

send code

nocturne grove
#

sure

#
 embed.react(emoji[0])
      .then(() => embed.react(emoji[1]))
      .then(() => embed.react(emoji[2]))
      .then(() => embed.react(emoji[3]))
      .then(() => embed.react(emoji[4]))
      .then(() => embed.react(emoji[5]))
      .then(() => embed.react(emoji[6]))
      .catch(() => {
            finish = false;
            notify(':warning: I don\'t have the \'Add Reactions\' permission in this channel anymore. I stopped executing this command.', 'Can\'t add reactions');
      });```
#

notify is just a function which sends a channel message/dm and log

#

and now when I try to log the error, it's not happening, even if I spam it

#

YES I got an error

#

@pale vessel (in case you were searching for something)

#
  message: 'Unknown Message',
  method: 'put',
  path: '/channels/662283278929362967/messages/705016983112122488/reactions/%F0%9F%94%B4/@me',
  code: 10008,
  httpStatus: 404```
#

so it can't find the message if it wants to react, I guess

#

but that's weird, it's just using

message.channel.send().then(async (embed) => {
  // rest of the code
});```
earnest phoenix
#

hello..

golden condor
#

What language you use?

earnest phoenix
#

js

golden condor
#

discord.js?

earnest phoenix
#

yes

#

v12

golden condor
#

Ok great

#

It is a bit weird sometiems

earnest phoenix
#

ok

golden condor
#

So

#

client.user.setStatus('dnd')

earnest phoenix
#

ahh ok

golden condor
#

It is a bit glitchy

earnest phoenix
#

how?

golden condor
#

Just keep tryna restart if it doesn't work

earnest phoenix
#

ok

#

thx

golden condor
#

In node.js, what is the new eval function?

earnest phoenix
#

client. is not defied

golden condor
#

Do you use bot?

earnest phoenix
#

yes

#

ahh i see

#

what's an efficient way to search or find an element in an sorted array
like find id(5) in array [1, 2, 4, 5, 8 ,19]
does array.find() use something like bst or just linear search?

pale vessel
#

arr[num] ?

zenith orchid
#

Use find function.

grizzled raven
#

array.find(a => a === 5)

pale vessel
#

might as well use array[a] no?

zenith orchid
#

No

pale vessel
#

ok

zenith orchid
#

If it is [1,2,5 ....] it will have problems.

earnest phoenix
#

is there a way when u inv the bot to ur server it sends a msg like hello im bot

wet dove
#

Yes.

earnest phoenix
#

ok so what is it?

#

is there a way to ignore a prefix? because my prefix is a! but it also response to c!

quartz kindle
#

to send a message on join, you need to check the channels of the guild, pick a channel and send a message to it

#

you want to have 2 prefixes?

earnest phoenix
#

no i want it to egnore a prefix

quartz kindle
#

then you're not checking for your prefix correctly

earnest phoenix
#

?

quartz kindle
#

if you have a prefix, and your bot is also responding to other prefixes, then your prefix checking is not working correctly

earnest phoenix
#

how?

quartz kindle
#

you need to review your code that checks for the prefix

earnest phoenix
#

this is it

  "prefix": "a!"
}
#

is it?

quartz kindle
#

thats how you define the prefix, but how do you check it?

earnest phoenix
#

wdym

quartz kindle
#

you should have a piece of code that checks the message content and checks if it starts with the prefix

earnest phoenix
#

this is the cmd im running

  name: "say",

  run: async (bot, message, args) => {
    var ids = [
      "669206927879962626",
    ];
    if (!ids.includes(message.author.id))
      return message.channel.send("You can't use this");

    let argsresult;
    let mChannel = message.mentions.channels.first();

    message.delete();
    if (mChannel) {
      argsresult = args.slice(1).join(" ");
      mChannel.send(argsresult);
    } else {
      argsresult = args.join(" ");
      message.channel.send(argsresult);
    }
  }
};
quartz kindle
#

likely before that

#

in your main file

earnest phoenix
#

?

quartz kindle
#

somewhere after .on("message")

earnest phoenix
#

oh ojk

#

umm

#

i cant see it..

quartz kindle
#

then show your main file

earnest phoenix
#

umm how?

#

-bins

#

-bin

quartz kindle
#

where is your bot hosted? what library does your bot use?

#

how are you starting your bot?

earnest phoenix
#

glitch im using glitch

#

oops i put typescript by accident

quartz kindle
#

here it is

earnest phoenix
#

i ment javascript

quartz kindle
#

can you see it? the code is checking your prefix

earnest phoenix
#

ummm no

quartz kindle
#

cant you see it?

earnest phoenix
#

ok yeah

#

now i do

quartz kindle
#

so this code is flawed

earnest phoenix
#

flawed?

quartz kindle
#

yes, its wrong

earnest phoenix
#

how?

quartz kindle
#

it never checks if the prefix is correct

#

it only checks the length of the prefix

earnest phoenix
#

oh

quartz kindle
#

meaning that your bot will work with any prefix that has the same size

earnest phoenix
#

oh i see

quartz kindle
#

the same number of characters

earnest phoenix
#

so how do i make it check if the prefix is correct?

quartz kindle
#

you can add this if(!message.content.startsWith(prefix)) return

#

right after let prefix

earnest phoenix
#

ok

quartz kindle
#

that code means: if the content of the message does not start with the prefix, then return and do nothing

earnest phoenix
#

ok thanks!

#

  if (!member.guild.me.hasPermission("MANAGE_CHANNELS")) return;```
#

Cannot ready proprety hasPermission of undefined

#

me?

#

#v11.6.4

#

how can i do?

#

no delu

#

deku*

#

why is there a me

#

.me.hasPermission

#

@quartz kindle can u help me please?

#

for the bot @earnest phoenix

#

ok

#

check if the bot has perm

golden condor
#

What is the new eval() function in node.js

tight plinth
#

eval()?

quartz kindle
#

@earnest phoenix are you using any sort of mod or framework? or some cache cleaning method?

#

your error means that the bot member is not cached, but that should never happen in a clean discord.js installation

#

put 8 sentences in an array/list, then pick a random one

earnest phoenix
#

Hi.
By using discord.js-commando, can each command group register its own prefix?

tight plinth
#

No

#

Best solution is to make multiple bots with multiple prefixes

earnest phoenix
#

and merge them into one bot?

tight plinth
#

No

quartz kindle
#

best solution is not use commando lol

tight plinth
#

Yea it works too

earnest phoenix
#

or I could do ugly way and check for the command file path and asign the prefix through message character checks.

#

😦

#

ok. thanks. 🙂

tight plinth
#

The prefix is assigned to the bot, not the **command group **

#

That's why u cant

earnest phoenix
#

any other discord.js framework that you could recommend besides commando?

quartz kindle
#

most people make their own

marble juniper
#

discord.js

#

just use it

#

the normal discord.js

quartz kindle
#

discord.js without any framework is already stupidly easy to use as is

#

and you can make a basic command handler in less than 10 lines

marble juniper
#

can

#

you can also do it in 1 line

#

with minimize

queen needle
#

https://ghostbin.co/paste/np3y7 thats my code for my queue and play command for my bot and if i add another song it just skips the current one and goes to the song i just asked it to play

#

but it should finish the song playing then do the second

quartz kindle
#

@queen needle every time you run the command you create a new active and new ops which in turn creates a new data

queen needle
#

ohh

quartz kindle
#

your old data is never reused, it always creating a new one

queen needle
#

how would i make it use the current one

quartz kindle
#

you need to save it somewhere

#

outside the function

queen needle
#

which part?

quartz kindle
#

everything that is relevant

#

you need to rework your structure, it wont work as it is

queen needle
#
  if(!data.dispatcher) play(client, ops, data);
    else{
      message.channel.send(`Added to the queue: ${info.title} | Requested by: ${message.author.id}`)
    }
    
    ops.active.set(message.guild.id, data)
    
    async function play(client, ops, data){
      client.channels.get(data.queue[0].announceChannel).send(`Now playing: ${data.queue[0].songTitle} | Requested by ${data.queue[0].requester}`)
      
     data.dispatcher = await data.connection.playStream(ytdl(data.queue[0].url, {filter: "audioonly"}));
      data.dispatcher.guildID = data.guildId
      
      data.dispatcher.once('finish', function(){
        finish(client, ops, this)
      })
    }
    function finish(client, ops, dispatcher){
      let fetched = ops.active.get(dispatcher.guildID)
      
      fetched.queue.shift()
      
      if(fetched.queue.length > 0){
        ops.active.set(dispatcher.guildID, fetched)
        
        play(client, ops, fetched)
      }else{
      ops.active.delete(dispatcher.guildID)
        
        let vc = client.guilds.get(dispatcher.guildID).me.voiceChannel
        if(vc) vc.leave()
    }
    }```
#

wouldnt that be all of that

quartz kindle
#

i mean just the data

#

for example, if you want active to be reused, then ```js
const active = new Map()
.on("message", message => { // or module.exports.run = (message) => { idk how your commands are structured
let guildData = active.get(message.guild.id)
if(!guildData) {
let guildData = {some default data};
active.set(message.guild.id,guildData)
}
})

#

the same if you want ops or data, idk how you want your structure to look like

#

but anything that you want to globally keep track of and reuse across commands needs to be done like that

#

defined outside of the entire command block, and checked if data already exists there

queen needle
#

so if it was active it would look like that

pale vessel
#

that website is so ugly

#

i can barely read the code

queen needle
#

haste bin doesnt work for me

pale vessel
#

devs need to step up their game

#

why not? just click the save button on top right or ctrl s

queen needle
#

when i try it doesnt work

pale vessel
#

ok

quartz hill
#

How to use setinterval with shard broadcasteval? discordj
I try this

client.shard.broadcastEval(`setInterval(${f},350000);`);

but not working

quartz kindle
#

what are you trying to do?

#

thats most likely the wrong way to do whatever you're trying to do

quartz hill
#

I want to run this function in all shards.

#

But this must be a repetitive function.

#

settimeout not good

quartz kindle
#

why cant you run the function in the shards themselves instead of broadcastEval?

quartz hill
#

All shards should start after they are ready.

quartz kindle
#

after all shards are ready or after each one is ready?

quartz hill
#

Since I didn't understand the shard well, if the last shard occurred, I run this command on it.

quartz kindle
#

ok then do this

#
// shard.js
function startInterval() {
  setInterval(() => {
    // your function
  },350000)
}

// manager/index.js
// after all shards ready
broadcastEval(`startInterval()`)
quartz hill
#

thx so much

queen needle
#

im still very confuse with my play command

wide ridge
#

UnhandledPromiseRejectionWarning: FetchError: request to https://discordapp.com/api/v7/channels/704479398253953146/messages failed, reason: read ECONNRESET
Is this an issue on Discord's end or my end?

quartz kindle
#

most likely network failure

#

could be on either end

wide ridge
#

and (node:31555) UnhandledPromiseRejectionWarning: Response: Internal Server Error would be discord's end I'm assuming?

quartz kindle
#

looks like it

clear wraith
#

I get the same thing, but its api related.

nocturne grove
#

Hey, can someone help me with a discord API error that says a message is unknown after sending it?

quartz kindle
#

show code

nocturne grove
#

mine?

clear wraith
#

yes

nocturne grove
quartz kindle
#

check if your bot has "view message history" permissions

nocturne grove
#

okay thanks, will do that. But can that explain why it's only sometimes giving an error? Not always

quartz kindle
#

message history is weird, im not sure how it works either. im also not sure if this is caused by it or not

nocturne grove
#

oh okay. Will check it through my bot itself just to be certain

quartz kindle
#

if it was indeed message history, it should give missing access error, not unknown message, but im not sure

nocturne grove
#
console.log(message.channel.permissionsFor(message.guild.me).has('READ_MESSAGE_HISTORY'));``` returns true 🤔
quartz kindle
#

can you show the full code block?

nocturne grove
#

same channel and audit logs gave no changes

quartz kindle
#

including before and after the reactions block

nocturne grove
#

isn't the linked code block enough?

#

oh lol you will almost cry if you see it, but sure 😂

clear wraith
#

Oh boy

nocturne grove
#

beginning with channel.send()?

quartz kindle
#

also before

nocturne grove
#

okay will use hastebin then

#

199 lines of complicated code

#

hastebin not working 🤔 , wait

#

why is my hastebin not saving? :/

#

okay I will send it as a file

#

I hope this is okay @quartz kindle

earnest phoenix
#
if(isNaN(time)) return message.channel.send("❎ | Le temps doit être un nombre compris entre 25000ms (25 secondes) et 120000ms (2 minutes).\n\n*Le temps que vous devez mettre doit être en ms (millisecondes)*")

if(Number(time) < 25000) return message.channel.send("❎ | Le temps ne doit pas être inférieur à 25000ms (25 secondes).")
if(Number(time) > 120000) return message.channel.send("❎ | Le temps ne doit pas être supérieur à 120000ms (2 minutes).")```


^ it’s good but how could I do that if time = 65 seconds (65000 ms) then the bot responds 1 minute 5 seconds?
nocturne grove
#

@earnest phoenix use something like this:

setTimeout(() => {
  message.channel.send(what_you_want);
}, time_in_ms);```
earnest phoenix
#

yes but setTimeout what xd

nocturne grove
#

ohh sorry I can't read (again :()

earnest phoenix
#

np

nocturne grove
#

something like this:

const totalSeconds = time_in_ms / 1000;
const minutes = Math.floor(seconds / 60);
const seconds = totalSeconds - minutes * 60;```
earnest phoenix
#

uh

nocturne grove
#

I think you can do the remaining part yourself

earnest phoenix
#

i replace seconds to totalSeconds

#

x)

nocturne grove
#

lol if you want that, sure. But don't make seconds and totalSeconds the same (well you can, but I wouldn't do that)

earnest phoenix
#

ye

#

thx u bro

nocturne grove
#

no problem

quartz kindle
#

@nocturne grove you were right, your code is confusing af lmao.
2 things tho, youre already using async functions, so try using await instead of .then
start the collector after your bot sets up the reactions, just to make sure it doesnt interfere
also, why are you requiring a client when you already have bot?

golden condor
#

What is the new method for eval()

quartz kindle
#

@golden condor wdym? there is no new method

nocturne grove
#

okay thanks! will try those two
and yeah, it's confusing 😂

client is the real Discord client, bot is a json object with things like the token, colours, standard_prefix etc.

golden condor
#

It keeps telling me it is deprecated

quartz kindle
#

oh lol, why not pass client in the function as well then?

nocturne grove
#

^ good question xD

#

and even the con then, database connection

quartz kindle
#

@golden condor show

golden condor
#

It kept sending a message before

#

But now it doesn't anymore

quartz kindle
#

well show it if it ever comes up again

nocturne grove
#

can I still catch all embed.react() things in one time? Or should I use try {} catch() {} instead?

quartz kindle
#

use try/catch

nocturne grove
#

okay

earnest phoenix
#

How to make a prefix changer for every guild? Like if an owner want the prefix to be ? He can change it

nocturne grove
#

make a database

quartz kindle
#

^

nocturne grove
#

and please don't use json as I did

cerulean pebble
#
const Discord = require("discord.js");

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

  if(!message.member.hasPermission("MANAGE_ROLES")) return message.channel(":tickNo: **| You dont have `MANAGE_ROLES` permissions.**");
  let rMember = message.guild.member(message.mentions.users.first()) || message.guild.members.cache.get(args[0]);
  if(!rMember) return message.channel.send(":tickNo: **| That user cannot be found!**");
  let role = args.join(" ").slice(22);
  if(!role) return message.channel.send(":tickNo: **| Please specify a role!**");
  let gRole = message.guild.roles.cache.find(r => r.name === role)
  if(!gRole) return message.channel.send(":tickNo: **| Couldn't find that role.**");
  if(rMember.roles.has(gRole.id)) return message.reply(":tickNo: **| They already have that role.**");
  await(rMember.addRole(gRole.id));
  message.channel.send(`:tickYes: | ${rMember} has been given the ${gRole.name} role.`)
earnest phoenix
#

@nocturne grove

let minutes = Math.floor(timeConvert / 60);
let secondes = timeConvert - minutes * 60;

let timeGet;
if(timeConvert < 60) timeGet = `${timeConvert} secondes`
if(timeConvert > 60) timeGet = `${minutes} minutes et ${secondes} secondes`

const embed = new Discord.RichEmbed()
.setTitle("✅ | Le temps de vérification a changé avec succès :")
.addField("⏰ Temps configuré :", `${time} (${timeGet})`)
return message.channel.send(embed)```

in the embed, in place of ${timeGet}, my bot say ‘undefined’
cerulean pebble
#

why code not work

#

@earnest phoenix try to delte ;

#

*let timeGet

#

*delete

nocturne grove
#

@earnest phoenix was it exactly 60 ?

earnest phoenix
#

yes

#

uh ok

#

thx u x)))

cerulean pebble
#

idk

nocturne grove
#

np

#

@cerulean pebble did you get an error?

cerulean pebble
#

role not find

#

not error

#

let gRole = message.guild.roles.cache.find(r => r.name === role)

#

i think i do wrong at this line

nocturne grove
#

doesn't it say a line?

cerulean pebble
#

?

nocturne grove
#

are you using D.js v12?

#

doesn't it say a line?
if it says where the error happened

cerulean pebble
#

i am using v12

nocturne grove
#

hmm

cerulean pebble
#

:/

nocturne grove
#

args.join(" ").slice(22); are you slicing an array here? Is that possible?

#

oh yes that's possible

#

what does the 22 represent?

#

why is it 22

cerulean pebble
#

:/

#

i see everyone do 22

nocturne grove
#

okay what if you do console.log(role) after the line where you do let role =?

#

and see if what it logs makes sense

earnest phoenix
#

@nocturne grove

let minutes = Math.floor(timeConvert / 60);
let secondes = timeConvert - minutes * 60;

let timeGet;
if(timeConvert < 60) timeGet = `${timeConvert} secondes`
if(timeConvert = 60) timeGet = `1 minute`
if(timeConvert > 60) timeGet = `${minutes} minute(s) et ${secondes} secondes`

const embed = new Discord.RichEmbed()
.setTitle("✅ | Le temps de vérification a changé avec succès :")
.addField("⏰ Temps configuré :", `${time}ms (${timeGet})`)
return message.channel.send(embed)

when i put any time < 60000 or > 6000, the bot say always 1 minute (same = 60)

quartz kindle
#

slice(22) is wrong in many levels

cerulean pebble
#

lol

quartz kindle
#

people use slice(22) in an attempt to use the bot's mention as a prefix, because the mention is approximately 22 characters long

cerulean pebble
#

:/

quartz kindle
#

however IDs are not guaranteed to be always the same length

cerulean pebble
#

so what should i do :/ for code work

#

people use slice(22) in an attempt to use the bot's mention as a prefix, because the mention is approximately 22 characters long
@quartz kindle oh

nocturne grove
#

@earnest phoenix timeConvert was a time in ms, so you shouldn't use 60 in your if-statements, but 60000

#

ohhh that's why

#

no that's not really save to do

quartz kindle
#

if you want to get a role based on role mention, then you should use message.mentions.roles

#

the same way you use message.mentions.users

earnest phoenix
#

so i replace timeConvert to time ??

nocturne grove
#

oh yes right, of course @earnest phoenix

#

didn't think of that variable

earnest phoenix
#

ok thx

nocturne grove
#

np

turbid bough
#

anyone know how to use css?

#

i cant seem to get the body to expand with the content

cerulean pebble
quartz kindle
#

vertically or horizontally?

#

what is the content?

cerulean pebble
#

@quartz kindle not work :/

turbid bough
#

nvm fixed it

#

vertically

#

it was some stupid default css that had height: 100% on body

quartz kindle
#

@cerulean pebble you dont need gRole

cerulean pebble
#
const Discord = require("discord.js");

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

  if(!message.member.hasPermission("MANAGE_ROLES")) return message.channel(":tickNo: **| You dont have `MANAGE_ROLES` permissions.**");
  let rMember = message.guild.member(message.mentions.users.first()) || message.guild.members.cache.get(args[0]);
  if(!rMember) return message.channel.send(":tickNo: **| That user cannot be found!**");
  //let role = args.join(" ").slice(22);
let role = message.mentions.roles.first()
  if(!role) return message.channel.send(":tickNo: **| Please specify a role!**");
  //let gRole = message.guild.roles.cache.find(r => r.name === role)
  //if(!gRole) return message.channel.send(":tickNo: **| Couldn't find that role.**");
  if(rMember.roles.has(role.id)) return message.reply(":tickNo: **| They already have that role.**");
  await(rMember.roles.add([role.id]));
  message.channel.send(`:tickYes: | ${rMember} has been given the ${gRole.name} role.`)
#

oke

#

tks

#

TypeError: rMember.roles.has is not a function

nocturne grove
#

oh btw Tim, I can't directly see if your suggestion fixed the command, but thanks for reading the mess 👌

cerulean pebble
#

lol :/

nocturne grove
#

TypeError: rMember.roles.has is not a function
@cerulean pebble use rMember.roles.cache.has

#

you have v12

cerulean pebble
#

lol

#

sorry i am stupid

nocturne grove
#

no problem, it's just weird if you used to do it the other way

cerulean pebble
#

everybody send me that :/

#

btw tks @nocturne grove -chan

nocturne grove
#

wtf

#

ohh because of that chan

#

np

surreal notch
#

I want to make cooldown that once a person used that command then he can use it for 24hrs

#

In command handler

#

discord.js v12

zenith orchid
#

You can use some database, and control some datas.

surreal notch
#

I know what to do in normal but dont know how to convert it in cmd handler

#

@zenith orchid

zenith orchid
#

I think you have message event file, this true?

ivory pebble
#

So I'm trying to do the simplest thing ever which is just changing the color of the bot title on top.gg. It doesn't work though of course...
Code:

    color: white !important;
}```
zenith orchid
#

Your selector is wrong.

ivory pebble
#

What is it supposed to be then?

pale vessel
#

bot title is span?

#

where did you get h1

ivory pebble
#

bot-title doesn't work

#

Thats why I tried h1

pale vessel
#

it's bot-name

ivory pebble
#

That doesn't work either

pale vessel
#
#bot-details-page .bot-name {
    color: gainsboro !important;
}```
#

literally from the source

ivory pebble
#

Doesn't work

#

I've wasted so much time trying to style the bot page and nothing works

zenith orchid
#

Clear cookies and try.

earnest phoenix
#

How can I show how many servers my bot is on

#

on the site

zenith orchid
slender thistle
#

Those are mostly outdated

summer torrent
slender thistle
earnest phoenix
#

thanks

ivory pebble
#

How hard is it to just edit the css lol

pale vessel
#

you're supposed to clear cache, not cookies lol

ivory pebble
#

I was told to clear cookies

#

Lol

pale vessel
#

but usually you don't need to clear cache if you use <style>

#

because the style loads as you load the page

earnest phoenix
#
let timeGet = Data_Time.get(`${server}.time.timeSet`)
if(!timeGet) time = `40`
time = timeGet / 1000```

In the embed : ```.addField("⏰ | Temps de vérification :", `${time} secondes`)```

time show « NaN » why?
zenith orchid
#

I think I am thoughtful these times.

#

let timeGet = Data_time.get(server.time.timeset)

quartz kindle
#

@earnest phoenix
if(!timeGet) time = 40 // timeGet doesnt exist
time = timeGet / 1000 // timeGet still doesnt exist

ivory pebble
#

Cleared both cache and cookies and nothing works

pale vessel
#

can i see the css code

ivory pebble
earnest phoenix
#

so how can i do? Tim

quartz kindle
#

is that in your top.gg long description?

pale vessel
#

damn html inside html

#

crazy

quartz kindle
#

Vinx use common sense lol. if timeGet doesnt exist, dont use it

ivory pebble
#

@quartz kindle yea

pale vessel
#

you only need

<style>
html, body {
    width: 99%;
      background: rgb(2,0,36);
    background: linear-gradient(180deg, rgba(2,0,36,1) 0%, rgba(18,16,78,1) 0%, rgba(72,32,114,1) 100%); 
    color: #FFFFFF !important;
}
  
#bot-details-page .bot-name {
    color: white !important;
}
</style>

<iframe src="https://eartensifier.net/">
</iframe>```
#

but i don't think that would fix the problem

quartz kindle
#

long description is a piece of code that gets injected into the existing top.gg page

#

its not a standalone html page

pale vessel
#

HTMLCeption

ivory pebble
#

Got it

earnest phoenix
#

ok thx

ivory pebble
#

Imagine if there was documentation on this though.

pale vessel
#

it's basic html though

quartz kindle
#

there is no need for documentation

#

you simply use the inspector / dev tools in your browser

ivory pebble
#

It just makes it easier though

turbid bough
#

would it work better if i have a better internet thonk

amber fractal
#

most likely, I don't think the api is having problems at the moment

#

the other ones are probably faster because of cache (the /me ones mainly)

turbid bough
#

the /users/@me yeah

hexed prawn
#

anyone know how to make a share command for example share currencies with another user

sudden geyser
#

you accept the first argument as likely the user, then the next argument as the amount you want to share, do a db request (or if you have a cache), check if they have enough to give, then do your database magic?

earnest phoenix
#

DBL Error: Error: 403 Forbidden
why is my bot saying this?

hasty sparrow
#

When posting the bot's status?

sudden geyser
#

Where/how is it happening.

earnest phoenix
#

@hasty sparrow @sudden geyser the bots server count

#

should I check token?

hasty sparrow
#

Yep

earnest phoenix
#

k

sudden geyser
#

I believe 401 is for wrong token.

slender thistle
#

Yup

earnest phoenix
#

lemme see

#

tysm guys

slender thistle
#

403 is for an endpoint you have no access to

earnest phoenix
#

hmm

#

mmmhhhhmmm

#

one min

pale vessel
#

that's new

earnest phoenix
#

why my bot dont responding only in this server

cedar mist
#

Check the guild id

amber fractal
#

it's most likely muted

#

mention it here

earnest phoenix
#

not muted tho

small prairie
#

any way to check if the message only contains a gif URL? d.js v11

earnest phoenix
#

no i can mention in here

summer torrent
#

check your console

earnest phoenix
#

it also contains the important stuff for gradle

cedar mist
#

Ok thats actually really useful

nocturne grove
#

Is there any difference between module.exports.run and module.exports.execute?

amber fractal
#

module.exports is an object of exports

#

you can define the properties as you want

#

module.exports.run could be anything, same with module.exports.execute

fallen arch
#

how can i get the rank of a user from the leaderboard
im using mongoose for a db

nocturne grove
#

you can define the properties as you want
@amber fractal ohhh thanks. Now you say it...

tight plinth
#

I need an api like nekos.life but without the questionable endpoints. which api can I have?

pale vessel
#

you can duckduckgo something like "anime weeb api" and it might come up

tight plinth
#

first result is nekos.life ;-;

copper cradle
#

there

fallen arch
#

how can i get a rank of a specific user from a res array?

for example

let res = [
  "user1"
  "user2"
  "user3"
]

how can i get the rank of user 2 with message.author.id or something like that

tight plinth
#

oh

amber fractal
#

that's not an array

fallen arch
#

oh thats an array

amber fractal
#

arrays use square brackets

fallen arch
#

i accidentally used that

amber fractal
#

do you know how to index into an array

fallen arch
#

like res[1]

#

that will get the user2

amber fractal
#

Yes

#

what is the problem

fallen arch
#

but im trying to get the user rank from a leveling system

amber fractal
#

you can use arr.find()

#

but it'd have to be an array of objects to do what you're attempting

fallen arch
#

.sort() returns a array right?

amber fractal
#

well yeah, that sorts the array with the given function

fallen arch
#

im gonna try using arr.find()

sudden geyser
#

<Array>.sort modifies the original array btw.

fallen arch
#

yea

#

what should i put in arr.find(HERE)

sudden geyser
#

A function.

#

The first parameter is the item from the array you're currently working with. The second parameter is the index. The third is the original array.

fallen arch
#

im trying to get the index
the position the user is in the res

sudden geyser
#

You can use <Array>.indexOf if you have the user ID and looking for the index.

fallen arch
#

oh okay

earnest phoenix
#

I need help fixing an issue where my bot would get 'execute' as unidentified. I've switched from one huge code file to separate code files using command modules and js files. when I execute command that aren't message commands, this happens, here is a snippit of my code if that would help https://gist.github.com/IF64/2341ce22f14a16796361b16e76fe188b and here's a log for further evaluation

    at Client.<anonymous> (C:\Users\jjpla\OneDrive\Documents\GitHub\disc-bot-rep\bot.js:39:17)
    at Client.emit (events.js:310:20)
    at MessageCreateAction.handle (C:\Users\jjpla\OneDrive\Documents\GitHub\disc-bot-rep\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
    at Object.module.exports [as MESSAGE_CREATE] (C:\Users\jjpla\OneDrive\Documents\GitHub\disc-bot-rep\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
    at WebSocketManager.handlePacket (C:\Users\jjpla\OneDrive\Documents\GitHub\disc-bot-rep\node_modules\discord.js\src\client\websocket\WebSocketManager.js:386:31)
    at WebSocketShard.onPacket (C:\Users\jjpla\OneDrive\Documents\GitHub\disc-bot-rep\node_modules\discord.js\src\client\websocket\WebSocketShard.js:436:22)
    at WebSocketShard.onMessage (C:\Users\jjpla\OneDrive\Documents\GitHub\disc-bot-rep\node_modules\discord.js\src\client\websocket\WebSocketShard.js:293:10)
    at WebSocket.onMessage (C:\Users\jjpla\OneDrive\Documents\GitHub\disc-bot-rep\node_modules\ws\lib\event-target.js:120:16)
    at WebSocket.emit (events.js:310:20)
    at Receiver.receiverOnMessage (C:\Users\jjpla\OneDrive\Documents\GitHub\disc-bot-rep\node_modules\ws\lib\websocket.js:800:20)```
Gist

GitHub Gist: instantly share code, notes, and snippets.

sudden geyser
#

how are you calling execute

amber fractal
#

doesnt matter, on execute they create a new listener

#

memory leak galore if that runs

sudden geyser
#

oh

#

ew

earnest phoenix
#

Hi, i'm making a serverinfo command and i'm not sure what is the "name" for US West or the rest

this is the code now:

    const region = {
   "europe": ":flag_eu: Europe",
      "rusia": ":flag_ru: Russia",
      "brazil": ":flag_br: Brazil",
      "singapore": ":flag_sg: Singapore",
      "japan": ":flag_jp: Japan",
      "india": ":flag_in: India",
      
    }
#

fur US West is us_west or uswest?

sudden geyser
#

It's us-west

earnest phoenix
#

and for hong kong is hong-kong?

sudden geyser
#

Discord actually has a lot of regions, which some are in the API but not selectable:

('singapore', 'europe', 'japan', 'southafrica', 'amsterdam', 'south-korea', 'dubai', 'brazil', 'us-west', 'russia', 'eu-central', 'india', 'frankfurt', 'us-east', 'us-south', 'eu-west', 'us-central', 'hongkong', 'london', 'sydney')```
earnest phoenix
#

Oh

sudden geyser
#

Hong Kong is hongkong

earnest phoenix
#

Tyvm

fallen arch
#

Kinolite im getting the index zero

#

actually -1

sudden geyser
#

If it's -1 the item wasn't found.

fallen arch
#

hmmm

#

this is what im doing let rank = res.indexOf(message.author.id)

surreal notch
#

Please tell how to solve this error

#

I am sick of it

fallen arch
#

read the error

surreal notch
#

yup i read that

#

how to do async function

amber fractal
#

step 2 is to learn js

surreal notch
quartz kindle
#
// normal functions
function bla() {}
() => {}

// async functions
async function bla() {}
async () => {}

() => {
  await bla // error
}

async () => {
  await bla // no error
}
amber fractal
#

asynchronous functions are a basic programming concept

fallen arch
#

yep

clear wraith
#

Hi.. Once again!
I am getting an error in my logs after I run my c!instagram command, can anyone help me figure out why?

#
    at Message.delete (/rbd/pnpm-volume/3e0e7ff0-a6f9-4413-afc4-43ee427079be/node_modules/.registry.npmjs.org/discord.js/12.2.0/node_modules/discord.js/src/structures/Message.js:501:44)```
amber fractal
#

<Message>.delete()'s options are now an object

clear wraith
#

Code:

const { stripIndents } = require("common-tags");

const fetch = require("node-fetch");

module.exports = {
    name: "instagram",
    aliases: ["insta"],
    category: "Info",
    description: "Find out some nice instagram statistics",
    usage: "!instagram <Username>",
    run: async (client, message, args) => {
        const name = args.join(" ");

        if (!name) {
            return message.reply("Maybe it's useful to actually search for someone...!")
                .then(m => m.delete(5000));
        }

        const url = `https://instagram.com/${name}/?__a=1`;
        
        let res; 

        try {
            res = await fetch(url).then(url => url.json());
        } catch (e) {
            return message.reply("I couldn't find that account... ")
                .then(m => m.delete(5000));
        }

        const account = res.graphql.user;

        const embed = new MessageEmbed()
            .setColor("RANDOM")
            .setTitle(account.full_name)
            .setURL(`https://instagram.com/${name}`)
            .setThumbnail(account.profile_pic_url_hd)
            .addField("Profile information", stripIndents`**- Username:** ${account.username}
            **- Full name:** ${account.full_name}
            **- Biography:** ${account.biography.length == 0 ? "none" : account.biography}
            **- Posts:** ${account.edge_owner_to_timeline_media.count}
            **- Followers:** ${account.edge_followed_by.count}
            **- Following:** ${account.edge_follow.count}
            **- Private account:** ${account.is_private ? "Yes 🔐" : "Nope 🔓"}`);

        message.channel.send(embed);
    }
}```
amber fractal
#

reason and timeout I believe

#

yep

#

m.delete({timeout: time})

earnest phoenix
#
const Discord = require("discord.js");
const fetch = require("node-fetch");

module.exports.run = async (bot, message, args) => {
    let msg = await message.channel.send("`Se genereaza....`");

    fetch(`https://nekos.life/api/v2/img/slap`)
    .then(res => res.json().then(body => {
        if(!body) return message.channel.send("`Nu am putut genera imaginea!`");
        target = message.mentions.users.first();
        if(!target) return message.reply(":no_entry_sign: **Specifica pe cine vrei sa plesnesti!**");
        then(msg.delete);

        let pEmbed = new Discord.RichEmbed()
        .setColor("#0061ff")
        .setAuthor(`${message.author.username} ii da o palma lui ${target.username}`, message.guild.iconURL)
        .setImage(body.url)
        .setTimestamp()
        .setFooter(bot.user.username.toUpperCase(), bot.user.displayAvatarURL)
        .setURL(body.url);

        msg.channel.send(pEmbed)
        msg.delete();
    }));
}

module.exports.help = {
    name: "slap",
    usage: "lt!slap [user]"
}

why i got error that target and then is not defined?

quartz kindle
#

add a let to target

#

and then doesnt exist

#

you probably meant message.reply().then()

earnest phoenix
#

in discord.js v11.5.1 then does not exist?

quartz kindle
#

no, in your code it doesnt

#

you're using then() as a standalone function

amber fractal
#

you mean to thenify the promise

quartz kindle
#

which is invalid

earnest phoenix
#

i want it to delete that messsage

let msg = await message.channel.send("`Se genereaza....`");
quartz kindle
#

thats what i said

clear wraith
#

What would be a good timeout amount?

quartz kindle
#

you probably meant message.reply().then()

pale vessel
#

3 seconds

amber fractal
quartz kindle
#

or in your case, if you want to delete msg then just msg.delete()

earnest phoenix
#

Ok, ty

fallow quiver
#

I'm working with discord.js. I want to get a role mentions. I used message.mentions.roles.first() and it got the first mention fine, but there isn't a mentions:roles:second() function and calling it as an array didn't work either. What is the correct way to get the value of the second role mention

amber fractal
#

because it's a collection

#

you can turn it into an array though

#

you can use <Collection>.array(), but I would use Array.from(<Collection>.values())

quartz kindle
#

isnt collection.values() already an array?

amber fractal
#

no it's a map iterator

fallow quiver
#

So the mentions is a map

amber fractal
#

it's a collection, which extends a Map

fallow quiver
#

Ah

honest perch
#
message.guild.owner.user.tag
``` this should work right?
amber fractal
#

not always

#

it'll work if the owner is cached

honest perch
#

right.

fallow quiver
#

I tried Array.from(message.mentions.roles.values());, an iterator of 0 returned the first mention and an iterator of 1 returned the 3rd

amber fractal
#

does it contain all mentions though?

#

Because if it does that's just an issue with how it returns

#

can't guarantee the order

fallow quiver
#

I printed it and I read all 3

amber fractal
fallow quiver
#

Oh

#

Hmm

amber fractal
#

You could parse them yourself I suppose

#

getting id's and fetching roles

clear wraith
#

My jumbo command is not replying to me but it replies to the logs, how can i get it to respond to me and work?

  let disabled = 0;
  var fs = require("fs");

  fs.readFile("./e/cmds.json", "utf8", function(err, contents) {
    var c = JSON.parse(contents);
    if (c.other === "0") {
      msg.channel.send();
    } else {
      cc();
    }
  });
  function cc() {
    if (args.length < 1) {
      throw "Please provide an emoji to enlarge.";
    }

    if (args[0].charCodeAt(0) >= 55296) {
      throw "Cannot enlarge built-in discord emoji.";
    }

    const match = args[0].match(/<:[a-zA-Z0-9_-]+:(\d{18})>/);

    if (!match || !match[1]) {
      throw "Please provide a valid emoji.";
    }

    const emoji = bot.emojis.get(match[1]);

    if (!emoji) {
      throw "That emoji could not be identified!";
    }

    msg.channel.send({
      files: [emoji.url]
    });
  }

  exports.info = {
    name: "jumbo",
    usage: "c!jumbo <emoji>",
    description: "Enlarges emojis!"
  };
};
#

It says this in the logs:

      ^
Cannot enlarge built-in discord emoji.
amber fractal
#

you can't enlarge built-in discord emojis because they are unicode characters

#

custom emojis are pictures

#

easily resizable

clear wraith
#

How can I get it to respond in the channel not the logs?

amber fractal
#

catching the error and routing it to the message's channel

#

using try{}catch(e){} syntax

earnest phoenix
#

you can't enlarge built-in discord emojis because they are unicode characters
@Steven4547466#1407

discord uses twemoji to render emojis, so you can

#

thank you discord

#

the emojis are in a vector format which means easily resizable

clear wraith
#

oh

amber fractal
#

Oh, I didn't know that

earnest phoenix
#

Hello.
How do you link two JS files? Please.

summer torrent
#

require(filepath)

earnest phoenix
#

And when the files are in a child folder?

quartz kindle
#

require("./folder/file.js")

earnest phoenix
#

Should I put
const client = require('./foldchild/foldchild/file.js');
?

quartz kindle
#

sure if thats what you want

#

your file.js needs to have module or module.exports

green vale
#

is it possible to check if a bot is verified in djs

earnest phoenix
#

ah how do we do to add a module.exports ?

quartz kindle
#

@green vale user.fetchFlags()

green vale
#

oh alr

quartz kindle
#

user.flags should also work

#

but its not guaranteed to be correct/updated

#

and also for some reason user.flags is not in the docs lol

#

@earnest phoenix for example ```js
// file.js
function abc() {
return 10
}
module.exports = abc; // export the function abc

// main file
const a = require("./file.js") // a becomes the function you exported in file.js
console.log(a()) // logs 10

hard owl
#

what permissions is the best idea for someone to need on muting someone?

sudden geyser
#

Manage Roles

hard owl
#

ok

#

thx

sudden geyser
#

That's only an example.

#

There are many

earnest phoenix
#

I'll try this that. Thank you ^^
If I have a bug I'll tell you 🙂

#
  if(command === "tes1") {
    let functions = require("./functions.js")
    const abc = functions.abc()
    console.log(abc)
  }```
i tried getting a function from another file
#
function abc() {
  return 10
}```
this is the function
#

and i have no idea how to access the function

#

Hmm ... I tried but it doesn't work @quartz kindle

#

I have a problem with a NSFW command, can someone help me in dm?

maiden mauve
#

is this bad practice?

#

( c - b )

#

leaving a value null for subtraction if it doesn't have a value, basically

mossy vine
#

subtracting by null? yes, absolutely

maiden mauve
#

it's either an integer or null

mossy vine
#

why not just default it to 1 then

earnest phoenix
#
  if(command === "tes1") {
    let functions = require("./functions.js")
    const abc = functions.abc()
    console.log(abc)
  }```
i tried getting a function from another file

@earnest phoenix

maiden mauve
#

I just was being lazy with validation

#

if it doesn't exist and subtracts nothing, that's what the validation would have done anyhow

#

if(null) skip this

mossy vine
#

oh wait it subtracts from c

#

not c+a

#

just default it to 0 then

#

still better

maiden mauve
#

yeah c+a was just in there lol

earnest phoenix
#

@earnest phoenix I tried but it doesn't work too

mossy vine
#

b = someDankVariableThatMightBeNull || 0

maiden mauve
#

well the context is that an object is null to begin with because theres no definition

#

"no equipped weapon"

#

so when a player equips a weapon that has stats

#

it adds the new stats and subtracts nothing (null)

#

whereas the more normal pattern is to subtract the old weapons stats

turbid bough
#

Anyone know how to deal with custom types in postgres and EF Core?
The property 'DiscordServer.stats' is of type 'ServerStatistics' which is not supported by current database provider.
Ive heard you can use JSON for simulating custom types, is there an another way?

maiden mauve
#

I could force there to be a value just looking at shortcuts

earnest phoenix
#

I have a problem with a NSFW command, can someone help me in dm?

maiden mauve
#

can't you just edit the command to make it SFW for someone to help you?

#

just how NSFW can it be

#

every single variable name and string is that diabolical

earnest phoenix
#

yall gotta stop implementing titties in your commands because you think 9 year olds will use them

#

@earnest phoenix I'm doing this only because my guild members want so

turbid bough
#

ah wait, you just need to make an entity of it, and it will work?

#

wait, lemme read it again

earnest phoenix
#

how can i access a function from another file?

#
        if(target.id === message.author.id) return message.channel.send(':no_entry_sign: **Nu te poti face asta!**');
                    ^
TypeError: Cannot read property 'id' of undefined
#

help ?

maiden mauve
#

Itay you require it and define it

earnest phoenix
#

target is not defined

#

target is already defined

#
  if(command === "tes1") {
    let functions = require("./functions.js")
    const abc = functions.abc()
    console.log(abc)
  }```
#

i tried that

#

but it didnt work

#

@maiden mauve

#
let target = message.mentions.users.first();A
maiden mauve
#

are they in the same folder?

earnest phoenix
#

there is no folder

maiden mauve
#

also

#

your functions.js has to properly export

earnest phoenix
#

oh

maiden mauve
#
const functions =  
{
    getRandomInt: function(min, max) {
          min = Math.ceil(min);
         max = Math.floor(max);
          return Math.floor( Math.random() * (max - min + 1) + min);
    },
};
module.exports = functions;

#

for example

#

then the rest of your code looks like it should work

earnest phoenix
#

thank

#

s

#

worked!

maiden mauve
#

👍

earnest phoenix
#

How can I make a file that does not contain my token work?

maiden mauve
#

you mean hide your token somewhere besides a file?

#

if your hosting it on a server you can define variables

#

token: process.env.WEBSERVERGLOBALVALUE

earnest phoenix
#

Make two files.
One with my functions and one with my token.

maiden mauve
#

just export like above

quartz kindle
#

you can use module.exports like i told you before

maiden mauve
#

define it in 1 file

#

and use it in another

#

it's a 101 require/export

earnest phoenix
#

I tried but it doesn't work sTim

quartz kindle
#

then you did it wrong

#

show what you did

opaque seal
#

How do I remove a role / user from the permission list of a channel? Like when you click remove #role from the permissions role list
I tried setting the permission to null but it won't actually remove the role from the list

maiden mauve
#

I'd start at whatever object that is in djs

#

or whatever language 😄

earnest phoenix
#

ReferenceError: client is not defined

maiden mauve
#

that's the error

#

show him what you have in each file, but change your token so you don't show everyone

#

it should only be a few lines of code as a bare bones example

earnest phoenix
#
  return 10
}
module.exports = abc; 

// Create an event listener for new guild members
client.on('guildMemberAdd', member => {
  // Send the message to a designated channel on a server:
  const channel = member.guild.channels.cache.find(ch => ch.name === 'member-log');
  // Do nothing if the channel wasn't found on this server
  if (!channel) return;
  // Send the message, mentioning the member
  channel.send(`Bienvenue ${member}`);
});```

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

client.on('ready', () => {
    console.log('I am ready!');
}); 

// Create an event listener for messages
client.on('message', message => {
  if (message.content === 'ping') {
    message.channel.send('pong');
  }
});

const a = require("./modules/bases/bienvenue.js") // a becomes the function you exported in file.js
console.log(a())

client.login('mytoken');```
#

I hidden my token by mytoken

maiden mauve
#

Well for starters

lucid pasture
#

yo does anyone know how to make a command where the bot addresses a certain person, like a kill<member> command? because mine is not working

maiden mauve
#

only 1 file should initialize the client

#

the file you define Discord in should have all your client#event functions

polar sedge
#

Is there any bot?
Who can ban any member.... And delete his all messages?

maiden mauve
#

that's your error message anyhow

quartz kindle
#

lol you just copied what i said

#

instead of reading what i wrote

maiden mauve
earnest phoenix
#

it seems that you did not understand my concern.

I would like to have a hidden file with my token and another set of files with my functions (which I will create later)

quartz kindle
#

i know what you want, and i explained it how to do it

#

but you didnt read what i explained, you just copied it

earnest phoenix
#

so people don't have access to my token

opaque seal
#

How do I remove a role / user from the permission list of a channel? Like when you click remove #role from the permissions role list
I tried setting the permission to null but it won't actually remove the role from the list
anyone knows?

quartz kindle
#

who would have access to your token?

#

are you going to post your code on github?

#

because for that its a different process

#

depending on why you want to hide it

blazing portal
#

@opaque seal in Discord.js sadly the only way i have found to do this is to get the current permission overwrites in an array, delete the one you want deleted and set the new permission overwrites to the array you just copied

mystic violet
#

28kbps smh

lucid pasture
#

yikes chief

maiden mauve
#

pull your wifi out of your attic

fallow quiver
#

Has the Discord.js method to add roles changed? member.addRole(id) doesn't seem to work anymore

opaque seal
#

@opaque seal in Discord.js sadly the only way i have found to do this is to get the current permission overwrites in an array, delete the one you want deleted and set the new permission overwrites to the array you just copied
@blazing portal I was hoping this wasn'tthe case

#

Rip

mystic violet
#

its hard wired connection doe

maiden mauve
#

@fallow quiver I learned alot from v11 to v12 notes

#

im not sure if that was hit or not

fallow quiver
#

Yeah, I know a lot changed

blazing portal
#

@fallow quiver in D.js it is now member.roles.add(role)

fallow quiver
#

Ah

#

cool

earnest phoenix
#

Files fonctionsconst { token, prefix, owner } = require('./auth.js'); client.login(token);

File auth const Discord = require('discord.js'); const client = new Discord.Client(); client.on('ready', () => { console.log('I am ready!'); }); client.login('mytokennumber');

fallow quiver
#

I had to go through my code when V12 came out and add a .cache to a lot of things

quartz kindle
#

@opaque seal @blazing portal channel.permissionOverwrites.delete()

opaque seal
#

@opaque seal @blazing portal channel.permissionOverwrites.delete()
does this delete all perms?

#

I just need to delete 1 role from them

quartz kindle
#

channel.permissionOverwrites.get(id).delete()

opaque seal
#

thanks

blazing portal
#

oh boy, dunno how i couldve missed that xD

#

ty

maiden mauve
#

@earnest phoenix both files can't login to the client, its a 1-time thing

quartz kindle
#

@earnest phoenix ```js
// auth.js
module.exports = {
token: "pgjpwiegjpw",
prefix: "we",
owner: "063094583045398450"
}

earnest phoenix
#

??

#

just that ?

quartz kindle
#

yes

maiden mauve
#

Tim gave you the exact syntax of a file that has variables

earnest phoenix
#

Files fonctionsconst { token, prefix, owner } = require('./auth.js'); client.login(token);

File auth```
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', () => {
console.log('I am ready!');
});
client.login('mytokennumber');

module.exports = {
token: "pgjpwiegjpw",
prefix: "we",
owner: "063094583045398450"
}```

#

?

quartz kindle
#

no

earnest phoenix
#

heu...

#

in a auth.js file ?

turbid bough
#

@earnest phoenix idk how you get that g.OwnsOne(x => x.AutoMod); working :/ im feeling that im doing the correct way, buts it not. trying also to use [Column] attribute to specify which column it is, but its still finding the wrong oen.

maiden mauve
#
//Index file:
const { token, prefix, owner} = require('./auth.js');
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', () => {
    console.log(`My prefix is ${prefix} and my owner is ${owner}`);
}); 
client.login(token);
//auth.js file:
module.exports = {
  token: "123",
  prefix: ">",
  owner: "dantheman"
}
#

its spoon feeding

#

but this is the basics of a bot file

#

You would do well to look at some intro videos for discord bots

earnest phoenix
#

in each files of fonctions I must put const { token, prefix, owner} = require('./auth.js'); const Discord = require('discord.js'); const client = new Discord.Client(); client.on('ready', () => { console.log(`My prefix is ${prefix} and my owner is ${owner}`); }); client.login(token);
Right ?

quartz kindle
#

no

#

the discord client is ONLY in the main file

#

and you only login once

earnest phoenix
#

because I want create many files .js

quartz kindle
#

then look into how to make a command handler

#

basically

#

your functions files will be this

maiden mauve
#

@earnest phoenix if you don't understand any line of what we're sending, do some research. This is only the beginning and its very basic.

quartz kindle
#
// myfunction.js

module.exports = (client,message) => {
  // do my thing with client and message
}```

and your main file will have this ```js
client.on("message", message => {
  // check for prefix
  // check for command
  // require the command file
  commandFile(client,message)
})
earnest phoenix
#

exemple
folder

  • index.js
  • auth.js
  • folder > modules
    _module1.js
    _module2.js
    _etc...
quartz kindle
#

your main file loads the modules when it needs them

#

if you receive a message that contains a prefix and a command, then you load the command module and run it

#

the module doesnt receive messages nor have a discord client, only the main file does

earnest phoenix
#

@quartz kindle so if I understood correctly I must:

  1. make an auth.js file with module.exports = { token: "123", prefix: "> or ! or blabla", owner: "owner" }
  2. make an index.js file with const { token, prefix, owner} = require('./auth.js'); const Discord = require('discord.js'); const client = new Discord.Client(); client.on('ready', () => { console.log(`Prêt`); }); client.login(token); client.on (" message ", message => { // check for prefix // check for command // require the command file commandFile (client, message) })
  3. all other module files with module.exports = (client, message) => { ... }

Right?

maiden mauve
#

do you understand the relationship between requires and module.exports?

#

you can scratchpad the code without your bot

earnest phoenix
#

I'm not english so I have so difficult too understand

maiden mauve
#

are you french?

earnest phoenix
#

yes

sour jungle
#

I cant seem to get a reboot command for py i can only do it for js but my bot is coded with python

maiden mauve
#

have you tried search for french videos on discordjs bot tutorials?

#

many people have good videos up with step-by-step explanations

earnest phoenix
#

yes but i don't find for that

#

Will discord.js v11 stop being supported ?

#

They don't hidden their token

#

But I know it's possible

#

so i'm asking here

quartz kindle
#

@earnest phoenix you will need to change some code depending on what exactly you want to do

#

if its commands for messages, it will be enough, but if its other events, for example when members join, or when the bot joins a new guild, then you will need to create specific code for that

#

and you will need to complete the code based on the comments i wrote

#

it will not work if you just copy and paste it exactly like that

earnest phoenix
#

ok that is fonctions

#

but for the rest is good ?

#

auth.js
index.js
and the base of module1.js ?

quartz kindle
#

if module1.js is a command, yes

earnest phoenix
#
  token: "123",
  prefix: "> or ! or blabla",
  owner: "owner"
} ```
2. make an index.js file with ```const { token, prefix, owner} = require('./auth.js');
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', () => {
    console.log(`Prêt`);
}); 
client.login(token);
client.on (" message ", message => {
  // check for prefix
  // check for command
  // require the command file
  commandFile (client, message)
}) ```
3. all other module files with ``` module.exports = (client, message) => {
client.on('message', message => {
  if (message.content === 'ping') {
    message.channel.send('pong');
  }
})
} ```
quartz kindle
#

no

maiden mauve
earnest phoenix
#
  token: "123",
  prefix: "> or ! or blabla",
  owner: "owner"
} ```
2. make an index.js file with ```const { token, prefix, owner} = require('./auth.js');
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', () => {
    console.log(`Prêt`);
}); 
client.login(token);
client.on (" message ", message => {
  // check for prefix
  // check for command
  // require the command file
  commandFile (client, message)
}) ```
3. all other module files with ``` module.exports = (client, message) => {
}
client.on('message', message => {
  if (message.content === 'ping') {
    message.channel.send('pong');
  }
})``` 

better ?
maiden mauve
#

do my example files make sense?

quartz kindle
earnest phoenix
#

Okay Tim I think I understand
thx

#

👍

carmine magnet
#

Hi ! How to get the ram usage of a bot ?

clear wraith
#
                                   ^
TypeError: eventFunc.bind is not a function```
#

Is that not a function anymore?

summer torrent
#

what is your node.js version oliythink

clear wraith
#

i use discord.js

#

not node

carmine magnet
#

Oof

pale vessel
#

yikes

carmine magnet
#

Djs use node

clear wraith
#

unless im supposed to use node.js

pale vessel
#

you ARE using node

#

by using discord.js

earnest phoenix
#

Does anyone know how to let a user bypass a command cooldown (python - dont hate)

clear wraith
#

I installed node.js as a package

mossy vine
#

oh boy

#

ok so

#

javascript is the language
node.js is the runtime, it executes the javascript code
discord.js is the code making it possible to communicate with discord

clear wraith
#

mhmm

pale vessel
#

discord.node.js

opaque seal
#

@opaque seal channel.permissionOverwrites.delete()
does this work for deleting all permissionOverwrites?

pale vessel
#

have you tried reading the docs

opaque seal
#

Couldn't find it

valid bison
#

Hello?

pale vessel
#

so you need to make a loop for channel#permissionOverwrites and delete them one by one. there's probably a better way than this honestly

#

like overwritePermissions

carmine magnet
#

Hi ! How to get the ram usage of a bot ?

valid bison
#

hello? >~<

carmine magnet
#

Hi

valid bison
#

I have a question but ill wait >~<

pale vessel
#

what programming language @carmine magnet

sudden geyser
#

Wait for what?

pale vessel
#

@valid bison ask away

carmine magnet
#

JS

pale vessel
#

node?

carmine magnet
#

Yes

pale vessel
quartz kindle
#

process.memoryUsage().rss

carmine magnet
#

Im using djs

valid bison
#

How do i set up a bot to send a message to a channel not as a reply? Also embarrassing disclaimer im pretty new to all this >~<

carmine magnet
#

Ok thanks

pale vessel
#

channel#send

valid bison
#

Do i need the channel ID?

pale vessel
#

no

carmine magnet
#

message.channel.send()

valid bison
#

Ok

mossy vine
#

@carmine magnet pretty sure thats not what they were asking for

quartz kindle
#

you need a channel, and there are many ways to get a channel, message.channel being one of them (the channel where the received message came from)

opaque seal
carmine magnet
#

Oof ok

green vale
#

How can I get the second mention in a message? I know that there's .first() but is there something like that for a second mention?

clear wraith
#
  throw err;
  ^
Error: Could not locate the bindings file. Tried:``` This error keeps popping up about a bindings file. even though i do not have a bindings file. I do not know where this came from.
green vale
#

I had an error like that before

#

Do you use better-sqlite3?

quartz kindle
#

run enable-pnpm in your glitch console

clear wraith
#

ok

quartz kindle
#

@green vale there is no specific method for second item in a collection, but there are many ways to get it

green vale
#

Oh alr

quartz kindle
#

for example Array.from(message.mentions.users.values())[1]

#

or message.mentions.users.first(2).last()

green vale
#

Would something like message.mentions.users.array()[1] work?

quartz kindle
#

but be aware that the order in which they are given is not the same order as they show up in a message

#

that would also work yes

clear wraith
#

Thanks Tim!

green vale
#

Okay

#

[0] would give the first object*, right?

quartz kindle
#

a second mention may be the first and the first mention may be the second

#

the order is not guaranteed

#

yes

green vale
#

That's alright

#

Okay ty

#

I'll just use the .first(2).last() example you used, because I'm already using .first()

quartz kindle
#

you can also do ```js
let mentions = message.mentions.users.first(2);
mentions.first()
mentions.last()

green vale
#

Oh okay

amber fractal
#

You have to be careful though, message.mentions is unordered

#

it may not be the same order as the message

copper cradle
#

to start the bot he does 'node <name>. js'
then proceeds to say: 'I use discord.js, not node.js'

quartz kindle
#

he uses glitch

#

so he never has to do that lmao

valid bison
#

I tried the channel thing but its not responding >~<

pale vessel
#

what's your code?

valid bison
#

I have it as a case under switch(args[0]){

I wrote it as
case 'welcome':
message.channel.send('Welcome new member!')

quartz kindle
#

is this in a message event?

#

show your full message event

pale vessel
#

put it inside a codeblock

valid bison
#

I feel dumb but what is that? >~< I need help

#

Im sorry

quartz kindle
#

this is the message event: client.on("message", ...)

pale vessel
#

it's okay, just paste the full message event here

quartz kindle
#

the full message event would be js client.on("message", message => { // everything inside here including the line above and below })

valid bison
#
bot.on('message', message=>{

    let args = message.content.substring(PREFIX.length).split(" ");

    switch(args[0]){
        case 'ping':
            message.reply('pong')
            break;
        case 'info':
            if(args[1] === 'version'){
                message.reply(version)
            }
            if(args[2] === 'creator'){
                message.reply(creator)
            }
            if(args[3] === 'admin'){
                message.reply(TJM)
            }
            else{
                message.reply('Invalid Command')
            }
        case 'welcome':
            message.channel.send('Welcome to the server new member!')
            break;
    }
})
#

whoops

#

i missed a part >~<

pale vessel
#

you can edit the message

valid bison
#

ye lemme do that

quartz kindle
#

and put the code inside code blocks

#

like this

#

```js
code here
```

valid bison
#

did it /~\ finally

quartz kindle
#

it should work

pale vessel
#

you adding a break before welcome

quartz kindle
valid bison
#

wait. . . oh!

quartz kindle
#

otherwise when you do the info command, it will run both info and welcome

valid bison
#

thats what i forgot im sorry >~<

quartz kindle
#

but the welcome command should work, i dont see anything wrong with it

valid bison
#

lemme run it again

#

It works >//~//< sorry for all that

pale vessel
#

we're here to help, no need to apologise! :)

valid bison
#

Okay ^//~//^

#

. . . under the info if statement. . if i were to add an if for "!info rules" how would I make the bot list all the rules? Cuz when i tried that it got confused and wouldn't run >~<

pale vessel
#

it should be args[1] on all of them

#

not 123

valid bison
#

Okay >~<

pale vessel
#

also, use else if:```js
if (args[1] === "something") {

}

else if (args[1] === "something") {

}

else {}```

#

you can also use a switch, which is faster

earnest phoenix
#

^

#

if you don't need to calculate or evaluate some values and only compare values directly, use switch

#

switch jumps to the point in the memory instead of doing extra operations

valid bison
#

Im understanding most of this >~< yes

#

Like this is how it should look now for what I sent earlier?

#
bot.on('message', message=>{

    let args = message.content.substring(PREFIX.length).split(" ");

    switch(args[0]){
        case 'ping':
            message.reply('pong')
            break;
        case 'info':
            if(args[1] === 'version'){
                message.reply(version)
            }
            else if(args[1] === 'creator'){
                message.reply(creator)
            }
            else if(args[1] === 'admin'){
                message.reply(TJM)
            }
            else{}
                message.reply('Invalid Command')
            break;
        case 'welcome':
            message.channel.send('Welcome to the server new member!')
            break;
    }
})
#

Is this right? >~<

pale vessel
#

message.reply should be in else { here }

valid bison
#

Oooooh

#

Whoops >~<

#

Ok

pale vessel
#

you can do this too:js case "info": switch(args[1]) { case "version": message.reply(something); break; } break;

#

please correct me if i'm wrong since i barely use switches

valid bison
#

Ive barely done any of this in so long so i hope Cry comes back /~\

pale vessel
#

yes, cry is god

valid bison
#

Lol

#

Sadly this is just me trying to learn basic before all the major stuffs buries me alive /~\ if i explained its desired functions do u think u could teach me or refer me to someone or a place that could help me gain better knowledge on how to properly code the bot? >~<

pale vessel
#

you would want to learn javascript first

valid bison
#

Yes >~<

pale vessel
valid bison
#

Thank u /w\

slim heart
#
  query (query, fill) {
    return new Promise((resolve, reject) => {
      const cb = (error, results) => {
        if (error) return reject(error)
        resolve(results)
      }
      this.db.query(query, fill || cb, fill ? undefined : cb)
    })
  }

  token (token) {
    return this.query(`SELECT * FROM users WHERE ?`, { token })
  }```
`mysql` library.
would this work 👀 ?
unique nimbus
#

if that is the right domain

#

smh

slim heart
#

i have no open sql db to use

viral kayak
#

no www

tight heath
#

why www

viral kayak
tight heath
#

www makes no sENSE there

slim heart
#

😔

#

ive literally never used sql sks

viral kayak
#

i only use better-sqlite3

#

wew

wintry sonnet
#

const { NovelCovid } = require('novelcovid');

const track = new NovelCovid();

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

    let nothing = new Discord.MessageEmbed()
    .setTitle('No country provided')
    .setDescription(':x: You have not provided a US state. Usage: `c!state <US STATE>`');

    let noresults = new Discord.MessageEmbed()
    .setTitle('Undefined')
    .setDescription(':x: Enter a **valid** US state. Usage: `c!state <US STATE>`');

if(!args[0]) return message.channel.send(nothing);

let corona = await track.historical(null, 'Canada', args.join(" "));

console.log(corona);

if(corona.result === undefined) return message.channel.send(noresults);
   
let coronaembed = new Discord.MessageEmbed()
.setTitle(`${corona.historical}`)
.setColor("#ff2050")
.setDescription(`ℹ Info on COVID-19 in **${corona.historical}**`)
.addField("Total Cases", corona.cases, true)
.addField("Total Deaths", corona.deaths, true)
.addField("Total Recovered", corona.recovered, true)
.addField("Today's Cases", corona.todayCases, true)
.addField("Today's Deaths", corona.todayDeaths, true)
.addField("Active Cases", corona.active, true)
.setFooter('COVID-19 Tracker', client.user.displayAvatarURL())

message.channel.send(coronaembed);


}
exports.help = {
    name: "province",
    aliases: []
}```

Error: Always returns undefined. It logs this in the console (https://hastebin.com/mekuhohedu.bash)
pale vessel
#

what always returns undefined

#

the embed

#

i see

wintry sonnet
#

The search. When I run the command (c!province Alberta), it always returns the noresults embed

pale vessel
#

if you look at the object there's no property called result

#

so it makes sense

wintry sonnet
#

So, get rid of result

earnest phoenix
#

does anyone know what this person means by " you load your commands in your client on message listener... move it outside"

quartz kindle
#

it means exactly what he said

heavy marsh
#

In discord.js - v12.2.2
Is this correct to get shard events

//Bot Shard Logs
//Shard Reconnections
bot.on("shardDisconnect", () => {
console.log(`Shard ${bot.shard.ids} disconnected!`) 
});
//Shard Reconnections
bot.on("shardReconnecting", () => {
console.log(`Shard ${bot.shard.ids} reconnecting!`) 
});
//Shard Resumed
bot.on("shardResume", () => {
console.log(`Shard ${bot.shard.ids} resumed!`) 
});
//Shard Ready
bot.on("shardReady", () => {
console.log(`Shard ${bot.shard.ids} ready!`) 
});
quartz kindle
#

not exactly

heavy marsh
#

What might be the error

#

${bot.shard.id} = undefined

quartz kindle
heavy marsh
#

but id gave me undefined

quartz kindle
pale vessel
#

what's the browser

quartz kindle
#

brave

heavy marsh
#
//Bot Shard Logs
//Shard Reconnections
bot.on("shardDisconnect", (id) => {
console.log(`Shard ${bot.shard.id} disconnected!`) 
});
//Shard Reconnections
bot.on("shardReconnecting", (id) => {
console.log(`Shard ${bot.shard.id} reconnecting!`) 
});
//Shard Resumed
bot.on("shardResume", (id) => {
console.log(`Shard ${bot.shard.id} resumed!`) 
});
//Shard Ready
bot.on("shardReady", (id) => {
console.log(`Shard ${bot.shard.id} ready!`) 
});
pale vessel
#

is vivaldi a good choice

heavy marsh
#

or is it just id

quartz kindle
#

@heavy marsh its in the order i showed you

heavy marsh
#
//Bot Shard Logs
//Shard Reconnections
bot.on("shardDisconnect", (id) => {
console.log(`Shard ${id} disconnected!`) 
});
//Shard Reconnections
bot.on("shardReconnecting", (id) => {
console.log(`Shard ${id} reconnecting!`) 
});
//Shard Resumed
bot.on("shardResume", (id) => {
console.log(`Shard ${id} resumed!`) 
});
//Shard Ready
bot.on("shardReady", (id) => {
console.log(`Shard ${id} ready!`) 
});
pale vessel
#

you need to add both parameters

quartz kindle
#

shardDisconnect gives you event and id

#

so .on("shardDisconnect", (event,id) => { })

#

each event have their own specific parameters

#

as explained in the docs

earnest phoenix
#
bot.commands = new Discord.Collection();

bot.on('debug', console.log);
bot.once('ready', () => {
    console.log('Bot Started With No Errors');
    bot.user.setPresence({
        activity: {
            name: 'Crying Without Knowing Why | . or >help to Start'
        },
        status: 'idle'
    })

})
bot.on('message', message => {
    const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));

    const args = message.content.slice(prefix.length).split(/ +/);
    const commandName = args.shift().toLowerCase();

    const command = bot.commands.get(commandName) ||
        bot.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));


    if (!message.content.startsWith(prefix) || message.author.bot) return;

    for (const file of commandFiles) {
        const command = require(`./commands/${file}`);
        bot.commands.set(command.name, command);
    }
    try {
        command.execute(message, args);
    } catch (error) {
        console.error(error);
        message.channel.send('there was an error trying to execute that command!');
        if (typeof execute !== 'undefined') {}
        }
    });``` this gives me a 'undefined' error. execute is supposedly undefined
#

this is for my command handler

heavy marsh
#
bot.on("shardDisconnect", (event, id) => {
console.log(`Shard ${id} disconnected!`) 
});
quartz kindle
#

@earnest phoenix if you still didnt understand:
this is an event listener -> client/bot.on("something") where "something" is the event
the message event listener would be client/bot.on("message", message =>) etc...
everything that is inside the event listener block gets executed on EVERY SINGLE MESSAGE you receive from discord, which can be hundreds of messages per second
you should not load your commands inside there as you're reloading them every single time and using a SHIT TON of cpu and disk for no reason

earnest phoenix
#

well that was WAY more clear than what I was getting in the official discord.js server

#

no offense to them

quartz kindle
#

i feel you

#

lmao

earnest phoenix
#

so the try command?

quartz kindle
#

fs.readdirSync is a command that scans all files in a folder

#

imagine you receive 100 messages per second from discord

#

you're scanning all your folders 100 times per second

#

instead, scan your folders when your bot starts and save the list of folders in a variable

#

so every time you receive a message, you just get the list of folders from there, instead of re-scanning again

earnest phoenix
#

well the bot has started for the first time since 12 this morning

#

thanks

#

but TypeError: Cannot read property 'execute' of undefined

quartz kindle
earnest phoenix
#

thank you for being transparent and working with me

quartz kindle
#

its fine as long as you understand why you should do what im telling you to do

earnest phoenix
#

it works thank you so much

#

allow me to add your bot to my server

quartz kindle
#

lol sure

turbid wharf
#

how to make undefined handler?

quartz kindle
#

wat

winged gull
#

can someone help me with 2 things?
first: how do i add a counter to my bot in python?
second: to keep my bot running all the time do i have to keep the cmd open?

quartz kindle
#

bots only run as long as their program is running, so yes

#

i dont use python so idk, but should be something along the lines of counter = 0 and then counter++

amber fractal
#

you can use a process manager tho

#

idk any windows process managers tho

proper mist
#

hey can someone help im trying to make a bot that create a channel when a command is sent and it says this
: msg.guild.createchannel is not a function

quartz kindle
#

which library and version of the library?

proper mist
#

how do i find this out

#

it's just the newest one

quartz kindle
#

which programming language?

proper mist
#

js

#

discord.js

quartz kindle
#

so discord.js v12 most likely

proper mist
#
client.on('message', msg => {
    if(msg.content.startsWith('/channels')){
      let channelname = msg.content.slice('/channels'.length); // cuts off the /private part
      msg.channel.send("Creating 50 New Text Channels Named: " + "**" + channelname + "**")

    var i;
    for (i = 0; i < 50; i++) {
    setTimeout(() => {

        msg.guild.createChannel(channelname,{type: 'text'})
        .then(console.log)
        .catch(console.error);

    },1*1) //3 seconden
    }
    }
#

i have this

#

and it says its not a function

quartz kindle
#

in discord.js v12, its guild.channels.create() instead of guild.createChannel()

proper mist
#

oh ok thx