#development
1 messages · Page 1570 of 1
{
"1721138": {
"ability": "Corrosion",
"iv": 88,
"stamina": 96,
"hp": 338,
"speed": 50,
"attack": 16,
"defense": 28,
"specialattack": 234,
"specialdefense": 307,
"id": 367,
"name": "Huntail",
"level": 18,
"catchChance": 0.8333333333333334,
"spawnId": 4236884,
"owner": "345138133429649408",
"catchTime": "01/18/2021 9:49 PM",
"nickname": ""
}```this is how the object looks
anyway, I have a bot that sends some things daily, and i want the user to easily edit the time where the bot will send the things like this:
User input: `!settings time 7AM`
Bot output: Successfully set the time of when I will send the facts to **7AM CET**!```The timezone will be CET no matter what, and i want the bot to set something like `Date.now() + time until 7AM CET` to it's db. How can I make that happen?
@eternal osprey I would not recommend using JSON as a database personally, as it can easily break and/or be corrupted
I understand, Thanks!
But i need to do this in json tho.
o
If you're constantly writing data to a json, you should not use a json file. json is only recommended to read from
If you absolutely need something high level, use sqlite
What precision do you allow users to set times to? seconds? minutes? hours?
minutes
(thanks google) I guess js Date.parse("5/4/2021 7:30 AM") works, but im pretty sure the user will be able to abuse it and set the time to 69 years somehow
first of all, you might need to use crontab
then just use regex to match keywords
Okay. I think it would be within reason to have a single interval which queries the database every minute to see if there are any reminders meant to be sent within that minute.
The alternative would be to store intervals in a Map keyed by user IDs and clear the Interval then re-set.
I think having possibly a bunch of timers ticking on a single thread wouldn't be the best idea. That being said, I would go for the query database option
let last1 = Object.values(mons).find(m => m.name === `${found.name}`)
fs.writeFileSync("./mons.json", JSON.stringify(mons), e =>{
//Handle error
last1.owner = `${targetMember.id}`; //Setting the owner ID
});
```i am trying to change the owner ids.
it is not working tho
module.exports = class BaseEvent {
name;
constructor(name) {
this.name = name;
}
async run(client, ...args) {};
}
i got this error:
TypeError: Class extends value undefined is not a constructor or null
remove the name; at the top.
declaring class properties is only necessary in TypeScript
Well. The error doesn't correspond with that code block. Look at the stack to see where the error is coming from. The issue is trying to extend something which is undefined or null or doesn't have any constructor signatures
const { BaseEvent } = require('../Bases/BaseEvent');
module.exports = class Ready extends BaseEvent {
constructor() {
super("ready")
}
async run(client) {
const guildcount = client.guild.cache.size
const username = client.user.username
console.log(`${username} is now ready!`)
client.user.setActivity(` over ${guildcount}`, { type: 'WATCHING' })
}
}
do not deconstruct the require
Export is of type BaseEvent
not { BaseEvent: typeof BaseEvent }
can you modify as well my text

All you need to change is the require statement. The export of that file is a class. Not an Object holding the class instance
Idk if it's rgb
figured
its something else, but i forgot how to search color number
it just says color code
but whats the actual name of those color codes
its not hex for sure, not rgb either
Discord.js logic to parse strings to number seems to suggest it's hex.
Their use of 0xffffff is hex
@opal plank They seem to parse the int to a radix of 16
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
The parseInt() function parses a string argument and
returns an integer of the specified radix (the base in mathematical numeral
systems).
edge
ty ❤️
nvm it was the service-worker script
mhm. I guess I should clarify that that was converting hex to what Discord accepts. Idk the inverse of that operation
await reaction.message.reactions.remove(matchEmojis[3])``` whats correct way of removing a reaction by id?
that gives me the idea of what to do tho, thanks 
ReactionManager.cache.get(id).remove()
Message.reactions is of type ReactionManager
thx
my bot uses heroku redis as a cloud storage system
and im on 9 of my 50 alloted MB
and its throwing a memory full error
i dont know why
and everything ive done to fix it deosnt work
help
;(
anyone know why when i type !help in discord nothing actually happens?
is your whole bot hosted on heroku?
yes
Does it give any errors?
im not sure
then the error is not with redis, but with your bot
it's reaching the max memo
Well there's an easy way to find out isn't there?
50MB alloc 
i cant see the console for the bot though
Why not?
i dont know how
but my bot only stores stuff on the redis thing and its an OOM redis error
How are you running the bot then?
Pretty sure Redis instances and application dynos are separate
the bot itself also uses memory
redis.exceptions.ResponseError: OOM command not allowed when used memory > 'maxmemory'.
im running it of heroku and before i could see the console now its changed and im not sure where to find it
Well, I'm pretty sure .setTitle() is supposed to take a string
oh yeah it should and i dont have a string
even a small bot could use 4GB of memory
C-create one? 
I would love to see a Discord bot which only takes 50kb of mem
that's not a bot, that's a microprocessor 
I probably couldn't even write a gateway lib which fits in that memory space
it works now ty for the help
You should figure out how to see the terminal, otherwise you're gonna have a really hard time
yeah ill try to figure it out
heroku's teminal is in the log tab
wheres the log tab?
dropdown menu on the top right
i think mines different or something
I think i found a discord bug. when someone uses a one time use invite link to a voice channel they can always view the channel even if i remove their view permission.
This is more than 50kb tho
your redis is 50mb or 500mb?
50mb is extraordinarily small for a redis instance
wtf
the free version is only 25mb lmao
also fucking 15 bucks a month, and guess how much you get
fucking 50mb
LMAO
I need help, my commands arent responding
bruh how
Can someone help please?
??
Tell me the number
Holy fucking shit
can anyone help me? please?
trying to create a convert time function js convertTime(time){ const m = moment(time) return m.toNow(); } using ?time 2d
how am i going wrong?
always returns in a day
oops
So, then it's a logical issue with finding a command and calling the function to execute
hence "show code"
theres the code
I need help with this issue, my bot isn't working and it's not Saying the Logs
hastebin pls
well yea
like one or two things in there are from pastebin
but its been working fine
until now idk why
He meant put the code in hastebin so we can see it. We don't wanna download a text file to help you

eh idc im a begineer so
Hey
"i copied this code from internet, why not work"
it worked
so
idk what u mean
nope
have you tried restarting the process
yes
like 100 times
and ive kicked the bot
and made it rejoin
still does not work
Lol okay
oh did i post it in the wrong thing lmao
or will that work too
i did hatebin instead of hastebin on accident lol
doesnt matter, as long as we can read the code without having to download anything
i dont use python but i remember someone saying you shouldnt mix commands with events
try removing the message event and see if the other commands work
also, is the bot even logged in?
when did i mix commands and events
You're writing annotations for both client commands and events
You literally have written
@client.command() and @client.event
Those are annotations for client commands and events
Yeah. And also the message event
so should i put the event before the command
Hello, So am currently trying to animate the Creators avatars on my bots page on top.gg. I need some help cause I am not mentally there with css. I tried a few different things and they failed
. If you know how to do this please dm me cause i'm
.
Don't mix them in the same file is what the suggestion looks like
so like this?
css animations 
No. Try putting them in different files or remove the events and test
oh
You fr gonna do me like that
?

Pain
Hello, So am currently trying to animate the Creators avatars on my bots page on top.gg. I need some help cause I am not mentally there with css. I tried a few different things and they failed
. If you know how to do this please dm me cause i'm
.
Please and thanks
well. What are the errors
lol
wait a minute dont clown me
im new to python
just tell me what im doing wrong

client isn't defined. You'll have to export client to that file somehow
oh wait
So I just get ignored but this guy gets help 
I'm not a front end developer

For a good reason, too
got it
yes
bruh wait
k
lmao
what
Just try removing the event code temporarily. Only run the client commands to see if they work
this is my event code
POG
it works without events
then how am i supposed to get events
i found out whats wrong
mixing them is fine
or atleast it works
but there was one that messed everything up lmao
i remember someone saying that if you use the commands extension, then it will create an internal on_message to handle the commands for you
and if you write your own on_message you're basically disabling the one responsible for the commands
Helllo, so I need help with my bot
V
this is my glitch project
my bot does not want to go online
For some reason, this returns true for both me (boosting for 5 months) and my friend (boosting for one week)
I'm trying to make it return true when they've been boosting for more than a week, and false if not.
const enabled = player.plugins.banned.enabled
const time = player.plugins.banned.time
if(enabled == true && Date.now - time >= 0) return user.send(bannedFromMatchmaking)``` this would return if enabled and the time is still not finish correcT?
@fierce ether or.... you could just ```ts
if(enabled && Date.now() > time) //do stuff
your thing is inverted and also you're removing 1 week from both of them
if premiumSinceTimestamp > Date.now() - 1week
So due to the nature of globalchat I am working on global bans
eyo anyone can help me on how to avoid TypeError: unexpected type, use Uint8Array in discord js?
you're passing a wrong type to an argument or something
It seems like it is thrown inside the api from time to time but it always crashes the bot when it happens
like once every month
thanks any idea on how to prevent this?
TypeError: unexpected type, use Uint8Array
at checkArrayTypes (/var/www/git.jmk.cloud/node_modules/tweetnacl/nacl-fast.js:2165:13)
at Object.nacl.secretbox.open (/var/www/git.jmk.cloud/node_modules/tweetnacl/nacl-fast.js:2190:3)
at PacketHandler.parseBuffer (/var/www/git.jmk.cloud/node_modules/discord.js/src/client/voice/receiver/PacketHandler.js:61:36)
at PacketHandler.push (/var/www/git.jmk.cloud/node_modules/discord.js/src/client/voice/receiver/PacketHandler.js:93:25)
at Socket. (/var/www/git.jmk.cloud/node_modules/discord.js/src/client/voice/networking/VoiceUDPClient.js:131:76)
at Socket.emit (events.js:315:20)
at UDP.onMessage [as onmessage] (dgram.js:919:8)
heres the whole message if you need it
does it say the line in your code where it went wrong?
its not in my code its in the node module thats the problem
aight thanks anywayys
sure
you're trying to play invalid data
either your audio stream got corrupted at some point, or it tried to play an invalid file
That actually makes sense thanks alot!
Only thing thats weird: Shouldn't the stacktrace go up to the method that triggers the playing?
meaning up to my code?
i see
its caused in the middle of the stream, and by then the code that started the playing is already long gone
let money = db.all().filter(data => data.ID.startsWith(`bal`)).sort((a, b) => b.data - a.data)
money.length = 10;
let finalLb = "";
for (var i in money) {
finalLb += `**${money.indexOf(money[i])+1}.** | ${money[i].ID.slice(25)} - \`${money[i].data}🪙\`\n`;
}
const embed = new discord.MessageEmbed()
.setTitle("Global Leaderboard")
.setColor("#ff0000")
.addField(`Leaderboard`, finalLb, false)
message.channel.send(embed);
}```
Issue: Returns embed that is messed up [shown below].
how do i turn that into the amount of money the user has?
either concatenate the individual properties of the object, or serialize it to JSON
console.log(money[i].data)
Ok
console.log ID as well
you're slicing 25 characters off of it, so if the ID is anything smaller than 25 characters , it will basically make it empty
Anyone have any idea how to (from the discord API/endpoints) have a wrapper see if channel is nsfw channel?
see, data is an object that contains 2 ids and 2 values
which of those do you want to show in the embed?
User ID and the bal
So like
#1 | USER ID - USER BAL
I need it to show all people though for the leaderboard
Yeah as 2 people have used my bot
yes, but arent ids supposed to be saved in money[i].ID?
In quick.db the ID is the name of the db
So if I logged sau
db.all();
It will look like
{
ID: 'bal',
data: { user id: bal, user id2: bal2 }
}
so then you want to loop over data, not over money
yes but you got your for loop wrong then
I want my bot to determine wether or not the message sent starts with the text "owo" and if it does then search through the array "list" if the message has any one of the values of the array
const msg = message.content.toLowerCase();
// Counting code
if (msg.startsWith('owo')) {
const afterowo = msg.slice(3).trim().split(/ +/);
for (let i = 0; i < list.length; i++) {
if (afterowo === (list[i])) {
message.channel.send('That was a command!');
}
else {
message.channel.send('That was not a command');
}
break;
}
}
or are there multiple things with ID bal?
Only 1 thing has id bal
then get the thing with id bal, then loop over its data
not over itself
for(i in money.data)
Ok
So finalLb += `**${money.indexOf(money[i])+1}.** | ${money[i].ID.slice(25)} - \`${money[i].data}🪙\`\n`;
Alr
I thought I need sort for highest to lowest?
data is not an array, its an object
oh
finalLb += `**${money.indexOf(money[i].data)+1}.** | ${money[i].data.ID} - \`${money[i].data}🪙\`\n`;
}```
Will this work?
no
Ahh I dont understand at all
both afterowo and list are arrays, so you cant compare them like that. use array.some() with array.includes()
Ok
Nothing seems to work for my leaderboard
I’ve used source code with a separate instance and still failed, idk whats wrong
your code is simply incorrect for what you want to achieve
first of all, if you have only 1 bal, then you should store is as a key
db.set("bal", { user1: balance1, user2:balance2, etc... })
If I switch to say, mongoDB, and use zapmongo’s built in leaderboard function, will that work better?
then you access it using db.get() instead of db.all()
If it was only sql...lul
they will be more complicated to setup than quick.db thats for sure
yeah. always worth a try though
mongo is probably better anywho
which you can accomplish with 2 lines of code
Built-in stuff are kinda dangerous I'd say
Like, you're stuck to whatever method it uses
lets say you have the object bal like this ```js
obj = {
ID: "Bal",
data: {
"345346346": 1,
"498376083": 50
}
}
yeah
sortedarray = Object.entries(obj.data).sort((a,b) => b[1] - a[1])
that will give you this
[["4545345", 50], ["45394579", 1]]
or the other way around, i never rememeber which way is descending or ascending
its just a matter of switching a and b
It'll be descending ig
then you can simply do ```js
for(let user of sortedarray) {
field += ${user[0]} - ${user[1]} \n
}
Yeah how will I make it show what rank they are?
Indexed for loop
like the top 3 have medals?
for(let i; i < user.length; i++) {
// code
}?
yes
yea
Is “Object” a built in js thing?
then instead of user[0] and user[1], you have to do sortedarray[i][0] and sortedarray[i][1]
yes
All data types except primitives extend Object
So it's the deepest u can go in classes' hierarchy
Object.keys() creates an array or keys
Object.values() creates an array of values
Object.entries() creates an array of key,value pairs
So I can basically do the Object.entries(db.all().find(dta => dta.ID == "bal")).sort((a, b) => a[1] - b[1]);
yes
B - A
alr
ill try it
ill do medals later. i just want the lb to function
Code is let sorted = Object.entries(db.all().find(dta => dta.ID == "bal")).sort((a, b) => a[1] - b[1]); let field = " " for(let user of sorted) { field += `${user[0]} - ${user[1]}` } message.channel.send(new discord.MessageEmbed() .setTitle("**Global Leaderboard**") .setDescription(field) )
Object.entries(db.all().find(dta => dta.ID == "bal").data).sort((a, b) => a[1] - b[1]);
use \n for newlines
not sure if tab will work, you can try
How can I limit it?
can I like use a .length and set that to a fixed amount?
To show say, 10 people at max
Must have done something wrong :/
const msg = message.content.toLowerCase();
const afterowo = msg.slice(3).trim().split(/ +/);
function checkCommand() {
return afterowo === list;
}
// Counting code
if (msg.startsWith('owo')) {
if (list.some(checkCommand) === true) {
message.channel.send('That was a command.');
}
else if (list.some(checkCommand) === false) {
message.channel.send('That was not a command');
}
else if (msg.includes('owo')) {
message.channel.send('👍');
}
Hug is in the list
you're missing the includes, and also the parameter for some
yep that worked tyvm
If the array is smaller than the length you set it to, you'll have <empty item> filling the rest
i also made it show tag by fetching the user through client’s cache and returning user.tag
Can’t I set the empty items to "Nobody#0000 - 0"?
you can
but its easier to just put an if
if(sorted.length > 10) sorted.length = 10
How do I fix the parameter?
.some iterates over each item of the array
so array.some(item => do something with item)
for each item of the array, you want to check if it exists in the other array
it randomly stopped working
so array.some(item => otherarray.includes(item))
Cannot read property of 0 of undefined
sorted.length = 10
let field = " ";
for(let user of sorted) {
field += `User: ${user[0]} - Balance: ${user[1]}\n`
}
message.channel.send(new discord.MessageEmbed()
.setTitle("**Global Leaderboard**")
.setColor("BLUE")
.addField("**Balance Leaderboard**", field)
)```
Then you need to define the thing that is undefined
remember the if?
does anyone know how to make the bot send a message as soon as someone invites it to their server
Could you use php to check if a specific python process is running?
if(sorted.length > 10) sorted.length = 10
i got it to send a plain message but when i try to use a embed it dosnt work anymore
I was like "Why isnt this working??"
Show the code you use to create the embed
lemmi find it rq
.setTitle("test")
.addField("test")
.setTimestamp();
message.channel.send(embed);
}```
is what i put after the code that makes it send a message when its added
Does it give you any errors when you try it?
client.users.cache.get(user[0]).tag is returning undefined
user[0] returns a id
idk if this will work but I can try client.users.cache.find(u => u.id == user[0]).tag
Could you show the code for the entire event?
nope neither works
let defaultChannel = "";
guild.channels.cache.forEach((channel) => {
if(channel.type == "text" && defaultChannel == "") {
if(channel.permissionsFor(guild.me).has("SEND_MESSAGES")) {
defaultChannel = channel;
}
}
})
let embed = new Discord.MessageEmbed()
.setTitle("test")
.addField("test")
.setTimestamp();
defaultChannel.send(embed);
})```
you should check if defaultChannel exists before sending the message
Also, isn't .addField() supposed to take at least 2 arguments?
yea i updated it
Also, instead of using forEach, just use collection.find()
guild.channels.cache.find(x => x.type == "text" && x.permissionsFor(guild.me).has("SEND_MESSAGES"))
much more simpler and it won't continue looping once it finds an element that matches the filter
{
'737918277866487928': 400,
'705731402972528690': 55474,
'733912649418670080': 25,
'752770336591839272': 150,
'586391264350699551': 150,
'719775900337700876': 50,
'804079538257657866': 1000,
'803199405598572554': 50,
'807170169474383895': 425,
'803711637105278978': 225,
'804779119791046657': 50,
'802096152295112735': 175,
'781055840488259604': 50
}
Is that a object
or an array?
Pretty sure that's a json object
Okay ty
rule of the thumb
surround it with [] to make an array
okay
How do you tell if a user can’t be dm’d
with .catch it doesnt reply anything like I tried
.catch(err => message.reply('can not dm.\n\n Back end error: '+err);
You can only catch it
It logs the error but doesnt reply to the user running the cmd saying it cant be dms
WHERE did you put that catch ?
if tis logging the error, you either didnt give the full snippet or its THROWING the error(not logging)
I put it right after it sends the user so it says
show full snippet
message.author.send(...).catch(err => message.reply("You have dms turned off!"))

and in console it says
at RequestHandler.execute (/home/runner/Augusts-bot-PRIVATE/node_modules/discord.js/src/rest/RequestHandler.js:154:13)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at async RequestHandler.push (/home/runner/Augusts-bot-PRIVATE/node_modules/discord.js/src/rest/RequestHandler.js:39:14)
(node:499) 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: 2)```
then what is that thing above?
.catch(err => message.reply('can not dm.\n\n Back end error: '+err);
that was what i tried the first time
it disnt work
so i changed it
still didnt work
use a try/catch with await then
ok
huh?
((err) plsss
¯_(ツ)_/¯
too tired for that today
lets just say after this major rewrite my brain is barely functioning anymore
Dont rewrite your brain
(discord.js) anyone know more specifically what "DiscordAPIError: Missing Access" might mean in the context of a guild fetch promise being rejected? it seems to happen at random times, with random guild ids, causing some fetches to fail for a reason I can't figure out.
means it has no access to the server/channel your fetching
if(sorted.length > 10) sorted.length = 10
let sorted2 = Object.entries(db.all().find(dta2 => dta2.ID == "level").data).sort((a, b) => b[1] - a[1])
if(sorted2.length > 10) sorted2.length = 10
let field = " ";
let field2 = " ";
for(let user of sorted) {
field += `User: ${client.users.cache.find(u2 => u2.id == user[0]).tag} - Balance: ${user[1]}\n`
}
for(let user of sorted2) {
field2 += `User: ${client.users.cache.find(u => u.id == user[0]).tag} - Level: ${user[1]}\n`
}
message.channel.send(new discord.MessageEmbed()
.setTitle("**Global Leaderboard**")
.setColor("BLUE")
.addField("**Balance Leaderboard**", field)
.addField("**XP Leaderboard**", field2)
).catch(() => null)```
Error: Cannot read property of tag of undefined.
The code worked fine until I added the xp lb, whats the issue?
likely you trying to fetch a guild that is still cached but they already removed your bot from it
no, I know it's happening in guilds that are using it currently. I've had it fail to fetch my own guild from the cache.
then no, im not sure why that would ever happen
strange, it seems to happen in bursts too. sometimes there will be no errors for hours, then suddenly 3 people using the bot will throw 3 separate missing access errors.
I know this is too little information to really diagnose, I guess I'm just hoping someone else has experienced the same thing.
Maybe some command is trying to access a channel it doesn't has access to
Also dm will throw that error if it's closed iirc
it happens in channels that I know the bot has access to, and the method throwing the error is client.guilds.fetch.
but it doesn't happen consistently in any channels
are you suggesting I check the cache first, then if nothing comes back, try .fetch? is that not what fetch already does?
cache is a collection
that's not how it works 
the cache is a collection, and I'm not seeing a fetch method on the collection type. are you sure?
plus if I just checked the cache, I'd still have to hit the API in some cases when the guild hasn't been cached recently.
bruh
I successfully got Chatlink to double up as a bridge on the alpha version of my bot!
is it a website?
It's a bot
The 2 clients pictured are Discord (Left) and Nertivia (Right)
The left one is Discord
The right one is Nertivia
That's 2 windows I have open
ok
you could use webhooks to mimic the user who send the message. the user will still have the Bot tag but also you could have the users PFP and Nick
how you make the bot come online
-faq 13 @sour warren
@sour warren
wrong website
Thats pog
You can't
Don't you need a user token for that?
Which means that you can't since it counts as self botting
It's not documented in docs, only the GET operation is
wait you can't change vanity url of server with bot?
Have you tried this
br
Try it ig
It might still work even if it's not documented
Also, it's body, not payload
Also, the method should be PATCH I think
Not POST
isn't the vanity url only modifiable by the guild owner
nope
huh interesting
fetch("https://www.discord.com/api/v6/guilds/762359120031907871/vanity-url", {
method: "PATCH",
headers: { "authorization": `Bot ${client.token}`, "content-type": "application/json" },
body: JSON.stringify({ code: "test458" })
});```might work, can't test it
Since you use Discord.js you can just use js client.api.guilds[<guiild id>]["vanity-url"].patch({ data: { code: <new vanity> } });
Yes
yes
How do I sort a object in alphabetical order
what lang
js
Also how do I delete a specific thing in a quick.db database?
Like I have a notes command
How do I delete a specific note
.delete(...)
hmm i tried to do it once but i didnt know how so i stopped
can i send a code i can't understand what's wrong?
sure
const Discord = require('discord.js');
module.exports = {
name: '8ball',
cooldown: 6,
description: '8Ball',
permissions: 'SEND_MESSAGES',
execute(client, message, args) {
if (!message.length == 4) {
return message.reply('Please ask a valid question')
} let responses = [
'Maybe.',
'Certainly not.',
];
let response =
responses[Math.floor(Math.random() * responses.length)];
const Embed = new Discord.MessageEmbed()
.setColor('RANDOM')
.setTitle('8ball')
.setAuthor('SD-14 Bot', '')
.setDescription('Gives A Answer As Yes/No')
.setThumbnail(\`${message.author.avatarURL({ dynamic: true })}`)
.addFields(
{ name: \`My Answer\`, value: \`${responses[response]}` }
)
.setTimestamp()
.setFooter(\`Requested By: ${message.author.username+message.author.id}`);
message.channel.send(Embed);
}
};
use codeblock please
ok
1 sec
const Discord = require('discord.js');
module.exports = {
name: '8ball',
cooldown: 6,
description: '8Ball',
permissions: 'SEND_MESSAGES',
execute(client, message, args) {
if (!message.length == 4) {
return message.reply('Please ask a valid question')
} let responses = [
'Maybe.',
'Certainly not.',
];
let response =
responses[Math.floor(Math.random() * responses.length)];
const Embed = new Discord.MessageEmbed()
.setColor('RANDOM')
.setTitle('8ball')
.setAuthor('SD-14 Bot', '')
.setDescription('Gives A Answer As Yes/No')
.setThumbnail(`${message.author.avatarURL({ dynamic: true })})
.addFields(
{ name: \My Answer`, value: `${responses[response]} }
)
.setTimestamp()
.setFooter(\Requested By: ${message.author.username+message.author.id}`);
message.channel.send(Embed);
}
};
This is the code
I am new to JavaScript
how do you slice the first character of a string?
slice(0)
ty brutha
wut?
isn't this slice(1)
isn't the first index 0?
idk
show code
It's amount of characters, not index
you are doing join(",") probably
what is your .join()?
you're thinking of indexing the string instead of slicing, but yeah if your goal is to only get the first character you should index the string instead
"gay"[0] // "g"
im doing args.join(' ')
im doing args.join(' ')
can you show the code for your embed builder?
.setTitle('Your Notes')
.setColor('RED')
.setDescription(`${no}\n`)
message.reply(eme)```
I can send my add notes command
if(!args.join(" ")|| n >= 10) return message.reply(`Error ID 166. Missing argument or exceeding note limit of 10!`)
message.reply('Note added.')
await db.push('note.'+message.author.id, args.join(' ')+'\n')
return db.add('notes.'+message.author.id, 1);```
you get the , bcs you display an array. idk if join() will actually remove the ,
have you tried
.setDescription(`${no.join('\n')`)
No problem. If you ever get variables displaying in a way you dont want them to, try console.log to see how those variables actually look
or try catch error if you wont like errors in console
const mons = require("./mons.json");
console.log(found.name)
console.log(founds.name)
let last1 = Object.values(mons).find(m => m.name === `${found.name}`)
fs.writeFileSync("./mons.json", JSON.stringify(mons), e =>{
//Handle error
last1.owner = `${targetMember.id}`; //Setting the owner ID
});
let last2 = Object.values(mons).find(m => m.name === `${founds.name}`)
fs.writeFileSync("./mons.json", JSON.stringify(mons), e => {
last2.owner = `${firstmember}`; //Setting the owner ID
});
```
hey so i am trying to change the value of key owner.
however it does not work, nor does it change anything.
```js
{
"1721138": {
"ability": "Corrosion",
"iv": 88,
"stamina": 96,
"hp": 338,
"speed": 50,
"attack": 16,
"defense": 28,
"specialattack": 234,
"specialdefense": 307,
"id": 367,
"name": "Huntail",
"level": 18,
"catchChance": 0.8333333333333334,
"spawnId": 4236884,
"owner": "345138133429649408",
"catchTime": "01/18/2021 9:49 PM",
"nickname": ""
}```
this is how the object looks like
i have not
i have looped thrtough the file to find the mons which name is the same as was put in
and named it last1
and later on changing it using last1.owner = ${variable}
@lusty quest
yea this will probably not work with the object you provided
why is that?
bcs of the id
if you get the object as the one you send earlyer you have to use the path ive provided otherwise you wont find it
owh shit
where is that id above ability then defined?
I am literally confused
var correctID;``` it is the correctid
but that was never passed into the json
might have found the solution
mons.[correctID].owner is what i should call
found.correctID
let last1 = Object.values(mons).find(m => m.correctID === `${found.correctID}`)
fs.writeFileSync("./mons.json", JSON.stringify(mons), e =>{
//Handle error
last1.owner = `${targetMember.id}`; //Setting the owner ID
});
let last2 = Object.values(mons).find(m => m.correctID === `${founds.correctID}`)
fs.writeFileSync("./mons.json", JSON.stringify(mons), e => {
last2.owner = `${firstmember}`; //Setting the owner ID
});``` so it would be like this right? @lusty quest
any help please?
I need some help im trying to do simple pages for a help command I use commando but dont like the help command it has
Can we use opengraphics for our bot page?
hey umm are setintervals and settimeouts considered event blocks? also do they cause lag?
what do you mean by event blocks
do you mean opengraph meta tags?
if you're thinking of opengl... uh no
that's not a web library
there's webgl but that's only accessible via js
setinterval and settimeout do not prevent other commands being used (if that is what you are on about)
and the amount of lag they cause is only the same as running the specified function every n seconds
Yeah
nope
the meta tags are scraped at top level, meaning the first head element that occurs
(which is going to be top.gg's head element)
...log inside of the try
if an error happens the flow will stop going through the try block and will jump to the catch block
finally will occur regardless whether an error happened or not
can i use custom dns for get request in node js?
uh yes
try
{
// do code
console.log("fine?");
}
catch(err)
{
// do something with err
console.log(err);
}```
how
yeah
?
that'll do
huh?
depends on what you need it for
that means your IP is likely to be flagged and blocked, this has little relation to dns if the webpage is blocking requests from your server
you will either need to use a VPN or a proxy to scrape the site
^
hmmm
you need a proxy, not a different DNS
google it
you're also probably going to have to buy a proxy list, 99.9% of free public proxies are already blocked by most major services
What the difference between
message.reply and message.channel.send?
oh message.reply actually replies now
oh yea ur python arent you
well mostly python but yeah
just install master
no
What am I doing wrong
client.getLevel doesn't exist
what should I do
create...??
did you copy this code from somewhere?
^
or did you create getLevel yourself?
getLevel is not part of discord.js
its a user-created thing
How can I snooze Team on
Elaborate
The shit you type in google vs the shit you ask in a dev question channel
The vanity url should always be a string
You need to await the fetchVanityData
const url = await guild.fetchVanityData().then(v => v.code);
destructure
what's the best module to do http requests in js
not axios or node-fetch
I was unironically thinking of switching to the built in http lib
It is. A few people in my dev server seemed to rave over one called centra
I have no personal opinion on what to use
got's api sucks
tim is the one that recommended got iirc
im personally a fan of axios
does most of the jobs for you
parsing, error cacthing/handling, intercepts shit, its everything i need tbh
axios logs the errors regardless of if you put it in a try catch block or not
I hate that
What it logs is large and unnecessary info
Believe me. It does. I wrote a rest lib and returned errors to the user level but there was no way I could handle them in my application like I did with discord.js.
its just really not doing it for me
do you have a test snippet?
either fixed in last patch or somethings up
Not on hand. I'd have to write something
im gonna be honest, i've never noticed that error logging you're mentioning, though its entirely possible i overlooked it, since i log a lot of errors
i think of my console as my friend, the only instance i dont log stuff is in prod
for that i have custom dumps and handler for it
hmmm thats odd tbh
Mostly just unauthorized
hey guys, I'm using djs and I want to make embed with variable number of fields in embed.
Ex. an array has x strings in it and I want every string in separate embed field
Is it possible?
yeah, just loop through the array of strings
how? I know it sounds easy
for() loop
Loops offer a quick and easy way to do something repeatedly. This
chapter of the JavaScript Guide
introduces the different iteration statements available to JavaScript.
I mean create embed fields
ik how to loop.. but I want to create embed fields at each iteration
const embed = <embed>
for (cond) {
<add field>
}```?
Do you use the MessageEmbed object to create embeds or do you just use raw objects
remember that theres a limit to how many firleds you can add
which i dont remember back of my head, 25 or something

25 yes
Should I make embed pagination or display emojis => role map in fields (maybe 25 emojis per field)
Pagination imo
Fields can be big
If you don't want reaction pagination you can make the user specify the page
thanks
125 per each
if (!kullanıcı) return message.channel.send(`Cihazını görmek istediğiniz kullanıcıyı etiketleyin!`);
let p = Object.keys(kullanıcı.presence.clientStatus).join(',')
let cihazisim = p
.replace(`mobile`,`Mobil`)
.replace(`desktop`,`Bilgisayar`)
.replace(`web`,`İnternet Tarayıcısı`)```
where is the error i have "cannot convert undefined or null to object"
i am using d.js v12
@earnest phoenix
@earnest phoenix kullanci is just a user and not Object with many keys
you can join them like kullanci.join(' ,')
i will try thanks
so i have setintervals that run every 3 minutes and they dont stop.. would this be a reason for lag high latency pings?
i have 3 such intervals that run every 3 mins and one runs every 3 hours, and 1 2 hours, and few other setTimeouts that run like after 15secs but these are cleared
Ive had one command before that ran every 2 seconds. Didnt cause lag for me
I suppose it depends what your intervals are actually doing
Hello,
I would like to know if in discord.js it is possible when we put an invitation link in the status its automatically ranks us? thank you in advance
my intervals make DB calls and updates
i dont think it would cause lag since they are async
also is it really not possible to serialize the message and client object that djs gives? ;-;
well nodejs nothing really executes parallely
so i thought the DB queries were causing lag which in deed took like 800ms - 1.2secs even more, i optimized those to 200ms or less
but the lag still persisted
so that wasnt the bottleneck
i thoguht maybe there some event loop block in my code
but my for loops are async
serial/parallel execution
concurrency != parallel
.. that's false, node supports parallelism
well i've never used it xd
JS can use multiple threads, but async is always ran on the same single threaded event loop
also i could use a second hand to review my code to figure out bottle neck
let me know if anyone can help
as to why your bot is lagging, the only way to find that out is to debug your code and track performance
yep i tried most of it
the lag only shows up when 2k people are using it
when i running my test bot
i see literally no lag
which is used by like 5 - 10 people
the same functions in both
In the guildMemberAdd event, there is no message, so how can I do this? let role = message.guild.roles.cache.get(server.mainRole);
client.guild
get the guild from the member
no
Oh.
member.guild
member.guild.
i really need to get a colored role so people stop ignoring me
I got you!.
also this
(i was kidding :p)
let role = member.guild.roles.cache.get(server.mainRole);
wont change anything 
people like to selectively listen to people only if its what they wanna here
@crystal wigeon it isn't because djs objects are too complex and have recursive properties
map properties you want to your own object
ye its the recursive that gets me grr. member.guilds.role haiz if i wanted this i have to serialize every single prop lol
just hinking of a way to make it easier
mmm
Hey folks, got question developing such algorithm that can take Spotify album image colour palette as input and return matching or suitable background colour that can be used, any idea if such thing can be achieved? would appreciate some of your thought process. 🙂
at the top of my mind, you would just go pixel by pixel and save the most dominant colors
If you're using python Numpy can be pretty good for this or OpenCV
colour that will possible be available lets say in this example green yellow and blue is give as input then my algorithm should workout the best possible output from that
okay, I have seen that too
your easiest solution is calculating the dominant colour
and matching that to x background or just using that dominant colour
Median cut is an algorithm to sort data of an arbitrary number of dimensions into series of sets by recursively cutting each set of data at the median point along the longest dimension. Median cut is typically used for color quantization. For example, to reduce a 64k-colour image to 256 colours, median cut is used to find 256 colours that match...
const { Schema, model } = require("mongoose");
const serverSchema = Schema({
name: String,
serverID: String,
prefix: String,
test: Boolean
});
module.exports = model("Server", serverSchema);
Hey, just quick question regarding MongoDB, I'd like to ask why whenever I add a new line such as test: Boolean, it doesn't update for all the saved ones that are in the database, and whenever the new command features wants to use the test: Boolean, it would simply not find it for the ones that are in the database as it didn't update to all the saved ones! What can I do?
This is also how it registers it..
if(!server) {
const newServer = new Server({
name: guild.name,
serverID: guild.id,
prefix: process.env.PREFIX
});
newServer.save().catch(err => console.log(err));
} else {
return;
};
I can simply just add the test: Boolean alright, but what about all the current saved ones? It doesn't update, what can I do?
agreed, I think should avoid complicating and thanks for the suggestion. 😊
overcomplicating is my middle name 
What can I do though! :(
<Schema>.add({name:type})
What do I do with this?
I'm currently having this issue where I'm trying to delete the obj (as defined in Guild.js) from the guildConfig collection. But when I try it, it just says that there were none found. It only works if I manually add in the _id to the admins object along with copying the actual id from the document. Anyone know how I can work around this https://srcb.in/dO70QonTqz
So, this unfortunately didn't work even though I discussed it with the user, so anyone got any other solutions I could deploy to fix this?
just create a server with express or something similar
just use nodejs' rate http lib 
rate?
how to check if a member didn't send any amount after the command in discord.py ? like !clear [amount]
If someone knows mongoose, can you help me with this?
use updateMany
just modify your model to contain the wanted new value and run a updateMany query to make the change on all existing documents
hey
also
quick question
so a Promise() without await is considered synchronous? can it cause event blocks?
something like
func() { new Promise(
Promise.all()
) }
something like this
i feel like it would cause blocks?
so using await will make it blocking?
from PIL import Image
def colorPicker():
example_image = Image.open('image url here')
image_colour = example_image.getpixel((250, 100))
print(image_color)
This solved my spotify colour picker from album image, but for pure accuracy can use K-Means Clustering in OpenCV but for simplicity this is does the job for the time being I have tried with various song on spotify so far the accuracy for the colour palette is decent. 😊
async func () {
return await new Promise(async () => {
return await Promise.all([])
}
}
would this cause event blocks?
To get the average color you could just iterate over all pixels and exclude white and black tho
No
Because the method it's in is async
It'll block only if you await it too
so awaiting the func would block it?
this func, if i call this func with await thats when it blocks everything right? but if that func is also used in another async func it wont block
if im correct
🤨 You know the whole point of async and await is to provide a higher level non-blocking api over promises right?
yeah but the reason im using promise all is to avoid for (...) loop since i want them to run parallely or something
because i wanna avoid nested for loops
if you call a async function from a synchronous context you're blocking the current thread to allow the event loop to manage the context to give the concurrency aspect
gotcha, so if i call a async function from async context there's no blocking right
it depends on what the internals are doing
then what is the point of them being asynchronous 
sowwy im slow :p
for example, no matter how much async you use, if deep down the core code is sync, it will block
there are only 2 types of true asynchronous code
streams and event loop skipping

Think those words are just gonna confuse them 😔
I/O like file reads, networks requests, TCP, etc... are all done through streams. a request is opened, and the data starts flowing in chunks, so it doesnt block
event loop skipping is a way to manually break down synchronous code by using setImmediate
so you have to look at what the actual code is doing
for example, a database request deep down uses streams, so it is true async
you can confidently use them knowing it wont block
Co
but numeric calculations, no matter how complex, are not async
unless you explicitly break them down in chunks using setImmediate
actually there are 3 types, timers are also async
but they can be grouped together with setImmediate kinda
well... Timers are synchronous they can just use the eventloop to schedule their execution at a given time
Go's entire runtime are just loop skippers 
xD
which as much as its useful to not worry about it's execution being blocking or not
it basically nuked it ability to expand it syntax and execution logic
Imagine making async code whike you could make synchronous code
most async things are 90% synchronous
The entirety of my async web server is written with synchronous code 
and then you start using a language where you're free to use threading 
threads is where it gets wild
threads are nice
it took me almost a month to actually understand their lifespan in c#
threads are easy in node
dataraces is what i like 
its just a pain to share data with them
I just go with async + threads 
race conditions are a pain
and then you fall back to locking, making it sync again
actors™️
async locking
^ has not been implemented even today
Thats completely untrue but what ever
again, thats completely un-true
Do you think OS' are synchronous
well some of them are
👀 That would be one fecking slow OS
none of them are
there's operations that some OS' do synchronously but all of them work in an asynchronous context
the very essence of multitasking is based on that
otherwise how would OSs multitask on single core 90s cpus
most modern OS' utilize work stealing to properly balance tasks
const getInformation = await client.playerModel.find({ })
.map((v) => v.id) ``` this should return all ids in the collection?
try it
i did
and?
it returns the whole collection
so I have an object like this:json { "location": { "name": "Blois", "region": "Centre", "country": "France", "lat": 47.58, "lon": 1.33, "tz_id": "Europe/Paris", "localtime_epoch": 1612714370, "localtime": "2021-02-07 17:12" }, "forecast_day": { "temp_c": 35.4 } }and a string provided by the user with placeholders such as [location.name] or [forecast_day.temp_c] in it. Is there an efficient way to replace the placeholders in the string with the values in the object without using 15 string.replace in js?
you could just regex it (or better yet, properly split with)
actually
let me get a step
1 sec
just split by a dot and loop through all props? Why use replace
oh
in the same stirng
string*
get all entries of the content
then split by .
get first entry of each iteration, on the split, check if your object has that property
Object.hasOwnProperty(regex[0])
if it does, then you assign that property to the second value
regex[1]
regex being one entry of your regexed item, split by .
keep in mind regex is slow af

