#development
1 messages · Page 898 of 1
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
roll = randominteger(1, 100)
if (roll > 30) win()
else lose()
Sounds like spoonfeeding
Hey, did something change with reacting with multiple emoji to a message and catching an error on it, in v12?
why'd you ask?
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
send code
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
});```
hello..
What language you use?
js
discord.js?
ok
ahh ok
It is a bit glitchy
how?
Just keep tryna restart if it doesn't work
In node.js, what is the new eval function?
client. is not defied
Do you use bot?
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?
arr[num] ?
Use find function.
array.find(a => a === 5)
might as well use array[a] no?
No
ok
If it is [1,2,5 ....] it will have problems.
is there a way when u inv the bot to ur server it sends a msg like hello im bot
Yes.
ok so what is it?
is there a way to ignore a prefix? because my prefix is a! but it also response to c!
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?
no i want it to egnore a prefix
then you're not checking for your prefix correctly
?
if you have a prefix, and your bot is also responding to other prefixes, then your prefix checking is not working correctly
how?
you need to review your code that checks for the prefix
thats how you define the prefix, but how do you check it?
wdym
you should have a piece of code that checks the message content and checks if it starts with the prefix
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);
}
}
};
?
somewhere after .on("message")
then show your main file
where is your bot hosted? what library does your bot use?
how are you starting your bot?
i ment javascript
can you see it? the code is checking your prefix
ummm no
so this code is flawed
flawed?
yes, its wrong
how?
oh
meaning that your bot will work with any prefix that has the same size
oh i see
the same number of characters
so how do i make it check if the prefix is correct?
you can add this if(!message.content.startsWith(prefix)) return
right after let prefix
ok
that code means: if the content of the message does not start with the prefix, then return and do nothing
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
What is the new eval() function in node.js
eval()?
@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
Hi.
By using discord.js-commando, can each command group register its own prefix?
and merge them into one bot?
No
best solution is not use commando lol
Yea it works too
or I could do ugly way and check for the command file path and asign the prefix through message character checks.
😦
ok. thanks. 🙂
any other discord.js framework that you could recommend besides commando?
most people make their own
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
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
@queen needle every time you run the command you create a new active and new ops which in turn creates a new data
ohh
your old data is never reused, it always creating a new one
how would i make it use the current one
which part?
everything that is relevant
you need to rework your structure, it wont work as it is
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
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
haste bin doesnt work for me
devs need to step up their game
why not? just click the save button on top right or ctrl s
when i try it doesnt work
ok
How to use setinterval with shard broadcasteval? discordj
I try this
client.shard.broadcastEval(`setInterval(${f},350000);`);
but not working
what are you trying to do?
thats most likely the wrong way to do whatever you're trying to do
I want to run this function in all shards.
But this must be a repetitive function.
settimeout not good
why cant you run the function in the shards themselves instead of broadcastEval?
All shards should start after they are ready.
after all shards are ready or after each one is ready?
Since I didn't understand the shard well, if the last shard occurred, I run this command on it.
ok then do this
// shard.js
function startInterval() {
setInterval(() => {
// your function
},350000)
}
// manager/index.js
// after all shards ready
broadcastEval(`startInterval()`)
thx so much
im still very confuse with my play command
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?
and (node:31555) UnhandledPromiseRejectionWarning: Response: Internal Server Error would be discord's end I'm assuming?
looks like it
I get the same thing, but its api related.
Hey, can someone help me with a discord API error that says a message is unknown after sending it?
show code
mine?
yes
https://discordapp.com/channels/264445053596991498/272764566411149314/705015405516816434 here is everything you need (message above here)
check if your bot has "view message history" permissions
okay thanks, will do that. But can that explain why it's only sometimes giving an error? Not always
message history is weird, im not sure how it works either. im also not sure if this is caused by it or not
oh okay. Will check it through my bot itself just to be certain
if it was indeed message history, it should give missing access error, not unknown message, but im not sure
console.log(message.channel.permissionsFor(message.guild.me).has('READ_MESSAGE_HISTORY'));``` returns true 🤔
can you show the full code block?
same channel and audit logs gave no changes
including before and after the reactions block
isn't the linked code block enough?
oh lol you will almost cry if you see it, but sure 😂
Oh boy
beginning with channel.send()?
also before
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
this is it
I hope this is okay @quartz kindle
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?
@earnest phoenix use something like this:
setTimeout(() => {
message.channel.send(what_you_want);
}, time_in_ms);```
yes but setTimeout what xd
ohh sorry I can't read (again :()
np
something like this:
const totalSeconds = time_in_ms / 1000;
const minutes = Math.floor(seconds / 60);
const seconds = totalSeconds - minutes * 60;```
uh
I think you can do the remaining part yourself
lol if you want that, sure. But don't make seconds and totalSeconds the same (well you can, but I wouldn't do that)
no problem
@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?
What is the new method for eval()
@golden condor wdym? there is no new method
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.
It keeps telling me it is deprecated
oh lol, why not pass client in the function as well then?
@golden condor show
well show it if it ever comes up again
can I still catch all embed.react() things in one time? Or should I use try {} catch() {} instead?
use try/catch
okay
How to make a prefix changer for every guild? Like if an owner want the prefix to be ? He can change it
make a database
^
and please don't use json as I did
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.`)
@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’
@earnest phoenix was it exactly 60 ?
idk
role not find
not error
let gRole = message.guild.roles.cache.find(r => r.name === role)
i think i do wrong at this line
doesn't it say a line?
?
are you using D.js v12?
doesn't it say a line?
if it says where the error happened
i am using v12
hmm
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
okay what if you do console.log(role) after the line where you do let role =?
and see if what it logs makes sense
@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)
slice(22) is wrong in many levels
lol
people use slice(22) in an attempt to use the bot's mention as a prefix, because the mention is approximately 22 characters long
:/
however IDs are not guaranteed to be always the same length
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
@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
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
so i replace timeConvert to time ??
ok thx
np
@quartz kindle not work :/
nvm fixed it
vertically
it was some stupid default css that had height: 100% on body
@cerulean pebble you dont need gRole
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
oh btw Tim, I can't directly see if your suggestion fixed the command, but thanks for reading the mess 👌
lol :/
TypeError: rMember.roles.has is not a function
@cerulean pebble userMember.roles.cache.has
you have v12
no problem, it's just weird if you used to do it the other way
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
You can use some database, and control some datas.
I know what to do in normal but dont know how to convert it in cmd handler
@zenith orchid
I think you have message event file, this true?
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;
}```
Your selector is wrong.
What is it supposed to be then?
it's bot-name
That doesn't work either
#bot-details-page .bot-name {
color: gainsboro !important;
}```
literally from the source
Doesn't work
I've wasted so much time trying to style the bot page and nothing works
Clear cookies and try.
@earnest phoenix #312614469819826177
Those are mostly outdated
@earnest phoenix https://top.gg/api/docs
There's plenty of official libraries on https://top.gg/api/docs
thanks
you're supposed to clear cache, not cookies lol
but usually you don't need to clear cache if you use <style>
because the style loads as you load the page
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?
I think I am thoughtful these times.
let timeGet = Data_time.get(server.time.timeset)
@earnest phoenix
if(!timeGet) time = 40 // timeGet doesnt exist
time = timeGet / 1000 // timeGet still doesnt exist
Cleared both cache and cookies and nothing works
can i see the css code
so how can i do? Tim
Vinx use common sense lol. if timeGet doesnt exist, dont use it
@quartz kindle yea
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
long description is a piece of code that gets injected into the existing top.gg page
its not a standalone html page
HTMLCeption
Got it
ok thx
Imagine if there was documentation on this though.
it's basic html though
there is no need for documentation
you simply use the inspector / dev tools in your browser
It just makes it easier though
i wish getting guilds weren't this bad https://img.thaun.dev/stxe5.png
would it work better if i have a better internet 
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)
the /users/@me yeah
anyone know how to make a share command for example share currencies with another user
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?
DBL Error: Error: 403 Forbidden
why is my bot saying this?
When posting the bot's status?
Where/how is it happening.
Yep
k
I believe 401 is for wrong token.
Yup
403 is for an endpoint you have no access to
that's new
why my bot dont responding only in this server
Check the guild id
any way to check if the message only contains a gif URL? d.js v11
no i can mention in here
check your console
@cedar mist Javacord has an example bot that might help you get started https://github.com/Javacord/Example-Bot
it also contains the important stuff for gradle
Ok thats actually really useful
Is there any difference between module.exports.run and module.exports.execute?
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
how can i get the rank of a user from the leaderboard
im using mongoose for a db
you can define the properties as you want
@amber fractal ohhh thanks. Now you say it...
I need an api like nekos.life but without the questionable endpoints. which api can I have?
you can duckduckgo something like "anime weeb api" and it might come up
first result is nekos.life ;-;
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
oh
that's not an array
oh thats an array
arrays use square brackets
i accidentally used that
do you know how to index into an array
but im trying to get the user rank from a leveling system
you can use arr.find()
but it'd have to be an array of objects to do what you're attempting
.sort() returns a array right?
well yeah, that sorts the array with the given function
im gonna try using arr.find()
<Array>.sort modifies the original array btw.
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.
im trying to get the index
the position the user is in the res
You can use <Array>.indexOf if you have the user ID and looking for the index.
oh okay
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)```
how are you calling execute
doesnt matter, on execute they create a new listener
memory leak galore if that runs
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?
It's us-west
and for hong kong is hong-kong?
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')```
Oh
Hong Kong is hongkong
Tyvm
If it's -1 the item wasn't found.
read the error
step 2 is to learn js

// normal functions
function bla() {}
() => {}
// async functions
async function bla() {}
async () => {}
() => {
await bla // error
}
async () => {
await bla // no error
}
asynchronous functions are a basic programming concept
yep
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)```
<Message>.delete()'s options are now an object
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);
}
}```
reason and timeout I believe
yep
m.delete({timeout: time})
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?
add a let to target
and then doesnt exist
you probably meant message.reply().then()
in discord.js v11.5.1 then does not exist?
you mean to thenify the promise
which is invalid
i want it to delete that messsage
let msg = await message.channel.send("`Se genereaza....`");
thats what i said
What would be a good timeout amount?
you probably meant message.reply().then()
3 seconds
or in your case, if you want to delete msg then just msg.delete()
Ok, ty
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
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())
isnt collection.values() already an array?
So the mentions is a map
it's a collection, which extends a Map
Ah
message.guild.owner.user.tag
``` this should work right?
right.
I tried Array.from(message.mentions.roles.values());, an iterator of 0 returned the first mention and an iterator of 1 returned the 3rd
does it contain all mentions though?
Because if it does that's just an issue with how it returns
can't guarantee the order
I printed it and I read all 3
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.
you can't enlarge built-in discord emojis because they are unicode characters
custom emojis are pictures
easily resizable
How can I get it to respond in the channel not the logs?
catching the error and routing it to the message's channel
using try{}catch(e){} syntax
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
oh
Oh, I didn't know that
Hello.
How do you link two JS files? Please.
require(filepath)
And when the files are in a child folder?
require("./folder/file.js")
Should I put
const client = require('./foldchild/foldchild/file.js');
?
is it possible to check if a bot is verified in djs
ah how do we do to add a module.exports ?
@green vale user.fetchFlags()
oh alr
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
what permissions is the best idea for someone to need on muting someone?
Manage Roles
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?
is this bad practice?
( c - b )
leaving a value null for subtraction if it doesn't have a value, basically
subtracting by null? yes, absolutely
it's either an integer or null
why not just default it to 1 then
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
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
yeah c+a was just in there lol
@earnest phoenix I tried but it doesn't work too
b = someDankVariableThatMightBeNull || 0
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
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?
I could force there to be a value just looking at shortcuts
I have a problem with a NSFW command, can someone help me in dm?
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
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 make your own type to store only relevant data from that object and then register it as an entity ; https://github.com/cryy/quiccban/blob/master/quiccban/quiccban/Database/GuildStorage.cs#L28
ah wait, you just need to make an entity of it, and it will work?
wait, lemme read it again
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 ?
Itay you require it and define it
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
are they in the same folder?
there is no folder
oh
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
👍
How can I make a file that does not contain my token work?
you mean hide your token somewhere besides a file?
if your hosting it on a server you can define variables
token: process.env.WEBSERVERGLOBALVALUE
Make two files.
One with my functions and one with my token.
just export like above
you can use module.exports like i told you before
I tried but it doesn't work sTim
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
ReferenceError: client is not defined
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
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
Well for starters
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
only 1 file should initialize the client
the file you define Discord in should have all your client#event functions
Is there any bot?
Who can ban any member.... And delete his all messages?
that's your error message anyhow

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)
i know what you want, and i explained it how to do it
but you didnt read what i explained, you just copied it
so people don't have access to my token
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?
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
@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
Any idea how to fix this terrible speed? https://prnt.sc/s87tep my internet is way faster then that
28kbps smh
yikes chief
pull your wifi out of your attic
Has the Discord.js method to add roles changed? member.addRole(id) doesn't seem to work anymore
@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
@fallow quiver I learned alot from v11 to v12 notes
im not sure if that was hit or not
Yeah, I know a lot changed
@fallow quiver in D.js it is now member.roles.add(role)
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');
I had to go through my code when V12 came out and add a .cache to a lot of things
@opaque seal @blazing portal channel.permissionOverwrites.delete()
@opaque seal @blazing portal channel.permissionOverwrites.delete()
does this delete all perms?
I just need to delete 1 role from them
channel.permissionOverwrites.get(id).delete()
thanks
@earnest phoenix both files can't login to the client, its a 1-time thing
@earnest phoenix ```js
// auth.js
module.exports = {
token: "pgjpwiegjpw",
prefix: "we",
owner: "063094583045398450"
}
yes
Tim gave you the exact syntax of a file that has variables
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"
}```
?
@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.
//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
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 ?
because I want create many files .js
then look into how to make a command handler
basically
your functions files will be this
@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.
// 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)
})
exemple
folder
- index.js
- auth.js
- folder > modules
_module1.js
_module2.js
_etc...
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
@quartz kindle so if I understood correctly I must:
- make an auth.js file with
module.exports = { token: "123", prefix: "> or ! or blabla", owner: "owner" } - 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) }) - all other module files with
module.exports = (client, message) => { ... }
Right?
do you understand the relationship between requires and module.exports?
you can scratchpad the code without your bot
I'm not english so I have so difficult too understand
are you french?
yes
I cant seem to get a reboot command for py i can only do it for js but my bot is coded with python
have you tried search for french videos on discordjs bot tutorials?
many people have good videos up with step-by-step explanations
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
It's not explain on discord.js.org
so i'm asking here
@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
ok that is fonctions
but for the rest is good ?
auth.js
index.js
and the base of module1.js ?
if module1.js is a command, yes
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');
}
})
} ```
@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 ?
do my example files make sense?
Hi ! How to get the ram usage of a bot ?
what is your node.js version 
Oof
yikes
Djs use node
unless im supposed to use node.js
Does anyone know how to let a user bypass a command cooldown (python - dont hate)
I installed node.js as a package
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
mhmm
discord.node.js
@opaque seal channel.permissionOverwrites.delete()
does this work for deleting all permissionOverwrites?
have you tried reading the docs
Couldn't find it
Hello?
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
Hi ! How to get the ram usage of a bot ?
hello? >~<
Hi
I have a question but ill wait >~<
what programming language @carmine magnet
Wait for what?
@valid bison ask away
JS
node?
Yes
you can use the os module in node: https://nodejs.org/api/os.html#os_os_freemem
process.memoryUsage().rss
Im using djs
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 >~<
Ok thanks
channel#send
Do i need the channel ID?
no
message.channel.send()
Ok
@carmine magnet pretty sure thats not what they were asking for
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)
https://discord.js.org/#/docs/main/stable/class/PermissionOverwrites?scrollTo=delete
@pale vessel feel ashamed xD
Oof ok
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?
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.
run enable-pnpm in your glitch console
ok
@green vale there is no specific method for second item in a collection, but there are many ways to get it
Oh alr
for example Array.from(message.mentions.users.values())[1]
or message.mentions.users.first(2).last()
Would something like message.mentions.users.array()[1] work?
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
Thanks Tim!
a second mention may be the first and the first mention may be the second
the order is not guaranteed
yes
That's alright
Okay ty
I'll just use the .first(2).last() example you used, because I'm already using .first()
you can also do ```js
let mentions = message.mentions.users.first(2);
mentions.first()
mentions.last()
Oh okay
You have to be careful though, message.mentions is unordered
it may not be the same order as the message
to start the bot he does 'node <name>. js'
then proceeds to say: 'I use discord.js, not node.js'
I tried the channel thing but its not responding >~<
what's your code?
I have it as a case under switch(args[0]){
I wrote it as
case 'welcome':
message.channel.send('Welcome new member!')
put it inside a codeblock
this is the message event: client.on("message", ...)
it's okay, just paste the full message event here
the full message event would be js client.on("message", message => { // everything inside here including the line above and below })
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 >~<
you can edit the message
ye lemme do that
did it /~\ finally
it should work
you adding a break before welcome
just add a break here
wait. . . oh!
otherwise when you do the info command, it will run both info and welcome
thats what i forgot im sorry >~<
but the welcome command should work, i dont see anything wrong with it
we're here to help, no need to apologise! :)
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 >~<
Okay >~<
also, use else if:```js
if (args[1] === "something") {
}
else if (args[1] === "something") {
}
else {}```
you can also use a switch, which is faster
^
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
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? >~<
message.reply should be in else { here }
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
Ive barely done any of this in so long so i hope Cry comes back /~\
yes, cry is god
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? >~<
you would want to learn javascript first
Yes >~<
Thank u /w\
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 👀 ?
i have no open sql db to use
no www
why www
www makes no sENSE there
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)
The search. When I run the command (c!province Alberta), it always returns the noresults embed
So, get rid of result
does anyone know what this person means by " you load your commands in your client on message listener... move it outside"
it means exactly what he said
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!`)
});
not exactly
but id gave me undefined
what's the browser
brave
//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!`)
});
is vivaldi a good choice
or is it just id
@heavy marsh its in the order i showed you
//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!`)
});
you need to add both parameters
shardDisconnect gives you event and id
so .on("shardDisconnect", (event,id) => { })
each event have their own specific parameters
as explained in the docs
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
bot.on("shardDisconnect", (event, id) => {
console.log(`Shard ${id} disconnected!`)
});
@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
well that was WAY more clear than what I was getting in the official discord.js server
no offense to them
so the try command?
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
well the bot has started for the first time since 12 this morning
thanks
but TypeError: Cannot read property 'execute' of undefined
thank you for being transparent and working with me
its fine as long as you understand why you should do what im telling you to do
lol sure
how to make undefined handler?
wat
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?
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++
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
which library and version of the library?
which programming language?
so discord.js v12 most likely
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
in discord.js v12, its guild.channels.create() instead of guild.createChannel()
oh ok thx
