#development
1 messages Β· Page 876 of 1
so its saying that guild is undefined for you grayald?
is the channel undefined
well your error is saying cannot read channels of undefined, so whatever is before channels is undefined
@cinder patio not sure but you wanted something like this?
const RandomElementGenerator = (array) => {
let tempArray = [...array]
return () => {
const randomNumber = Math.floor(Math.random() * tempArray.length)
const elementToReturn = tempArray[randomNumber]
tempArray.splice(randomNumber, 1)
if (!tempArray.length) tempArray = [...array]
return elementToReturn
}
}
const exampleArray = [23, 351, 213, 521, 4123]
const randomElementGenerator = RandomElementGenerator(exampleArray)
console.log(randomElementGenerator())
console.log(randomElementGenerator())
console.log(randomElementGenerator())
console.log(randomElementGenerator())
console.log(randomElementGenerator())
console.log(randomElementGenerator())
you'll need to get message from reaction
changing the listener?
(reaction, message, user)
no no, so messageReactionAdd passes reaction and user - you just need to pull message from the reaction object
in bot.on
messageReactionAdd does not pass message
please best paste code
Ima copy code one sec
ok
case 'ping':
//message.channel.send('pong!');
//console.log(message.member + ' USED 'ping' PROMPT')
//break;
ping_msg = message.channel.send(π Pinging...)
message.channel.send(`π Pong!\nLatency is ${Math.floor(ping_msg.createdAt - message.createdAt)}ms\nAPI Latency is ${Math.round(bot.ping)}ms`);
break;
Ignore the first bit (itβs old code)
It starts at ping_msg =
ok
message.channel.send(`:ping_pong: Pong!\nLatency is ${ping_msg.createdTimestamp - msg.createdTimestamp}ms\nAPI Latency is ${Math.round(client.ping)}ms.`);
try it
I think the last thing I need is the system to make the bot know when people reacted. Then it will change the number from 0, and will add 1 for each time the users reacted. when it reaches the limit (7) in this case, it should send a message...
@oak cliff Really thank you for helping me :')
so you want something to incriment every time you get a vote and then when it hits a certain number, stop?
exactly
@coarse topaz that shouldn't be too hard
and it will send a message when the limit is reached
Np
well you could either store it in a db or call message.reactions.cache.size every time
You just check on the message reaction add event if the message id = the id of the message
and check the reaction size
@coarse topaz that shouldn't be too hard
@golden condor I'm sincerely noob at programming, anyway, I've been reading a lot of pages to work it by my self... tho I didn't find something about these features I'm asking here... π
are u on discord.js?
yep
let guild = bot.guilds.cache.get(`675254454139748352`) const channel999 = guild.channel.cache.get(`694189734146211901`) channel999.send({ embed: embed }) });
error: Unhandled Rejection TypeError: Cannot read property 'channel' of undefined
well you could either store it in a db or call message.reactions.cache.size every time
@oak cliff i think the second one is better
yeah probably
and Hector, congrats on trial mod
Sooooooo, how could I figure it out? x)
Thanks Grayal! ^^
I'm trying to give my best π
Yeah
Ah, by the way, I think Discord.js changed the way to send embeds, so I need to work with normal messages... Is there another way to send embeds?
When I try to send an embed, it doesn't work '-' And I'm sure I'm doing everything fine...
I am tryna figure this out wait a sec
Ok, thanks Cx! ^^
There is two ways to do embed
hector can you go general please?
Sure! I'll
const Embed = new Discord.MessageEmbed() //basically the same as RichEmbed
.setTitle("whatever") //etc.
message.channel.send(Embed)
//or
message.channel.send({embed:
title: "whatever" //etc.
})```
@earnest phoenix ^^
client.on("messageReactionAdd", async(messageReaction, user) => {
const emoji = messageReaction.emoji //the reaction emoji
const message = messageReaction.message //the message reacted to
if(!emoji.id === "") //unicode emoji (normal emoji) or a custom emoji (id)
if(!message.id === "the message id") //checks if it is the message you want
if(message.reactions.cache.size === 7) message.channel.send("whatever")
})
message.reactions.cache.size
@coarse topaz I have tried to explain everything in there as best I could so you can understand rather than just spoonfeeding, hope it helps!
oopsy
i always forget too lol
I'm back...
Oh I see! Give me some minutes, I'll try it all... Thanks for being friendly with me! :)
@golden condor
@golden condor Is this how it should be?
My bot doesn't answer to that command '-'
cxllm
how do fix my problem cxllm
@earnest phoenix yes
ejs
okey
Maybe I can try help
@earnest phoenix is that a bot or an OAuth2 login
has nothing to do with discord.js if that's the case
whats the error tho
You on v11?
ah, yes '-'
That'll be it
yeah then update to v12 or change MessageEmbed to RichEmbed
will try they both, thanks!
no dont try both
Not both at the same time
RichEmbed is a v11 thing and MessageEmbed is v12
but updating to v12 changes everything
not that much
i changed it manually
Obviously not they both at the same time, nubie haha
If one doesn't work, then let's try with the next one
You should fix some of that indentation
It's almost impossible to read with that terrible indentation
On glitch you can use the format buttpn
At least something like this 
if(message.content === `testembed`){
const Embed = new Discord.MessageEmbed()
.setTitle(`Hey!`)
.addField(`Hello`, `Hello`);
message.channel.send(Embed)
}```
why should i format that? :(
anything would be better than that indentation
Because it's unreadable
I used to do the same, where my indentation is terrible, but then it would be a nightmare to rewrite / read back my code
I use the vsc auto indenting
It also helps you understand the concept of scoping better
Then what do you mean with identation? π€
like
this
I'm a bit noob at this, really sorry x)
Like when you press the tab button
oh, of course
In
dent
i got it
What happened is that i just copied from what u sent to me, but i tend to make it readable, don't worry about it π
I can change the versions manually, right?
F
Put a proper ver
I tried putting "12.x" , but didn't work.
That's because that's not a proper version number
a
ah
Is JavaScript good choice for Discord bot backend RESTful API?
Really thanks for all your help... I'm trying it now
nah, already ran the command and didn't work again...
Is the Discord.js version a wrong one?
ah, nvm
Hmm.. No... Still not working
Β―_(γ)_/Β―
already updated everything
Just do npm install discord.js
Ohh!
Glitch also needs a start script
What do you mean with that?
"scripts": {
"start": "node index.js"
},```
or something like that
I don't remember
I haven't touched glitch for a long time
You should read this guide if you're really going to use Glitch https://anidiots.guide/other-guides/hosting-on-glitch
where's the error?
@earnest phoenix run this in console
npm install discord.js
b r u h
what?
I wanted to see if he had or not discord.js downloaded haha, you just ask him to install it
#solving problems even easier
@spare goblet ok
http://alex.is-bad.com/8tzk7nz.png
can someone explain me what does that mean? CompressedFormatData is an array
holy shit
Mans added everything he could find online.
http://alex.is-bad.com/8tzk7nz.png
can someone explain me what does that mean? CompressedFormatData is an array
bro you have so many packages wth
Mans added everything he could find online.
^^^ lmao
@coarse topaz did it work?
app@yurianbot:~ 16:36
$ npm install discord.js
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN discord.js@12.2.0 requires a peer of bufferutil@^4.0.1 but none is installed. You must install peer dependencies yourself.
npm WARN discord.js@12.2.0 requires a peer of erlpack@discordapp/erlpack but none is installed. You must install peer dependencies yourself.
npm WARN discord.js@12.2.0 requires a peer of libsodium-wrappers@^0.7.6 but none is installed. You must install peer dependencies yourself.
npm WARN discord.js@12.2.0 requires a peer of sodium@^3.0.2 but none is installed. You must install peer dependencies yourself.
npm WARN discord.js@12.2.0 requires a peer of utf-8-validate@^5.0.2 but none is installed. You must install peer dependencies yourself.
npm WARN discord.js@12.2.0 requires a peer of zlib-sync@^0.1.6 but none is installed. You must install peer dependencies yourself.
npm WARN prism-media@1.2.1 requires a peer of ffmpeg-static@^2.4.0 || ^3.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN prism-media@1.2.1 requires a peer of @discordjs/opus@^0.1.0 but none is installed. You must install peer dependencies yourself.
npm WARN prism-media@1.2.1 requires a peer of node-opus@^0.3.1 but none is installed. You must install peer dependencies yourself.
npm WARN prism-media@1.2.1 requires a peer of opusscript@^0.0.6 but none is installed. You must install peer dependencies yourself.
npm WARN ws@7.2.3 requires a peer of bufferutil@^4.0.1 but none is installed. You must install peer dependencies yourself.
npm WARN ws@7.2.3 requires a peer of utf-8-validate@^5.0.2 but none is installed. You must install peer dependencies yourself.
- discord.js@12.2.0
added 15 packages from 17 contributors and audited 15 packages in 1.862s
found 0 vulnerabilities
AAAAAAAAAAAA
@golden condor Hey! Thanks for asking!... Actually, after updating discord.js package, the bot doesn't answer to any of the commands :c
@spare goblet
@coarse topaz things change in discord.js v12
@golden condor cxlm sorry :D
Unless you wanna update to the new version
@earnest phoenix It's totally ok, no need to paste all that here
@earnest phoenix it should be fine then
And change it to RichEmbed
try running your bot again
It's practically the same
it said discord.js is v12.1.1
he wasn't talking to you?
it said discord.js is v12.1.1
@earnest phoenix Yep, it's the last version
@coarse topaz if you allow me into your glitch project (in dms) I can try help
@coarse topaz if you allow me into your glitch project (in dms) I can try help
@golden condor If you really want, I would thank it very much :)
Let's move to DMs then π
It still said "Error" in the Tools menu
is this glitch or smth?
glitch
add engines in package.json
glitch supports a max of v12 apparently
so i need to downgrade the node to v12
ok
and hilariously it said
"engines": { "node": "8.x" },
it still stuck on the node v8.x
xd
discord.js is v12.2.0 now
Cannot read property of members of undefined
try reading the error
if(command === "someone") {
var user = message.guild.cache.members.random();
const embed = new Discord.MessageEmbed()
.setDescription(`${user.user}`)
.setColor(0x00AE86)
message.channel.send(embed)
cache is inside members
so message.guild.members.cache.random() ?
no
can you specify the amount of shards that you want created?
Does anyone know a bot that can verify that you own an instagram account?
@warm cloud No but a bot that says " Put (LOL) in your bio" and then it checks if you do it and then youre verified
ahh is this a place where i can talk about my errors
Hey folks, I'm using the cooldowns guide from here:
https://discordjs.guide/command-handling/adding-features.html#cooldowns
How can I get out the remaining time in moment.js?
someone knows how to write this correctly at v11.6.2?
my bot keep exceeding 256 mb ram though its only in 340 servers, what'd be the reason?
Hey @earnest phoenix
I tried this myself
if(command === "bansize") {
message.guild.fetchBans()
.then(banned => {
message.channel.send(banned.size)
})
}```
Its supposed to work
fetch the bans
then send banned.size
is there any ratelimit against a bot leaving >n guilds at a time
so its message.guild.fetchBans().size if i aint wrong
i alrdy tried that
see what
wait*
use the method i told you
if(command === "bansize") {
message.guild.fetchBans()
.then(banned => {
message.channel.send(banned.size)
})
}```
@earnest phoenix
is there any ratelimit against a bot leaving >n guilds at a time
@valid frigate
ratelimits exist on all endpoints, if you're using a library which handles them for you, you have nothing to worry about
I am hella confused at this point lmao
ok
i was planning to make a command which allowed my bot to leave any number of guilds but i was limiting it to 5 max per command to be on the safe side
@earnest phoenix your code is a mess
i fixed it
XD
your code is mess xD
it's still a mess
falzepe change avatar pls
Going personally I would use only fields if you can do it.
hmm
You calling someone a self-bot for posting an embed?
just in right order
Ok nvm
to make colums of some fields
in the meantime the AMOLED theme on discord android is entirely black lol
Darkness 100
I have a question on discord.js v11.4.8
Is it possible to make the bor await 10seconds
await member.addRole(`700446711692263544`);
await member.addRole(`700446747083931708`);
await member.guild.channels.get(staffwelcomechannel).send(` **Welcome to the staff server <@${member.id}>!**`);```
setTimeout
oh setTimeout sounds familliar
unfortunately js is singlethreaded so you can't do parallel execution blocking, you have to use setTimeout
I mean wait for 10 seconds then do this part
await member.addRole(`700446711692263544`);
await member.addRole(`700446747083931708`);
await member.guild.channels.get(staffwelcomechannel).send(` **Welcome to the staff server <@${member.id}>!**`);
yes
encapsulate it and pass to settimeout as function
or
just make arrow function afaik
setTimeout(() => {
}, 1000);
await member.addRole(`700446711692263544`);
await member.addRole(`700446747083931708`);
await member.guild.channels.get(staffwelcomechannel).send(` **Welcome to the staff server <@${member.id}>!**`);
Like this?
move all the code into that arrow function
why do you think that the first parameter of setTimeout asks for a func
But then want it do every thing after each 10 seconds
hm
wat
wait 10s
await member.addRole(`700446711692263544`);
wait 10s
await member.addRole(`700446747083931708`);
wait 10s
await member.guild.channels.get(staffwelcomechannel).send(` **Welcome to the staff server <@${member.id}>!**`);
Director
what
Will it do it like that?
no
idk
await member.addRole(`700446711692263544`)
}, 10000);
setTimeout(() => {
await member.addRole(`700446747083931708`)
}, 10000)
setTimeout (() => {
await member.guild.channels.get(staffwelcomechannel).send(`:joins: **Welcome to the staff server <@${member.id}>!**`)
}, 10000);```
I am not JS master, but I would move all rest of code into that arrow function
This should work
hm
OOh so that will do each taking 10 seconds
hm
?
setTimeout(() => {
await member.addRole(`700446711692263544`);
await member.addRole(`700446747083931708`);
await member.guild.channels.get(staffwelcomechannel).send(` **Welcome to the staff server <@${member.id}>!**`);
}, 10000);
are you guys blind
why 3 settimeouts
wHAT WILL THIS DO?
Uhh
1 settimeout
guess what it will do
Wait for 10s then does that?
OOh ok thats what I need
yes
thank you
move entire code you want to have executed after that 10 s
is there anyway to have pm2 restart even when bot responds
Error: getaddrinfo ENOTFOUND
Having a hosting provider network issue but wish the bot to continously retry reconect until it succesds
Perfect π
pm2 restart?
So like this
setTimeout(async() => {
await member.addRole(`700446711692263544`);
await member.addRole(`700446747083931708`);
await member.guild.channels.get(staffwelcomechannel).send(` **Welcome to the staff server <@${member.id}>!**`);
}, 10000);
await console.log(`[ Staff Server Join ] ${member.user.tag} (${member.id}) joined the staff server!`);
i mean having pm2 automatically restart the script once it fails connecting to discord api
Error: getaddrinfo ENOTFOUND
yup director, that's correct
with that error
@serene cliff if you need to have restart when either bot responds or not you just need to use cron to stop and rerun the bot
by the way awaiting console.log won't do anything, it doesn't return a Promise
if you want to do restart once you have error
you need to make your discord bot execute a script which stops the bot and also rerunning it once stopped
@royal herald i think he does it but he is unable to reconnect the bot once it stops i think
why?
Hmm read the error
hosting provider having continous issues and when that occur all of my bots are dead and requires a manual pm2 restart command.. which is tedious and looking for an automation of this mess
what is pm2?
It's a module that keeps your bot alive and you can also use it to restart a bot through a command and stuff
[But need to know how it works though]
I don't know this so I'd better not help π€
process manager
0|dbm | at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:56:26)
0|dbm | (node:19837) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
0|dbm | (node:19837) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.```
This is a issue because my servr couldnt connect discord api due to providers network issue but beside that. im trying to find a way to get the bot to reconnct to discord api
not sure what way
where are you hosting your bot
nothing on the api status page, so it's definitely on your end yeah
anyways d.js should auto reconnect, if not just call login again
This has been happening for a while
Never seen that before (not the client.emojis) that thing in the image
Does anyone know how to create economy commands?
Example: Bal, work, rob, daily, weekly, etc?
@clear wraith lib?
and then use commands to operate on that database I think
also you might need a database or json file
But i prefer database
json is not a database
I have a database file
cry who said that?
json is not database but... hm mongodb uses json to store data
it's glorified json yes
but mongo, while still being trash, is an actual database wrapper
so json can be used as database
What's the idea behind nosql databases?
performance I guess
uh no
he said "performance I guess" and I don't know what he mean by writing so
it's a guess
so he thinks nosql databases are faster
while mongo is utilising json, it isn't only json
people here tend to be stupid and still go for writing into raw json files
and then complain when they experience data loss and poor performance
i have a question, how can i make the bot leaves from a voice channel when no one is in the voice channel? (I'm using js)
I have a question about how i can remove an owner from my bot. I've tried on Top.gg, but it didn't remove the user
Ok
i have a question, how can i make the bot leaves from a voice channel when no one is in the voice channel? (I'm using js)
@wet dove get the array of users connected to the voice channel
if its size equals to 0 then leave
put that inside a cronjob or infinite loop
and do it when someone leaves
onLeave event triggers on guild member leave
hm
you can't listen to members leaving a vc
there is no onvoicechannelleave event?
no
:C
afaik
there is voiceStateUpdate
oh ty
hm
what's the v12 change for js message.guild.roles.find("name", "rolename");
.cache.find
update your node.js version
im on 12.0.0
are you sure? do node -v
yep
show full error
.find("name","value") was removed
use .find(function)
like this: .find(item => item.name === value)
let muterole = message.guild.roles.cache.find("name", "muted");```
im using it for a muterole function
https://paste.menudocs.org/paste/zbu42
I want it so when i type
-page 2 with the space then my embed will send
but normally with a Modules file, u cant have a space in ur main command
so i added a args[0] but its not working
Tag me when you find an answer
the sender isnβt the problem
but normally with a Modules file, u cant have a space in ur main command
you can, there's nothing stopping you from doing this
Ik
Also didnt understood
how do i do it
Just put it in the command name?
why are you checking for args and for message.content? they are both doing the same thing
console.log your args to see what they look like
console.log your args
Args[0]
nothing shows in your console?
Or whatever u use
Nope
wait
i have an idea
let me try something
Yea because originally i had all my help commands with -page 2 and stuff in my main js file, but due to adding in custom prefixes. Everything got wonky and it wouldnt check for prefix in my main file so i switched it all to command folders
Ok big new
i tried console.log(args[0])
and nothing popped up when i typed the command
In-order to get all the songs from a spotify playlist do I have to use their API?
Or is there an easier way?
api
How can I make it so if someone mentions a role then the bot replies
it's the only way afaik
in v12 discord.js
Alright, Thanks!
and please note that spotify LOVES to change their api and not notify devs
Anyone?
Oh
yo here
itβs easy
once you specify the role that is being mentioned
do message.reply(βnoβ)
okay thatβs easy too
so itβs all args. what u need to do is add this
let rRole = message.guild.roles.get(βROLE IDβ)
then you do
Thatβs how u grab the role
then you need to add it to an args statement
so that would be this..
how about without the id
let rUser = message.guild.roles(message.mentions.roles.first() || message.guild.roles.get(args[0]));
so it would work if its any role?
what about if its named that role
then it works without id
let rRole = message.guild.roles.get(βrole hereβ) ?
let rUser = message.guild.roles(message.mentions.roles.first() || message.guild.roles.get(args[0]));
Like he said
Name and mention will work
@rolename or rolename
what about @rolename
-page 2
oh
let rUser = message.guild.roles(message.mentions.roles.first() || message.guild.roles.get(args[0]));
This command like i said will work
Just specify rUser in ur message
Try it
Ty @earnest phoenix
right
Yeah
but just for a role named 'test' for example
...
Thats easy
Oh @earnest phoenix do u know how to add a space to a command modules file. I tried specifying args if (args[0] === '2') { Like that but its not working
Just add to command name
you want to have the command name with a space?
Add a space in command name?
"Command name"
Wouldn't it be more convenient to use something like a dash? You'd have to make a workaround joining the entire string then checking if it starts with the command name.
No a space is how its always been
My prefix is a dash
so i feel itll be ugly and weird if i add a dash instead of a space
-page-2
ew
add a space where
"Page 2"
where i define args
Command name
module.exports.help = {
name: "page 2"
}
Why not?
Its the command name
And "" lets you put whatever name
why not make 2 be the subcommand or something
He tried with args
But he can use both ways
Name or sub
so look
in chat u type -help
it sends u a dm
then in dms u type -page 2
and it goes to page 2
but it was working fine with my main js file, but ever since i added custom prefixes i had to switch everything to modules
only the -help command will work because no space is specified
I use server.js with custom prefixes
Using quick.db
I use a main file
Use quick.db and set a custom prefix for a guild
/PREFIX FILES
bot.on("message", message => {
const botconfig = require('./botconfig.json');
if(message.author.bot) return;
if(message.channel.type === "dm") return;
let prefixes = JSON.parse(fs.readFileSync("./prefixes.json", "utf8"));
if(!prefixes[message.guild.id]) {
prefixes[message.guild.id] = {
prefixes: botconfig.prefix
}
}
let prefix = prefixes[message.guild.id].prefixes;
if(!message.content.startsWith(prefix)) return;
let messageArray = message.content.split(" ");
let cmd = messageArray[0];
let args = messageArray.slice(1);
let commandfile = bot.commands.get(cmd.slice(prefix.length));
if(commandfile) commandfile.run(bot, message, args);
})
//Files commands
fs.readdir("./commands/", (err, files) => {
if(err) console.log(err);
let jsfile = files.filter(f => f.split(".").pop() === "js")
if(jsfile.length <= 0){
console.log("Couldn't find commands.");
return;
}
jsfile.forEach((f, i) =>{
let props = require(`./commands/${f}`);
console.log('\x1b[34m%s\x1b[0m', `${f} loaded!`)
bot.commands.set(props.help.name, props);
})
})```
so anyone can change the prefix to their own server
so its setup with a database
but this only works with Command Module Files
- Avoid using JSON as a database.
- Check if you're in a guild. If the command was not run in a guild, default to your default prefix.
^
Oh no this is working perfectly fine
First one is true
Json is bot a good db
with module command files atleast
We are in a chrisis rn Zin
ok sry
uno momento
Also you can just Not sure about this actuallyrequire instead of JSON.parse(fs.readdirSync)
Quick.db imo is not a good alternative.
Wobbly, what worked for you? The JSON db or something else
ok nvm i got it
alright
Ok look. So the json file isnt the problem. The custom prefix where you can change ur prefix works perfectly fine with the Command Module folders, but with my main JS file at the start, Custom prefixes dont work and it uses my main and original prefix which is "-" while all the other commands that arent in my main js file use a different prefix. My problem here is i need to specify Custom Prefixes in my main js file, but i dont understand how to because the fact my big brain int working rn
that gives me anxiety when im trying to reread it, but its fine lol.
^^^^^^^^^^^
^^^^^^^^^^^^
Lol would u like me to re word it or go into a testin vc while i turn on live to show u
Just go into vc and mute
and ill show u
Not the right time
Im waiting for your stream to load. :\
ok i got an issue - basically im trying to add a text to my HTML webpage, but i gotta use <font> tag or a CSS. I'm trying to add text to the middle but i'm not sure how. It's been a while since I coded so please do understand I can't remember much. So issue: can someone add a text for me in the middle
Stream won't load. SLOW
Ok short story
How tf do i get custom prefixes to work in my main.js file
they work perfectly fine with my command module files
u add prefixes in config.json
//PREFIX FILES
bot.on("message", message => {
const botconfig = require('./botconfig.json');
if(message.author.bot) return;
if(message.channel.type === "dm") return;
let prefixes = JSON.parse(fs.readFileSync("./prefixes.json", "utf8"));
if(!prefixes[message.guild.id]) {
prefixes[message.guild.id] = {
prefixes: botconfig.prefix
}
}
let prefix = prefixes[message.guild.id].prefixes;
if(!message.content.startsWith(prefix)) return;
let messageArray = message.content.split(" ");
let cmd = messageArray[0];
let args = messageArray.slice(1);
let commandfile = bot.commands.get(cmd.slice(prefix.length));
if(commandfile) commandfile.run(bot, message, args);
})```
No ur a god
Just add them to the config and make it so if there is a prefix it will use it instead of the normal prefix
{
"prefix":"-"
}```
yes
This is my bot config
what would i add
"-","pe","!"
LOL
The system will do it
Bro
Listen
ok i got an issue - basically im trying to add a text to my HTML webpage, but i gotta use <font> tag or a CSS. I'm trying to add text to the middle but i'm not sure how. It's been a while since I coded so please do understand I can't remember much. So issue: can someone add a text for me in the middle
π€―
That's not a very good way of doing it. is prefixes[guildID].prefixes going to be a single string as the prefix, or an array of prefixes?
When they do the !set prefix command the bot will take args and that would be the prefix
It will make it so each guild id have its own prefix
So just make it ON MAIN JS TOO
it works with my command module files because of this code i added to Filesystem
lool]
//PREFIX FILES
bot.on("message", message => {
const botconfig = require('./botconfig.json');
if(message.author.bot) return;
if(message.channel.type === "dm") return;
let prefixes = JSON.parse(fs.readFileSync("./prefixes.json", "utf8"));
if(!prefixes[message.guild.id]) {
prefixes[message.guild.id] = {
prefixes: botconfig.prefix
}
}
let prefix = prefixes[message.guild.id].prefixes;
if(!message.content.startsWith(prefix)) return;
let messageArray = message.content.split(" ");
let cmd = messageArray[0];
let args = messageArray.slice(1);
let commandfile = bot.commands.get(cmd.slice(prefix.length));
if(commandfile) commandfile.run(bot, message, args);
})
I DONT KNOW HOW THO
LMFAO
I tried to do this
bot.on('message', message => {
let prefixes = JSON.parse(fs.readFileSync("./prefixes.json", "utf8"));
if(!prefixes[message.guild.id]) {
prefixes[message.guild.id] = {
prefixes: botconfig.prefix
}
}
let prefix = prefixes[message.guild.id].prefixes;
})```
hello baes
But this doesnt work
botCount is not a thing. Filter the guild member collection and check for if the member is a bot.
guild.users is not a thing.
//PREFIX FILES
bot.on("message", message => {
const botconfig = require('./botconfig.json');
if(message.author.bot) return;
if(message.channel.type === "dm") return;
let prefixes = JSON.parse(fs.readFileSync("./prefixes.json", "utf8"));
if(!prefixes[message.guild.id]) {
prefixes[message.guild.id] = {
prefixes: botconfig.prefix
}
}
let prefix = prefixes[message.guild.id].prefixes;
if(!message.content.startsWith(prefix)) return;
let messageArray = message.content.split(" ");
let cmd = messageArray[0];
let args = messageArray.slice(1);
let commandfile = bot.commands.get(cmd.slice(prefix.length));
if(commandfile) commandfile.run(bot, message, args);
})
``` How do i make this work for my main.js thoooooooooooooo
π
Message.guild.members.filter(member => !member.user.bot).size
Kinda spoon feeding lmao
lol
The custom prefix where you can change ur prefix works perfectly fine with the Command Module folders, but with my main JS file at the start, Custom prefixes dont work and it uses my main and original prefix which is "-" while all the other commands that arent in my main js file use a different prefix. My problem here is i need to specify Custom Prefixes in my main js file, but i dont understand how to because the fact my big brain int working rn
Are you properly saving the file?
wut.
When you say "JS file at the start", do you mean when you restart your bot, or whenever you send a message? Are you using your DB's write function (fs module, even though you still shouldn't be using JSON a db)?
No lol
js file at the start meaning my main js file i started with from the beginning
the first one i ever made
main.js
Faxxxxxxxxxxxxx
This confuses me.
Bruh not as much as me
π© \
Ok here
So i made custom prefixes right?
Now when someone does
-setprefix !
It changes the prefix to ! for their specific server
right? Now if you do !ask which is a command, it will works perfectly fine
because its in a commands folder using modules filesystem
but the custom prefixes wont work for my main.js file because custom prefixes isnt defined in it and i dont know how to define it
for example i defined it in my modules command script like this
//PREFIX FILES
bot.on("message", message => {
const botconfig = require('./botconfig.json');
if(message.author.bot) return;
if(message.channel.type === "dm") return;
let prefixes = JSON.parse(fs.readFileSync("./prefixes.json", "utf8"));
if(!prefixes[message.guild.id]) {
prefixes[message.guild.id] = {
prefixes: botconfig.prefix
}
}
let prefix = prefixes[message.guild.id].prefixes;
if(!message.content.startsWith(prefix)) return;
let messageArray = message.content.split(" ");
let cmd = messageArray[0];
let args = messageArray.slice(1);
let commandfile = bot.commands.get(cmd.slice(prefix.length));
if(commandfile) commandfile.run(bot, message, args);
})
//Files commands
fs.readdir("./commands/", (err, files) => {
if(err) console.log(err);
let jsfile = files.filter(f => f.split(".").pop() === "js")
if(jsfile.length <= 0){
console.log("Couldn't find commands.");
return;
}
jsfile.forEach((f, i) =>{
let props = require(`./commands/${f}`);
console.log('\x1b[34m%s\x1b[0m', `${f} loaded!`)
bot.commands.set(props.help.name, props);
})
})```
But i dont know how to make it work for the rest of the commands in my "Main.js" file
So for example. if the prefix is set to !
my lockdown command is in my main.js file so if you do, -lockdown on. it will work with "-" but not "!"
now i think this is the reason
const { prefix, token } = require('./botconfig.json');
But if i remove the prefix part of it, how will i make it work with custom prefixes
Dude, just set a prefix column for your guild configuration table
wut
Instead of saving the prefix globally "botconfig.json", save it per-server
So every server start with the prefiz set to -, but can be changed individually
So what's the issue?
Why?
Ok look
Where are you getting the prefix in the other files?
Now when u have a commands folder you define it like this
//PREFIX FILES
bot.on("message", message => {
const botconfig = require('./botconfig.json');
if(message.author.bot) return;
if(message.channel.type === "dm") return;
let prefixes = JSON.parse(fs.readFileSync("./prefixes.json", "utf8"));
if(!prefixes[message.guild.id]) {
prefixes[message.guild.id] = {
prefixes: botconfig.prefix
}
}
let prefix = prefixes[message.guild.id].prefixes;
if(!message.content.startsWith(prefix)) return;
let messageArray = message.content.split(" ");
let cmd = messageArray[0];
let args = messageArray.slice(1);
let commandfile = bot.commands.get(cmd.slice(prefix.length));
if(commandfile) commandfile.run(bot, message, args);
})
//Files commands
fs.readdir("./commands/", (err, files) => {
if(err) console.log(err);
let jsfile = files.filter(f => f.split(".").pop() === "js")
if(jsfile.length <= 0){
console.log("Couldn't find commands.");
return;
}
jsfile.forEach((f, i) =>{
let props = require(`./commands/${f}`);
console.log('\x1b[34m%s\x1b[0m', `${f} loaded!`)
bot.commands.set(props.help.name, props);
})
})```
this script is in my main.js file like everyone else has it
because thats how u get command folders to work
But i added this part to it
Why aren't you getting the prefix dynamically?
``
let prefixes = JSON.parse(fs.readFileSync("./prefixes.json", "utf8"));
if(!prefixes[message.guild.id]) {
prefixes[message.guild.id] = {
prefixes: botconfig.prefix
}
}
let prefix = prefixes[message.guild.id].prefixes;``
message has a guild attribute
well i know that
Use it to get tge prefix just how you did
my brain hurts
The code above is the answer
Copy it into main.js
If you used a sql database it'd be as simple as "SELECT prefix FROM guild WHERE id = :id"
ok here
let me make it simple
let prefixes = JSON.parse(fs.readFileSync("./prefixes.json", "utf8"));
if(!prefixes[message.guild.id]) {
prefixes[message.guild.id] = {
prefixes: botconfig.prefix
}
}
let prefix = prefixes[message.guild.id].prefixes;```
Do u know how to make this work for all of my commands in my main.js file
Yes
Do the following:
Create a Helper.js
Inside it put that code inside a function that returns a string
Then import Helper.js anywhere where you need to get the prefix
so
in helper.js
would i add this
bot.on('message', message => {
let prefixes = JSON.parse(fs.readFileSync("./prefixes.json", "utf8"));
if(!prefixes[message.guild.id]) {
prefixes[message.guild.id] = {
prefixes: botconfig.prefix
}
}
let prefix = prefixes[message.guild.id].prefixes;
})
and then in my main.js
i would do
const prefix = require("./helper.js")
@lyric mountain did u die
No
Also no for your other question
Just put it inside this:
function getPrefix(guildId) {
//CODE
return prefix;
}
function getPrefix(guildId) {
let prefixes = JSON.parse(fs.readFileSync("./prefixes.json", "utf8"));
if(!prefixes[message.guild.id]) {
prefixes[message.guild.id] = {
prefixes: botconfig.prefix
}
}
let prefix = prefixes[message.guild.id].prefixes;
return prefix;
} ```
my brain
hurts
okay wait
would i add that to helper.js
or main.js
where my code it
is
the idea of using a helper file is to centralize commonly used functions
since you'll be calling that file pretty much everywhere
so i cant do this in my main.js
const prefix = require("./helper.js");
so i cant do this in my main.js
const prefix = require("./helper.js");
@calm shore no
so would this be my helper.js file then
bot.on('message', message => {
let prefixes = JSON.parse(fs.readFileSync("./prefixes.json", "utf8"));
if(!prefixes[message.guild.id]) {
prefixes[message.guild.id] = {
prefixes: botconfig.prefix
}
}
let prefix = prefixes[message.guild.id].prefixes;
})```
const helper = require("./helper.js");
then
const prefix = helper.getPrefix(message.guild.id);
so then this would be my helper.js if ur getting prefix
function getPrefix(guildId) {
let prefixes = JSON.parse(fs.readFileSync("./prefixes.json", "utf8"));
if(!prefixes[message.guild.id]) {
prefixes[message.guild.id] = {
prefixes: botconfig.prefix
}
}
let prefix = prefixes[message.guild.id].prefixes;
return prefix;
} ```
oh
in the function's call
Got error with command handler:
at load (C:\Users\Cools\Downloads\azbot\handlers\command.js:14:36)
at C:\Users\Cools\Downloads\azbot\handlers\command.js:28:27
at Array.forEach (<anonymous>)
at C:\Users\Cools\Downloads\azbot\handlers\command.js:28:14
at FSReqCallback.oncomplete (fs.js:152:23)```
Code:
```const { readdirSync, lstatSync, readdir } = require("fs");
const logger = require("../utils/logger");
const Discord = require('discord.js')
const client = new Discord.Client();
const fs = require("fs")
const ms = require('ms');
module.exports = (bot) => {
const load = dirs => {
const commands = readdirSync(`./src/commands/${dirs}/`).filter(d => d.endsWith('.js'));
for (let file of commands) { //for each of these files
let pull = require(`../src/commands/${dirs}/${file}`);
bot.commands.set(pull.config.name, pull);
if (pull.config.aliases) pull.config.aliases.forEach(a => bot.aliases.set(a, pull.config.name));
};
};
readdir(`./src/commands/`, (err, directories) => {
if (err) logger.error(err);
var dirArray = [];
directories.forEach((f, i) => {
if (lstatSync(`./src/commands/${f}`)) {
dirArray.push(f);
}
});
dirArray.forEach(x => load(x));
});
};
bruh great flood
Its a flood
Ik lol but no one was talking when i did it
Still
he just completely wiped my convo
Whatever
^
i mean yea ig i shouldnt talk
ok so
I made a helper.js
added this in it
let prefixes = JSON.parse(fs.readFileSync("./prefixes.json", "utf8"));
if(!prefixes[guildId]) {
prefixes[guildId] = {
prefixes: botconfig.prefix
}
}
let prefix = prefixes[message.guild.id].prefixes;
return prefix;
}```
then added this to my main.js
const helper = require("./helper.js");
then i put this inside my command script
const prefix = helper.getPrefix(message.guild.id);
this is my error
(node:185720) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 85) (node:185720) UnhandledPromiseRejectionWarning: TypeError: helper.getPrefix is not a function
bot.on('message', async message => {
const prefix = helper.getPrefix(message.guild.id);
^
TypeError: helper.getPrefix is not a function
@astral yoke do you still need assistance? Are you sure you're exporting something with the property config?
No I don't, I was ignored and I found out it was due to one of the commands I added but I removed it and it worked. Thanks though.
Np.
(node:185720) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 85) (node:185720) UnhandledPromiseRejectionWarning: TypeError: helper.getPrefix is not a function
@calm shore have you defined the function correctly?
function getPrefix(guildId) {
let prefixes = JSON.parse(fs.readFileSync("./prefixes.json", "utf8"));
if(!prefixes[guildId]) {
prefixes[guildId] = {
prefixes: botconfig.prefix
}
}
let prefix = prefixes[message.guild.id].prefixes;
return prefix;
}
i did that
that went in helper.js
const helper = require("./helper.js");
const prefix = helper.getPrefix(message.guild.id);
this went in main.js
just a sec
did you export it
Well its not in a folder
did you do module.exports or exports
here
this is my whole helper.js file
const botconfig = require('./botconfig.json');
const Discord = require('discord.js');
const filesystem = require('filesystem');
const fs = require('fs');
const files = require('files');
const bot = new Discord.Client();
function getPrefix(guildId) {
let prefixes = JSON.parse(fs.readFileSync("./prefixes.json", "utf8"));
if(!prefixes[guildId]) {
prefixes[guildId] = {
prefixes: botconfig.prefix
}
}
let prefix = prefixes[message.guild.id].prefixes;
return prefix;
}
Thats all of it
put export behind the word function
I guess
don't remember how to export a function in js
export.function getPrefix(guildId) {
let prefixes = JSON.parse(fs.readFileSync("./prefixes.json", "utf8"));
if(!prefixes[guildId]) {
prefixes[guildId] = {
prefixes: botconfig.prefix
}
}
let prefix = prefixes[message.guild.id].prefixes;
return prefix;
}
export function getPrefix(guildId) {
@sudden geyser is this howw you export a function?
module.exports = function (msg) {
console.log(msg);
};
do that
put module.exports = behind that function
module.export = function getPrefix(guildId) {
Kuu that's one way of doing it.
But that assigns the entire export.
If you plan on having multiple, you'll have to make properties for it.
like module.exports.property = function() {...}
@calm shore
module.exports.property = function getPrefix(guildId) {
bruh
.
guess it'd be module.exports.prefix = function (guildId) {
const prefix = helper.getPrefix(message.guild.id);
^
TypeError: helper.getPrefix is not a function
so
how would i make that const then
const prefix = prefix(message.guild.id);
Set the property as whatever you want it to be when exported, and use that same property to call it.
const prefix = helper.prefix(message.guild.id);
You're already exporting when making modular commands so this shouldn't be difficult
Hi
i want to post my bot servers count in site how ?
I am trying to do a command on discord.js v11.4.8
I am trying to give/remove a role/roles of staff members.
I want to run a command for example $xxx then it takes the roles from the main server adds or removes them to/from user in the staff server.
Its around 18 roles in total. What will the best way be?
Even if there is 18 roles π
yes
it doesn't add them individually
the api allows you to pass an array of snowflakes to modify the member roles
So I will have to check each role?
wat
$.ajax({
method: 'POST',
url: `https://top.gg/api/bots/xx/stats`,
data: {
server_count: client.guilds.size
},
headers: {
authorization: 'xxxx'
}
});
now how can define server_count: client.guilds.size in the site ?
Wdym
You tell top.gg ur server count and the site will display it
you dont need to do anything else except one post request


you can set it to 9999999 yourself if you want
it will work
but most likely will get you banned from top.gg
Well, good night to everybody, before all.
I wanted to ask you something, to see if you can help me with it :)
I run a command > Bot sends a message > Bot reacts to its own message with a specified emoji > And now, I need to make a system to make it know how many people is reacting, so when it reaches a specified reacts number, it will send a message...
I would thank it a lot if someone of you could help me. :P
(Please ping me when answering) π
in which lib
Discord.js
the event gives you a MessageReaction object which has a count property (https://discord.js.org/#/docs/main/stable/class/MessageReaction?scrollTo=count)
you'll have to check if the reaction was added to the message you want to keep track of
do that by comparing message ids
when executing the command you'll have to store the message id somewhere so you can compare it later in messageReactionAdd
store it in some form of a database if you want it to stay persistent, if not a variable is enough
there is an easier way to do that
is there?
ye
message.createReactionCollecter
And how am I supposed to use it? :p
and then collecter.on('collect', ()=>{ some function here })
but then you can have a collector running forever
no
'-'
you can specify a time limit
He doesn't want a time limit tho
isn't the collector just a subscription to messageReactionAdd under the hood
exactly
I need to make a system to make it know how many people is reacting, so when it reaches a specified reacts number, it will send a message...
then set the time to like a week

