#development
1 messages · Page 933 of 1
k i stored it in a var
do you know how to access an array?
ok, now create a random integer from the length of the variable
or that
Read that link
i think i do but im not sure
Thaun it doesn't matter if we spoonfeed
Let's not spoonfeed
we probably gonna waste even more time explaining him how to create an embed while accessing all the data his result is giving
he's almost getting the first fish, stay strong guys
at least i know how to make an embed
You know how to make an embed but not access arrays¿
kk now "for" gives me invalid syntax error message
if you watched like a youtube tutorial, wouldnt arrays be like on episode 2
probably one
you do not need a for loop
@turbid bough and where is the fault
idk have yet seen your code
@pale vessel ep 1 https://www.youtube.com/watch?v=WGJJIrtnfpk
you cant store a for loop in a variable
"name reddit is not defined" go this after debugiing
uuh, how does your code look again?
the whole code, if possible
did you have a reddit api?
idk you havent require'd it probably oh wait its python lol
check the imports
so many js devs im beginning to confuse python with js
I’ve used this before
so many js devs im beginning to confuse python with js
I’m the opposite lol
you're gonna need to import reddit
i have
isnt it possibly praw.subreddit then?
^
ah nvm
import praw
reddit = praw.Reddit(client_id="my client id",
client_secret="my client secret",
user_agent="my user agent")```
module praw has no attribute to subreddit
yes i got that haun
thaun*
isnt it possibly praw.subreddit then?
@turbid bough no
docs dont say so
did you make reddit a global variable
yes but reddit also has no attribute to subreddit
Oh
yeah sure 1 sec
btw, if you have reddit initialized in another python file, you would need to import the other python file too
Error: Could not locate the bindings file.
I Tried to see wtf it wanted.... But i couldn't figure it out. Any suggestions on what I should do/be looking for?
@turbid bough
reddit needs to be above
yeah you need to do the reddit = stuff before you do reddit.subreddit
lol that's very poorly hidden
now im confused again
yeah
put reddit = ..... above client = ....
Yeah
for example
so you are saying i need to make a new variable or just move the "memes" up
Just move it up
lol
you can't put the chariot in front of the horses
print(test) = undefined
test = "test"
print(test) = "test"```
No undefined in python
print(test) in that case would be an error
Oh
excuses smh
show code v2
Just to piss you off as C# dev, 'string'
Wdym
char*
if i am using command groups can i add different cooldowns to each sub command? (Python:
)
You can use that in python
👀

your reddit line
@earnest phoenix Move the line where you assign to reddit above the memes line

not the memes = ... one, the other reddit one
@wise quartz @commands.cooldown(1, delay, commands.BucketType.user)
holy shit i feel so dumb
With delay being the cooldown
@wise quartz
@commands.cooldown(1, delay, commands.BucketType.user)
@warm karma thats not what i ment...
Technically you should be able to
Since they're sort of different commands on their own
@earnest phoenix Move the line where you assign to
memesline
@slender thistle sorry i do not get this.
reddit = ...
memes = reddit.stuff```
I feel like we are just teaching Mr. at this point
ugh
Maybe let one person handle this instead of inserting your 5 cents in constantly
i mean they're not really different commands like you can count them as arguments for example if the group is called work and the sub command is build you can do !work build
the only thing i do not get is what has to be after the reddit =
the reddit.subreddit
@wise quartz have you tried?
Ok
i just wanted to make sure
just put the memes inside the command function
wait what
bruh
yes i am confused
why did you remove your initialization lol
why is this guy trying to get memes from reddit? theres alot meme api(s) out there and they're much easier to use tbh...
you know praw.Reddit
oh god
you're overriding the module name
@modest maple the name of it is praw, right?
praw is blocking
uhh not just reddit("dankmemes")?
don't use it
@next remnant don't make it more confusing we've come this far
10 people teaching 1 guy 😅 this is fun to watch
yes that makes it confusing af
Why do you feel the need to insert something that doesn't contribute to the current topic whatsoever
10 teachers trying to force learn a student how to code
i mean if he just made some searches thru docs or so he could've done it by now
Yeah
@earnest phoenix Read this documentation: and you will see how it works. https://praw.readthedocs.io/en/latest/getting_started/quick_start.html#authorized-reddit-instances
nah
But he dosent even know how to move code
he doesnt understand python basics, giving him the docs and saying "read" isnt gonna help
I told him this at the very beginning
i meant this docs literally shows you how to do it basicly without telling him everything all over again
well if he doesn't know the python basics then he wont make it unless someone spoonfeed him the code
him: no
i know the very basics just not how to implement them into this reddit command
no buddy
idk how more i can help if you cant read the simple doc
Why are there so many people active at once
This isn't a channel for you to entertain yourself
trying to find out why flatlist ain't working
in the mean time I'm trying to help him
i mean we're trying to help 😂
lol
i just need this simple command done so 10 people being toxic at me isnt helping
I tried using praw once
10 people at once trying to help doesn't actually help
it has gone one hour since he asked his first question
yes
Show your full code again
Without the keys
Couldn’t figure out how to send the image
boomboom it is still the same because 10 people are all telling me different things
boomboom has no power
:readthedocs:
@earnest phoenix Send your current code
(Yeah but there was more at the bottom, I want to see if you changed it)
See the reddit = ... stuff?
ok, and now look at this image https://img.thaun.dev/mvuwv.png
ohhhhhhhhh
it was all in the docs
bruh
coding works by going top to bottom, so a thing at the top can't use something defined below
Command raised an exception: TypeError: object of type 'ListingGenerator' has no len
alway remember define -> use
not use -> define
so it's an error at memes
since it's the only listinggenerator there
this is my current code + error
try casting memes with .list()?
list(generator)
do i put that list(generator) in my client.command part?
What is the best discord lib for c++?
Not literally that
yea
Depends on what they want 

omg same but with an arduino
gotta write a bot in delphi
i fried it
lmao]
@slender thistle sorry for ping but somehow i still messed up
I thought I fried my Raspberry Pi 2
Send code
I just corrupted Raspbian
oh lord
oh
You can just pass memes as argument to random.choice without any need for list
so random.choice.memes?
argument for a function
aka function(argument)
If you did choice.memes, you'd say "memes is a property of choice"
but you need memes to be an argument of choice
now i did random.choice(memes) but i guess thats still not correct
That looks correct
it gave me the listing generator has no len error again
oh well, list(memes)
so random.list(memes)?
No, list(memes) will be the argument for function choice
You basically convert the ListingGenerator to a list, and then choose a random element
ok so i did random.choice(list(memes))
but for some strange reason now my async def on_ready has an error
What's the error
The full error please
Traceback (most recent call last):
File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 193, in _run_module_as_main
return _run_code(code, main_globals, None,
File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 86, in run_code
exec(code, run_globals)
File "c:\Users\Gebruiker.vscode\extensions\ms-python.python-2020.5.78807\pythonFiles\lib\python\debugpy\no_wheels\debugpy_main.py", line 45, in <module>
cli.main()
File "c:\Users\Gebruiker.vscode\extensions\ms-python.python-2020.5.78807\pythonFiles\lib\python\debugpy\no_wheels\debugpy/..\debugpy\server\cli.py", line 430, in main
run()
File "c:\Users\Gebruiker.vscode\extensions\ms-python.python-2020.5.78807\pythonFiles\lib\python\debugpy\no_wheels\debugpy/..\debugpy\server\cli.py", line 267, in run_file
runpy.run_path(options.target, run_name=compat.force_str("main"))
File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 262, in run_path
code, fname = _get_code_from_file(run_name, path_name)
File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 237, in _get_code_from_file
code = compile(f.read(), fname, 'exec')
File "c:\Users\Gebruiker\Desktop\bot\bot.py", line 34
async def on_ready():
^
SyntaxError: invalid syntax
how can i add a cooldown to a command in a commands group? (rn it just takes the same cooldown as the one given to the group itself. but i want every command in that group to have a different cooldown so is it possible?) 
Anything below that error?
invalid syntax
nope
c++ not a good option for programming a discord bot?
What does your on_ready look like
now all my @lient.command text is not in use
Most people don't go with .NET @viral spade
Send full code tbh
as in all or all related to the reddit command
hey @slender thistle i am having some trouble related to server count, can you please check #topgg-api ?
everything
Most people don't go with .NET
@vivid crescent
cpp is not a part of .net
c#, q#, f# and vb are
Alright my bad
(Thanks for letting me know) But anyway still; if they are fine to code in that language it shouldn't be an issue
it is an issue
all code
you often don't go with cpp for discord bots because it's very hard to implement a websocket handler in such a low level language
that's why all of the cpp libs are abandoned
it's really hard to keep up with gateway changes and implement them in cpp
@earnest phoenix Add one more closing parenthesis in the list(memes) stuff
wat
but that is a problem
since some memes are gifs
praw did return it correctly before when it just sent 100 memes
yup but not anymore
well with this code i have
what api do you recommend for images if i were to use that
cant you just simply get the image url?
nope it only returns the final part
im in class hehe
@work.command()
@commands.cooldown(1, 120, commands.BucketType.user)
async def builder(self, ctx):
await ctx.send("Worked")
@builder.error
async def builder_error(self, ctx, error):
if isinstance(error, commands.CommandOnCooldown):
seconds = error.retry_after % 60
msg = 'Try again in **{:.0f} Seconds**.'.format(seconds)
embed = discord.Embed(title= "Cooldown", description= f"{msg}", colour = discord.Colour.red())
await ctx.send(embed=embed)
shouldn't this work?
thats a command group btw
im only 12 im not anderstanding nothing and im from Brasil goodbyr
@reef meadow You are 12 years old?
yes
discord terms joined the chat
had to be BR
bye bye 


see you all later
see ya in 2 years
This is #development just in case
@work.command()
@commands.cooldown(1, 120, commands.BucketType.user)
async def builder(self, ctx):
await ctx.send("Worked")
@builder.error
async def builder_error(self, ctx, error):
if isinstance(error, commands.CommandOnCooldown):
seconds = error.retry_after % 60
msg = 'Try again in **{:.0f} Seconds**.'.format(seconds)
embed = discord.Embed(title= "Cooldown", description= f"{msg}", colour = discord.Colour.red())
await ctx.send(embed=embed)
so why this ain't working?
what isn't working
what api do you guys recommend for random images?
@earnest phoenix there's tons of api(s) just search on google and you'll find them all
what isn't working
the cooldown
its taking the group cooldown instead
which is 60 seconds
Tried asking in d.py Discord yet?
ye but none is answering 😂
،
-dotpost @abstract glacier
@abstract glacier
Please do not post dots to clear your messages/get attention. It adds absolutely nothing to the conversation and just causes spam If you need to get attention, then say hello everyone. If you need to clear your messages, then press the Esc key. If you do not follow these instructions you will be muted.
ok 
you're comparing an object to a string and boolean btw
And I want to detect is lUser is a bot and if it's a bot, don't do the rest of the commands
Yeah it don't work
if (commandName === 'warn') {
let lUser = message.mentions.members.first();
if(!lUser) return message.channel.send("You have to mention someone to warn!")
if(lUser == message.author.id) return message.channel.send("You can't warn yourself!")
warns[lUser.id].warns++;
message.channel.send('<@'+lUser+'>' + " has been warn.");
}
In C#, is there a way to create an array while applying certain arithmetic operations?
In Python which would be, for example, [x - 2 for x in myArray]
lUser is going to be an instance of GuildMember. You're doing <GuildMember> === <String>. What does not work about your code.
I'm getting a error can someone help me please..
Oh ok It can work
Missing paranthese@still merlin
oh ty
I need to create a more advanced command handler, this one is so simple, it works but hard to deal with
const fs = require('fs');
client.commands = new Discord.Collection();
client.aliases = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
for(const file of commandFiles){
const command = require(`./commands/${file}`);
client.commands.set(command.name, command)
}
client.on("message", message => {
let args = message.content.split(" ");
let command = client.commands.get(args[0])
if(command)command.execute(message, args);
});
On the last line
warns[lUser.id].warns++;
Also is this an in-memory object? How are you going to store it when the bot goes offline and comes back online?
i fixed it and still error?
@sudden geyser It goes on a json
let warns = JSON.parse(fs.readFileSync("./warns.json", "utf8"))
@still merlin the msg.channel.bulkdelete line is missing the parentheses
OHH thanks
After messages
I use the warns for other things
Like an auto anti-spam
(it's the goal of the bot, auto moderation)
If I use
fs.writeFile("./warns.json", JSON.stringify(warns), (err) => {
if (err) console.log(err)
It would save it, no ?
You need to compare the same thing for the if statement to work
Ok thanks
Great
i have this html button code html <a class="btn btn-primary btn-lg">More Info</a> and i want to link it to something how do i do that if i try with href then the css for it wont show
@digital ibex didnt you ask that before? whats your current code?
@hardy vector wdym the css for it wont show?
let r = message.channel.guild.members.map((e) => message.channel.guild.roles.get(e));
message.channel.guild.members.map((e) => e.roles.include(r))
``` i asked before, yeah, then i had to go
that code makes no sense
i edited it
still kinda makes no sense, you're remapping members into roles, but using the member to get a role?
then remapping again?
well, yeah. since that is what i would do since i've only got an array of id's
does guild.roles.get(member) gets you a list of roles that the member has?
uh, lemme try it
and if it does, why not simply using member.roles which does the same thing according to the docs
have you tried what i said yesterday? members.filter(member => member.roles.some(role => arrayofroleids.includes(role)))
message.guild.roles.cache.get(message.member) returns undefined, @quartz kindle
but maybe v11 wasn't
hes using eris
ow oops
message.channel.guild.members.filter(member => member.roles.some(role => guild.mod.roles.includes(role).id))
``` is what i done , `guild.mod.roles` is an array like `message.channel.guild.roles`
remove .id
kk
ok, it sends quite a bit, like a lot where my terminal can't see the top of it
so, 2 secs while i run my bot on command prompt
lmao
eris has that weird problem
when i tried running eris for a test, it kept spamming my console with garbage for no reason
even tho i wasnt listening to any event
ah ha, it returns a massive array, so i have to do ...includes(role)[0].wahever
so
i done js message.channel.guild.members.filter(member => member.roles.some(role => guild.mod.roles.includes(role))).map((e) => e.roles.includes('703361344312967212')) and that returns ```js
[
true, true,
true, false,
false, false,
true, false
]
[discord.js] How do I disconnect the bot from a voice channel?
@earnest phoenix Thanks
My bot has to delete a voice channel, but I get the API error below as response and the channel does not delete. The bot is added in the channels permissionOverwrites and has VIEW_CHANNEL and MANAGE_CHANNEL. How can I solve this, besides giving the bot administrator(which does solve the issue)
DiscordAPIError: Missing Access
at RequestHandler.execute (/rbd/pnpm-volume/36094c96-e504-4ecf-ab99-62f02cdefd9c/node_modules/discord.js/src/rest/RequestHandler.js:170:25)
at processTicksAndRejections (internal/process/task_queues.js:88:5) {
name: 'DiscordAPIError',
message: 'Missing Access',
method: 'delete',
path: '/channels/711971461811929129',
code: 50001,
httpStatus: 403
}
well does the bot have delete messages perms?
@lethal hawk a bot requires CONNECT and MANAGE_CHANNEL to manage the channel
oh it's MANAGE_CHANNELS btw
that solves it, I thought seeing the channel and managing was enough.
Thanks for the help
No i mean, if you make it so @everyone cant see that channel, the bot can neither see it
but if you add that to the permissions, then the bot is able to see it
i think
how i make custom guild prefix?
with a database
if u have link pls send
btw, I saw guild.deleted can be changed over time, it will just change the object when the guild is not in client.guilds anymore. Does this also count for guild.available? Will that automatically change on existing objects?
you have to setup a database
@earnest phoenix
i understand
you could either host it locally or check some paid options
I recommend sqlite or some other embeddable db
if 75 points means 75%/100%. Then what is 8000 points?????
if this works i can able to make a level card like mee6 so please tell me
meth
lol
@nocturne grove saves space, prefer it. doesn’t have random stuff like d.js
djs 4 me 🤢
there are a lot of reaons why i chose eris over djs tbh, thats just the main reason
I am thinking about adding an url shortener to my bot, but is it allowed to lock some features behind voting? (For example: Password locked url, auto qr codes, etc)
is it allowed to lock some features behind voting?
yes and it is encouraged
Ok, thank you :)
dis*couraged
im gonna make so the !vote command is disabled until you vote
@digital ibex oh okay thanks
btw, I saw guild.deleted can be changed over time, it will just change the object when the guild is not in client.guilds anymore. Does this also count for guild.available? Will that automatically change on existing objects?
anyone who can confirm this?
you could use slice
or
var fruits = ["Banana", "Orange", "Apple", "Mango"];
delete fruits[0]; // Changes the first element in fruits to undefined
something like this
go here
and read
actually dont use delete
use slice
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(0, 1); // Removes the first element of fruits
here is an example
0 is where it starts
and 1 is how many elements to remove
so if you wanna remove 2 after the index of 3
its array.slice(3, 2)
array.indexOf()
yes
what's your code
and what are you storing in the array
discord send my damn message
What would be a smart way of making this async? I'm still kinda new to async but still
const helpList = [];
client.commands.forEach(function(value, key, map) {
helpList.push(`${key} = ${value.description}`)
})
msg.reply(arr)```
oh
use the for keyword
hmm
ye
is there way to get all servers bot is in?
async forEach is a very bad idea
I'm not going to do the forEach i'm rethinking it now
client.commands is a map
client.guilds
oh thanks,
what difference with map and collection?
collection extends map
which means collection is built on top of map to include more functionality
I think collection better than map
its been on the back of my mind for a while but how would i handle timed events in the most reasonable way possible? aka something other than setting timeouts e.g. for mutes/timed rewards etc
like
run a loop or smth idk how to go about this really
a timeout is the only reliable way
however you can make a mix of timeouts and intervals
@valid frigate make a database with timestamps and check every minute / 5 minutes which one should happen
or just like
how to remove floats past 2 decimal places
well imagine if the bot's process gets interrupted
like crop off the ending numbers
the timeout would also go poof?
on boot get all of the entries from the database and queue a setTimeout for each entry
substring lol
.toFixed(2) will crop the number, but will also convert it into a string

sounds like a good idea
if you dont want string convertion, the only way is parseInt(number * 100) / 100
so like store a timestamp and when the bot starts again, run over each document and start a timeout counting down till that time
why on boot? Then you can't add new timestamps to it
yes... you can?
ok cool thank you
ok but why xd
I'd do it the other way bot sure
to reduce database load
and you can cancel each timeout
just from memory
(in case someone decides to unmute, unban etc)
since temporary actions like bans and mutes need to be accurate to the second, the approach of queueing a new setTimeout for each entry is more viable
the most efficient way possible would be something like this
setInterval(() => {
if(dateToUnmute < Date.now() + 600000) {
setTimeout(() => {
unmute()
}, dateToUnmute - Date.now())
}
}, 600000)
you can mix that with a database and adjust the timers to your preference
Why should they be precise? I mean: does 4:00:10 or 4:00:56 make a difference?
imagine you want to mute someone for 1 minute
and they only get unmuted after 1 minute and 50 seconds
¯_(ツ)_/¯
lol
Yeah okay but 1 min is weird haha
it really isn't
Sup
1 minute tempmutes etc. are warning signs for "hey you should maybe calm down" or something like that, if your bot isn't accurate, don't expect people to use it
"fuck your opinion - i decide the length"
well, you just have to temporary store short-timed timers, and if its long-timed then you use a db
$mute someone 30 minutes
"Approximate Bot": someone muted for approximately 30 minutes
Is there a way i can keep my bot online 24/7
and it already will be kinda accurate
is there any way for me to get the shard latency for each shard, in eris?
keep your program running 24/7
Lol
well, you just have to temporary store short-timed timers, and if its long-timed then you use a db
you should always store in the db no matter how short the action is, if a crash happens while the short period is near expiring, well, they're going to stay muted/banned forever
like,
shard 0 - 100ms
shard 1 - 10ms
shard 2 - 200ms
yeah, imagine muting someone, bot goes offline, and then they will never unmuted
@earnest phoenix yeah ofcourse if you are using mutes yeah, but like if you were doing like non-important timers
@digital ibex websocket latency can be found in client.shards.get(shardID).latency
ah, ty
Ow wait I also still got a question somewhere
btw, I saw guild.deleted can be changed over time, it will just change the object when the guild is not in client.guilds anymore. Does this also count for guild.available? Will that automatically change on existing objects?
This one
yes
if you do guild = client.guilds.cache.get() (if you're in djs v12)
then guild is a reference of the original guild, not a copy
DiscordHTTPError: 503 Service Unavailable on POST /api/v7/channels/702241622926295092/messages
Like you store them in a var and it changes
so whatever happens to the original guild, your copy of guild will also be affected
lmao
unless you do something so dumb that causes the server to crash
oh
or course with something as big as discord, that should never happen
cough
||host a giveaway with 250k members in the guild expecting nothing will go wrong despite knowing your platform is prone to crashing 🙃 ||
i have no idea what they're even using right now
what would that change?
their api is a clusterfuck
probably a bit of every lang out there
the gateway used to be python i think? or is? i dont know
but the rest api is a different lang
imagine if they have a component running on LOLCODE or brainfuck just for the lulz
secret endpoint
^
oh
programming is neverending, you can study it for 50 years and still find a gazillion things you dont know
also because a lot changes every year lmao
i've only been programming for like, 7 months
so everything you spent years learning is now suddenly obsolete
0_______________________0
well, it doesnt happen that fast
but look at flash, it was once upon a time the most used lang on the internet, every website and their grandmother was using it
and now its dead
my school still requires it so we can use their online books
rip
people who were the gods of flash games now have to learn how to port all their games to html5
We never did js at school but did Python and C#, and Python doesnt seem to have a high reputation lol
Oof
python was experimental at our school
Afaik internet games :)
it ended up getting thrown out because 90% of the students in the experimental class didn't like it
Ow lol
flash was primarily used for interactive content, games, videos, animations, etc
How can I make it dm me with their server link?
even youtube was based on flash
o damn
i cant read that pic at all @raven urchin
skies, forcefully creating invites into the guild isn't really advised
if you don't implicitly state that you're creating an invite, that's some form of api abuse
client.users.get('ur id').send('oof some1 removed ur bot')
data.money += currency*10
is ^ the right script?
HeLp
i don't know, is it?
Oh, How can I make it dm me?
np
how slow would doing Object.keys() on an object with 1k fields that have IDs for keys, such as "707952322172420157"?
yo does anyone use table from npm?
Is it any good?
If it already exists, just try
@grizzled raven log a timestamp at the time of you starting and the time of finish
check ms
i dont have one but i guess when i get the chance
how do i make this a function
.setImage(`${message.author.displayAvatarURL}`)
does anyone know what this screen means?
i tried but it didn’t do anything when i tried to update my server list thing
refresh i guess
discord's api is having a stroke and DBL depends on discord
so
everything is having a stroke
there's nothing you can do but sit, wait, and possibly have a mental breakdown while doing so
how do i make this a function
.setImage(`${message.author.displayAvatarURL}`)
python troubles ahaha
ok so essentially i want to be able to choose a random element from a list minus another pre-chosen element
so if i had a list k = [1, 2, 3, 4]
and i randomly choose 2 thru random.choice(k)
then is there a way to do random.choice(k) again but with no chance of it picking 2 again? i need all the elements to still be in the list, but the two random choices must be different
alternatively, as im assigning variables to each element chosen, if there's a way to do so with random.sample id love to know lol
Idk Python really well, but cant you make another array with all indexes of the first apart from the specific choice, get a random thing of that array, and get that index in k array?
ooh, ill try that :0
Hmm. But if that affects the original array, it will not directly work the way he wants
I am trying to add my server to the discord servers website but every time I try, it says there's an error
I have this const top10 = sql.prepare("SELECT * FROM scores ORDER BY usd DESC LIMIT 10;");
@marsh vale you using the discord calculator and put your bot ID to generate invite link ?.
but it says top10 is not iterable
embed.addField(client.users.get(data.user).tag, `$${data.usd}`);
}``` with this
I went on the discord servers website and tried adding an invite link and description to my server but it won't allow me
oof i had that kind of trouble before.
Pfff, if we can't use the perm administrator, this perm is unusefull
Give all perms is quite similar to give the perm Administrator
++
what is better for a bot?
Node.JS or Java?
what ever
so I ended up getting sidetracked af over the past two days. Made a module for easily creating and handling little minigame type things on discord. Made 5 fully finished minigames and started work on a 6th, and decided to just put the minigame commands into a new bot entirely 😄
the JS Libs are both pretty bad but so is Java's
anyone got any ideas for other minigames that could be neat on discord? 🙂
things i can make little boards using ascii/emojis are ideal 😄
ngl thats fucking clean
why thank you 🙂
help? my stats error doesn't work (discord.js v12)
const Discord = require("discord.js");
const run = module.exports.run = async (bot, msg, args) => {
const os = require('os');
const arch = os.arch()
const used = process.memoryUsage().heapUsed / 1024 / 1024;
let totalSeconds = process.uptime();
let realTotalSecs = Math.floor(totalSeconds % 60);
let days = Math.floor((totalSeconds % 31536000) / 86400);
let hours = Math.floor((totalSeconds / 3600) % 24);
let mins = Math.floor((totalSeconds / 60) % 60);
var cpu = process.cpuUsage().system / 1024 / 1024;
var cpu_usage = Math.round(cpu * 100) / 100;
let info = new Discord.MessageEmbed()
.setColor('#ff9900')
.setDescription('**PAPER STATS**')
.addField('📂 Total Servers', `**${bot.guilds.cache.size}** guilds`, true)
.addField('📡 Total Channels', `**${bot.channels.cache.size}** channels.`, true)
.addField('👥 Total Users', `**${bot.users.cache.size}** other users.`, true)
.addField('💾 Memory usage', `${Math.round(used * 100) / 100}MB`)
.addField('💾 Node', `${process.version}`, true)
.addField('💾 Library', 'discord.js', true)
.addField('💻 Operating System', `${os.platform} ${arch}`, true)
.addField('💽 CPU usage', `${cpu_usage}% Used`)
.addField('⏲️ Uptime', `Days: ${days} | Hours: ${hours} | Minutes: ${mins} | Seconds: ${realTotalSecs}`, true)
.setFooter(`${bot.user.username}`, bot.user.displayAvatarURL)
msg.channel.send(info)
}
module.exports.help = {
name: 'stats'
}
'dowpdown' is the same design, but is a match3 tetris dropdown type of thing with different color counters 😄
@earnest phoenix What are you talking about?
What is the stack error? Can you paste what it errors on here?
idk, it just don't work
how do you not know? Did you not write this?
This is a module export, how do you call the export itself? Are you calling the run()
You need to call the export and fire it off, typically in another file when this is used.
let me add it to my testbot I'll show you
Ok
See here
I copied your code and it works for me
I call my command via module.export and I require() it inside of my index.js and I fire it off using client.commands.get('info').execute(_, msg)
Ok
how did you manage to get a bot using 14mb ram
I use .rss that way it shows the full process
wtf
He is doing the math wrong
oh
used = process.memoryUsage().heapUsed / 1024 / 1024;
i know someone that used external to make his usage look small ass
it was like 500kb
yeah
rss isnt 100% accurate still tho
theres no real way to properly calculate true memory usage
my calculation is this
function formatBytes(bytes){
if (bytes>=1000000000) {bytes=(bytes/1000000000).toFixed(2)+'GB';}
else if (bytes>=1000000) {bytes=(bytes/1000000).toFixed(2)+'MB';}
else if (bytes>=1000) {bytes=(bytes/1000).toFixed(2)+'KB';}
else if (bytes>1) {bytes=bytes+' bytes';}
else if (bytes==1) {bytes=bytes+' byte';}
else {bytes='0 byte';}
return bytes;
}
formatBytes(process.memoryUsage().rss)```
you can probably do this more effectively using base 10 logarithms but math
So I'm sorting all of my bot's commands into folders inside of my command folder. At the moment, I use a command handler from An Idiot's Guide tutorial that I followed two years ago; Here's what I currently use to load commands:
const { promisify } = require("util");
const readdir = promisify(require("fs").readdir);
var commands = await readdir(client.config.commandsroute);
commands.forEach(f => {
if (!f.endsWith(".js")) return; // I don't know if subdirectories count as files, so..
const response = client.loadCommand(f);
if (response) console.log(response);
});
How can I do it so the fs module will read from the subdirectories? (I know that I can manually give each category folder its own forEach statement and stuff but I want to have it so the bot'll load the files automatically.)
read the parent directory for the subdirectories and read the contents of each subdirectory iteratively
alright
I could but that's gonna be a pain if I move it later
Unless if I deliberately make a new Linux user called "pi" and put my folder in the Desktop
OH it does
How can I send a message to a server having the id in discord.py?
what do you mean @rigid raven
i have the bot on my server and i want to send a message every 1hour (for example)
In that case, discord.py docs are your best friend
yeah, but i didn't see it 😦
wdym
and Jacher, I don't have a lot of experience with fs; how can I check inside the subdirectories in a forEach?
const subDirectories = readDir(parent);
subDirectories.forEach(directory => { const files = readDir(directory);
// add nested forEach here for files
})
you need the id to the text channel too, the guild id alone won't cut it
you need the id to the text channel too, the guild id alone won't cut it
@earnest phoenix ohhh, ok
-
what is
parentdefined as? -
would readDir be another thing like this
const { promisify } = require("util");
const readdir = promisify(require("fs").readdir);
but readdir is replaced by readDir?
Mongo Gods, I need your help, I'm trying to get the top 5 rsults from my DB but I cant figure out mongo very well
This is what I have so far, how can I return the result itself?
client.database.collection('guilds').find({}, {
sort: {
'fcount': -1
},
skip: 0,
limit: 5
});
The length of this is 0
are you using mongoose
yea

Why does it DM everyone
sounds like abuse tbh
Literally just use a role or @everyone mention
Mass DMs are API abuse and against Discord ToS
if this is a retarded question just say you cant dont yell at me
but if you get an error
like this
at item.request.gen.end (/rbd/pnpm-volume/8026e4ea-29c1-4714-8479-5e7241f9946b/node_modules/discord.js/src/client/rest/RequestHandlers/Sequential.js:85:15)
at then (/rbd/pnpm-volume/8026e4ea-29c1-4714-8479-5e7241f9946b/node_modules/discord.js/node_modules/snekfetch/src/index.js:215:21)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:7141) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:7141) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.```
how are you able to check like where it came from
instead of just having it as an error
by making sure that your bot has correct permissions
C a t c h it
Every single promise MUST have a catch
Else you risk being that lost
Where the error happened is written there btw
you'll have to go over all your code
and add catches to all methods that interact with the api
Ah
I found it
since danny said to catch it
why is this erroring catch (error) return; SyntaxError: Unexpected token catch ```bot.on("messageDelete", async message => {
let logs = await message.guild.fetchAuditLogs({type: 72});
let embed = new Discord.RichEmbed()
.setTitle("DELETED MESSAGE")
.setColor("#fc3c3c")
.addField("Author", message.author.tag, true)
.addField("Channel", message.channel, true)
.addField("Message", message.content)
.setFooter(Message ID: ${message.id} | Author ID: ${message.author.id});
let channel = await bot.db.fetch(modlogchannel_${message.guild.id})
if(channel === null) {
return;
}
bot.channels.get(channel).send({
embed: embed
});
catch (error) return;
})```
thats not how you catch things
Is it if error or what because catch error worked for my ban code?
you have 2 promises in that piece of code
fetchAuditLogs and send
fetchAuditLogs is being awaited, so if that errors, you will receive a normal error
send() is not being awaited nor caught, so if that errors, you will receive an unhandled promise rejection
so if you do await bot.channels.get().send(), the error will become a normal error
if you do bot.channels.get().send().catch(), you will catch the error in the promise
so basically
// option 1
try {
await function()
} catch(error) {
console.log(error)
}
// option 2
function().catch(error => console.log(error))
if you await it, it is forced to return to the normal flow, and its error will be converted to a normal error
if its not awaited, then it never returns to the normal flow, so you have to .catch() it to catch the error inside the promise
The Owner widget don't work
from 1-10, how good of an idea is it to make a new thread for each command executed?
in c#
depends what the commands do
resource intensive shit should always be ran on its own thread to make it non blocking
this guy said he hosted his bot on his old computer does that mean he has to keep it on 24/7
yes
i mean an old computer uses less power
tru
old computers usually use more power
OOF
a raspberry pi is an extremely affordable and efficient way to host a small discord bot at home
Just invest in a VPS
a vps is going to be an order of magnitude cheaper compared to the electricity cost of self-hosting
a pi can actually be cheaper than a vps ye
a single laptop cpu uses 5-10x more power than an entire pi lmao
just the cpu
i should host my bot on a pi cluster
one pi per guild :D
honestly the only problem with pis is the lack of cooling but for most use cases they shouldnt be getting that hot
one pi per guild wtf
you can buy this 750 pi cluster
you can probably run 1 pi per shard
how much for it?
is it preconfigured for shared resources? or do i have to install linux 700 times
get one of those and resell it as vps hosting
add some ssds and configure your virtualizer to use them as ram
cheap high-core high-ram vps
those poor ssds
not to mention the "ram" will be 🐌
rip to all the sata ssds that have died a painful death of swap overdose
honestly nvme swap isnt even that slow
you can raid a few nvme's and get about half the speed of actual ram
which is more than good enough
but seek time tho?
the noobs who will be buying your hosting wont notice
makes sense
id still use this over windows server ngl
use some cool tech that keeps hot data on actual ram and delegates the bulk to the ssds
get one of those and resell it as vps hosting
@quartz kindle big brain moment
how can i make a bot send a message in a channel every x hours
^with a timer
cron jobs too
Need a bit of help with this. trying to send a discord private message to users with a certain role. Have everything done, minus the actual sending of the message.
if(command === "test") {
let user = message.author
const role = message.guild.roles.cache.get("712058154090758248");
if (!role) return user.send('That is not a role!');
let membersWithRole = message.guild.roles.cache.get("712058154090758248").members;
membersWithRole.client.send("test")
}
Have been getting the error "cannot read property send" of undefined, which I expected.
wait
you cant use a members list to send messages, check the docs
plus massdming would be considered api abuse afaik
Its used in a private server where the people have all asked/agreed to be private messaged from it
it is a case by case thing
A collection does not have the property .client
u should be fine if its private
you should use a for loop and await send to each user
A collection does not have the property
.client
I've been going through docs and anything I can find to try and see what I can do
okay well go to the class about guild member manager
using a for loop like tim said would work fine
and iterate over the .cache property like tim said and use a for loop
role.members already gives you a collection of members, you can iterate directly on it
and send to each member in a loop
How do I take out each individual member from membersWithRole and add them to the loop queue?
the easiest way is using a for of loop
for(let [id,value] of collection) {
// do things
}
So put the loop inside that, then send the message?
Hello guys
Hello guy
I don't know how to pull data from collections, this is a first
Is there any bot that can boot my server
wut
Is there any bot that can boot my server free
I think he means boost
boost?
A) No, that's not how it works, B) This isn't the channel for that.
yeah buy nitro see above
I am looking for someone who wants to make my own server beautiful
@tepid hedge membersWithRole is a collection
so for(let [id,value] or membersWithRole) will give you the id and value of each item in the collection
in this case, the id of the member as id, and the member object of the member and value
This is development, and a bot list discord, I think you are in the wrong server to ask that question.
Is there anyone like that
....
I'll redo your discord for $60 Wrong server, we don't do that here, maybe ask in #memes-and-media
Ok... Im getting frustrated. I have uninstalled and reinstalled quick.db for the 3rd time in a row... Because that is what i had to do to fix the error that was occurring.
What can I do to decrease the times I have to uninstall and install quick.db?
uninstalling and reinstalling isnt gonna fix the issue
how to crop off end of a float to 2 decimal places
i keep getting numbers like 1.0000000002
/rbd/pnpm-volume/3e0e7ff0-a6f9-4413-afc4-43ee427079be/node_modules/.registry.npmjs.org/bindings/1.5.0/node_modules/bindings/bindings.js:135
throw err;
^
Error: Could not locate the bindings file. Tried:
→ /rbd/pnpm-volume/3e0e7ff0-a6f9-4413-afc4-43ee427079be/node_modules/.registry.npmjs.org/better-sqlite3/6.0.1/node_modules/better-sqlite3/build/better_sqlite3.node
→ /rbd/pnpm-volume/3e0e7ff0-a6f9-4413-afc4-43ee427079be/node_modules/.registry.npmjs.org/better-sqlite3/6.0.1/node_modules/better-sqlite3/build/Debug/better_sqlite3.node
→ /rbd/pnpm-volume/3e0e7ff0-a6f9-4413-afc4-43ee427079be/node_modules/.registry.npmjs.org/better-sqlite3/6.0.1/node_modules/better-sqlite3/build/Release/better_sqlite3.node
→ /rbd/pnpm-volume/3e0e7ff0-a6f9-4413-afc4-43ee427079be/node_modules/.registry.npmjs.org/better-sqlite3/6.0.1/node_modules/better-sqlite3/out/Debug/better_sqlite3.node
→ /rbd/pnpm-volume/3e0e7ff0-a6f9-4413-afc4-43ee427079be/node_modules/.registry.npmjs.org/better-sqlite3/6.0.1/node_modules/better-sqlite3/Debug/better_sqlite3.node
→ /rbd/pnpm-volume/3e0e7ff0-a6f9-4413-afc4-43ee427079be/node_modules/.registry.npmjs.org/better-sqlite3/6.0.1/node_modules/better-sqlite3/out/Release/better_sqlite3.node
→ /rbd/pnpm-volume/3e0e7ff0-a6f9-4413-afc4-43ee427079be/node_modules/.registry.npmjs.org/better-sqlite3/6.0.1/node_modules/better-sqlite3/Release/better_sqlite3.node
Then how can i fix the issue
n.toFixed(2) if you're fine with converting it to string
parseInt(n * 100) / 100 if you want to keep it as a number
@halcyon ember
@digital ibex discordjs
then tims way
@quartz kindle if i need to keep it a float with two decimal places do I parseFloat or what
cuz i need it precise to like 2 decimal/4 decimal places but parseInt would convert that to integer
multiply by 100 to move 2 digits to the left
parseInt to remove decimals
divide by 100 to move 2 digits back to the right
if you want more digits, change 100 to the number of 0s you want digits
Idk why it keeps saying i have an error then... If its the same error showing up 300 times a day. And I've tried everything I can do. @earnest phoenix
how do I put it into a function that applies that to every user every min
@clear wraith try running enable-pnpm in your glitch terminal/console
What will that do?
restart and reinstall your project
Ok
roman, not really relevant to ur problem, but, when i was getting errors with quick.db, i just switched to mongo, 100% recommend
I suck at switching
@clear wraith whats the error?
Its up there a couple messages 👆 @earnest phoenix
my code gives user 2 currency every now and then, but somehow it goes into decimal places like 0.00000000001. How do I put what tim did (n.toFixed(2) and parseInt) into a function that does it to every user every few seconds
you dont need to do that every few seconds
you just need to do that when you actually use those values
oh
for example, when putting those values in an embed
just do value.toFixed(2) in the embed
ahhh
ok that worked pretty well, excpet theres like numbers with excess 0s at the end
like 1.00?
.toFixed() does that, as its name implies, it fixes the length of the number by adding or removing decimals
@quartz kindle Came back after a bit, im testing out what you said (js for(let [id,value] of collection) { // do things }
If I run console.log as a test, how do I post the values?
if you dont want it to affect integers, you need to either ignore them Number.isInteger(n) ? n : n.toFixed(2) or use the math way as explained before parseInt(n * 100) / 100
Also got this error along with that:
well of course, you need to put your own collection in there






