#development
1 messages · Page 945 of 1
someone dm advertised me and they have my bot in there server
and i wanna like
have the bot leave the server its self
Hmm, what lib? @astral yoke
in discord.js its simply guild.leave()
But thats it there
You can pass an ID into the leave()
like a serverid?
you will need to specify which guild you want to leave
discordis missing so you'll need to push that to the heroku server too
@magic jackal how do i do this, do i put it into the requirements.txt
@viral mortar Same way you did with everything else dependency wise
just with discord now
it needs to be in your requirements so you can install the requirements on the heroku server
So if its required, make sure its in there.
ok
Should work out smoothly
@earnest phoenix We have no idea what you're talking about. I need more context :^)
you mean a simple math command?
all programming languages have built in math operators
it should be as simple as variable + anothervariable
ye
you may need to convert them to numbers first
because discord gives you text by default
@quartz kindle Im sending that too a lavalink type server
if you do 5 + 5 as text, the result will be 55
its deprecated (but still works) im trying to make it work like a lib called discord.js-andesite
basically extending shoukaku
you can convert text to number by using Number, for example Number("5")
@mystic violet i've seen that error happen when the server crashes
or the payload causes the server to crash for some reason
weird
@quartz kindle btw for returning a true user count for everything on the client, isn't it client.users.cache.size or is it something different, caching is being weird rn
a true user count can only be obtained by reducing guild.memberCount
well i would like everything, all across all guilds
users.cache = cached users only
yes, you need to use a reduce function on guild.memberCount
@magic jackal omg thank you so much it works! : D
client.guilds.cache.reduce((total,guild) => total + guild.memberCount, 0)
how are you reading the file? with fs.readFile?
@quartz kindle yes
read it with require instead
?
let myfile = require("./myfile.json")
fs.readFile reads a file from disk1
require reads a file from disk and stores a copy of it in the require cache
wait
so the next time you require the same file, it reads the copy of it in the cache, instead of reading it from disk again
but can you read it with only let myfile = require("./myfile.json")
@quartz kindle
im confused
you can read files into your app with require
require will pull the whole contents into a variable
oh
whoops
.cache.reduce (my bad)
gn
sniff i smell bd sniff
Nodejs isn't a language 
discord.js eats ram for breakfast
unless you put a leash on it and hit it with a whip :^)
300Mb of ram wtf
quite normal if presences are enabled and you're using a non-modified discord.js and no cache sweeping
pretty yikes
?
Hey is there any way to compare the position of 2 users ? (In js) like know their both highest role and know who is higher than the other ? (Pls Ping me I don’t read every messages 😉 )
you asked the question, check up on the channel for the answers lol
grab the highest role of both users and compare their position
Yep but how ?
i think you can use the sort method, order by descending order and grab the first value in that
account for that a user might not have any roles
But isn’t there any property for this ?
in which lib
no and you don't need it
cause you can do it yourself
lol
also you might want to consider updating to v13
v12
discord is soon going to force stateless design with intents, d.js v11 doesn't support intents
Hey got it
message.member.highestRole.comparePositionTo(message.mentions.members.first().highestRole
)
Tu stackoverflow x))
Ty*
I’ll try
why did i even expect of you to even attempt to approach the problem yourself lol
x)))
one day you will learn that figuring the problem out for yourself is much more beneficial than "how do one compare roles d.js!@!?"

Just I’m quite new with djs
And instead of loosing long hours to learn it by heart I ask if someone knows
😉
It’s my way to learn maybe not yours, but it’s mine
you are not learning though
that isn't learning
you're teaching yourself a bad behaviour pattern
For me it is
Well this is working great for me
Why are you saying that it’s not If i tell you it is ?
one could say that independent problem solving correlates to intelligence but lets not go there
I’m developer since 2 years now and I know how I work
im way too tired to deal with a help vampire
If for me this works don’t say it doesn’t
You’re not with me so you can’t really know
That’s why the only information you have is what I say
And because it’s the only one you have you should trust it 😉
If that's your way of learning then okay but it'll be more useful down the road if you learn through browsing documentation and trying it out to problem solve
it helps no one, not even yourself
@amber fractal how can you say that without even knowing me ?
You don’t know who I am
Because google isn't an end all solution
One day Stackoverflow wont have your answer
You don’t know my name you don’t know my age you don’t know my profession you don’t know my formations
and you'll be fucked because you don't know what you're doing
Yeah maybe and this day I’ll figure out
Thank you for caring so much about me
But your way of dozing it is useless
.setDescription(`🏓\`${Date.now() - message.createdTimestamp}\`ms`);
message.channel.send(ping);```
Is the ping in this command the API? If not, what is it?
Nah
look at the WebSocketManager
This will just show you the time at which the message has been created
Ok
If you wanna get the api use client.ping 😉
well no
not in v12
which is why you use the docs to see what you're doing.
v11 and v12 are different
I know how to read the docs thank you
Really thank you for having so much care to me
client.ws.ping
You also know how to search stackoverflow, doesn't make you a good dev
comparing message timestamps isn't really accurate, if you want completely accurate REST ping, Date.now before sending message, Date.now after and subtract the two, even better if you can use a stopwatch
But it’s useless
There isnt a need for that comment bro, we are all here to help
@amber fractal okey please stop this discussion before it starts to be violent
Cry is right
Log a timestamp before and after the promise resolves
It should give you a reading of the actual total execution time
But this won’t be the latency
This will be the speed at which the server runs the command
It will be the entire request until the promise resolves
This includes server and REST time
If you need WS time Discord JS includes that under client.ws.ping
It will be the entire request until the promise resolves
@magic jackal no bcs the first date will be at the beginning of the command so after receiving the message and the last one will be before sending the edit

???
Thats the entire point of the request, youre handing the command through the API
im lost, youve confused me
a snowflake is generated before the rest of the entity, it's why you measure time before sending up until the entity is returned from the request
does anyone know why my bot only shows 18k of users and the server has 103k?
not all members are cached
@cerulean hornet client.guilds.cache.reduce((total,guild) => total + guild.memberCount, 0)
Use this for a total count
This will show you totals, by indexing through each key
which one is right? I count the total members using this ai command or rely on this command "message.guild.memberCount"
The latter will get you a count of cached members
While the former will give u the real count
what is a count me cached members?
Like, let's say your server has 50 members and the djs cache limit is 30
The latter will return you 30 as the total count of members
The former will return you 50
Note that not using cache can significantly increase memory usage for a short period of time if the amount of users is too big
how i get the avatar of the mentioned?12v
then it pays to use the other code?
i know ops is undefined here but how would i define it how come this errors with
at Object.run (/app/src/commands/music/nowplaying.js:15:23)```
```const { RichEmbed } = require("discord.js");
const ytdl = require("ytdl-core");
const hi = require("../../index.js");
module.exports = {
config: {
name: "nowplaying",
description: "playing songs",
aliases: ["n", "nnowplaying", "np"]
},
run: async (bot, message, args, ops) => {
let premium = bot.db.get(`premium_${message.guild.id}`);
if (premium === null)
return message.reply("Sorry but you don't got premium! Buy it today!");
if (premium) {
let fetched = ops.active.get(message.guild.id);
if(!fetched)
return message.channel.send("There isn't any music playing in this guild!");
let queue = fetched.queue;
let nowPlaying = queue[0];
let resp = `__**Now playing**__\n**${nowPlaying.songTitle}** -- Requested by **${nowPlaying.requester}**`;
message.channel.send(resp);
}
}
}```
Is there any way to make a string somewhat obfuscated
but still characters
like a formula that changes a name to a certain number
and the number equals the name and the name equals the number
Would using the OS for listing all the files for dynamic handler be better than a recursive function iterating over a dir?
anyone good with .htaccess?
I want to block mobile users from my website, because it's not optimized for it yet. And I want it to display a message on the website
Wouldn't you just be better using a query and display the error if screen size is too small?
As it will allow browsers that use small windows
But I don't want to go in my files again, I want to make like on .htaccess file and done
@tired nimbus if the code is public, a reverse engineer of your code will unravel any obfuscated string
not code just text
Just encrypt it with some SHA key them
Like randomly shifting bytes in the string, and using the key as a seed to the randomizer
im new to this so i was looking up tutorials and i copied the script word for word and it doesnt work does anyone know why? https://pastebin.com/bYaVTmag
"copied word for word" is bound to have errors
oh...
Try to understand the code first
Most of the time you'll need to adapt it to your situation
i tried to read it i understood most of it
What error is it giving?
im just trying to send an embed message
one sec
im using it on my laptop and its booting up but its slow
but i think it said module not found or somethin
Have you imported the discord.js lib?
yes
ivve had a command work before
it was the jsbot1
wait
i didnt include it
its still loading up...
if (message.content.startsWith(`${prefix}approve`) && message.author.id === owner) {
let person = message.mentions.users.first()
}```
how can i make it so that when i do a!approve @ the bot sends a dm to them saying you're bot was approved
Hi how to ended song leave voice ? js const channel = message.member.voice.channel; channel.join().then(connection => { connection.play('*****************', { volume: 0.2, }); })
i went afk its up now
its been up for awhile
wow that took forever
it had some stupid updates
@open oracle remember to do npm install to install the modules if you're working on a copy of an older project
How can I solve it if I leave the room after the sound playsjs const channel = message.member.voice.channel; channel.join().then(connection => { connection.play('*****************', { volume: 0.2, }); })
i already did that
wait
there is no errors now
wtf
thats my code
it still doesnt work
nvm there is an error
what error
sorry, i can't
its ok
because you used pastebin
oh
i can use normal
one sec
C:\Users\bigtr\firstbot.js:20
const embed = new Discord.RichEmbed();
^
TypeError: Discord.RichEmbed is not a constructor
at Client.<anonymous> (C:\Users\bigtr\firstbot.js:20:17)
at Client.emit (events.js:322:22)
at MessageCreateAction.handle (C:\Users\bigtr\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\bigtr\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\bigtr\node_modules\discord.js\src\client\websocket\WebSocketManager.js:386:31)
at WebSocketShard.onPacket (C:\Users\bigtr\node_modules\discord.js\src\client\websocket\WebSocketShard.js:436:22)
at WebSocketShard.onMessage (C:\Users\bigtr\node_modules\discord.js\src\client\websocket\WebSocketShard.js:293:10)
at WebSocket.onMessage (C:\Users\bigtr\node_modules\ws\lib\event-target.js:125:16)
at WebSocket.emit (events.js:310:20)
at Receiver.receiverOnMessage (C:\Users\bigtr\node_modules\ws\lib\websocket.js:800:20)
there
@open oracle your bot is version 12?
if fle is: const embed = new Discord.MessageEmbed
add ()
add ;
i already have those
client.on('message', message => {
if(message.author.bot) return;
if (message.content.toLowerCase() === 'jsbot2')
{
const embed = new Discord.RichEmbed();
embed.setAuthor(client.user.username, client.user.displayAvatarURL);
message.channel.send({embed});
}
});
we gave you a potential solution
try it
and if you're actually on v12, displayAvatarURL is a method so you have to add ()
you can also just simply use .send(embed) instead of {embed} because you used the constructor
if you guild has more than 3k members and you want to find a member by a nickname how can I do it
Ive tried looping through members of a guild but it seems to only reach a certain group of users
you filter them by using member.nickname && member.nickname === something
Hi, we're trying to make a bot display what we say in a different channel according to the channel's name, rather than the id.
THe reason for this is because we're trying to make it cross-server compatible, so as long as the other server has the channel by the name #something then it will display the thing, given the command in a separate server
Discord.py not ,js lol
@pale vessel i did this:
client.on('message', message => {
if(message.author.bot) return;
if (message.content.toLowerCase() === 'jsbot2')
{
const embed = new Discord.RichEmbed();
embed.setAuthor(client.user.username, client.user.displayAvatarURL());
message.channel.send({embed});
}
});
```is this right?
if fle is:
const embed = new Discord.MessageEmbed()
@ Igor#5850
please read next time
just change RichEmbed to MessageEmbed
Greetings I need a little help;
The bot refuses to set up after allowing him all the required permissions even in the channel where it is desginated.
May I get some aid?
can someone tell me how to disable message points multiplier for point bot
hello
support serevre psl
HEWLO
@true widget
@rigid summit
?
i need help
with?
@thorny moth
have any errors?
ask your question then and wait
dont mass ping
@scenic kelp this guy right here
pls
what i do
BOI when
#development isn't a place to ping people to ask for code
^
we are not going to spoonfeed you code
ok another problem im trying to change the color this is what i have but it doesnt work can anyone help me
client.on('message', message => {
if(message.author.bot) return;
if (message.content.toLowerCase() === 'jsbot2')
{
const embed = new Discord.MessageEmbed();
embed.setAuthor(client.user.username, client.user.displayAvatarURL());
embed.setColor('GREEN');
message.channel.send({embed});
}
});
```but it doesnt work
@open oracle try using hexadecimal values
for the most "green" version of green, it would be ```js
0x00FF00
@open oracle in the code snippit you've provided you passed in string GREEN
thats not a hexadecimal..
i dont know what to say to you then
i use hexadecimals and they work perfectly fine for me
ok
ok another problem im trying to change the color this is what i have but it doesnt work can anyone help me
client.on('message', message => { if(message.author.bot) return; if (message.content.toLowerCase() === 'jsbot2') { const embed = new Discord.MessageEmbed(); embed.setAuthor(client.user.username, client.user.displayAvatarURL()); embed.setColor('GREEN'); message.channel.send({embed}); } }); ```but it doesnt work
@open oracle anyone else know?
discord.js should accept those colors
do u want me to post the error?
sure
ok
internal/modules/cjs/loader.js:960
throw err;
^
Error: Cannot find module 'C:\Users\bigtr\firsbot.js'
[90m at Function.Module._resolveFilename (internal/modules/cjs/loader.js:957:15)[39m
[90m at Function.Module._load (internal/modules/cjs/loader.js:840:27)[39m
[90m at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)[39m
[90m at internal/main/run_main_module.js:18:47[39m {
code: [32m'MODULE_NOT_FOUND'[39m,
requireStack: []
}
there
that's not the color's fault
oh...
does that error happen when you try to start the bot?
uhh ithink let me double check
or when you run a command
when i start it
how do you start your bot?
node firstbot.js
ye
did you just make a typo in the command
created it in notepad :/
You made a typo
did you just make a typo in the command
wdym
bruh
you pepega
the error says firsbot.js is not found, but you siad you wanted to run firstbot.js
i want to die
^ that moment when you realize you should have taken 5 seconds to try figure out your issue before asking for help.
const warns = require("../../models/warns.js");
const { MessageEmbed } = require("discord.js");
module.exports = {
name: "warns",
run: async (bot, message, args) => {
let user = message.mentions.members.first();
if(!user) {
const q = new MessageEmbed()
.setColor("#ff9900")
.setDescription(":no_entry_sign: **You need to specify an user!**")
.addField("Correct Usage", "lt!warns [userMention]");
message.channel.send(q);
return;
}
warns.findOne({ Guild: message.guild.id, User: user.id}, async (data, err) => {
if(err) console.log(err)
console.log(data.Warns.length)
if(!data.length) {
const p = new MessageEmbed()
.setColor("#ff9900")
.setDescription(`:white_check_mark: **${user.user.tag} has not got any warns!**`);
message.channel.send(p);
return;
}
let f = new MessageEmbed()
.setTitle(`${user.user.tag}'s warns`)
.setColor("#ff9900")
.setDescription(data.map(d => {
return d.Warns.map((w, i) => `${i} - Moderator: ${message.guild.members.cache.get(w.Moderator).user.tag} Reason: ${w.Reason}`)
}))
message.channel.send(f);
})
}
}
Cannot read property 'Warns' of null
but in console i still get the data
😆
@earnest phoenix
@golden condor does this change something ?
It will work yes
uhm, ok
Also change !data.length to !data.Warns.length
ok
@golden condor Now i got this error here
data.map is not a function
.setDescription(data.map(d => {
return d.Warns.map((w, i) => `${i} - Moderator: ${message.guild.members.cache.get(w.Moderator).user.tag} Reason: ${w.Reason}`)
}))
so data.map is wrong
yeah
data.Warns is not a function
yeah, it's an array
It's data.Warns.map
Use eval to try ur code dude
are ad's allowed in bots?
like, lets say i have a small ad shown at the bottom of a command's embed
is that against any kind of tos?
I use node-fetch
That's your bots info
yes
oh
How do some bots have a rounded server size when you invite them?
It says used in x servers and some have a rounded number
bent is a good modern api for handling requests from the maker of request which is now depreciated 🙂
are you talking to me?
nope 😗

Hello, could someone help me with a cooldown with mongoDB?
🤔 why do you need to cooldown your db

👀
i'd love to be the one explaining to users that their data wasnt saved because the database was in cooldown... \s
when I reboot the bot, the cooldowns too
Command cooldowns?
yes
you should be able to considering you can with almost every language.
its just spawning a process via a shell.
time to learn it
😛
you should be learning golang or something
@cinder oxide for execute a batch file?
I think I misunderstood your sentence
message.language?
what is that
message.language?
constructor
@robust moth dont use nodemon when developing a bot
discord will make your token invalid
caause nodemon makes it login every time you make a file change
Only if you restart your bot very often
it happened to me a bunch before i realized wth was happening
nodemon restats auto after every single file change
Ok
If message.language is a constructor, why are you calling get on it?
@hasty sparrow I've gone completely crazy
omg my bot almost stoped working thank god there is good people to help me
wow that was stressful 15 minutes
Code:
async def unban(ctx, user: discord.Member, *, reason=None):
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split('#')
for ban_entry in banned_users:
user = ban_entry.user
if (user.name, user.discriminator == (member_name, member_discriminator):
await ctx.guild.unban(user)
await ctx.send(f'Unbanned {user.mention}')
return```
Error:
``` if (user.name, user.discriminator == (member_name, member_discriminator) :
^
SyntaxError: invalid syntax```
Can someone help?
F my bad!
This one doesn't close 🙂
^
@frail ocean @slender thistle thx for the help
Hmm is 214.93mb ram use on 2016 guilds and 300k users reasonable ram use? How much ram are everyone's bots using here, just looking to get a quick survey going see if I can figure out the average ram used per user or per guild
How can i delete a specific element from a array in Javascript?
@green kestrel depends heavily on library and how much caching you do
thx
aegis.cpp, Jacher
have "fun" with that! lol
that is a death sentance
although if i needed to write stuff in cpp for my bot i'd just make an api for it
doing this again, not sure i'd use C++, its really good performance but time to compile and test is an ass
websockets are abstracted away by aegis in my case cry
aegis is a really nice library
it uses websocketpp and asio under the hood
if you compare this to djs
you can get 200mb ram easily with djs in like 20 guilds
different languages i know but for caching everything 2k guilds and 200mb ram is pretty impressive
200mb for 2k guilds with cached everything is really good
yeah its hard to get a good reading on how much adding guilds is affecting ram in my case too, it always seems to waver around 150-200mb, regardless of how many guilds, it was 180mb ram last november when i only had like 200 guilds lol
i cache basically nothing and hover at 40mb rss
my bot used to sit at around 210 with 2k guilds and every member cached
though with intents and discord forcing stateless design there won't really be a need for caching
my cpu hates me but the minimal caching is actually rlly nice to work with
i also cant figure out why there was a huge spike in ram use a couple of months ago
i suppose the drop around late april coincides with moving to using intents
theres no problems with managing possibility that entity is not cached
it might be websocket buffers to handle all the presence messages or something shrug
presence update alone was making me exceed my bandwidth limit
yeah, look at my bandwidth graph now lol
those two spikes are a restart and synching members
apart from that, barely goes above 5k/sec any more
i couldnt even tell you what those spikes are lol
but intents have got me down to about 400kbps also
i imagtine the majority of that isnt actually from the bot though
i only track messages, reactions, and guild updates
Anyone knows if you can actually code a command, but disable it.
Without if statements ^^
Python btw
depends on your command handler I guess
if you have a property on your client with all your commands just remove it from there
if you dont then you cant easily
Alright
I have a bot written in D.JS that's in around 180 servers and uses 75MB of RAM max, and it doesn't cache anything
if you dont cache anything then server count makes no difference
or extremely little difference
yea, well I cache guilds and roles
im running a test using jemalloc with node.js
i need to wait a few days for results
const file = require('../data.json');
if (file.includes(guild.id)) console.log('triggered');
file.includes is not a function
but for a 1 day uptime, my bot's rss usage was about 50mb lower than before
@earnest phoenix includes is a method on arrays. Not a JSON object.
thisIsAnArray = [1,2,3,4,5];
thisIsAnObject = {1:10,2:20,3:30}
thisisAnArray.includes(3) // true
thisisAnArray.includes(7) // false
thisIsAnObject[3] // 30
thisIsAnObject[7] // undefined
😉
because 30 is a "truthy" value, you can do if(thisIsAnObject[3]) {}
so file[guild.id]
yes
idk im stupid sometimes sorry
same problem as yesterday @quartz kindle
which is that it doesn't refresh the json file
JSON for you.
?
are you using glitch?
if you are using glitch then you most likely need to refresh your glitch project or go out of glitch then go back in
then the JSON file should update
im not
how are you updating it
then you will need to show more code
them some sexy graphs i see @green kestrel @white anvil ❤️
any recommendation for a good monitoring system that supports per-process metrics?
netdata does that i beleive
the amount of metrics it gives is actually astonishing
graphs for days
how are you updating it
@cinder patio im not, because idont know how to do that
then what do you mean by "refreshing"?
@neat ingot i believe i've used netdata, but i couldnt figure out how to get a per-process list
its all about the entire system
i dont use containers, so i need it to be per-process
nope
i wanted for example, a specific node.js's process cpu/ram/network/bandwith graphs
or at least monitor a process by pid
ahh, i get that from using containers, idk how well it'd work outside of containers though
but it does seem to support giving metrics for all the things running on my host machine
you will need to show more code wolfy
@neat ingot i ended up uninstalling it lol
lmao
it was a while ago
i like it cause its a single container. the other way i was trying was using cadvisot/grafina/prometheus, and needed containers for db and all kinda junk
it woulda been 7 containers just for metrics 😐
cadvisor *
those graphs above are from netdata noob 🙂
the user with the chinese-CF8 name put me onto it 🙂
you need to customize apps.plugin and apps_goups.conf to make it work per process
but i couldnt get it to work
it works in docker, it works without
its a software you can install via command line on linux
it opens a webserver on some port
and you access the graphs from your browser
can also super easily define password and such for login to view the metrics
i have mine running at dekitarpg.com/netdata, but its all secure and junk 🙂
nvm
@earnest phoenix that doesnt help
you didnt make the change i told you to do
ye i did that as wel
use require instead of fs
changed it back because i had the same problem
tbh tim i'd give netdata another bash. for everything it offers in the one package its worth an hour or two of setting up imo 🙂
super easy to setup like, alerts and junk for when things go offline or w.e
i was kinda worried it would increase resource usage
since my instance is only 1 core 1gb
yea i mean, it keeps running and junk, but it seems to be really efficient unless its lying to me about its usage 😄
@earnest phoenix yes, but everywhere
ah
change all your JSON.parse(readFileSync to that
thats why you have to change it everywhere
@neat ingot i'll give it another try sometime
it also allows for fairly easy creation of custom graphs and w.e using simple html 🙂
im just periodically checking my bots using process.memoryUsage() in node lol
lmao
i made a handy clientInfo method for that
await writeFile(filePath, JSON.stringify(data))
with
data[msg.guild.id] = { name: msg.guild.id }; & const filePath = join(__dirname, '..', '/data.json') right?
do you programatically save the data to a file to view later? or only when you do it manually?
like, does it check every like 5 minutes or w.e and save the data toa file so you can check previous usage and see spikes and the like
im not really controlling usage history
just checking current usage and comparing it to what i remember last time i checked lmao
lmao
24 ping o0
ws ping
which host provider do you use tim?
i was using digital ocean, moving everything to contabo cause its cheap afffffzzzzz
so the reason it worked was because it is copied in the cache right
instead of only disk1
thats about my average when bots running on current server/my local machine (in uk)
i got my new server in new york though as i hear discord latency is good from there 😄
@earnest phoenix yes, essentially you have 2 copies, one in the cache and one in the disk. the disk is only a backup that is used when your bot restarts. the cache copy is where you should do everything with
so everything you do, you use the cache version and then save a copy to the file backup
yes
the reason for doing this, is that the cache is much faster than the disk
and saved
if you did everything using only the disk copy, it would be very slow
this is for json files with config or something?
writing to a file
storing guild data in json
another thing
if your bot crashes during saving to file
your json file will get corrupted and you will lose all data in it
that would be a gg
a good way to prevent this, is to save the file in 2 steps: save to a temporary file with a different name, then rename the temporary file to the original file
tbh i need to add that into my json data storage module thing
but why would it crash though?
it only records how many times i reboot my bot tho so it wouldnt be catastrophic if it rekt the file
but why would it crash though?
the same reason why windows crashes
any reason
oke
👍
crashes can happen at any time, because of coding mistakes, not handling errors properly, or in extreme cases, power failures and hardware failures in the machine
if the crash happens exactly while writeFIle is writing to the file, the file will become corrupted
ah
it takes a bit of bad luck, but can happen
when my bot went live, i discovered that people somehow find imaginative ways to break your bot that you would never have thought of.
yes
ok ill have to look into that then
thanks
when my bot went live, i discovered that people somehow find imaginative ways to break your bot that you would never have thought of.
this
always write your code so that it's fool proof
impossible.
fool-proof is not enough, it needs to be animal-proof
your users are brainless animals
ok
lmao
¯_(ツ)_/¯
but you should always have a mindset of "someone's going to do their best to break my app"
and retard-resistant.
tbh, yes.
i've had people join my support server specifically for that reason 😄
"hmm, what are some ways a retard could think of to break my app"
microsoft please take that advice and fix your shitty os
for example, typing a command with a 2000 char arg
check the node.js's fs documentation
(node:2752) UnhandledPromiseRejectionWarning: RangeError [EMBED_FIELD_VALUE]: MessageEmbed field values may not be empty.
nothin happened ❤️
xD
.addField('Antes', oldMessage.content, false)```
my bot used to generate 8000x8000 images from user input, and people can add objects to the image using args and options
and people would sometimes use all 2000 chars adding random stuff to the image
and it would crash the bot occasionally
help?
@earnest phoenix the error says it all
one of your embed fields is empty, which means, oldMessage.content doesnt exist
lmao
it sent fine as well 😄
why is the id so long tho
i cant find it
uuid v1
@earnest phoenix
duckduckgo lol
yeah
never been keen on that engine
it sucks
lol
its certainly not as user friendly as google, but i guess it has other benefits
they even include a !g command for that reason lmao
if you search node fs !g it redirects you to google's search results lmao
oh thats neat 😄
i guess they kinda had to do something though or users woulda stopped using when they can never find anything 😄
yeah lmao
people only use ddg for privacy reasons
i decided to give it a try
im also using brave browser, decided to give it a try as well
side question: anyone got any ideas for commands i can add to my discord minigame bot? this is the list it has atm 🙂
but it has the same issues chrome has
ive never tried brave
i heard firefox is doing some premium browser thing as well now
my issue is that i never close the browser, and i never shutdown/restart my pc
i often go months without a single restart or pc or browser
@neat ingot google feud
👀
and after a while the browser starts lagging like crazy
your poor pc
and im forced to close it and reopen it
feud is a game?
i have no idea what this is meant to be lol
do i need to do that for example every hour
if you want to do periodical backups, yes, but one hour would be too much
make it one day or something
but if you use the rename technique you should be 99% safe
except for system crashes
so
You have to guess the most searched queries that start with something
for example "is it wrong to be ____"
gay
I have the main json file - and the backup json file.
it deletes the backup file every 24h, and makes a copy of the main file and calls that backup?
you don't have to
you can scrape ddg
not since they tried to charge me a fortune for map api
you can also do guess the wikihow article
@earnest phoenix thats a way to do backups yes, but the renaming technique is like this:
- save file to "myfile.temp"
- rename file from "myfile.temp" to "myfile.json"
I can also just to fs.constants.COPYFILE_FICLONE_FORCE every 24h, because that will overwrite the copied file right?
thats a constant, not a function
would that auto overwrite a file with same name that already exists? ive never tried to rename a file in node 😄
constants are used as options for specific functions, not used by themselves
yeah it will
can just do
yes
👍
Hey, im making my bot on Glit** but when i add a status its not working
@flat kraken
You mean this channel, right?
Yeah. This channel. But I can't really help
Oh, ok! Dont worry 🙂 Thx anyways 🙂
is that Glitch but censored or do you mean something else
show us how you're doing it, how is it not working?
any errors?
😐
mhm
thats actually hilarious
thats not considered advertising, what kind of crackhead server was that lol
dont tell the name
it worked @quartz kindle !
hey there, I'm switching to mongoDB and I'm currently trying mongoose. I've seen in the docs you have to use .save() to save, but how to select the collection? thx in advance
wdym
const datathing = new Model({data});
datathing.save();
When I create a new document, I need to specify the model, right?
client.user.setActivity('looking SyntaxRP');
yea 🙂
@cinder patio
weird that should work
and then I use smth like js <mongoCollection>.insert(datathing) right?
Try adding {type: "PLAYING"} as the second parameter but I don't think it's required
i've never used any insert function with mongoose. I just create a new instance of my model, which is part of a collection, and then call save on it and it inserts itself
but how can it find the right collection to go if it isn't specified anywhere?
for example, lets say i have a collection of players and some model like:
const Player = mongoose.model('Player', playerSchema);
const my_player = new Player({ name: 'Dekita' });
my_player.save();
that auto saves into the 'Player' collection.
np 😗
before you explained, I didn't really understand the difference between schemas and models but now I do
a schema is like, a data blueprint, a model is like, a constructor that uses the schema to instantiate the document that will be added to the collection specified when creating said model 🙂
or as mongoose says:
great, thanks 👌
do i need to have the presence intent to set my bots status via setPresence?
lol
it wasnt workinng cause iw as trying to set it with v11 structure
ie, game: {} instead of activity: {}
ah xd
i wonder if they will ever give bots custom status'
Dunno about d.js, but in d.py it's being considered: https://github.com/Rapptz/discord.py/issues/2400#issuecomment-557045336
😮 i thought it was a limitation imposed by discord directly
it is
Discord.js v12 .features How can I use
i went to link my steam to discord, clicked the little thing to add steam and got this:
👀
norton?!
Norton
Nuff said
lol yea its just the norton websafe thing 😛
i dont actually have any antivirus software other than that 😐
and steam community pages load fine normally
Norton's crap, bin it
hey
Anyone ever used webmin?
cannot find module genius-lyrics
if you're using this module, you need to install it
also syntax error
🔭
yes, you appear to have more errors that you're not showing
do i need an api from genius too?
i got this code from here
im new to coding
so im learning as i go
I don't think straight up copying from another bot is learning as you go
i go over it
and how is that a tutorial? its just flat out giving the codebase 😄
the genius-lyrics module does require an api token apparently
hmmm
but in your case, you need to install it first
cries in no pc
oh
i randomly 'taught' my bot the lyrics to 'big shaq ~ mans not hot' for when people use the math command 😄
do i just look up genius api?
ok ill try that brb
xD
the github project uses genius-lyrics v2
you installed v3, which might work differently
this is how v3 works
how much security does the state thing provide in oauth? is it worth implementing?
it helps against some kinds attacks i guess
hey, is this agianst rules?
do i need to uninstall v3?
The primary reason for using the state parameter is to mitigate CSRF attacks.
When you use state for CSRF mitigation on the redirection endpoint, that means that within the state value there is a unique and non-guessable value associated with each authentication request about to be initiated. It’s that unique and non-guessable value that allows you to prevent the attack by confirming if the value coming from the response matches the one you expect (the one you generated when initiating the request). The state parameter is a string so you can encode any other information in it.
yeah but are those attacks easy/harmful enough to be worth implementing additional protection against?
csrf is one of the main attack vectors these days, along with xss, but it does require access to the target machine, via botnets or similar
the idea is that you intercept the initial request, send it somewhere else, and return a fake version of it from another machine, before the first machine is able to respond to it
or something similar
i dont know the details
ah
can also be done by man in the middle attacks, so the end result is that you give access to the wrong person
@austere gale if you want to use v2, you need to change the version in your package.json file
does anyone know how i can make the Reported At line only say the exact time the user was reported, instead of it saying all that extra stuff?
Roman you need to format the date object.
@clear wraith
in javascript
@austere gale better would be to change your code to use v3
but that requires knowing what you're doing
you read the v3 documentation and change the code accordingly
i just got into it 2 weeks sago
Fetches Lyrics from Genius at Ease.
whats that
their docs
oh
for v3?
from the looks of it, the examples are out dated
oof
but just read the docs
ok will do
emit is not a promise
He seems to only need to use reportedAt.toLocaleTimeString( )
Thanks
can someone tell me if anything wrong in this
for extension in initial_extensions:
try:
client.load_extension(extension)
except Exception as e:
print(f'Failed to load extension {extension}', file=sys.stderr)
traceback.print_exc()```
```Traceback (most recent call last):
File "main.py", line 24, in <module>
traceback.print_exc()
NameError: name 'traceback' is not defined```
define trackback
^ ^
i mean i didn't get what to do
const Discord = require("discord.js");
const client = new Discord.Client();
client.commands = new Discord.Collection();
let xp = require("./xp.json");
var DBL = require('dblapi.js')
var dbl = new DBL(process.env.DBL, { webhookPort: 5000, webhookAuth: 'password' });
dbl.on("posted", () => {
console.log("Server count posted!");
});
dbl.on("error", e => {
console.log(`Oops! ${e}`);
});
dbl.webhook.on('ready', hook => {
console.log(`Webhook running at http://${hook.hostname}:${hook.port}${hook.path}`);
});
dbl.webhook.on('vote', vote => {
client.channels.cache.get(715201063375863809).send(`${vote.user} has voted for Cryptic!`)
});
I had someone vote for my bot to test if it will send that a user voted for it in a channel. But it didn't send it in a channel when he voted. Why did it not send the ${vote.user} has voted for Cryptic?
try to do console.log("voted")
The ID must be a string
and see if it appears in your console
The ID must be a string
^
@viral mortar
