#development
1 messages ยท Page 1517 of 1
uhh dosent message.author just tag the users ID without pinging?
if i were to change the member's nickname, i just put the nickname i want in the () ?
ig you want to make it a mention, do toString()
oh what
you should really learn what functions are, and yes
<Message>.author gets converted into the user's mention if it gets concatenated to a string
yeah lol
im fairly certain you need to do toString() to get a mention
i dont think author by itself resolves on a mention
Now im confused
${message.author} and message.author.toString()
My bot did this
Both gives a mention
because ` turns it to a string
because js calls the toString() method automatically
normally i'td be resolved into [Object] no?
that .toString()s it
Concatenating it like '' + message.author will be their ID, but concatenating it like ${message.author} or message.author.toString() will become their mention
ooh
hmmm thats a quirky thing i wasnt aware of
im just dumb lol
wait a sec
My goal is to learn discord.js or js in 2021 bruh
i thought i put this in my if function?
if(guild.me.permissions.has('MANAGE_NICKNAMES')){```
it says that missing perms
the normal approach is learning js, THEN doing a bot
You should learn JS before discord.js
if you have all of 2021, i would spend a few months on JS
a bot isnt something simple and uses advanced stuff from js
lol yeah XD
I'm pretty sure "" + message.author will still call the toString method
no clue how they got the ID from that
I mean maybe but the return value isn't the same
nah
oh, @umbral zealot
before you leave
i did the thing yesterday
im about to finish some last touches, but thats improvements, the whole thing is in place already
nice
ty for yesterday
You can't edit a guild member who has a higher role than the client's highest role
._.
Oh okay
Make it ignore itself and the other bots
so how do i check if the user is in a higher rank?
how would i do that?
Make an if statement that returns if the message author is the bot
probably shouldnt respond to every message with the word help in it.
user.bot
Compare role positions
...
user.bot is true if its a bot, false if it isnt, check that
and it's because using + makes it a number (Number(author)) which returns the ID
Not understandable enough?
Also, I got another issue with MariaDB that confuses me
theres a role for every bot that you invite right? It's impossible to delete that role because it's managed by discord right?
Which is weird, the number is useless
if (message.content.includes("help")) {
console.log("help from " + message.author.toString())
message.channel.send("Hello, " + message.author.toString() + "! My main purpose is to manage tickets, but I have some other commands too!\n use **,help** to see the list of commands!")
}
if you invite the bot with 0 perms it wont make the role
that's so inconsistent
<Guild>.me.roles.highest.position < <GuildMember>.roles.highest.position
......
Dotpost combo broken
actually maybe it isn't Number()
So this is my table right?
When I fetch the 'money' field it returns 980 as it should, but when I fetch the 'times_gambled' field it returns 'times_gambled'
How do i define this
if (message.content.includes("help")) {
to only listen to users
i can check it by
if(guild.me.roles.highest.position){
}```?
hey
learn js first
pretty sure people gave you copy paste examples
Ok
does anyone know why youtube_dl is not importing? when i try to import it it just gives me a generic error of "can't import module" and when i do pip freeze it is listed as installed
Did you read whatever i sent
you'll be coming back here every 5 minutes if you dont
ok
uhh yes
And?
i know, im not trying to scare you away
just letting you know to focus on JS first, not on d.js
here, let me give you a quick help
lol
Why does javascript not automatically call toString when an object is being added to a string, and more importantly why is message.author turned to the id
why?
trust me
tim level question on the second half.
this sounds like an awful way to phihising tokens :/
just do it
Your import: youtube_dl
The dependency name: youtube-dl
youtube_dl is correct.
๐ฟ
Anyone able to explain this? 
Like how we import discord.py as discord
done?
okay, now, heres the tip
take a look at this
see on the left side? those are basically the categories or things you gotta check
now, i'd like you to skim at least through:
Maps, functions, variables, arrays
there is a best practices thing too, which has some good suggestions
whenever you are reading one of those, put some dummy code in your test.js
so you can play with the code yourself
just add code in your test.js and then run node test.js
its basically: Read the guide, and try yourself sort of thing
Discord mobile 
https://www.w3schools.com/js/js_operators.asp
https://www.w3schools.com/js/js_variables.asp
https://www.w3schools.com/js/js_statements.asp
https://www.w3schools.com/js/js_objects.asp
https://www.w3schools.com/js/js_functions.asp
https://www.w3schools.com/js/js_arrays.asp
https://www.w3schools.com/js/js_comparisons.asp
@harsh blade read at least those
AT LEAST those, pereferably learn the rest too, but this should give you some footing on js
like i mentioned, read one of those topics, try it on test.js and run with node test.js to run whatever you put in test.js
rinse and repeat
why does w3schools still use var for everything tho
cuz old shit
It's JS documentation is outdated but can be easy to grasp.
i tried that but it gives a syntax error for the -
in their best practices it even says dont use global variables 
eh, global variables can be useful
cant believe there are still people with full knowledge of js who use var
If I don't want to pass around some state across my files and scopes globals are helpful -- when they need to live throughout the entire lifespan of the program at least 
well globals are kinda useful for splitting stuff in browser javascript
Thank u
no problemo
What's the difference at that point?
none, they both are idiot stuff to do
nah
though attaching to process can be handier
i was THIS close from attaching my client onto process
but decided not to
like, take a logger variable. I don't need to attach it to some other variable and pass it around. Attaching it to some other variable so you can use it everywhere else doesn't have much of a difference imo. I understand why people see not using globals as better practice
Bruh I'm getting a headache 
To bounce around locally scoped variables to other files or other scopes, you could create a file which only exports an Object then Object.assign to that Object and require the Object in other files.
example pls
on the 27th it was at 160, on the 24th it was at 110, so roughly 2 weeks for 400 guilds
2.5 i guess
you can check user bots in #commands
just do -bots userid
this one im showing is GenshinUtils
ding ding, correct
passthrough.js
module.exports = {};
index.js
const passthrough = require("./passthrough.js");
const client = new Client(options);
Object.assign(passthrough, { client });
require("./utils.js");
utils.js
const passthrough = require("./passthrough.js");
const { client } = passthrough;
console.log(client);
output
Client {
token: "blah"
user: [ClientUser]
someOtherProp: "idk"
}
ty 
took a while to do ngl, i guess around 1 or 2h
its actually not that complicated either apart from the frames
yea animations are simpler than i thought
Does it matter where these closing brackets are }
@keyframes and transform: translate am i right?
epik
i saw something similar on a friend's company website, decided to yoink it
floating animations are subtle but make stuff look better
i was actually thinking about tilting based on scroll, but decided against it
to keep the invite and vote stuck in position and follow the page along as you scroll
and then add translation on scrolling
make some smooth animation during the transition
but thats a lot more math involved than i'd like to admit
tl;dr cba
was about to ask that
its doable with css, its just a hell lot of math im not in the mood for
and for something that minor
page is already unique as is
yeah the page's cool right now
Swapping from Vultr to Galaxygate reduced my bots latency by like 75ms 
what was the location for the vultr vps?
Amsterdam, I believe
probably why then
Yeah, makes sense
vultr is nice but the price/ram just didn't work for me
I liked the fact that they charge hourly instead of monthly. Makes it easier to try different plans without paying for the entire month.
thats the benefit of very large providers, they can do stuff like that efficently.
https://top.gg/bot/696973408000409626 's CSS is the most unique one
oh man, a headache and a half
lmao
- { display: none }
Hi guys, dont know if its the right channel to ask for it , But, when I am trying to trasfer my bot to my linux vps, and once I am typing node . it gives me this error:
Error: Cannot find module '/root/Among Us Bot/node_modules/sqlite3/lib/binding/napi-v6-linux-x64/node_sqlite3.node'
Require stack:
- /root/Among Us Bot/node_modules/sqlite3/lib/sqlite3-binding.js
- /root/Among Us Bot/node_modules/sqlite3/lib/sqlite3.js
- /root/Among Us Bot/index.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:815:15)
at Function.Module._load (internal/modules/cjs/loader.js:667:27)
at Module.require (internal/modules/cjs/loader.js:887:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.<anonymous> (/root/Among Us Bot/node_modules/sqlite3/lib/sqlite3-binding.js:4:15)
at Module._compile (internal/modules/cjs/loader.js:999:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
at Module.load (internal/modules/cjs/loader.js:863:32)
at Function.Module._load (internal/modules/cjs/loader.js:708:14)
at Module.require (internal/modules/cjs/loader.js:887:19) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'/root/Among Us Bot/node_modules/sqlite3/lib/sqlite3-binding.js',
'/root/Among Us Bot/node_modules/sqlite3/lib/sqlite3.js',
'/root/Among Us Bot/index.js'
]
}
you need to reinstall your modules
halp
ye
halp again
what is mentionedRole
mentionedRole is defined here
const mentionedRole = message.mentions.roles.first();```

a Role doesn't have a roles property, it's not a member
soo
If message.member.roles.highest is a role, and to get it's position you do.position, how would you get the position of mentionedRole, which is already a role
How do you guys track statistics on your bot?
so i just do js mentionedRole.position
yeah
k
what kind of statistics?
Most used command, how many guilds its in, etc.
Basically asking for other people's strategies. If someone asked me "What is your most popular command" -> I couldn't tell them. Naively, I could just keep a counter and update a graph overtime; however, I just didn't know if there was already a pre-build solution for something like this.
i dont keep statistics for that
Well, dbl-bot keeps track of the builds and such on my behalf ... but most used commands overtime and such would probably be beneficial. Like said, I could custom build something that keeps a counter ... just wasn't sure.
you'll need to do that yes
if you want a fully featured solution, look into a time series database
they are optimized for storing logs for example
then you can query it in all sorts of ways, get the times of the day with most usage, etc
Yep, I've used time series databases before ๐
Just didn't want to invest in that ๐ฌ
you can self host one
is there by any chance a ratelimit on webhooks? As my code just gets stuck on "await" for creating a webhook for 15 minutes after I used it too much
it probably does then
if (!webhook) {
try {
webhook = await channel.createWebhook(name, {
avatar: avatar
});
} catch {
channel.send("Something went wrong please wait a minute and try again.")
}
}
it just gets stuck here
since its on the channel route, its possible it shares or has similar limits as other channel-specific limits
for example, only being able to change the channel name twice every 10 minutes
on djs, how do i change a role's color using hexcode?
...pass the hex
role.edit({color:"bla"}) or that ^
oki thanks
also that
Could someone help me code my bot
now i want to visit this page while being Drunk. i think you will not make it for long
i cant figure this out
message isnt defined
define message
have you tried reading the error
make sure you run it inside the message event
i did?
i c
im just 2 dumb u see
many errors are plain English.
im not from england
im not from england and still understand it
you're aware... england isn't the only country where english is spoken, right?
yall rude
hey don't blame us on your incompetency
ok cool
X is not defined means that X does not exist in the place where you're trying to use it
meaning, you're trying to use something out of place or in the wrong place
lmao
Just submitted my discord bot's verification approval. How long did it take for anyone else that's done that?
Like 40 days
It should take around a week now
that one's just 5 days or so
They just reopened the form from the holidays. I'm curious how long it's going to take ๐ฌ
It has been closed / greyed out since Dec. 24th
an article they made says 4-5 business days or something
That's unfortunate
My hopes of actually doing a marketing campaign this week are shattered ๐ข
well at least it's not too long
yeah thats the bad thing
after 4-5 days, a bot probably won't appear anymore on the "new trending bots" section
Yeah, my bot has been off of that for a while. I mean I simply can't pay to place my bot on an advertisement.
To be fair, it was a longer process back then before they mandated it ... right?
And you got that nice shiny early bot developer badge
ohh yeah that thing
i didn't get to verify my bot in time
I didn't start developing my bot until Nov, lol
Now there's fishing, hunting, town / grid management, connect4, tictactoe, full economy system, store, bag, etc.
Been grinding
cool stuff
@earnest phoenix
in python how to I stop a if statment
I tried using break but only works for while loops
pretty sure you can't break out of if statements
why
does py got return?
if message.content == "hey":
await self.delete(message, warning=f'{message.author.mention}, hey')```
yeah it has return
why did you want to break out of an if statement?
i don't think you need break
just use another if statement
look
then execute IF its valid
@commands.Cog.listener()
async def on_message(self, message):
if self.config.get('status', True) and message.channel.id in self.config.get('channel_ids', []):
if message.content == "hey":
await self.delete(message, warning=f'{message.author.mention}, hey')
if message.author.bot:
await asyncio.sleep(5)
await self.delete(message, warning=None)
elif len(message.attachments):
if len(message.attachments) > 1: #message.attachments[0].filename.endswith('.gif')
await self.delete(message, warning=f'{message.author.mention}, send 1 emoji at a time.')
elif not (message.attachments[0].filename.endswith('.png') or message.attachments[0].filename.endswith('.jpeg') or message.attachments[0].filename.endswith('.jpg') or message.attachments[0].filename.endswith('.mp4')):
await self.delete(message, warning=f'{message.author.mention}  Only images/captions/gifs are allowed in this channel!')
else:
await self.delete(message, warning=f'{message.author.mention}  Only images/captions/gifs are allowed in this channel!')```
if not dont execute
where did you put it
is it return None?
if message.content == "hey":
await self.delete(message, warning=f'{message.author.mention}, hey')
return```
like this
then the condition you set wasn't true
return should work
did await self.delete(message, warning=f'{message.author.mention}, hey') work
yeah but what error
well idk what cogs are 
return just doesn't work
yeah
Hey, I need a JS-native (not using node) solution for getting today's date, and today's date minus 7 days. Can someone point me in the right direction?
id use Date
get the date in ms
JavaScript Date objects represent a single moment in time in a platform-independent format.
and substract the equivalent of 7 days in ms
or yeah i think the Date class has methods for that
if message.content.startswith == "https://":```
is there a better way to check if this is a link?
because this isn't working, and it's not efficient
make a request to it
huh
there's no way to verify if a string is a valid, working link without making a request to it
I wanna check if there is a link in the msg
also use some regex to check beforehand
Thanks!
That's pretty much what I needed
๐
Just if it is a link
oh
how would I do thwat?
check out https://urlregex.com/
Simply copy and paste the URL regex below for the language of your choice. PHP (use with preg_match) %^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@|\d{1,3}(?:.\d{1,3}){3}|(?:(?:[a-z\d\x{00a1}-\x{ffff}]+-?)[a-z\d\x{00a1}-\x{ffff}]+)(?:.(?:[a-z\d\x{00a1}-\x{ffff}]+-?)[a-z\d\x{00a1}-\x{ffff}]+)(?:.[a-z\x{00a1}-\x{ffff}]{2,6}))(?::\d+)?(?:[^\s])?$%i...

i cant even read that regex 
http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+```
regex hurts my eyes
so see if this is contained.. in the msg?
or am I thinking wrong ๐
match it against the message content
if the match returns something
there's a link
regex = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?ยซยปโโโโ]))"
url = re.findall(regex,string)```
I found this online, is this the right path?
i don't do py so no idea
ah
well I will look into it
thx
if message.content.startswith("https://"):
#ignore```
Also.. I just simply wanna know for future builds, why did this not work lol
I don't see what I did wrong
it's exactly how it's suppose to be
that checks if your message starts with exactly that
it won't detect .https://
it will detect
https://
is that js?
๐ค
Is it possible to see from which application the specific bearer token comes from?
That's why I'm saying..
what
Asking about your attempted solution rather than your actual problem
what is your actual goal
I also did python if message.content.contains("https://"): #ignore
and it didn't detect if https:// was in the msg
Want to get application id out of discord bearer token
you can't
that should work just fine
it doesn't hmm
can you share a bigger snippet
@commands.Cog.listener()
async def on_message(self, message):
if self.config.get('status', True) and message.channel.id in self.config.get('channel_ids', []):
if message.content.contains("https://"):
#ignore
else:
if message.author.bot:
await asyncio.sleep(5)
await self.delete(message, warning=None)
elif len(message.attachments):
if len(message.attachments) > 1: #message.attachments[0].filename.endswith('.gif')
await self.delete(message, warning=f'{message.author.mention}, send 1 emoji at a time.')
elif not (message.attachments[0].filename.endswith('.png') or message.attachments[0].filename.endswith('.jpeg') or message.attachments[0].filename.endswith('.jpg') or message.attachments[0].filename.endswith('.mp4')):
await self.delete(message, warning=f'{message.author.mention}  Only images/captions/gifs are allowed in this channel!')
else:
await self.delete(message, warning=f'{message.author.mention}  Only images/captions/gifs are allowed in this channel!')
discord broke some formats
that's super weird
tried printing inside the first if?
yup
testing rn
AttributeError: 'str' object has no attribute 'contains'```
@earnest phoenix
hmm
wat
python doesn't have a contains method then
__contains__()
ben wdum
why does this not display? <img src="<%- user.avatar %>" alt="Profile Photo">
you know what
user.avatar displays 4115e7278b04e8e40117dd55e700b291
so contains?
in and __contains__ are the same. in uses contains
Before I do something really hacky to get this to work, can someone point me in the right direction to get the output of a date in the format of MM-DD-YYYY?
ok
what language?
JS
var endDate = new Date(Date.now())
var startDate = new Date(today - 7 * 24 * 60 * 60 * 1000)
I'm trying to get the MM-DD-YYYY string of those.
Very unfamiliar with JS. But I need it for an API Testing script
Yup. There's no real reason to do __contains__ as opposed to in
Use new Date().toISOString()
I saw, but it seems to be... odd
I thought about that, but figured i don't want to split and slice that a bunch
getFullYear()
Much better
.getMonth() + 1
Why is the month - 1?
0 based index
tricks
๐คทโโ๏ธ alright, lol. What a strange language
It's not that bad new Date().toISOString().split("T")[0].split("-").reverse().join("-")
"11-01-2021"
almost
the date should never go first
ah MDY
yeah
I was looking for the equivalent of:
moment().subtract(0, 'day').format("MM-DD-YYYY"))
moment().subtract(7, 'day').format("MM-DD-YYYY"))
Without moment
kredet ples
you can use moment in js too
I can't require. I'm not in nodejs
In a ECMAScript ECMA environment for JMeter
Thanks all
<img src="https://cdn.discordapp.com/avatars/<%user.id%>/<%user.avatar%>.png" alt="Profile Photo"> but if i log the link its correct so whats the problem?
can someone help me?
when I am trying to start my node folder, it gives me this error:
Error: Cannot find module '/root/Among Us Bot/node_modules/sqlite3/lib/binding/napi-v6-linux-x64/node_sqlite3.node
(I am using ubuntu)
try reinstalling your modules
make sure sqlite3 is in you package.json
it is
you can theoretically use node_modules and a node environment and then webpack and optionally babel your code, no?
new Date().toISOString().split("T")[0].split("-").sort((x, y) => y == 1 ? 1 : -1); lmao
I need help with lua Im trying to take a screenshot of an emulator then write a file that is a png
this is the docs for the emulator
I tried doing
local file = io.open("screen.png", "bw+")
file:write(gui.gdscreenshot())
but it kept crashing it
@quartz kindle can i just delete the sqlite3 module?
is there a reason why
{
backdrop-filter: blur(20px);
}
doesn't work on ios?
#loader {
position: fixed;
backdrop-filter: blur(20px);
height: -webkit-fill-available;
width: -webkit-fill-available;
z-index: 10;
margin: 0;
top: 0;
}```
if you copied your node_modules folder from your pc to your server, delete all of it
node_modules should never be copied, always reinstalled
try npm install sqlite3 --build-from-source
you likely need to install build tools
same error @quartz kindle
Do you have python installed?
yes
Can you try run the python command as it may not be in the bin
what is the python command?
Just python
just to type python there?
Im trying to take a screenshot of an emulator then write a file that is a png
https://code.google.com/archive/p/vba-rerecording/wikis/LuaScriptingFunctions.wiki
this is the docs for the emulator
I tried doing
local file = io.open("screen.png", "bw+")
file:write(gui.gdscreenshot())
but it kept crashing it
@golden condor
Yes
type python --version
but i do have it
will it just fix it if i rebuild all of my modules?
???
like uninstall all of it
then npm i
?
@quartz kindle
What's the rate limit info on renaming a channel?
probably pretty low
I guessed that
2 times within 10 minutes or something
But I'd like to find some docs
My emoji size downscales in embeds the bigger I make them... How can i make my emoji appear bigger in my embeds??
I have been looking for them to document that a while now. I haven't been able to find it, as they only have the General Rate Limit topic. But it's very close to 2 times per 10 minutes per channel
Once an hour is probably ok right? 
discord doesnt provide the ratelimits
yes once an hour is fine
since ratelimits are dynamic
set the env variable
when you install python... should be a tick "add to path"
You dont have python in your vps
Did you install build-essential?
Whats your vps's operating system?
well you could answer my questions
i just downloaded python on it
what about the other questions
idk what it is
idk what it is as well
.>
not sure how people can help you debug then
type neofetch
does anyone use pm2 with djs
yes
css is not working
How the f do i make emojis appear bigger in embeds? They are soooo small.. I have rescaled them and tried just about everything I can think of.
IJPKJOIKLNHBIUYGTCDV HJ
hey guys
how would i loop through a json file to find a specific name?
Like i want to find evan in a json file of names.
well could be both, either your code or the site.
whats the structure of your json?
Depending on what field you put the emojis in, they'll be small by default. How emojis can be bigger is if they're in a field which doesn't clamp the size and if there is no text in the field. The same applies for message content. Only up to a certain number of emojis can appear in a field/content before their size is clamped
objects
looks like an array to me
huh
.find()
but it is wrapped in [] so they are objects
help me pls
or have i learned it wrong
will have a look
thank you for clearing that
Yo so i know all of that. However even with the same format of embed from other bots and the same emojis.. they still appear smaller.
Are you putting any text in the same fields
how to update immage
what image
CSS is a #development question. Not a #support question. We're not going to help people code their page in support. They can ask HTML / CSS questions here if they need help.
Could of been an issue with top.gg relax lmao.
I think that reply for for me.
I'm just pointing it out since they went back to support. ๐
what
I think they meant to reply to me.
indeed, and yes. I'm just pointing out that it could of also been an issue related to the website. great concern.

on DJS how do i check if a user's account is under 10 days old?
hey```js
if (message.content.startsWith("!specific")) {
let params = message.content.trim().split(/ +/g);
console.log(params[1]);
const main = require("./dex.json");
const found = main.find(element => element == params[1])
message.channel.send(found)
spawnHello();
};``` i want to use the variable found all the way down the code
in a function
but ofc it is undefined if i represent it like this,.
how would i make the variable found defined in general?
user.createdAt or user.createdTimestamp
then compare it to the current date
okay
let found;
if(...) {
found = ...
}
How do i get the current date?
if that works, i will hug you
new Date() for the date object, Date.now() for the current timestamp
okay
let found;
if (message.content.startsWith("!specific")) {
let params = message.content.trim().split(/ +/g);
console.log(params[1]);
const main = require("./dex.json");
found = main.find(element => element == params[1])
message.channel.send(found)
spawnHello();
```hmm like this? It looks kinda sketchy
as we are already defining found right>?
so it would give an error that it is already declared
@quartz kindle
youre assigning not declaring
i know this is wrong 
yes
createdAt is a Date. Date.now returns a number
it is still not defined
the function is literally defined all the way down the code
show full code
soo how do i turn createdAt into a number?
use createdTimestamp
okay
https://hatebin.com/vidabdfbgl check line 78(for the command call) and the function at (488)
if(member.user.createdTimestamp - Date.now() < 10){
}``` this is right ?
<Date>.getTime() alternatively
Then just check for if now - (10 days as ms) > created time stamp
That will aways return false
...
@quartz kindle ping me when you know the answer.
so instead of Date.now() i can use Date.getTime()
no lol. user.createdAt is a Date. You want to compare a number to a number and Date.now already returns a number
thats not how it works
owh
im confused 
sheee tim is writing for ages. Have i fucked it up that hard?
user.createdAt // Date
<Date>.getTime() // number
Date.now() // number
user.createdAt.getTime() // number
(Date.now() - (1000 * 60 * 60 * 24 * 10)) > user.createdAt.getTime() // boolean
client.on("...", () => {
if(...) {
let abc = 10; // declared inside the block, only valid inside the block
console.log(abc) // 10
}
console.log(abc) // error, abc is not defined
let something; // declared outside the block, valid in the outer block and in all inner blocks
if(...) {
something = 10;
console.log(something) // 10
}
console.log(something) // 10
})
console.log(abc) // error
console.log(something) // error
// this is outside the block where either of them were declared
function bla() {
console.log(abc) // error
console.log(something) // error
// this is a separate block, its still outside the block where both of them were created
}
@eternal osprey
โAwsomeโ ๐ง
Everything else but this line works :-: Any ideas? been fiddling around with this for quite a while
log the value of message
console.log(image);
const imageembed = new Discord.MessageEmbed()
.setTitle(subRedditName)
.setImage(image)
.setColor(9384170)
.setDescription(`[${title}](${link})`)
.setURL(`https://reddit.com/${subRedditName}`)
message.channel.send(imageembed)
thats having the issues
How can i add a .then after a forEach, it say, .then() is not a function
Like that
message.guild.members.cache.forEach(m => {
console.log(m.user.username)
}).then(console.log('Finished'))
where did you get message from?
okay
1 second
forEach doesn't return a Promise. It's synchronous, so code execution will continue after it finishes. You can just add the console.log after the forEach
Right, how do i get the message again 
Uhh still confused
show the code you have before the code you showed
message is obviously defined. Log the value of message
The last line is literally what you're looking for
const https = require('https');
const Discord = require('discord.js');
const url = 'https://www.reddit.com/r/meme/hot/.json?limit=100'
module.exports = {
name: 'meme',
description: 'sends meme',
execute(message, args) {
https.get(url, (result) => {
var body = ''
result.on('data', (chunk) => {
body += chunk
})
result.on('end', () => {
var response = JSON.parse(body)
var index = response.data.children[Math.floor(Math.random() * 99) + 1].data
if (index.post_hint !== 'image') {
var text = index.selftext
const textembed = new Discord.MessageEmbed()
.setTitle(subRedditName)
.setColor(9384170)
.setDescription(`[${title}](${link})\n\n${text}`)
.setURL(`https://reddit.com/${subRedditName}`)
message.channel.send(textembed)
}
var image = index.preview.images[0].source.url.replace('&', '&')
var title = index.title
var link = 'https://reddit.com' + index.permalink
var subRedditName = index.subreddit_name_prefixed
if (index.post_hint !== 'image') {
const textembed = new Discord.RichEmbed()
.setTitle(subRedditName)
.setColor(9384170)
.setDescription(`[${title}](${link})\n\n${text}`)
.setURL(`https://reddit.com/${subRedditName}`)
message.channel.send(textembed)
}
ok
now is the current timestamp in milliseconds. 1000 * 60 * 60 * 24 * 10 = 10 days as milliseconds.
if (now - 10days > user created at as a number) doThis()
ok
wait nevermind, managed to fix it bruh
just needed to define the message which i forgot
its 2 am bruw
pgrep 'node' | xargs ps -o pid,user,%mem,command -p $1 | sort -b -k3 -r | tee /dev/stderr | awk '{mem += $3;} END {print mem}'; echo '%MEM TOTAL'```
lil command to show how much memory node processes are using, for some reason pm2 doesn't show you an accurate number
๐
or in native JS
const ram = process.memoryUsage()
console.log(ram.rss - (ram.heapTotal - ram.heapUsed))
hey
how can i check if an id is inside the db? i'm using easy.database cause i have about 5 IDs only
never heard of it, should look at the docs for that database
client.on('guildMemberAdd', member => {
const embed = new Discord.MessageEmbed()
.setTitle('Member Joined')
.setAuthor(member.user.displayAvatarURL(), member.user.tag)
.setDescription(`\`${member.user.tag}\` has joined the server.`)
.setThumbnail(member.user.displayAvatarURL())
.setFooter(`Member ID: ${member.user.id}`)
.setColor('GREEN')
.setTimestamp()
member.guild.channels.cache.get('779410338336210956').send(embed).catch(console.error);
if((Date.now() - (1000 * 60 * 60 * 24 * 10)) > user.createdAt.getTime()){
const embed2 = new Discord.MessageEmbed()
.setTitle(' Warning!')
.setDescription('User has joined the server and user\'s account age is under 10 days!')
.setColor('ORANGE')
.setFooter(`Account Creation: ${member.user.createdAt}`)
.setTimestamp()
member.guild.channels.cache.get('779410338336210956').send(embed2).catch(console.error);
}
})``` when a user joins the server nothing happens
generally that information is in the documentation for that database.
hey there
how is pm2 inaccurate?
Haha, Woo back at it again!
i ran that and got a very similar result to what pm2 shows
I'm using a sharded bot, so pm2 seems to only show memory use for the master process
it should show correctly if you set the sharding manager to worker mode
because it's displaying my memory use as 110mb while each shard is running around 400-500mb each
yea, I'm using process mode
is worker mode favorable?
its more memory efficient since there's only one node.js instance controlling all threads
workers share the same memory spaces and caches
it's just spreading the ws connections across different threads
and they can restart individually as well?
yes
uhhhh. Depends on what you mean by restart
workers share the same global variables, so process.exit ing 1 of them exits all of them
client.on('guildMemberAdd', member => {
const embed = new Discord.MessageEmbed()
.setTitle('Member Joined')
.setAuthor(member.user.displayAvatarURL(), member.user.tag)
.setDescription(`\`${member.user.tag}\` has joined the server.`)
.setThumbnail(member.user.displayAvatarURL())
.setFooter(`Member ID: ${member.user.id}`)
.setColor('GREEN')
.setTimestamp()
member.guild.channels.cache.get('779410338336210956').send(embed).catch(console.error);
if((Date.now() - (1000 * 60 * 60 * 24 * 10)) > user.createdAt.getTime()){
const embed2 = new Discord.MessageEmbed()
.setTitle(' Warning!')
.setDescription('User has joined the server and user\'s account age is under 10 days!')
.setColor('ORANGE')
.setFooter(`Account Creation: ${member.user.createdAt}`)
.setTimestamp()
member.guild.channels.cache.get('779410338336210956').send(embed2).catch(console.error);
}
})``` when a user joins the server nothing happens
is the member in the guild that channel is in? member.guild.channels.cache.get('779410338336210956')
yeah
no
In Worker threads, this function stops the current thread rather than the current process.
Oh. Huh. I thought you had to send the worker a specific signal to kill specifically
so does that mean you can fetch a single user object across any shard?
yeah
no
Don't they share the same caches?
icic
heaps or caches?
I was told worker_threads share the same memory space
and any user code
from an operating system point of view they do, they are seen as a single process with multiple threads
well I faced a roadblock with sharding earlier since I can only listen to dms on shard 0
workers share the same node.js process, so you dont need separate node.js instances
but they have separate heaps
so I'm just trying to figure out if I can pass objects between shards more easily
i see
Node docs declare they share the same global constant which would imply require cache would be shared since the require global would be the same across each thread
where does it say that
re-reading the docs to find where. I remember reading that somewhere which is why I initially migrated to worker threads
if you have 2 shards using workers, and you eval client.guilds.cache.size, you'll see half of the total guilds
Okay. Now I'm reading that 2 workers can't mutate the same reference which is two completely different things
There's some overhead with node, so yes
worker threads CAN share memory, but its more complicated than that
makes sense
I did read there was a SharedArrayBuffer class
you can transfer buffers from one worker to another, and there is a sharedArrayBuffer
but only buffers and http handles are transferable objects
you cant transfer objects
so then, they do share the same memory space, but they don't
like, if you create a buffer in worker 1
gotta love programming
and you transfer it to worker 2
it will stop existing in worker 1
if you try to access the reference it will throw an error
the memory address was transfered ownership to worker 2
so its a handoff more than shared memory?
if you dont transfer it, it will create copy instead
the SharedArrayBuffer class is the only exception, it can be transfered across workers without losing ownership
Alright. That makes more sense. Is the standard send duplicating or is it transferring ref ownership?
its the only truly shared memory
i could see both being used frequently
tim where'd you learn all this
Also, I haven't bothered to check if you can only post primitive values or fully instanciated classes from another worker.
Alright so it is transferring
you put values, ie an object, a class, a function, etc, in the value field
then you put any transferable thing you want to transfer in the transferList
if you put a buffer in the value, and in the transferList, it will be transfered. if you put it only in the value, it will be copied
transferList may be a list of ArrayBuffer, MessagePort and FileHandle objects. After transferring, they are not usable on the sending side of the channel anymore (even if they are not contained in value). Unlike with child processes, transferring handles such as network sockets is currently not supported.
If value contains SharedArrayBuffer instances, those are accessible from either thread. They cannot be listed in transferList.
value may still contain ArrayBuffer instances that are not in transferList; in that case, the underlying memory is copied rather than moved.
What if you post a class which has a property that references something in use by one worker? Would it be duplicated or would all of the child references be transferred?
a class is not transferable, it will be copied
Alright. I see.
all references it contains should be copied with it
passing data between workers does not have the same limitations as IPC between child processes (which needs to serialize to json)
that is super cool
you can send more complex data without any problems
value may contain circular references.
value may contain instances of builtin JS types such as RegExps, BigInts, Maps, Sets, etc.
value may contain typed arrays, both using ArrayBuffers and SharedArrayBuffers.
value may contain WebAssembly.Module instances.
value may not contain native (C++-backed) objects other than MessagePorts, FileHandles, and KeyObjects.
Oh. That's nice. I was assuming it was only primitive objects that could be transferred
Or just passing a reference which you could mutate across workers
Guess I'll have to make some optimizations and possibly use SharedArrayBuffer
nothing except SharedArrayBuffer can exist in more than one worker simultaneously
Unfortunate
What would that implicate?
Is there a max ArrayBuffer size
depends on node, os, etc, but im pretty sure it should handle at least 4gb
Oh okay. So just the default max memory size
I wonder how a resizable SharedArrayBuffer would work; If they'd just do it similar to Objects where data added after instanciation is just appending a reference to another address
i dont think so
Unless you can resize in C++
arraybuffers are essentially low level memory blocks, pretty sure they are contiguous
Ah I see
the proposal also includes ResizableArrayBuffer
but the shared one is only growable, not resizable
because they deemed it dangerous to shrink shared memory
I can probably see why
Although node doesn't particularly have to be safe. Lower level languages can be unsafe
but they dont want node to be unsafe
they want it to be idiot proof
well, if you really want to, just code in c++
pretty sure you can multithread all you want in c++ land, then just interface it with node-addon-api
Does that basically just implement the node interpreter?
nvm. Reading the git
At that point, I'd just rewrite the entire application in a lower level language
node itself is built in c++
so you can integrate your own c++ code as a shared library and similar
On this note, Node is already idiot proof. If people wanna fuck with lower level memory spaces, sucks for them if they cause a SEGFAULT
this is extremely common in libs for electron
doing user32 calls from cpp and then interfacing it
ye
wasm :^)
you might be interested in https://github.com/OsamaAbbas/bytenode
this + webpack + javascript obfuscator will protect your source a fuckton
I wish you luck debugging template errors
time to completely clean my git history and implement this
Why do that
public source code but non permissive license is what's currently implemented, but just for the meme lords that wanna try to recreate some of my systems. I'm relatively small currently so could be easy for someone to pull
Does anyone know good places to advertise a game?
steam
That is quite low
const role = message.guild.roles.cache.find(role => role.id === '798347600910614538');
message.member.add(role)```
okay
const role = message.guild.roles.cache.find(role => role.id === '798347600910614538');``` how do i change this to tostring?
change what to string?
if you are displaying on a web page or something, use Role.name
iirc
because role.toString() replaces it with the mention
iirc
See the docs!
That removes a role from a user.
If you want to delete the role, you need to use <Guild>.roles.remove
is there a minimum age to verify a bot
like when you verify your identity on stripe
$5 real money or wallet also counts?
oh so if ur allowed on discord ur allowed to basically
Stripe itself doesn't impose any age rule, it's discord who will handle the data
{
"token":"No stealing my token dude"
}```
```js
client.login(require('./config.json').token);``` so i put my token in a JSON file. WHen i put it into a panel for hosting, can the devleopers of the hosting panel see the token?
If you share the file, yes
they would see it regardless because those are their machines
Json files are normal files
uhh how do i make it not visible or unable to ope nthe JSON file?
Use environment var maybe
How do i use that?
again they would see it because those are their machines
Or use some external file storage
they won't use it though, stop being paranoid
okay
real money i think
I guess so, it'd be quite easy to get $5 wallet
So my bot currently stores all user data in (persistent) arrays but if I am correct this won't work if/when I use sharding. What would be the best way to have a single database all shards can access at once? library is discordjs
mysql db?
Does it have a lot of relationships?
what do you mean by linked
Do you have sql knowledge?
i've used phpmyadmin
For example
User A has inventory, balance, sub-inventories, cart, etc etc
Sorry for the delay
Hi everyone, I need help on discord.js, someone knows how to send images in a JSON file
would i make a single database server, then each of the shards links up to that endpoint?
yeah
Phpmyadmin isn't sql, it's a database manager
Ok, so you know basic CRUD operations? (create, read, update, delete)
What I mean is like:
CREATE TABLE bla bla bla
SELECT * FROM bla bla bla
UPDATE bla bla bla SET bla bleh
You'll need to practice it a bit then, since you'll need to use CRUD for operations inside the code
will do for sure
About the database, I suggest postgresql
It does have Phppgadmin if you're used to php-based managers
And pgadmin4 if you wanna go fancy
haven't touched sql in years so ill have to relearn a lot but tysm!!
what's the best npm module for interacting with DBs?
That's something I can't answer, im not used at all with node
I'd suggest also reading about OneToMany/ManyToOne/ManyToMany relationships, you'll use it a lot
And basic database sanitization, to keep your data safe
I'm a little stuck on posting server count and shard count, the following code isnt working, ive also tried logging something if the post is successful but nothing has been logged
client.on('ready', () => {
setInterval(() => {
dbl.postStats(client.guilds.cache.size);
}, 1800000);
});```
Iirc the lib does that automatically
Did you wait for the interval to actually trigger
oh ok thanks
how would i make certain features only accessible to premium users
check if the user is premium before executing the command...?
how can i align something to the bottom of the page?
Hi, does anyone know how to create an anti raid bot? for discord.js
you probably wanna use async/await
do you have any examples of that
async function fetchJSON(url) {
// Imagine get() is a fetch function or something idk
const res = await get(url);
const json = JSON.parse(res.data);
return json;
}
you can use await to resolve promises inside async functions
and any async function by itself returns a Promise instead
You can use .then/.catch or async/await like Cholo demonstrated. The code you showed is correct, but the .then(...) part is useless because .then returns a promise holding the value of whatever was evaluated in the .then function you passed.
So, think of members.fetch(theID) is Promise<A>. .then(val => {return val;}) returns Promise<B> with B being the value of calling val => {return val;}.
ah so the key is to use .catch?
If you need to handle an error, use .catch. It still returns a promise.
oh
If you want the value inside the promise, you need to use .then or await. What to remember is you can't access the promise value directly.
To get the collection, use .channels.cache
so a corrected version of this would be
async function getUser(theID)
{
let x = await message.guild.members.fetch(theID)
return x;
}
?
oh wait i have to use await
well i mean
An async function returns a promise resolving to whatever value is returned from the function
oh so i have to resolve it
function resolveAfter2Seconds(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}
async function f1() {
var x = await resolveAfter2Seconds(10);
console.log(x); // 10
}
f1();
so in this example the 1st function returns a new promise that resolves to x, so when f1 is called it unboxes the promise and returns 10?
client.db.redis.get(`${data[0]}_p`, function(err, d) {
console.log(err, d);
if (d) {
return d;
} else {
// eslint-disable-next-line max-len
const find = client.db.collection('prefixes').findOne({'g_id': data[0]}).then((doc) => doc.prefix || undefined);
if (find) {
client.db.redis.set(`${data[0]}_p`, find);
return find;
} else {
client.db.redis.set(`${data[0]}_p`, 'ab!');
return 'ab!';
}
}
});``` just me being a twat or should this work?
i can console.log it and d is the prefix
but it returns undefined
yep
that works exactly as you intend
oh right
So either chain it with another callback or use promises as an alternative
you can promisify it and use async/await
function getMember(theID) {
return message.guild.members.fetch(theID);
}
async function getUser(theID) {
return await getMember(theID);
}
does this also work?
okay
this seems awfully circuitous to find a member by ID
is there a faster way
or maybe a way to encase 1 function in the other to tidy the code?
i'd say just keep the first one over here
okay
that's pretty much everything
@drifting wedge you can wrap the div around an anchor tag
tysm, was really confused about promises LOL
apparently that's semantically correct as of html5
wdym anchor tag?




