#development
1 messages ยท Page 1977 of 1
there's a ยฃ100 bounty for you 
well this is just a general banner for the master readme
so yes i do want to take the version
How about... no logo
mmm no
Oh, no.
why
I don't like either of them
Those are not comparable
why not:(
agreed
also agreed authough i have less experience with it and its harder to do (foe me atleast) its not like js where you can run broken code and only find out about it when it brakes at some random point in the future
also
thinking of js
typescript
how do i get the guild id of a guild the bot was kicked from?
in guessing its somthing like ```js
bot.on("GUILD_DELETE", guild() => {
info("bot removed from server. deleting server file")
let id = guild.id
clear(id)
});
guild =>
havent used that event since v12 so idk
oh yeah i forgot to delete that cuz it was just () => and then i added guild
just fiorgot to remove it
but thx though
but other than that should work right?
also clear(guild.id)
no need to assign a variable
and add more info to that log, you can barely know what guild was it
fair enough
ok so i kicked it from my test server
and it didnt register the event
and also somthing i noticed is the reddy event hasnt bee firing either
do you really need to delete anything
seems like you're just losing data for no reason
yeah but bot has a file for each server
welp, there's ur problem
said literally no GDPR lawsuit ever
what does gdpr have to do with this lol
so if its kicked from the server it needs to delete redundent data other whise the directory will fill up with crap
have you considered using a database instead
its saves a message and it can be as big as the discord character limit
and since thats only 1 field theres almost no reason to use on it would over complicate things
a single message
sqlite is stupidly easy and simple honestly but your call I guess
working on getting it to do more than one for each server but havent doen much with that atm
true but i'd still have the same issue if needing to delete entrys from servers the bot isn't in any more
so we'de be back at square one
also in need food be back in a bit
real programmers eat and code
real programmers don't advertise it
real programmers send what they eat on facebook
However sqlite is probably a LOT faster and is meant for storing data, unlike reading and writing to raw files all the time
Hi
how do I prevent this from happening ("confirm" an interaction)
Respond to the interaction
How would I download a file from the internet?
Ex. if I have https://challonge.com/w9KSb8cCFd.svg and want to convert that image to a .jpg using sharp or fs, I'd need to download the image first. How would I accomplish this?
It depends on the langauge.
For example, in JavaScript, it's popular to use the fetch module.
Yeah I'm using JS
you mean of a discord timestamp?
Ah okay. Thanks.
or you wanna generate an id from a timestamp?
i mean like on guild join i want to send the timestamp
oh
since you're using discord.js, isn't that included on the guild object (e.g. .createdTimestamp)
not guild creation
i mean like get the current time so i can see when the bot joins the server
Yes, and it formats it as well
Though I don't know if dividing it by 1000 will give the correct time (I don't think it's necessary).
But you can use .joinedTimestamp like I mentioned
To get what time Discord thinks the bot joined
That will literally just convert ms to s, so yes it works as the provided timestamp still is in UTC
But make sure to use floor or abs in order to prevent a float in your message (time) format
But doesn't Discord process the timestamp in milliseconds
For <t:...> at least
Thatโs why he divides the timestamp provided by the event by 1000
I meant that I thought Discord processed timestamps as milliseconds, including when using <t:...>, so thought using seconds would be way under.
But tried it with milliseconds just now and it's way over instead
It says seconds in the docs if Iโm not wrong
Well okay but the example at least shows it
But still
But make sure to use floor or abs in order to prevent a float in your message (time) format
const { MessageEmbed } = require("discord.js");
module.exports = {
name: "guildCreate",
async execute(client, guild) {
let embed = new MessageEmbed()
.addField("ยป Owner", `<@${guild.ownerId}>`, true)
.addField("ยป Channels", guild.channels.cache.size, true)
.addField("ยป Created at", `<t:${Math.round(guild.createdTimestamp / 1000)}:D>`, true)
.addField("ยป Members", guild.memberCount.toString(), true)
.addField("ยป Roles", guild.roles.cache.size, false)
.setThumbnail(guild.iconURL())
.setTitle(guild.name)
.setDescription(`<t:${Date.now()}:D>`)
.setFooter({text: `ID: ${guild.id}`})
client.channels.fetch('941808789575835748')
.then(channel => {
channel.send({embeds: [embed]})
})
}
}```
RangeError [EMBED_FIELD_VALUE]: MessageEmbed field values must be non-empty strings.
at Function.verifyString (/workspace/node_modules/discord.js/src/util/Util.js:416:41)
at Function.normalizeField (/workspace/node_modules/discord.js/src/structures/MessageEmbed.js:544:19)
at /workspace/node_modules/discord.js/src/structures/MessageEmbed.js:565:14
at Array.map (<anonymous>)
at Function.normalizeFields (/workspace/node_modules/discord.js/src/structures/MessageEmbed.js:564:8)
at MessageEmbed.addFields (/workspace/node_modules/discord.js/src/structures/MessageEmbed.js:328:42)
at MessageEmbed.addField (/workspace/node_modules/discord.js/src/structures/MessageEmbed.js:319:17)
at Object.execute (/workspace/events/guildCreate.js:8:14)
at Client.<anonymous> (/workspace/index.js:34:46)
at Client.emit (node:events:520:28) {
[Symbol(code)]: 'EMBED_FIELD_VALUE'
}```
Date.now() returns ms, iirc
You gotta divide it and round it, too
And fill your empty field value (not title) with an actual string
ahhhh
use toLocaleString() instead of toString() to format the number (e.g. 1,000)
You may wanna read what I mentioned two times above
i hate how modules are becoming import only
been using require for years and now i have to import which i have to enable explicitly because it isnt enabled by default
is this a protest or something ๐
yeah we're just lazy
except for the refresh part
restarting your entire app to change some text on the screen is painful
apparently one of the ways to refresh using ESM could cause a memory leak
ffs just what i said
reject import, return to require
yeah say that to express
is it straight up disallowed?
yep it doesnt work
just gets more complicated doesnt it
top level await isnt a thing yet in stable either
except if your module/app is in ESM
been there since node v14.8
or v14.3 under --experimental-top-level-await flag seems like
i am one step from quitting the javascript ecosystem
because grace periods and if some person comes in complaining because it actually caused a breaking change
e.g. what happens in the rust community often
and theres also a very fucking load helicopter flying outside which is making me extra pissed off
try riding it
๐ก๐ก๐ก๐ก๐ก๐ก๐ก๐ก๐ก๐ก๐ก
const excelToJson = require('convert-excel-to-json');
const result = excelToJson({
sourceFile: 'quest.xlsx'
});
let d = message.author
let z = ''
let de = result.Sheet1
console.log(de)
let n = ''
const keys = Object.keys(de);
for(let i = 1; i < 11; i++) {
console.log(de[keys[i]].A)
n += `**Keywords:** ${de[keys[i]].A} --- **SearchVolume:** ${de[keys[i]].B} --- **Category:** ${de[keys[i]].C} --- **Average Price:** ${de[keys[i]].D} --- **Monthly Sales:** ${de[keys[i]].E} --- **Monthly Revenue:** ${de[keys[i]].F} --- **Review Count:** ${de[keys[i]].G} --- **Reviews Rating:** ${de[keys[i]].H}\n\n`
}```How would i remove the 11 de[keys[i]] from the excel file?
So that they cannot be drawn again
use interactions with user/message types
harass me all you want nerds
but for quick and dirty projects which need a database quick.db is ๐ฅ
its in the name after all
yeah nothing wrong with it
I read/write to a local db.json file in my project and call it a day
objects are the future
who even uses rows and columns nowadays
๐๐๐๐๐๐
Does anyone know a way?
you're using a package that converts excel to json
meaning its probably only from excel to json, and not back
you need something that can create or edit excel files
or save the json file and use the json from there on, and delete the excel file
I did something easier.
I just read the file outside the cron function, globally defined that.
At the end removed the keys from the json file, boom.
A cron function only runs once right? If the parameter is for example: Monday.
Would it run only once each monday? Yeah rigt?
it should yeah
Or would it constantly start another instance each monday.
Because that would be fucked up
@quartz kindle congratulations your discordjs library is becoming significant https://github.com/abalabahaha/eris/issues/1174
lel
can I get your autograph
sure, here you go:
- Tim
How does one get mem usage for python discord bot
have you tried googling python memory usage?
import psutil
print(psutil.cpu_percent())
print(psutil.virtual_memory()) # physical memory usage
print('memory % used:', psutil.virtual_memory()[2])
import os
import psutil
pid = os.getpid()
python_process = psutil.Process(pid)
memoryUse = python_process.memory_info()[0]/2.**30 # memory use in GB...I think
print('memory use:', memoryUse)
Is that a accurate module ?
guys i found a new curced discord bot on github
its a pokimon bot
and its got 12k lines of code in a single file
most of which are else if chains
does it have a giant if else for each pokemon?
having a lot of lines in a single file is not necessarily a bad thing
basically
oh no
but 12k lines for a discord bot in one file is fucking atrocious
i remember some dude here writing a pokmon bot like that
wonder if its the same dude
show the code
imo it doesn't matter the project. what matters is files are separate for clear reasons (e.g. putting your interaction stuff in interactions.js).
its all in one file
oh god
how do i see the bot i put on topgg?
but hey it's well documented
this is a nice class tho ```js
function Pokemon(name, nick, no, form, type, item, level, totalxp, moves, ability, abilitySlot, nature, stats, iv, ev, gender, region, location, caughtAtLevel, shiny) {
this.name = name;
this.nick = nick;
this.no = no;
this.caughtIn = "Pokรฉ Ball";
this.type = type;
this.item = item;
this.level = level;
this.totalxp = totalxp;
this.moves = moves;
this.ability = ability;
this.abilitySlot = abilitySlot;
this.nature = nature;
this.stats = stats;
this.IVs = iv;
this.EVs = ev;
this.gender = gender;
this.ot = "None";
this.otid = 0;
this.date = moment().format();
this.region = region;
this.location = location;
this.caughtAtLevel = caughtAtLevel;
this.shiny = shiny;
this.lead = 0;
this.form = form;
this.friendship = 50;
this.evolving = 0;
this.status = null;
this.pv = Math.floor(Math.random() * 4294967296);
}
Itโs really difficult to read 12k lines of code on 99% of projects
98% of the time it's due to no categorizing
Not to mention he destroys his client and logs back in each time he gets an unhandled error...
?
and theres this function had to zom out to see all the elseif statements
I don't mind 3k long java files because they're well placed
lmao
3k lines in a Java file is different though
Types make everything a lot less ambiguous
And itโs basically a pure OOP lang
Lmfaoo the most lines of code i ve had in single file is no more then 500 lines
Which means the entire language is basically structured around organizing data
omg this is literally that that function does
x to doubt
Yeah but Java's version is why you have 1k long java files by default
Iโd rather see "String x" than just "x" in a function parameter and have to look through what the function does to see what "x" is
then stretch that across 100-200 classes
that doesn't really have to do with file length though
that's about functions in general
like you'll see stuff like this https://github.com/OtagamerZ/ShiroJBot/blob/master/src/main/java/com/kuuhaku/utils/Helper.java
but imagine doing that for every function in a 3k line project
far easier to read with types imo
so many imports lmao
yeah I've seen that
to be fair though it's just static helper methods
just a lot of them
the longest file i've ever written is a .d.ts file lmao
guys pls reply., how can I give someone owner perms on my bot?
5k lines
I've seen much longer
anyone?
I think Discord.js's d.ts is like 30k-50k lines long
oh I was way off
the only reason mine has 5k lines is because i put typings + jsdoc together in the same file
the jsdoc alone is like 3k lines
Something something web3
Why hasn't cancel culture kicked in yet
what should I make with my beginner-intermediate skill level in c++
a web server
anyone know why guild_delete isnt fireing when the bot is kicked from a server?
do you have the GUILDS intent
SDL?
yee
graphics library so I'm not forced to work with raw ogl
bot.on("GUILD_DELETE", guild => {
info(`bot removed from ${guild.name} deleting server note`)
clear(guild.id)
});
thats the code
use the flag for the event
guildDelete
thats for v12 isnt it
no..?
i thought they changed it in v13
they changed intents
ah
ah ok
now for some reason the info command it trying to run on startup for some odd reason but thats probably cuz i did somthing dumb
and also the guild delete event runs at startup too every time
probably cuz theres an unavalable guild
and i heard that causes the thing to fire the delete event for no reason
yeah just did that
working nicely
(also yes i knwo i missed the colon on the warn)
congrats ๐
and yeah
a lot of issues happened earlier but our 3rd developer fixed it
my friend aka our 3rd developer is the owner of our hosting service
#include <SDL.h>
#include <iostream>
#include <SDL_image.h>
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
bool init();
bool loadMedia();
void close();
SDL_Window* gWindow = NULL;
SDL_Surface* gScreenSurface = NULL;
SDL_Surface* gHelloWorld = NULL;
int main(int argc, char* args[])
{
if (!init()) {
std::cerr << "Failed to initialize" << "\n";
}
else {
if (!loadMedia()) {
std::cerr << "Failed to load media" << "\n";
}
else {
SDL_BlitSurface(gHelloWorld, NULL, gScreenSurface, NULL);
SDL_UpdateWindowSurface(gWindow);
SDL_Delay(5000);
}
}
close();
return 0;
}
bool init()
{
bool success = true;
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
std::cerr << "SDL Could not be initialized!\tErr: " << SDL_GetError() << "\n";
success = false;
}
else {
gWindow = SDL_CreateWindow("First game", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if (gWindow == NULL) {
std::cerr << "SDLWindow Could not be created!\tErr: " << SDL_GetError() << "\n";
success = false;
}
else {
gScreenSurface = SDL_GetWindowSurface(gWindow);
}
}
return success;
}
bool loadMedia()
{
bool success = true;
gHelloWorld = IMG_Load("./helloWorld.png");
if (gHelloWorld == NULL) {
std::cerr << "Image resource could not be loaded!\tErr: " << IMG_GetError() << "\n";
success = false;
}
return success;
}
void close()
{
SDL_FreeSurface(gHelloWorld);
gHelloWorld = NULL;
SDL_DestroyWindow(gWindow);
gWindow = NULL;
SDL_Quit();
}
sdl is fun
wtf
the result lmfao
lmao
hey tim guess what
wat
cool
uvuvwevwevwe onyetenyevwe ugwemubwem ossas
you turned on a privileged intent that your bot was not approved for
but I thought that isnt needed until april 30
either guild members or guild member presences intent
I sent an application, but discord never emailed me saying I did
anyone know how long it takes them to accept / deny the application for intents
One message removed from a suspended account.
@sage bobcat
One message removed from a suspended account.
@sage bobcat
One message removed from a suspended account.
@sage bobcat Faithy

well this is me @hybrid cargo
...ok?
hello I try to connect my Heroku application to discord webhook but this is don't work and Heroku is getting me this
{"message": "Cannot send an empty message", "code": 50006}
That seems to be an error from Discord.
It means you aren't supplying content to be sent with the embed message
Like passing an empty string.
meant message
you have to supply either a non empty content string, an array of embed(s) or an array of file(s)
{
"id": "3e3a2b50-b52f-4bbc-a837-37c046befe20",
"created_at": "2022-02-12T05:21:22Z",
}
like this
That doesn't work
then how i can connect it ?
this is mean i need to create a code to connect it like get the heroku json and change it to embed\
I don't understand
heroku have a webhook too
When you pass a raw json to send to a channel, the lib you're using is assuming that it's data that can be transformed to raw data to send to Discord, which isn't the case in this instance. Most channel send functions in libs offer an overload to quickly send a string as content
I really can't see the appeal of people trying to make their own Discord lib. It's such a large commitment, that it most often ends up being a waste of time
most of my time is spent reading commit history instead of writing actual code which sucks
Modals seem really situational as well
why this code is dont work
message.mentions.members.second()
good question
๐ what i do wrong in this code
Would help if I knew what error you had.
2022-02-12T07:21:14.626739+00:00 app[worker.1]: /app/commands/Images/bed.js:24
2022-02-12T07:21:14.626756+00:00 app[worker.1]: const user2 = message.mentions.members.second() || message.guild.members.cache.get(args[1])
2022-02-12T07:21:14.626756+00:00 app[worker.1]: ^
2022-02-12T07:21:14.626757+00:00 app[worker.1]:
2022-02-12T07:21:14.626758+00:00 app[worker.1]: TypeError: message.mentions.members.second is not a function
2022-02-12T07:21:14.626758+00:00 app[worker.1]: at Bed.run (/app/commands/Images/bed.js:24:48)
2022-02-12T07:21:14.626758+00:00 app[worker.1]: at module.exports.run (/app/events/messageCreate.js:148:11)
2022-02-12T07:21:14.626759+00:00 app[worker.1]: at processTicksAndRejections (node:internal/process/task_queues:96:5)
this is the error
i try to get 2 mention user by this code
const user = message.mentions.members.first() || message.guild.members.cache.get(args[0])
const user2 = message.mentions.members.second() || message.guild.members.cache.get(args[1])
the fist one is work
but the second is not
yeah .second is not a thing in discordjs Collection
There's only first and last*.
you can always do .entries on members and get the second one from that
I mean you could probably do const members = message.mentions.members.values() and get an array
you might want to do this
[...message.mentions.members].map(x => x[1])[1]
I'm glad we all gave different answers.

LOL
Yui's answer works but that is putting twice the effort into something simple
kinda right but it worksโข๏ธ 
And I bet it probably has a performance issue as well
tis is work like members[1]?
members would then become an array yes
If you're boldy assuming there's at least two mentions. Sure.
Why do you want the second mention though
ok and ty
Probably a hug command or something.
Mmm
i need it for bed command
Wkkwkwkkw
Hello,
how can i get the user who voted for my bot?
Hi
if 'test' in message.content:
db[message.author.id] = int(5)
if 'test2' in message.content:
f= int(db[message.author.id])
g= f + 5
await message.channel.send(g)
error:-
Ignoring exception in on_message
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "main.py", line 44, in on_message
f= int(db[message.author.id])
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/replit/database/database.py", line 439, in __getitem__
raw_val = self.get_raw(key)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/replit/database/database.py", line 477, in get_raw
r = self.sess.get(self.db_url + "/" + urllib.parse.quote(key))
File "/usr/lib/python3.8/urllib/parse.py", line 851, in quote
return quote_from_bytes(string, safe)
File "/usr/lib/python3.8/urllib/parse.py", line 876, in quote_from_bytes
raise TypeError("quote_from_bytes() expected bytes")
TypeError: quote_from_bytes() expected bytes
help?
late but since nobody said it: js const [user1, user2] = message.mentions.members.first(2);
lmao u still doing this in on_message
How do i get what day it is today
I know its Date.now() and that i can format it, but how can i only get the day it is atm
So: Tuesday
or Wednesday
It's February 12th
btw your cat is adorable
if you are using js use moment module
It's .day() or something lemme double check
.getDay()
Will return an int, 0 = Sunday
6 = Saturday
hahah yeah i just saw it online, never knew that .getDay() was a thing. Thank you wowoowo!
how can i make something like
a timeout but without restarts
It'll countdown every 12h and change shop items, but I don't want it to restart every time the bot does, any solution?
setTimeout

set Interval is probably better, as the function to change shop items is probably always the same thing.
i noticed that when you add your bot on the website, when you insert your app ID, the field "short description" is autocompleted with your app's description, i'd like to know how to get the description of a user or bot using the discord api or an other method because i need this feature for my bot
https://discord.com/developers/docs/resources/application#application-object
seems to be included in the application object
Integrate your service with Discord โ whether it's a bot or a game or whatever your wildest imagination can come up with.
thx! so there are no methods to get the description of a user ?
at the moment that's unavailable to bots.
ok thanks for the infos!
you want the timeout to be fixed every 12 hours starting from a specific time, even if the bot restarts, instead of 12 hours starting from when the bot last started?
oh i see, i misunderstood ๐
const collector = new Discord.MessageCollector(message.channel, filter, {
max: questions.length,
time: [60000]
})```how would i set the filter to work in a dmchannel of a user defined as user1?
await message.author.createDM() to get the dm channel
filter is the same as any other, check for the author id
.. saving for later
Thanks tim!
it picks a random item from a list/array
from when the bot starts and infinitely
and is there a better way to accomplish this? (shorter way) ```js
if (rarity === "Common") {
if (lvl === 1) req = 1;
if (lvl === 2) req = 2;
if (lvl === 3) req = 4;
if (lvl === 4) req = 10;
if (lvl === 5) req = 20;
if (lvl === 6) req = 50;
if (lvl === 7) req = 100;
if (lvl === 8) req = 200;
if (lvl === 9) req = 400;
if (lvl === 10) req = 800;
if (lvl === 11) req = 1000;
if (lvl === 12) req = 2000;
if (lvl === 13) req = "Max";
}
one time is nothing but i'm doing it repeatedly with other rarities
const reqs = [1,2,4,10,20,50,100,200,400,800,1000,2000,"Max"];
const req = reqs[lvl - 1];
If you do the same thing, you can create a function to avoid repeating. I could suggest a Map with the level as key and req as the value
Or that yeah
ok
so like, the bot starts, run it once, then set a timeout to run it again every 12 hours? but if the bot restarts after like 2 hours, then it will run again, and 12 hours after that, meaning instead of 0-12-24 it would run at 0-2-14-26
if you want it to be fixed at 12 hours, regardless of bot restarts, you can do it with a bit of math
ok
a bit of explanation?
reqs is an array, arrays are zero indexed
the reqs[lvl -1] part
for example ["a", "b", "c"] means "a" is at index 0, "b" is at index 1, etc
if your lvl starts at 1, then you need - 1 to get the first item in the array
because arrays start at 0
oh then this'll work same as my ifs?
yes
-2
you have to convert lvl to index
index always starts at 0
so you always have to convert the start level to 0
if start level is 5, then 5-5 = 0
now i'm confused
this js ["a", "b", "c"] is the same as this ```js
{
0: "a",
1: "b",
2: "c"
}
how do you get "a" ? you do object[0]. and to get "c"? you do object[2]
Anyone know a good discord.js slash command lib?
Or just how to use them in discord js
IMO it's best to write your own slash command handler.
If you want a boilerplate I can give you mine.
Write a simple algorithm to get required exp for a level. I use * .15
time to get to work on my bot
Mind giving it?
I'm a fucking noob when it comes to making discord.js slash commands
I'll link you to the gist once I am on my laptop.
Okay
lol i have a developer team of 4 people working on one bot
And i'm doing this
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
if (interaction.commandName === 'ping') {
await interaction.reply('Pong!');
}
});```
for slash commands rn but the old commands don't go away
What could be the issue?
It takes time for cache to flush.
@earnest phoenix this is what iโm doing rn
i kicked and re installed the bot
Are you pushing the commands to discord?
cool, but why are you telling me?
idk
If you made global commands before and changed command names so it's not the same they wont go away you'll have to delete ALL the commands first then regenerate them.
What do you mean..?
The slash command IS on discord, but it's my old command description even when I don't have a set description on the current code i'm using
Or use the PUT method. It replaces them.
iโm bored and waiting for my developer team to get started on our command handling update
Ah, how do I do delete them instead of just doing it manually or something?
And deletes all commands that are non existent in the new array of commands.
bc iโm an idio
Ah
idiot*
Also youโre using a deprecated event
What would be a good way of deleting old ones?
I used d.js pre-built slash commands for this testing https://discordjs.guide/interactions/replying-to-slash-commands.html#responding-to-a-command
ik iโm fixing that part
I use the PUT method on the API to push changes.
ik but how's that - 1 and - 2?
because level 0 doesnt exist?
the first result exists in object[0], but you dont have a level 0
so how would you ever get the first result?
const req = reqs[lvl - 1];
if lvl is 1, with -1 it becomes 0, so it gets the first item in the array/object
so if the level is 3, it'll be const req = reqs[lvl - 3];?
if level is 5, then with -1 it becomes 4, so it gets the 5th item in the array/object
if level is 22, then with -1 it gets the 22nd item in the array/object
because the level starts at 1, but the array starts at 0, the difference is always -1
ohhh
ty for the explanation
now I understand
the lvl is from the db so I don't need the "if === epic", "if === rare"...
yes
So I'm having trouble making commands; I make a file, fill the file with the command I want, deploy the command to the guild and I do not see it when I do /{command_name}
lol why is it this hard to get new cards?
i'm just doing this ```js
if (arena <= 0) commorate = 2;
if (arena === 1) commorate = 4;
if (chss.rarity == 'Common') chr = Array(commorate).fill('nada');
if (chss.rarity == 'Rare') chr = Array(24).fill('nada');
if (chss.rarity == 'Epic') chr = Array(39).fill('nada');
if (chss.rarity == 'Legendary' || chss.rarity == 'Champion') chr = Array(84).fill('nada');
chr.push('chr');
I can understand rare, epic or legendary but commons are hard equally
boy
please use switch when due
also idk what exactly you're doing there
other than filling arrays with nada
I can explain
common, rare... are rarities
i'm filling with nada to later choose a random content from length
thats very inefficient
yeah ik
and wheres the code that does the random selection?
before i used some math.random from here but it was too easy to get cards
let chra = chr[Math.floor(Math.random() * chr.length)];
that's the random selection
but if the rarity is rare, if they dont get rare, should they still try to get common?
or do they get nothing?
they get xp for owned cards
yes but like
if rarity is rare
you have 1 in 25 chance of winning
if you dont win, do you still have a 1 in 5 chance to get a common?
so its always "or nothing"
yeah
then its much easier to use Math.random() directly, without arrays
but will be better with your suggestion
how
Math.random() gives you a random number between 0 and 0.9999999
so if you do for example if(Math.random() > 0.8)
thats basically 1 in 5 chance for the random number to be bigger than 0.8
then it's similar to this
this worked a while but I tried removing all my data and starting new, but then I saw that it's really easy to get cards
then you need to adjust the numbers
Yeah used that too
0.01 is 1 in 100?
with the code from init you showed above, 1 in 100 would be 0.99
yes
that's why it didn't work
0.01 is basically 99% chance of winning
realized it
init's code is doing a different comparisonl
also remember that rng is unbiased (well, mostly)
so you can always get 10 legendaries in sequence
or none in 1000000 tries
oh
well, thats why its random
well no problem
if you do want to GUARANTEE that at least one WILL drop in 100 tries you need to bias the rng
like store how many tries since last legendary drop
it depends on player's luck
ok
FetchError: request to https://top.gg/api//bots/stats failed, reason: connect EHOSTUNREACH 2606:4700::6810:ae38:443
Ahh.. I love when this CRASHES MY BOT.
i love when people dont handle their errors
ah, how I love the scent of UncaughtException crashes
oh god iโve seen this before
hm...what?
Is there a code that can make this error not crash my bot?
Youโve already shared it many times
catch the error
my hosting is confusing
for sure it is
Also what are you trying to show in that pic
idk
What am I supposed to be catching? ๐
module.exports = async bot => {
try {
const AutoPoster = require("topgg-autoposter");
const ap = AutoPoster(process.env.TOP_GG, bot);
ap.on('posted', () => console.log('Successfully posted the server count at "Top.gg API".'));
} catch {
console.log('Failed to post the server count at "Top.gg API".')
};
};
ap.on
oh wait
i did not see that lol
AutoPoster actually
I have node 17-4-0, even catching crashes it. ๐
not for promises
tim uses double quotes for js too (โฟโกโฟโก)
yes, an error listener
Oh, if it was called 'posted', it's called the posted listener?
Basically, a listener.
yes
I can't seem to find the list of listeners on the documentation.
posted is the name of the event
Ohh..
so a listener for the posted event would be the event listener
is that the top.gg sdk lib?
async stuff never gets caught with try-catch cuz they run in an entirely different context
That's the code. 
How can I check if an arg is undefined in js (for my bot in discord.js)?
this is in the topgg-autoposter source code
so yes, there is an error event
however, it should not be crashing your bot
if (!variable) { do stuff }
Alright, thanks
if a listener for the error event is not found, it should default to console.error
which does not crash the bot
So adding this code...
ap.on("error", error => console.log(error));
yes
you can also omit error => and just do ap.on("error", console.log)
Oh, fair enough.
My bot is starting but the commands aren't working, I never touched my bot for 4 days. ;-;
Just catch the error
any errors?
any muted exceptions?
No errors, nothing?
Weird, shard 0 has been launched.
by muted exceptions I mean try { code } catch { nothing }
do u use pm2?
Indeed.
how many crashes today?
you might have been ratelimited for excessive IDENTIFY attempts
I'm afraid I don't understand.
like, you can only login so many times in 24h
if your bot keeps crashing and restarting you might hit that limit
can or can't?
well thatโs just great i just had a hosting server failure
can
Wasn't it 1000 per like minute or hour
unless you have an obscene amount of shards or got stuck in a restart loop
pretty sure it's per day
Shrug
What is this, tf? - https://sourceb.in/tR3YK4II5N
Point still stands though, the ratelimit is being hit ๐
524, same issue as the one in #support
heavy load, so the server loses some requests
what u got there was the whole cloudflare error page in html
that was fast
i gotta re code my bot great
my developer team didnโt setup command handling so i gotta do that now
You better choose a different team then 
how tf do you even start a bot if not from command handling?
with a bunch of if elses ?
that's haram
That what like most people have done in the beginning I guess 
Develop the web
is there a way of check if a message collector ended because the time ran out with djs?
my devs are weird
@harsh nova
SCAM ABOVE
FREE CRYPTO????
ha he got banned
one last question @quartz kindle, if 0.9 is 1 in 10, then how will it be 1 in 20 and so on?
Anything greater than 0.95 is about 1 in 20
(If youโre using Math.random() Iโm assuming)
oh that makes things easier
1 in 30 would be about 3.33%, so it would be 0.9667 ish
nvm it's hard
How
how I calculate
๐
You can round it to the precision you think is correct
but will it be correct to put all?
It would be more accurate, yes, but probably not necessary
ok
Considering a number like that expands infinitely anyways
Depending on how small the probability is, 4-5 decimal places should be enough
But if you have really small probabilities then using more decimal places is likely necessary
ok
async getRepos(): Promise<IGithubUserRepo[]> {
// @ts-ignore
const { data } = await this.octokit.request('GET /users/{username}/repos', {
username: 'MistyyBoi'
}) as IGithubUserRepo[]
const repos = data.filter((r: IGithubUserRepo) => !r.private)
return repos
}
async getCommits(): Promise<Map<string,number>> {
const repos = await this.getRepos()
const map: Map<string, number> = new Map()
for(let repo of repos) {
const { data } = await this.octokit.request('GET /repos/{owner}/{repo}/commits', {
owner: 'MistyyBoi',
repo: repo.name
})
map.set(repo.name, data.length)
}
return map
}
Love how i get repos and commits?
Well blame github
they don't make it easy to get commits of a repo
They should just give you the commit count and shit
instead they give you the commits api url
export interface IGithubUserRepo {
id: number;
node_id: string;
name: string;
full_name: string;
owner: IGithubRepoOwner
private: boolean;
html_url: string;
description: string;
fork: boolean;
url: string;
archive_url: string;
assignees_url: string;
blobs_url: string;
branches_url: string;
collaborators_url: string;
comments_url: string;
commits_url: string;
compare_url: string;
contents_url: string;
contributors_url: string;
deployments_url: string;
downloads_url: string;
events_url: string;
forks_url: string;
git_commits_url: string;
git_refs_url: string;
git_tags_url: string;
git_url: string;
issue_comment_url: string;
issue_events_url: string;
issues_url: string;
keys_url: string;
labels_url: string;
languages_url: string;
merges_url: string;
milestones_url: string;
notifications_url: string;
pulls_url: string;
releases_url: string;
ssh_url: string;
stargazers_url: string;
statuses_url: string;
subscribers_url: string;
subscription_url: string;
tags_url: string;
teams_url: string;
trees_url: string;
clone_url: string;
mirror_url: string;
hooks_url: string;
svn_url: string;
homepage: string;
languages: number | null | undefined | string
forks_count: number;
stargazers_count: number;
watchers_count: number;
size: number;
default_branch: string;
open_issues_count: number;
is_template: boolean;
topics: Array<string>;
has_issues: boolean;
has_projects: boolean;
has_wiki: boolean;
has_pages: boolean;
has_downloads: boolean;
archived: boolean;
disabled: boolean;
visibility: string;
pushed_at: string;
created_at: string;
updated_at: string;
permissions: IGithubUserRepoPermissions
template_repository: string | null | undefined
}
All the lovely data you get back when requesting for a repo
Not what I am using this for
The numbers are the amount of commits that repo has
make a git globe like in github
how can i check if a command isn't executed by a group of users then return
that shows real-time pushes
i want to input the specific user ids
if (!condition) return;
Sounds like a lot of effort
like if (message.author.id != id1 id2 id3) return;
NO
use includes
Make an array of IDs and use includes
OR IS NEVER AN OPTION AFTER EQUALS
Lol
carve this in ur head
if(![arrayOfIds].includes(msg.author.id)) return;
After not equals
One thing I dislike about this is the open space bellow the cards
I can't figure out how to center it tho without fucking up the grid
TypeError: connection.execute is not a function```
const mysql = require('mysql2/promise');
const bluebird = require('bluebird');
const connection = mysql.createConnection({
host : 'server',
user : 'user',
password : 'password',
database : 'dbname'
});
(async () => {
const allUsers = await connection.execute('SELECT * FROM `blacklist`');
allUsers.forEach(function(user) {
console.log(user[0])
})
})();```
pov you import bluebird but dont do global.Promise = bluebird;
oh fuck i see
forgot Promise: bluebird
been a long time since i used sql
moving away to a selfhosted mongo instance
same error
you know what just log connection
ohhhhhhhhhhhhhhhhhhhhhhh waitttttttttttttttttttttttttttttttttttttttttt
createConnection could be a promise
next time keep your promises
you should also setup eslint to prevent things like that in the future
Use of TypeScript + ESLint = cleaner and less error prone code
do you need eslint when you're using typescript
and i personally stay away from typescript
it slows down my productivity
i often make and abandon a ton of projects and the ts setup just takes absolute ages
Eslint just annoys the fuck out of me
I delete eslint configs from projects that I use a gen on like angular, nestjs, etc
The opposite for me. ESLint catches a few issues TS doesn't, plus consistent code style an old colleague of mine and I made up
I can't stand eslint
then sit down
Did anyone ask for ur smartass comments :c
no
you only have a stupid hat
look how cool i am
also did i mention this avatar costs 3k
Did you just call my otter stupid
why tf do you need bluebird in 2022
because its cool
idk exactly how but
rip
it says its faster and more memory efficient and supports cancellation
so i trust it
Rip insteed
I can't imagine myself ever moving to mongo
Going from a perfectly ok relational DB to mongo
For a system that is largely wide column / relational
yeah maybe in like 2016 when native promises weren't optimized properly
i think mongo is one of the most heavy databases out there
because it is
you add like 50 million records and it's eating up 5GB of Ram from the get go
actually yeah bluebirds npm has been dead for 2 years ๐
you know what's an interesting db
Sled is nice
I've never had the chance to use it
We use it for out metadata store in lnx
Its really nice for rust because it's threadsafe unlike Sqlite
I only have 5k entries
@woeful pikethis is interesting
Never gonna get many
so bluebird is essentially dead yeah
so... why mongo
Because I hate MySQL
native promises used to be big time garbage but they're fine now
So just use Maria
I use mariadb
So why do you hate it?
๐ Schemas exist to help you
one day I will find a usecase for mongodb
will you though?
big doubt
is mysql too different from mariadb (other than different storage engines)
ignoring the fact ones ran by an evil corporation
every time I've picked up mongo it's like how do I put relationships in this non-relational database
and then I go back to a relational db
just store everything in the same document
๐คก It's a complete meme of a system though
incredibly big brain
no like
yeah they do actually have a concept of foreign keys now
At least I no longer store all my blacklist in a single json file
holy moly they're slow and awkward
I did 3 months ago
you can do some black magic to get data integrity too right
not sure
does schema validation support foreign keys
it just makes me feel like... if the goal was to get away from relational databases why are you adding that exact concept back to mongo instead of just using something that was meant to work that way from day 1
only thing i like about mongo is you can nest objects and arrays
thats about it
even then it looks good on paper but can become difficult to query
it's a bit of a pitfall to think about databases the same way you think about objects in memory
because they realised that people actually want relations
people went "oh new tech" and then went "oh wait actually relations are nice, schemas are nice"
I love starting db wars
not really wars
Lmao
I just hate MySQL and prefer mongodb
mysql is shitty yes
I just switched to MySQL originally because it was the only one I really had access to/knew how to use
use maria then
Im going to use scylla because discord uses it 
maria is mysql but less random seizures
was very cool talking to everyone
if discord jumped off a bridge-
im gonna use quick.db because turkish bots use it
Scylla low key scarely fast though
I do want to try cassandra/scylla but where tooling
do I need to write raw queries for every single operation
you don't say
you just found a gap in the marketplace
damn that's nice
Also I dont think you massively need it as much as your do SQL
your queries are always going to be simple
you're never going to have sub queries or these complicated join aggregations etc...
is that a wide column thing or
it's mostly a performance thing
like what do you do instead
also may i ask are bots on the website stored separately to bots in the queue
JOINs are very expensive
and people use them too liberally
so it forces you to manually write your joins
or rethink your structure in a more wide column design
but if you're not doing joins on the database layer you're doing it at the application layer no?
that's kinda the original mongodb problem
which is actually quite nice once you get over the initial hump
bearing in mind it has concepts of arrays, maps and set as first class types
so your lookups with them are incredibly fast and efficient
they are separated with a boolean field
2 separate queries is cheaper than 1 query doing a JOIN equivalent to the 2 queries
it's more efficient to do multiple round trips?
the drivers are able to pre-calculate what node they need to send the query to
so you go directly to the right node for each set of values you want to read and write on
that's kind of sick
and in some case it can even target the exact core/shard
this is the whole Token aware system
Which gives you these scary setups like my current project in progress which has a mean latency of 1ms or less
is this in cases where you have a partition key you're doing lookups by that the db knows the right node to go to for that query?
yeah
wouldn't you have to like restructure your db as you need different kinds of lookups then
let users = vec![12, 123, 1234];
session.query_prepared("SELECT * FROM users WHERE id = ?", (users,).await?:
very fast
that tends to be the idea of limiting it
tho I guess you literally do that when you add new indexes in relational dbs
it forces you to rethink your design from the relation based system
Relationships tend to cripple performance at large scale
so you have the same denormalization issue as mongodb
ish
ngl
it is nice once you get used to it
because suddenly you go "oh i dont need redis or cache"
is it too much of a pain to change things once you need different kinds of business logic? Cuz you can't expect to perfectly plan out your db schema ahead of time
and then go "oh it is so much easier to read without the joins
you can alter the schemas but generally, its a little tedious to do migrations
hmmm
I could see that being an issue if you're just starting out
I guess cassandra and friends are there to solve a scaling issue once you have a fleshed out db with known data access patterns?
a bit, although the simpler structure points out problems faster tbh
#[derive(Object, FromRow, ValueList, FieldNamesAsArray, Debug, Clone)]
#[oai(rename_all = "camelCase")]
pub struct DiscordRegisteredUser {
pub id: JsSafeBigInt,
pub username: String,
pub discriminator: JsSafeInt,
pub avatar: Option<String>,
pub guilds: Vec<JsSafeBigInt>,
pub co_owned_guilds: Vec<JsSafeBigInt>,
pub created_on: Timestamp,
}
derive_upsert!(DiscordRegisteredUser, table = "users");
My lovely lil helper system for db models
I only use the free mongo cloud clusters for small projects, otherwise postgreSQL all the way
So I'm having trouble making commands; I make a file, fill the file with the command I want, deploy the command to the guild and I do not see it when I do /{command_name}
Since you're using application commands, did you set them as global or guild commands?
If you just created new commands (as in the command wasn't registered before), it can take up to an hour to appear.
If you created guild commands, they should appear instantly, but you may need to run a command to have Discord refresh the list.
Guild commands. I did node deploy-commands-guild.js
What's the command?
any command, though it should still appear instantly regardless
But I also deleted a command and updated it and it was still there.
can you share the file
deploy-commands-guild.js
Alr.
const Discord = require('discord.js');
const { SlashCommandBuilder } = require('@discordjs/builders');
const { Permissions, MessageButton, MessageActionRow, MessageSelectMenu } = require('discord.js');
const { token } = require('discord.js');
const clientId = require('discord.js');
const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const fs = require('fs');
const commands = [];
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
// Place your client and guild ids here
"guildId"; "Id for the main guild"
"clientId"; "Id of my bot"
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
commands.push(command.data.toJSON());
}
const rest = new REST({ version: '9' }).setToken(token);
(async () => {
try {
console.log('Started refreshing application (/) commands.');
Routes.applicationCommands(clientId),
{ body: commands },
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}
})();```
Routes.applicationCommands(clientId),
{ body: commands },
Is this supposed to update the application commands? This looks incorrect.
Yes, I suppose so.
But it was there before I think and it updated it.
But I mean, what should I change it to?
A more correct answer would be
await rest.put(Routes.applicationCommands(clientId), { body: commands });
This would update the global commands. It comes from the example on the front page https://discord.js.org/#/docs/discord.js/stable/general/welcome
So it would update the global commands, including the guild commands?
Guild commands are local to a specific guild
For example, if you wanted to develop a command in a test server without anyone else seeing it.
Exactly.
Worst case scenario it becomes a feature


