#development
1 messages ยท Page 1233 of 1
true matching
oh lol
You'd use it in cases like undefined. value === undefined
oops
instead of value == undefined (incorrect)
i forget to change id
but may pass
i m sorry
You do !=
For not equal to
Nope
It's right ๐
Too deep in this to go home now
ECMAScript 6 stuff
nearly 10+ years old standards
Ahh
K
or if the value could be int, but may return undefined
!== undefined
Strict comparisons
For most part if you triple up; you're good to go
on all ends. But it looks really un-professional. ๐
Chat died
--
To finish that, they wanted to compare what could be known as int type to a string representing an INT type; and the use of strict compare does a cast check between the types; for a proper-deeper match. Now this is as basic and straight to it as it gets.
no chat didn't die
Real coding talk was had.
i'm still here
All those who had questions mouth's dropped.
You kinda did babble on tho...
..
@pale vessel can you draw a gradient in canvas with transparency?
The weather APIs are becoming paid for
Bruh
I hear of python or lower-end languages doing good scrubs
to pull the data without using active API but it's messy them scrubbers
See it most with python projects.
I use discord js
Oh yeah no scrubbing with JS
it's very minimal there, you get as far as cross-site injection and that's it, no real power to surf the web and pull site-pages.
So yeah use an API from a weather network
(maybe costs) or use a better language to scrub it out.
Mhm
can you draw a gradient in canvas with transparency?
sounds really weird but i need it for a gay command
you can't make an image transparent in canvas so i had to make the rainbow gradient transparent
any idea how?
What do you mean by "good scrubs"? What does the language really have to do with using an API?
No idea, my graphics end is poopsky
Javascript doesn't have the power to execute a browser launch and cipher its components
like C#/python or even java
Those can hook for days and tell a browser to do whatever, grab data then process it.
Javascript will never have that power without added modules like NodeJS/etc.
Which won't power that.
Javascript doesn't have the power to execute a browser launch and cipher its components
@unique patio there is one npm package that can execute any installed web browser in the system inside the termnial iirc
So, acting like a browser?
There is actaully!
But it's not as good
But yeah if you can do that, by all means use that! But experience taught me a lower-end language to get that stuff done for scrubbing sites.
But if it's built in now via NPM hell yeah you winnin'
Javascript generally on its own cannot access different executed PIDs in the CPU and read them out.
but apparently with some additional modules you may get some support there but not full?
hey guys. How do i actually make a hyperlink like this?
like this????
or embed
i already have made a bot that shows the coordinates
Looks more like an embed.
addfield/addfields
but i have got a weather search bot
There's a whole write-up on it, I don't use them much.
so if you use $po rain it returs countries with raining weather
but that means that the countries change all the time
so i cannot just use addfield
Hmmm just use >>>
markdown links
so it can look like this instead.
lol
You just want the line?
OR
Some balling code?
?
cosmos that is a terrible idea
what are you citating all the time
man wants an embed not a quote
Embed though has limits
i am using weather-js package to actually make the searchs
i want to define one google maps link to each country
but i've got no idea how to do that.
Yo guys, I am a bit confused, maybe you can help me out. I'm using Discord.js 12.3.1.
I am trying to fetch a message from a guild text channel, but i get the Missing Access error.
But when I log the permissions i have in the channel of the text, i have
[
'ADD_REACTIONS',
'VIEW_AUDIT_LOG',
'STREAM',
'VIEW_CHANNEL',
'SEND_MESSAGES',
'EMBED_LINKS',
'ATTACH_FILES',
'READ_MESSAGE_HISTORY',
'USE_EXTERNAL_EMOJIS',
'CONNECT',
'SPEAK',
'USE_VAD',
'CHANGE_NICKNAME'
]
``` these... Since I have `VIEW_CHANNEL` and `READ_MESSAGE_HISTORY` I don't understand why i have missing access. any ideas?
does your actual bot have the permissions through discord developer portal?
yeah
@blazing portal hey
wait. what permission in the developer portal do you mean exactly?
Lol
srry, but hey is not helping
When you invite bot to server you set perms for it to have
Trial it as an Admin in your server and request it.
If it works, yeah you need to set more perms for it.
That's brave, I'd admin for testing, no bot in my mind needs admin priv unless it's coded wrong.
i said so
i usually give my bots the permissions it needs
but admin permissions are left open
yea
Other night watched a main discord bot token get stolen
does anyone know how to send a link to the country in google maps, that changes for every country?
as it spammed links all over the discord
oowh fuckkk
Yeah...
you gotta regen that shit fast
But the Permissions it has on Server level don't matter, if the channel overwrites give these permissions i logged
Some public bots get takenhard
but
no clue tbh
just try giving the perms to your bot
and see if that fixes your problem.
btw guys
this is my code. How can i add links to the embed, that changes for each country.?
https://pastebin.com/iV75XkrV
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Doing some homework on your request there jonny.
I just made Koya gay XD
I can't replicate the permission error myself, so it's hard to test if admin would help it. My public running bot sometimes logs this error, might it be related to a guild not being ready or smth? But would that resolve in a missing access error?
yeah im awaiting it
Blind-firing is always a problem sometimes
but wouldn't that result in an unknown message error?
Yeah undefined
I only ever pull on the go, cause discord blocks a bit of the retrieval process without, "hacks"
so on events, never; tell the server like, YO gimme dat.
Tends to be a fight with discord, especially when they revamp code restrictions, I think it was last API they revoked priv on guild usage in bot.
But I don't think it'd prevent what you wanted to do.
tested my rainbow gradient on Koya's pfp and I made him gay ๐ณ๏ธโ๐
Nice!
hmmm
had to do a bit of math
@pale vessel can you use HEX colors in
CanvasGradient.addColorStop()
yes, you can use rgb, rgba, hex on anything that uses colors
@pale vessel can you draw a gradient in canvas with transparency?
@earnest phoenix yes, use rgba, e.g.grd.addColorStop(0, "rgba(255, 212, 111, 0.2)");
@pale vessel thanks for introducing me to this awesome thingy i wanna hug you now man 
@earnest phoenix yes, use rgba, e.g.
grd.addColorStop(0, "rgba(255,212,111, 0.2)");
@pale vessel I have a HEX value
you can use https://davidwalsh.name/hex-opacity
add those two extra hex for opacity support
so it like #3179bd -> #3179bde6
neat
cool
How can I get the dominant color and color palettes from a url?
Which module or api should I use?
nvm i used globalAlpha and it works
no need to set the transparency for everything. Just doctx.globalAlpha = 0.5;, draw your stuff which you want to be transparent, doctx.globalAlpha = 0;then draw the other stuff which you don't want to be transparent
How can I get the dominant color and color palettes from a url?
Which module or api should I use?
@earnest phoenix why not goto https://stackoverflow.com instead of repeating the same question multiple times
What's the matter, little boy? @earnest phoenix
@earnest phoenix Your repetitiveness, and ignorance with that last statement I'd assume now.
@earnest phoenix You make no sense, make sense before you ask for help.
But like code suggested, child-overflow be best for you.
god damn thats blunt as fuck
How can I get the dominant color and color palettes from a url?
Which module or api should I use?
@earnest phoenix you can use the color-thief module - https://www.npmjs.com/package/color-thief
lol
love it
grab the image and get its buffer and use that module
this returns a 2d array that contains [r, g, b]
@pale vessel You do a lot of image work or something?
sometimes
Just turn all images rainbow? lol
lmao i've been usingping Telk's API for most of my stuff but i don't want rate limits so i tried to make my own
a number is an int though
use hastebin.com
return self.randrange(a, b+1)
TypeError: can only concatenate str (not "int") to str
@drifting wedge
can i get a random number not as an int?
"10" ??
xD
it is string
but still number
:))
no
its giving errors
yikes
LoL
what's b?
for xp in exp:
cur_xp = xp["XP"]
randomxp = random.randint('15', '25')
new_xp = cur_xp + randomxp
collection.update_one({"_id": author_id}, {"$set":{"XP":new_xp}}, upsert=True)```
py
no space?
why inside 's?
yeah remove them
should i have spaces?
that's a string
lol
alr
@pale vessel how can i send a Discord.Attachment inside the image: {} object of an embed?
works!
pog
poggers

code wait
yeah
you buffer.... or else
let image = new DIscord.Attachment(canvas.toBuffer(), "image.png");
use embed.attachFiles()
Yeah
how can i make it reset my xp after a i level up?
xp = 0
like reset a thing in mongo
make it a zero
yea
lol ok buddy
use embed.attachFiles()
@pale vessel so i can't directly pass an embed object insideTextCHannel.send()cuz I'll need to do some SHIT to it
const embed = new Discord.MessageEmbed()
.setImage("attachment://image.png")
.attachFiles({ name: "image.png", attachment: <buffer> });```
@unique patio you seem like you possess a brain. Welp I guess we're on different teams now (I don't possess a brain);
like this
Is there a buffer in Discord's message timestamps or something?
@pale vessel I'm using an embed object
const exampleEmbed = new Discord.MessageEmbed()
.setTitle('Some title')
.attachFiles(['../assets/discordjs.png'])
.setImage('attachment://discordjs.png');
channel.send(exampleEmbed);
do the same
from the library
i only use MessageEmbed when I need a constant
let me give you an example for embed objects
yeah
like compare mongo db
figure it out
in your send options:js { embed: { image: { url: "attachment://image.png" } }, files: [{ attachment: <buffer>, name: "image.png" }] }
to whoever has the most of one specific thing?
images inside embeds use the attachment:// protocol (if you were to upload images to discord instead of using a url)
hello i was wondering how i could add my bot to tog.gg i have it all coded and is finished and i am able to run it
you include the attachment inside files as buffer
#region Message latency
var end = DateTime.Now.ToUniversalTime();
var start = context.Message.Timestamp.ToUniversalTime();
var messageLatency = (end - start).TotalMilliseconds > 0 ? end - start : start - end;
#endregion
Tryna figure out why end is less that start... I feel like Discord is adding seconds to the timestamp
and use attachment://<file name and extension> inside the embed object
the name is the one you provided in the array of files
@pale vessel wait files: [] will also show the file outside the embed right
lemme test
yes
It's gotta be some kinda buffer, right?
I fixed my android issue, few firmware adjustments hard-locked it with screen-off; I must quad-tap to make it show-able again
left it on 24/7
This problem I swore took all night to even think about... like wth.
@pale vessel wait
files: []will also show the file outside the embed right
@earnest phoenix wait no, only if you didn't use it inside the embed, i misread
i thought you asked me whether the property was outside embed 
I guess I did something wrong
var colorThief = new ColorThief();
const image = trackIMG;
const imageStream = new Buffer(image);
const attachment1 = new MessageAttachment(imageStream);
colorThief.getColor(attachment1)
.then(color => { console.log(color) })
.catch(err => { console.log(err) })
trackIMG is URL
you should use something like node-fetch to grab a buffer from the url
i'm not sure what you're planning to do with the palette though
do you want to generate an image? that requires some knowledge on canvas
ah
I want to set the background color to the dominant color of the song
i see
huh
you have to convert the rgb value to hex
yeah
you should use await
I successfully made a gay command YEETUS
Isn't that just a random num
That's kinda gay
@earnest phoenix i don't think that function returns a promise though
you don't need .then
getColor returns a promise
any API which returns random 4096 x 4096 background images?
my goals are beyond your understanding
neither do palette, which is what i use
Huh, wait brb
voltrex
How did you all implement message latency? I was comparing date time now to the message time stamp
m.createdTimestamp - message.createdTimestamp ?
So would that require me to edit the initial message
yes
const embed1 = new MessageEmbed()
.setDescription(`blablabla`)
message.channel.send(embed1).then(m => {
let ping = m.createdTimestamp - message.createdTimestamp
yeah
i use that method too
Gotcha ty
because you're using node-fetch with it lol
if you already have a buffer, it doesn't return a promise
at readdirSync (fs.js:955:3)
at /home/container/handlers/command.js:13:26
at Array.forEach (<anonymous>)
at module.exports (/home/container/handlers/command.js:11:32)
at /home/container/server.js:21:35
at Array.forEach (<anonymous>)
at Object.<anonymous> (/home/container/server.js:20:13)
at Module._compile (internal/modules/cjs/loader.js:1137:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
at Module.load (internal/modules/cjs/loader.js:985:32) {
errno: -20,
syscall: 'scandir',
code: 'ENOTDIR',
path: './commands/announce.js/'
[ .....] - postinstall:container: sill install printInstalled internal/fs/utils.js:269
throw err;
Error: ENOTDIR: not a directory, scandir './commands/announce.js/'
at readdirSync (fs.js:955:3)
at /home/container/handlers/command.js:13:26
at Array.forEach (<anonymous>)
at module.exports (/home/container/handlers/command.js:11:32)
at /home/container/server.js:21:35
at Array.forEach (<anonymous>)
at Object.<anonymous> (/home/container/server.js:20:13)
at Module._compile (internal/modules/cjs/loader.js:1137:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
at Module.load (internal/modules/cjs/loader.js:985:32) {
errno: -20,
syscall: 'scandir',
code: 'ENOTDIR',
path: './commands/announce.js/'```
whats the error?
fs can't find that file
announce.js is not a directory
but it was working fine before 
it doesn't work now 
on my another bot its okay
let dm = message.guild.members.cache.get(WinningUsers.map(u => u.id).join(`\n`)) dm.send(`Congratulations! You won a giveaway in **${message.guild.name}** Your prize: ${prize}\n${link}`); Im trying to dm every giveaway winner, but this code gives an error when more than 2 people won
But you may want to look at your loader
@pale vessel Oh yea not a promise 
Milo .get takes a single ID
What you should do instead is iterate over every WinningUsers, try to find them your cache (or rest API), and DM them.
what should I make first, a profile card or a rank card? 




depends. which one is easier
const ascii = require("ascii-table");
// Create a new Ascii table
let table = new ascii("Commands");
table.setHeading("Command", "Load status");
module.exports = (client) => {
// Read every commands subfolder
readdirSync("./commands/").forEach(dir => {
// Filter so we only have .js command files
const commands = readdirSync(`./commands/${dir}/`).filter(file => file.endsWith(".js"));
// Loop over the commands, and add all of them to a collection
// If there's no name found, prevent it from returning an error,
// By using a cross in the table we made.
for (let file of commands) {
let pull = require(`../commands/${dir}/${file}`);
if (pull.name) {
client.commands.set(pull.name, pull);
table.addRow(file, 'โ
');
} else {
table.addRow(file, `โ -> missing a help.name, or help.name is not a string.`);
continue;
}
// If there's an aliases key, read the aliases.
if (pull.aliases && Array.isArray(pull.aliases)) pull.aliases.forEach(alias => client.aliases.set(alias, pull.name));
}
});
// Log the table
console.log(table.toString());
}```
@stable eagle Just do a loop to get all one by one

See here: js const commands = readdirSync(`./commands/${dir}/`).filter(file => file.endsWith(".js"));
Look at your ./commands/ directory. You'll probably find the announce.js file which belongs to the ./commands/ directory rather than an inner directory.
Regular functions created using function declarations or expressions are constructible and callable. Since regular functions are constructible, they can be called using the new keyword. However, the arrow functions are only callable and not constructible, i.e arrow functions can never be used as constructor functions.
uhh k ||
||
@restive shell that's a frickin awesome image
@earnest phoenix thank you !
lmao that was ten hours ago
Is anyone good with UNIX that can help me real fast with scp
I just woke up xD
Look at your
./commands/directory. You'll probably find theannounce.jsfile which belongs to the./commands/directory rather than an inner directory.
@sudden geyser its in./commands/only
sorry
Is anyone good with UNIX that can help me real fast with
scp
@magic jackal just ask your question man
sorry i didnt mean to hit enter
@restive shell what even is that image lol
it's the bank account
So shouldn't it be in another directory, as you're trying to read each directory in ./commands/ as well (such as ./commands/general/)
profile card?
It's fun
I want to move multiple directories without a wildcard like this
scp -r folder1/ folder2/ folder3/ user@IP:/dir
So shouldn't it be in another directory, as you're trying to read each directory in
./commands/as well (such as./commands/general/)
@sudden geyser oh yeah
ty
can you do this?
only $399
my profile card is just a ran- don't want my idea to be stolen lol
Make it customizable
If you ever need help just dm me 
hey i need help in adding more commands to my bot
@severe hare huh ?
So you need help with making the meme command ?
yep
how to get the users who wrote a certain command that i will setup
Use reddit
till now all i got is a function inside a function inside an async function (yeah i counted). need to stop using let someImage = new Image() and should start using let someImage = await loadImage().
Meme is just fetching random queries from reddit @severe hare
i want to get thr users u ran the command
hmm yea
Use a package like node-fetch to fetch the json from the reddit api as a get request
or use ("random-puppy")
Then filter it by nsfw if you want and get a random post from the posts property
Random puppy is not stable
ok
randompuppy isnt stable???
can anyone help me? any ideas?
@lethal raptor sorry I didn't understand
so random puppy is for dogs and all ri
For it to be working doesn't mean it's stable
@lethal raptor you want to like log the messages ?
do you need to await User.avatarURL() in discord.js? I used it without it and got some timeout errors
kinda and will use them later
@earnest phoenix No it's a sync function
@lethal raptor you want to like log the messages ?
@restive shell temporarily
yes you can do this
@earnest phoenix No it's a sync function
@earnest phoenix then the issue is probably with smth else
how to
how to?
console.log(`[(${message.guild.me.user.username}) (${message.guild.name}) (${message.author.username}) (${command}) (${args.length == 0 ? "No args detected." : args})]`);
something like that

in you message handler file

ok
@lethal raptor do you have like a message handler ?
only the commands
do you wanna log the messages ?
yes
It won't log the commands that are being used if you don't have a command handler
I want to move multiple directories without a wildcard like this
scp -r folder1/ folder2/ folder3/ user@IP:/dir
@magic jackal I did some research on thescpcommand. I don't see how you're using a wildcard.
It won't log the commands that are being used if you don't have a command handler
exactly
like if msg == 'test':
#then it will log it
Unless you put a logger under every emit of commands
who like after every commands?
but what if i log one and only message
like as i said above
// Bind message event to client
console.log(`${<message>.author.tag} used a command!`);
// End of the event```
like if msg == 'test':
#then it will log it
@earnest phoenix he is not asking for that
oh
no no
then he said msg == 'test'
a unique messsage
๐คฆโโ๏ธ
ohhh
i want to log that
just do this
if(message.content == "test") console.log(`${message.author.username} just said "test"`)
So if a message equals to something log it
this should work ?
if (["test", "bruh", "no", "yes", "holy", ...string[]].some(e => message.content === e)) console.log(`${message.author.tag} said ${message.content} with the ID of ${message.author.id}`);```
oh
this is more complicated to him ><
It would but my is more efficient because it can detect more than one string
yes
lmao, triviabot's running so many active games at once that the !active command cant show them, the table is over the size limit for a discord message ๐คฃ
i guess im going to have to make that web based.
instead of a command
is anyone here good at erela.js?
This isn't general Brain
thats a development statement
๐
the message is over the api size limit
theres no other way, right?
i mean i could split my ascii table into multiple messages but that will look spew
thats not the reason its too big, its an ascii table ๐
Ascii tables sure does take a lot of chars, but there's no way to limit it until you slice it
@lethal raptor if you wanna log more than 1 word
@restive shell where will it get logged?
@lethal raptor you can do channel / console.log / author
@wintry timber what does that even mean
@restive shell verified
@lethal raptor you can do channel / console.log / author
@restive shell can i log them in json file?
@lethal raptor you can do
bot.channels.get("channel.id").send("TEXT")
oh
ley Logs = bot.channels.get("channel.id")
Logs.send("Text")
cant i log those ids in a json file?
also why json
@earnest phoenix bcaz i will be iterating through them and send them rewards
im making a currency bot
use a database for that
mysql is shit
i dont have any idea how dbs work ;-;
I used mongoose , sqlite3 , better-sqlite
if you're going for a server based sql database, go for postgresql
Mysql with heidiSQL is perfect for me
i dont have any idea how dbs work ;-;
there's a first time for everything
mysql is anything but good lol
hmm
@earnest phoenix how so ?
ok then how do i start then?
from dapi:
do research on databases, what are some popular ones and pick one that suits your needs
so which db should i use?
do research on databases, what are some popular ones and pick one that suits your needs
ok
...ok?
oof
mysql might be suck
Yeah.
but it is famous
but at least it isnt a json "db"
oracle is known to fuck up everything they touch
for idk wide use?
*cough* update ur java
Cough why you guys talking about MySQL
postgres is opensource, constantly updated, has a fuckton of features that just throw mysql in the bin (jsonb, native unsigned longs etc)
@earnest phoenix scroll up lmaooo 
y do u guys hate MySQL
read above
why is mysql exist
ok lol
im tryna publish something to npm but i get this
npm ERR! 403 a package version that is forbidden by your security policy.```
is there more to the forbidden error
npm ERR! /home/nerd/.npm/_logs/2020-09-11T14_53_09_074Z-debug.log```
what's the full stacktrace
idk dude, for me ? it's working just fine 
npm ERR! 403 In most cases, you or one of your dependencies are requesting
npm ERR! 403 a package version that is forbidden by your security policy.
npm ERR! A complete log of this run can be found in:
npm ERR! /home/nerd/.npm/_logs/2020-09-11T14_53_09_074Z-debug.log```
thats everything
a simple google search, that you could've done yourself, gave this https://stackoverflow.com/questions/62830477/how-to-debug-npm-err-403-in-most-cases-you-or-one-of-your-dependencies-are-re
How do I buffer a picture from a URL.
in what language
in "guildMemberAdd" if member join is bot then return;
what command?

client.on("guildMemberAdd")?
<node-fetch>(<URL>).then(res => res.buffer());``` @earnest phoenix
i need idea about how a lock command works ?
like if i say -lock #channel_name bot will lock a channel for everyone except for the people who have mods/admin role.
i know if i overwrite the channel permission of 'send message' to false will may be work .but my question is how i can revert it as it was ?
npm ERR! 403 In most cases, you or one of your dependencies are requesting npm ERR! 403 a package version that is forbidden by your security policy. npm ERR! A complete log of this run can be found in: npm ERR! /home/nerd/.npm/_logs/2020-09-11T14_53_09_074Z-debug.log```
@hardy vector Do you have any file in the base path that are empty that you're publishing
@cerulean salmon just revert the changes when the time is up
ok thx
- add this
if(!message.channel.nsfw) return message.channel.send(
new RichEmbed()
.setDescription("Please run this command in a `NSFW` channel."));
ok
memes should be in NSFW channels
don't spoonfeed code
oh boohoo
memes should be in NSFW channels
@restive shell wHaT
instead lead them to that solution
because it's random flaz
bruh i use the reddit's json interface and filter out using over_18
@earnest phoenix it's fine :)
too bad
how to use client.channels.get on onether shard?
how do i get information from a server where the bot is not available? example: number of members, id, server name
you don't
gm devs
"how do i get inside of a car if i don't have keys for it"
dod it's just a question lmao you don't have to make fun of him 
i'm not making fun of them
my friend. you must probably be crazy.
it's just an anology as to why you don't (& can't) do it
If you don't know, just say I'm not sure. YOU CAN NOT! instead of saying.
what are you talking about
bb.

Anyone have experience with selenium
why would you use selenium
I've got some. But I have an issue that's being can you save, even on Google
It's what my company uses
how can i check that a message still exists before i attempt to edit it?
fetch like aprox said (that'll cost you 2 requests, one to fetch, one to edit)
or
try catch the edit (costs a bit of memory but that's 1 request)
or
keep track of the deleted messages via the event
How do I control the amount of memory my bot uses?
memory isn't something you can directly control
new Discord.Client({
memUsage: 0
})
how do I control/fix the bot crashing because of running out of memory?
inb4 hosting on a free hosting
better what? ram?
yeah
I have 32 GB available
yes
jesus what does your bot do
are you sure the process uses up all of the 32 gigs? (or a big sum of it)
the bot only uses like 2 GB
Ooh yeah I remember node having a maximum memory usage
I think you can set it with a flag
ok, I currently have like 20 avalible total... but the RSS memory for the bot is up to 2 GB
Use this flag --max-old-space-size to set the limit of memory the process can use
thanks, It started fine, I put it on 6GB just for a test
usually it crashed after like 2 or 3 days due to the memory usage...
in megabytes, right?
nodemon --max-old-space-size=6144 index.js
Do someone know why my bot is not online?
you never login
dont you need to log it in / start it
oh.
//Bot Login
bot.login(`${settings.token}`);
why `
or bot.login(token) since you did define it
Where do i put that?
or a .json file
I'm trying to make a eris bot and I was wondering if you can use
switch and case "": in eris
How can I convert the given 3 numbers (RGB) to hex?
var colorThief = new ColorThief();
fetch(trackIMG)
.then(res => res.buffer())
.then(buffer => colorThief.getColor(buffer))
.then(color => { message.channel.send(color)} )
I want make my bot
Which manage
Web moderator
Moderator for server
divide r, g,b by 16 and multiply their remainders by 16
quick question -
when users vote, i dm them with rewards. if they have my bot blocked or something, i get the DiscordAPIError: Cannot send messages to this user. i know i can catch the error, but doesnt this contribute towards being ratelimited if my bot is getting api errors?
I want make my bot
Which manage
Web moderator
Moderator for server
@near ether it does
unfortunately you can't do much about dming
discord does not offer and refuses to add a way to check if you can dm a user before actually doing it
damn that really sucks
so going off of that, if i try to catch the error when attempting to edit a message, doesnt that also contribute to being ratelimited?
yes, however the ratelimit bucket for that message is going to be dead since the message is gone
How I make bot
@gilded sage #502193464054644737 it's outlined here
Why do I sometimes get:
Cannot read property 'bot' of undefined
on
module.exports = async (client, reaction, user) => {
try {
// Don't listen to DMs or Bots
if (reaction.message.channel.type !== 'text' || user.bot) return;
@gilded sage specifically here https://discordapp.com/channels/264445053596991498/502193464054644737/555644686199422976
@opaque seal user is undefined sometimes.
why that
What event are you listening to
this is message reaction add
And can you show where you call it
//Get events files and bind them to the bot client
const events = requireAll({
dirname: __dirname + '/events',
filter: /^(?!-)(.+)\.js$/,
});
for (const name in events) {
const event = events[name];
client.on(name, event.bind(null, client));
}
it works fine
it just happens some times
which is weird
So sometimes it works, and sometimes it doesn't work. 
One solution would be to check if user was undefined in the event handler, but I'd also try logging name or seeing if something weird is happening. On the documentation (and it's source code), user shouldn't be null/undefined.
What event are you listening for?
Also you don't need to use event.bind, you can just run it like this
client.on(name, (...args) => event(client, ...args))
@gilded sage out of curiosity how old are you?
22
hmmm
They said message reaction add, so I assume it's the messageReactionAdd event.
@honest perch help
Oh it only gives user?
o nvm
@gilded sage you need to learn programming
try catch
you're probably not using it correctly
show code
const Discord = require("discord.js")
const fetch = require("node-fetch");
module.exports = {
name: 'pokemon',
description: "pokemon info",
async execute(msg){
const { get } = require("request-promise-native");
const { MessageEmbed } = require("discord.js");
const args = msg.content.split(" ");
let pokename = msg.content
.split(" ")
.slice(1)
.join(" ");
if (!pokename) return msg.reply("Tell a name Boomer");
try{
const options = {
url: `https://courses.cs.washington.edu/courses/cse154/webservices/pokedex/pokedex.php?pokemon=${pokename}`,
json: true
};
}catch(err){
console.log(err)
msg.channel.send(`Frick, Caught an error ! ${err}`)
}
try {
msg.channel
.send(
"Fetching Informtion for API. If You don't get any result within 5 seconds then pokemon doesn't exist in records of API. **Not every pokemon is in our records**"
)
.then(msg => {
get(options).then(body => {
let embed = new MessageEmbed()
.setAuthor(
body.name,
`https://courses.cs.washington.edu/courses/cse154/webservices/pokedex/${body.images.typeIcon}`
)
.setDescription(body.info.description)
.setThumbnail(
`https://courses.cs.washington.edu/courses/cse154/webservices/pokedex/${body.images.photo}`
)
.setColor("#ff2050")
.setFooter(
`Weakness of pokemon - ${body.info.weakness}`,
`https://courses.cs.washington.edu/courses/cse154/webservices/pokedex/${body.images.weaknessIcon}`
);
if (!body.info.description) return msg.reply("Pokemon Not found");
msg.channel.send(embed);
msg.delete();
});
});
} catch (err) {
console.log(err);
msg.channel.send(err);
}
}}```
@honest perch yes
it's the same issue from yesterday and the day before yesterday lol
really?
it doesn't go into the catch
try catch finishes before the promise does
Should all commands be in one folder??? Sry I'm new
File I mean
either await it or .catch the promise, await is preferred though, pgamer
try catch finishes before the promise does
I seriously don't get the meaning of this
@honest perch I need to learn programming help me
its not something i can help with
@earnest phoenix it genuinely does not matter however it's suggested you split your commands into their own folders/files for easier readability
pick a language and learn
either await it or .catch the promise, await is preferred though, pgamer
@earnest phoenix what should i await
the promise
but I am try and catching this thing
try{
const options = {
url: `https://courses.cs.washington.edu/courses/cse154/webservices/pokedex/pokedex.php?pokemon=${pokename}`,
json: true
};
}catch(err){
console.log(err)
msg.channel.send(`Frick, Caught an error ! ${err}`)
}```
here how should i await
i don't think any promise is there (unless I am dumb af)
@honest perch how much you help me
@earnest phoenix it genuinely does not matter however it's suggested you split your commands into their own folders/files for easier readability
@earnest phoenix OK, and what command should I use to run the bot? I use discord.js
huh?
there's nothing to catch in the first place
Sorry, but i still don't get it
OK, and what command should I use to run the bot? I use discord.js
@earnest phoenix you run it with node <filename>.js
๐ถ
why are you making a bot if you can't use try catch

you need to try catch the bloody fetch request
help vampirism at its finest
@earnest phoenix you run it with node <filename>.js
@misty sigil thx
not the bloody options
@gilded sage learn yourself
you need to try catch the bloody fetch request
@misty sigil
oh only dat?
i'd just try catch the entire command if u dont know where to put it imo
I have that as well
I have 2 catches
but it won't work
Because cry said some promise related thing
you can also just catch straight in your command handler when you execute the command lol
theres no need to await sends unless you need to resolve the promise
oh
one more thing
i can't recall
.catch(err, =>{
})
is this how you do it ?
no
Also you don't need to use event.bind, you can just run it like this
@golden condor I wanted to have events in different files in a clean way and it has always worked. It works fine too now. It just happens rarely which was just weird
Are there any docs related to catch try which i can read
yeah one second
.catch and the catch keyword are also two completely different things that you don't quite seem to distinct yet
ok
asynchronous programming never sits well with people who didn't take CS
can we do .then on .catch
I mean can we do promise.catch().then()
i feel like promise.then().catch() would work
Why do I sometimes get:
Cannot read property 'bot' of undefined
onmodule.exports = async (client, reaction, user) => { try { // Don't listen to DMs or Bots if (reaction.message.channel.type !== 'text' || user.bot) return;
?
.then(msg => {
get(options).catch((error) => {
console.error(error);
msg.channel.send("Another Error! I suck tbh ```" + err + "```")
})
}).then(bod```
Something like this
oh
but not .catch().then()
ok
but probs works both ways
k
it works because catch returns a promise
it's usually an antipattern though
you'd usually chain a then on a catch if you're working with multiple promises and you're wrapping them under a single one
ohh
it's the best to just use async/await instead yeah
what's your code
one min
are you doing it in the ready event
you
you create the activity list outside of the ready event
code in a bin - https://hastebin.com/cewocofode.js
pgamer please start binning your code this is annoying
ok
you're calling then on an object
bruh
why didn't you read the links you got sent
I am trying
because that's the first thing that the mdn promise docs cover
stop being a help vampire, it's quite annoying
we gave you resources that you asked for and you still don't use them
goddamn
Why do I sometimes get:
Cannot read property 'bot' of undefined
on
module.exports = async (client, reaction, user) => {
try {
// Don't listen to DMs or Bots
if (reaction.message.channel.type !== 'text' || user.bot) return;
This is the messageReactionAdd event
And it happens rarely
my discord bots been hacked yet again
this time i KNOW i didnt have jack shit to do with it
a discord bot can't be hacked
Well it apparently was
you leaked your token
it can only be compromised by your own stupid self
My
Is use this Matthew:
// Listen to raw events to emit messageReactionAdd event on uncached messages
client.on('raw', async event => {
// Listen only to reactionAdd events
if(event.t !== 'MESSAGE_REACTION_ADD') return;
const { d: data } = event;
if(typeof client.channels.cache.get(data.channel_id) === 'undefined') return;
const channel = client.channels.cache.get(data.channel_id);
// if the message is already in the cache, don't re-emit the event
if (channel.messages.cache.has(data.message_id)) return;
const user = client.users.cache.get(data.user_id);
const message = await channel.messages.fetch(data.message_id);
// Custom emoji are keyed by IDs, while unicode emoji are keyed by names
const reaction = message.reactions.cache.get(data.emoji.id || data.emoji.name);
client.emit('messageReactionAdd', reaction, user);
});
bot was hacked
it cant be hacked
I didnt leak my FUCKING token
bots cant be hacked
I didnt leak my FUCKING token
yeah you did
Cant isnt in my vocab
Giuliopime, do you use partials by chance?
try again
it can be compromised by your own stupid self or your stupid team
Giuliopime, do you use partials by chance?
^ https://discordapp.com/channels/264445053596991498/272764566411149314/754021871468675082
just regen the token lmfao
- I dont have a team
- my token was not leaked
It just happends some times
You host your bot on a VPS?
@opaque seal the user isn't in cache
bots do not get hacked
use fetch instead
ofc they can
no they cant
@opaque seal the user isn't in cache
@earnest phoenix I'm using raw data
yes they can
it automatically gets the user
yes, fetch the user
i saw
You host your bot on a VPS?
@near veldt
and i told you to fetch
yes, fetch the user
how?
no
it automatically gets the user
shouldn't it?
no they can't. why?
bots tokens consist of 3 elements
https://cdn.discordapp.com/attachments/265156286406983680/750062815301206126/image0.png
they need to get 2 parts out of 3, its practically impossible
no
@near veldt localhost?
@opaque seal it does get the user... from cache
ok
no
fetch automatically puts the user in cache
fetch is a cache lookup -> if not found make an api request -> cache the user
localhost or VPS, one of these two
fetch is a cache lookup -> if not found make an api request -> cache the user
@earnest phoenix yep got it
"hacked"
how
const economy = require('../economy');
const tokens = require('../tokens')
const { MessageEmbed } = require('discord.js');
module.exports = {
name: 'balance',
description: 'shows ur balance',
cooldown: 5,
async execute(message, args) {
const target = message.mentions.users.first() || message.author
const targetID = target.id
const guildId = message.guild.id
const userId = target.id
const coins = await economy.getCoins(guildId, userId)
const tokensMoney = await tokens.getTokens(guildId, userId)
const BalanceEmbed = new MessageEmbed()
.setAuthor(`${target.tag}`, `${target.displayAvatarURL()}`)
.setDescription(`Crystals: ${coins}\nTokens: ${tokensMoney}`)
.setFooter('Your balance is per-guild. don\'t ask if you have 0 crystals in one server and 10 in another server.')
.setTimestamp()
message.channel.send(BalanceEmbed)
},
};```
i get Tokens: undefined
how to fix it
i'm hosting my bot on repl.it and i forgot that i created a test account that was visible and had the bots token in it
do you have a file in ../tokens?
lmfao
lol
it's tokens.js
i knew it was free hosting
so you leaked the token
it's tokens.js
@cinder sandal ../ means one directory up the current one
but i still dont understand how they coulda used an invalid token
if it's in the same directory as the current file it should be ./
it's in the main folder
well whoever they are came from the same server that tried saying they didnt hack shit
the commands are in command folder
In my raw event I used this, should be fine now right?
const user = await client.users.fetch(data.user_id);
yes
it's in the main folder
then should be fine but it isn't so you are wrong somehow
yes
great ty
share the tokens.js file
tokens is an economy value like coins so
const mongo = require('./mongo')
const profileSchema = require('./schemas/profile-schema')
const tokensCache = {}
module.exports = (client) => {}
module.exports.addTokens = async (guildId, userId, tokens) => {
return await mongo().then(async (mongoose) => {
try {
console.log('Debug Mode: running find one and update')
const result = await profileSchema.findOneAndUpdate(
{
guildId,
userId,
},
{
guildId,
userId,
$inc: {
tokens,
},
},
{
upsert: true,
new: true,
}
)
console.log('Debug Mode: RESULT:', result)
tokensCache[`${guildId}-${userId}`] = result.tokens
return result.tokens
} finally {
mongoose.connection.close()
}
})
}
module.exports.getTokens = async (guildId, userId) => {
const cachedValue = tokensCache[`${guildId}-${userId}`]
if (cachedValue) {
return cachedValue
}
return await mongo().then(async mongoose => {
try {
console.log('running findone()')
const result = await profileSchema.findOne({
guildId,
userId
})
console.log('[DEBUG] Result:', result)
let tokens = 0
if (result) {
tokens = result.tokens
return tokens
} else {
console.log('[DEBUG] Inserting docs')
await new profileSchema({
guildId,
userId,
tokens
}).save()
return tokens
}
} finally {
mongoose.connection.close()
}
})
}```
if i try a command to get a Tokens: 1
it returns
(node:23) UnhandledPromiseRejectionWarning: CastError: Cast to Number failed for value "[Function] { addTokens: [AsyncFunction], getTokens: [AsyncFunction] }" at path "tokens"
how would I give out a role to the most active chatter each month
you'd need to store the amount of messages in a database
and at the end of a month, you check the db
alr
Why do node . dont work?
@native osprey you're doing node comma
he is
wait why is your folder called index.js
no hes in the indexjs file
Wai-
..
What should it be called then?
oh shit here we go again










