#development
1 messages · Page 1232 of 1
ok
i have a json file and i think other json files are configured in the same format
(reason being why i said "i think" a lot as if i dunno bcuz if i was wrong, i woudnt wanna look dumb 😂. humans make human mistakes)
lol its fine
so how do i make this work, like how do i make it to react with a prefix + text
const cooldownAmount = (command.cooldown || 3) * 1000;
^ should the last bit of numbers be in miliseconds?
How to make bot plz tell plz
....
How to make bot plz tell plz
@bright musk code it
ty
@bright musk just code it
@hazy sparrow like i said learn how to code before trying to make a bot
@earnest phoenix dud i 100% understand the code written there but i have no idea where to put it
smh
When I get votes for my bot I want him to send a message
@rigid maple #topgg-api
@earnest phoenix do you know how to program stuff
no im new to all this
well it would be a terrible idea to start developing bots rn
^
you need to be experienced as hell to make good bots
Help to make a bot
Im trying to make it so when my bot clears messages it replies then deletes that reply 5sec later
message.channel.bulkDelete(argument2);
.then(async (deleted) => {
newamountdel = `${deleted.size`;
let response = await message.channel.send({embed: clearsuccess});
reponse.delete({ timeout: 5000 })
let response2 = await message.reply("ping");
response2.delete({ timeout:500 })
client.channels.cache.get('732708641039319101').send({embed: clearsuccesslog});
})
Im currently getting the error
SyntaxError: Unexpected token '.' (refering to the '.'then(.....)
How would I go about fixing this?
You have to remove the semicolon
guys i made my bot!! thanks a lot @earnest phoenix @near veldt
what is .toFixed() and how does it work? js btw
anytime kid
and now I'm getting a different error ;-;
is there something thats meant to come after a .then?
hi
@hazy sparrow from my understanding, .toFixed is made to turn a number into a fixed point notation. it's like rounding. for example,
var num = 5.56789;
var n = num.toFixed(2);
That would turn 5.56789 into 5.57 because the whole number or something to 5.56789 is 5.57
case 'attack':
if (talkedRecently.has(`a${message.guild.id}-${message.author.id}`)) {
message.reply("Bro you need to rest, you can attack in 45 mins");
} else {bot.commands.get('attack').execute(message, args);
talkedRecently.add(`a${message.guild.id}-${message.author.id}`);
setTimeout(() => {
talkedRecently.delete(`a${message.guild.id}-${message.author.id}`);
}, 86400000);
}
break;
i use this for my cooldown btw
and this is my command;s file
@hazy sparrow from my understanding, .toFixed is made to turn a number into a fixed point notation. it's like rounding. for example,
var num = 5.56789;
var n = num.toFixed(2);
That would turn 5.56789 into 5.7 because the whole number or something to 5.56789 is 5.57
@near veldt thank you so much!
let guild = db.get(`guild_${message.guild.id}_${message.author.id}`)
let inv = db.has(`inv_${message.guild.id}_${message.author.id}`, "hammer")
let amount = Math.ceil(Math.random() * 600)
let amount2 = Math.ceil(Math.random() * 11)
if (guild === "Warrior") {
if (inv){
if (amount2 === 5) {
let embed = new Discord.MessageEmbed()
.setColor("GREEN")
.setTitle(`**Raid Loot**`)
.setDescription(`You pillaged a nearby town with your hammer and looted \`${amount}\` coins.`)
.setFooter("You can only use the command again in 2700 seconds or 45 Minutes")
message.channel.send(embed)
message.reply("You also found a shiny coin, worth 200 regular coins!")
db.add(`money_${message.guild.id}_${message.author.id}`, amount+200)
}
else {
let embed = new Discord.MessageEmbed()
.setColor("GREEN")
.setTitle(`**Raid Loot**`)
.setDescription(`You pillaged a nearby town with your hammer and looted \`${amount}\` coins.`)
.setFooter("You can only use the command again in 2700 seconds or 45 Minutes")
message.channel.send(embed)
db.add(`money_${message.guild.id}_${message.author.id}`, amount)
}
}
else {
message.channel.send("Lol you aren't eligible to attack. You need to first buy a hammer from the shop for 50 coins, by doing `t!buy hammer`")
talkedRecently.delete(`a${message.guild.id}-${message.author.id}`);
}
}
else {
message.reply("Only players under the `Warrior` guild can go on attack raids\nYou can change your guild however using `t!guild <guild_name>`")
talkedRecently.delete(`a${message.guild.id}-${message.author.id}`);
}
jeez
i dont use db
i cant delete the timer from here
i use mongoose
oh, ok
i just need to know if i can
whats the matter then
delete the timer from here
like see when i do t!attack
and like i didnt mention an arg
it tells me to do that
but due to the cooldown
i can only do it after 45 mins
what would cause a "SyntaxError: Unexpected end of input"? I know it has something to do with the .then function I've just added as it was working before.
so like i need to know if there is a way thru which i can disable the cooldown for that stuff
or delete the timer
which i tried doing but it didnt work
i cant find where the } is
-___-
"}" isnt supposed to be there bow
yea i know, but wheres the extra }
yeah ,_,
lol
2020-09-11T07:44:06.998787+00:00 app[worker.1]: SyntaxError: Unexpected end of input
2020-09-11T07:44:06.998788+00:00 app[worker.1]: at wrapSafe (internal/modules/cjs/loader.js:1053:16)
2020-09-11T07:44:06.998788+00:00 app[worker.1]: at Module._compile (internal/modules/cjs/loader.js:1101:27)
2020-09-11T07:44:06.998796+00:00 app[worker.1]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
2020-09-11T07:44:06.998796+00:00 app[worker.1]: at Module.load (internal/modules/cjs/loader.js:985:32)
2020-09-11T07:44:06.998796+00:00 app[worker.1]: at Function.Module._load (internal/modules/cjs/loader.js:878:14)
2020-09-11T07:44:06.998796+00:00 app[worker.1]: at Module.require (internal/modules/cjs/loader.js:1025:19)
2020-09-11T07:44:06.998797+00:00 app[worker.1]: at require (internal/modules/cjs/helpers.js:72:18)
2020-09-11T07:44:06.998797+00:00 app[worker.1]: at Object.<anonymous> (/app/index.js:11:18)
2020-09-11T07:44:06.998797+00:00 app[worker.1]: at Module._compile (internal/modules/cjs/loader.js:1137:30)
2020-09-11T07:44:06.998797+00:00 app[worker.1]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
I'm guessing its something in my .then function but im not sure
ok
what commands are for changing the bot's status??
"SyntaxError: Unexpected end of input" It's a syntax error meaning that a character or string was incorrectly placed within a command or instruction so the code is unable to be executed
that requires a ready.js, Hype
I've clicked every line, i cant find the issue
that requires a ready.js, Hype
@near veldt oh ok
let argument2 = parseInt(argument) + 1;
message.channel.bulkDelete(argument2)
.then(async (deleted) => {
newamountdel = `${deleted.size`;
let response = await message.channel.send({embed: clearsuccess})
reponse.delete({ timeout: 5000 })
let response2 = await message.reply("ping");
response2.delete({ timeout:500 })
client.channels.cache.get('732708641039319101').send({embed: clearsuccesslog})
});
Is there anything wrong with this code?
argument, newamountdel and the embeds are defined in the code before that
100% coded this myself before anyone complains that i have copypasted it from somewhere
const db = require("quick.db");
module.exports = {
name: 'work',
description: "flip a coin!",
execute(message){
const cooldown = new Set();
const cooldownAmount = 3600000;
const expirationTime = Date.now() + cooldownAmount
const now = Date.now();
if(now < expirationTime){
const timeLeft = (expirationTime - now) / 1000;
message.channel.send(`You have worked recently! Please wait ${timeLeft} seconds before you can work again!`);
}
else
if(message.author.id == 542278740537769985) {
const bal = new db.table(`${message.author.id}mybal`);
if(message.author.id == 542278740537769985) {
db.add(`${message.author.id}mybal`, 2000);
message.channel.send(`You got **2000** bowbucks for working...`);
}
else {
db.add(`${message.author.id}mybal`, 2);
message.channel.send("you got **2** bowbucks for working");
cooldown.add(message.author.id)
setTimeout(() => cooldown.delete(message.author.id), cooldownAmount);
}
}
}
}
oh wait a second, i found the issue
bow pro thanks, ur code showed me my issue lol
lol
@forest drift "${deleted.size"
i think ur missing a "}"
bow pro thanks, ur code showed me my issue lol
@forest drift welcome?
the ending has the required });
oh.... im blind... wait how does the rest of my code stay to format if... im so cinfused rn
wow did i just fix someone elses problem with my problem
He copy it from somewhere
@earnest phoenix i think he was using an advanced technical term called joking -___-
No, he isnt.
help me pls ;-;
does anyone else also plead when they launch their code that its gonna work?
Gotta say, bow pro, please dont lie about coding
No
but i refered to the d.js thing
He copy it from discord.js guide
it doesnt look copied
let response = await message.channel.send({embed: clearsuccess})
reponse.delete({ timeout: 5000 })
Now I'm getting "response isnt defined" ;-;
wait i cant spell
and im blind
lol
He copy it from discord.js guide
@earnest phoenix I didn't copy it, I just reffered to it
reffered*
refered*
refried
^^^ according to copyright, as long as u state the source its legal
Refferenced
is there a limit by youtube video requests? (my bot send a message if someone upload a video)
@steady anchor yes
also @earnest phoenix my code and the d.js guide clearly has some difference
:(
Google api gave rate limit
Unless you buy upgrade i think
@hazy sparrow
name: 'work', description: "flip a coin!"
thats not the issue @earnest phoenix
but still it's weird
if im using export modules, could i just add "client" to the export thingy on the send and recieve and itd work? or is this also gonna be annoying
but still its not the issue
@forest drift yes
:D for once its less work
u mean module.exports.client ?
require('path/to/file').{name}
terrible way
you'll still need to put .name at the end
when he stores all commands in individual files anyways
lol
now can someone help me :/
yeah
yeah
yes you can
yes you can
@pale vessel how
damn

gave yo ass the docs
lol

lol
module exports are annoying but way better than putting everything in 1 file... wish id known that a month ago...
indeed, module.exports are annoying
why is it annoying
module exports are annoying but way better than putting everything in 1 file... wish id known that a month ago...
@forest drift you'd still need module.exports if you storw everything in one file
indeed, module.exports are annoying
@near veldt fuck no every single npm package NEEDS module.exports to have the code available to other modules thatrequire()it
ok boomer
what the fuck
lmaoo
ok boomer
ok whitename
@forest drift you'd still need module.exports if you storw everything in one file
@earnest phoenix u do ;-; welp i was clearly coding wrong then
k imma ask my "question" again
const db = require("quick.db");
module.exports = {
name: 'work',
description: "flip a coin!",
execute(message){
const cooldown = new Set();
const cooldownAmount = 3600000;
const expirationTime = Date.now() + cooldownAmount
const now = Date.now();
if(now < expirationTime){
const timeLeft = (expirationTime - now) / 1000;
message.channel.send(`You have worked recently! Please wait ${timeLeft} seconds before you can work again!`);
}
else
if(message.author.id == 542278740537769985) {
const bal = new db.table(`${message.author.id}mybal`);
if(message.author.id == 542278740537769985) {
db.add(`${message.author.id}mybal`, 2000);
message.channel.send(`You got **2000** bowbucks for working...`);
}
else {
db.add(`${message.author.id}mybal`, 2);
message.channel.send("you got **2** bowbucks for working");
cooldown.add(message.author.id)
setTimeout(() => cooldown.delete(message.author.id), cooldownAmount);
}
}
}
}
oh yeah, i was storing everything in 1 file, had tried module.exports, that was 2 weeks after i had started, found in annoying af and didnt understand it, so just carried on and now im having to convert everything to module exports
oh wait i think i know how to fix it
setTimeout
@hazy sparrow what even is the fucking problem
@earnest phoenix
i think bowy boi forget a setTimeout for his cooldown
@hazy sparrow yeah what is the problen
explain it
instead of pinging me with a screenshot
i just explained for him, code
take a deeper look
3600 seconds
for each msg
it doesnt change
impossible to change it with setTimeout
it doesnt count down
yes ans all messages are 10 seconds apart
node won't tell how much time is left before the timeout ends
just wait an hour
then try again
its been 2 fking days since i used bow work
i think bowy boi forget a setTimeout for his cooldown
@near veldt didnt i set it in the bottom of the code?
It's possible if you give the timer an argument
im blind
should i use a .then?
bullshit
@near veldt do you fking know how to do that
you just told him to use setTimeout
you didn't tell him how exactly to return the amount of time left for the cooldown to end
i know how
but y'all are too toxic
how am i toxic
nice assumption
@near veldt

hey there uh may i ask what coding language yall use for ur bots?
javascript
@vague horizon js
same lmao
not suprised
i see a lot of people who try to say they use javascript
but they use like bad websites
that dont even make u code
just buttons
and watermarks
lmao yea
and that stupid stuff
whats that
👀
non coding bot website?
yes
yes
lmao
var muteTimer = setTimeout(function, milliseconds, Date.now());
^If you give your timeout the current timestamp you can get time remaining with this:
timeRemaining: muteTimer._idleTimeout - (Date.now() - muteTimer._timerArgs[0])
Just throwing this in here now
btw
do any of u know
how to uh
do the authorization
also how do u get uh the bot dev role
That's something for #topgg-api - But you define "authorization" (or the password) in your bot's options for DBL
DSL?
you should ask in #topgg-api
lol
const db = require("quick.db");
module.exports = {
name: 'work',
description: "flip a coin!",
execute(message){
const cooldown = new Set();
const cooldownAmount = 3600000;
const expirationTime = Date.now() + cooldownAmount
const now = Date.now();
if(now < expirationTime){
const timeLeft = (expirationTime - now) / 1000;
message.channel.send(`You have worked recently! Please wait ${timeLeft} seconds before you can work again!`);
}
else {
if(message.author.id == 542278740537769985) {
const bal = new db.table(`${message.author.id}mybal`);
if(message.author.id == 542278740537769985) {
db.add(`${message.author.id}mybal`, 2000);
message.channel.send(`You got **2000** bowbucks for working...`);
}
else {
db.add(`${message.author.id}mybal`, 2);
message.channel.send("you got **2** bowbucks for working");
cooldown.add(message.author.id)
setTimeout(() => cooldown.delete(message.author.id), cooldownAmount);
}
}
}}
}
``` it doesesnt let me work even though its been like 2 days since ive done bow work
The cooldown code should be in your message event listener
not in every command
Did you follow the tutorial?
you can also just put the cooldown outside the execute function
you're doing everything wrong @hazy sparrow
The cooldown code should be in your message event listener
@cinder patio i jist want it for this command
Still
You can do it like flazepineapple said, but it's not flexible that way
What if you want to have another command with cooldowns later on?
i just make a temporary cooldowns collection in mongodb and add and remove stuff to the collection and when my bot restarts i delete the collection else everyone will be stuck on infinite cooldown
hello
What if you want to have another command with cooldowns later on?
@cinder patio thats not the problem
I suggest actually reading the whole command handler tutorial instead of copying the code blindly. Then you'll be able to see where to put the code. It's okay to copy code from guides / the internet, but you have to understand it. If you don't know where to put it then you don't understand it.
- i understand the code
- i didn't just straight up copy it
- wont it work if i put it inside the command file?
also 4. i didnt copy the command handler from the guide
tim told me
It depends where you put it. If you did understand it, you would've been able to put it in the right place. Do you think putting the entire cooldown code in the command's execute function makes sense, considering the function is executed every time someone does the command?
holy i didnt think of that
The set you are creating gets created every time someone runs the command. You should put it outside of that function
And maybe put cooldownAmount outside of it too, so you don't allocate memory for a number every time the command is ran
no
No
hello, why my DSJS bot's presence don't changing?
bot.user.setPresence({
status: "online", //You can show online, idle....
game: {
name: "Using !help", //The message shown
type: "STREAMING" //PLAYING: WATCHING: LISTENING: STREAMING:
}
});
```\
@hybrid roost Any errors?
activity not game
No errors
(I am calling this in bot.on('ready')
oh, I understand. Now I'm using bot.user.setActivity() and it working!
Question
How does it mean by the following
infrastructure_third_party_accounts_description: Must be between 100 and 2000 in length.```
how to make the execute() an async
const economy = require('../economy')
module.exports = {
name: 'balance',
description: 'shows ur balance',
cooldown: 5,
execute(message, args) {
const target = message.mentions.users.first() || message.author
const targetID = target.id
const guildId = message.guild.id
const userId = target.id
const coins = await economy.getCoins(guildId, userId)
message.channel.send(`${target.tag} has ${coins} Crystal(s)!`)
},
};```
if it has an await in the command
aysnc execute()
async execute(message, args)?
yes
k thx
np
I am tired of dying here
someone pls send me a snippet to save prefixes in an object so I don't have to request the DB every time
I tried something that isn't working
@outer perch 
what
let databeis = new ConectionToDeitBeis("hello", "learn", "your", "self");
databeis.run("SELECT * FROM users WHERE id = "1234";");```
const ref = db.collection('servidores').doc(message.guild.id);
const prefixes = new Object();
if (!prefixes[message.guild.id]) {
ref.get().then(doc => {
prefixes[message.guild.id] = doc.get('prefix');
});
}
const prefix = prefixes[message.guild.id];
this sends me prefix = undefined
yeah, it's copy paste.
.
you lol
I don't know
the only thing that makes sense is the ref.get there
the then function doesn't send the value outisde
can anyone help me with code of getting info of voters in our server channel
setting up mongodb
i gave myself a challenge that if i don't setup mongodb within 72 hours i will have to make a biggo giveaway
can anyone help me with code of getting info of voters in our server channel
@faint zenith you mean on DSL?
LOL ok
@faint zenith you mean on DSL?
@earnest phoenix yes dsl and dbl both
i made a code but its not working idk why
😔
Get information about who voted the server in the past 12 hours?
yes
we can do that in DBL not sure about DSL the DSL API is still in beta
Get information about who voted the server in the past 12 hours?
server or bot
hits up docs
i hits up docs i setup everything but its not working there they said contact in dbl server
but noone is helping here
😔
but noone is helping here
@faint zenith i said i am checking the docs for info on how to get information on votes
i foound it
ohhk
You need to have the webhook setup
wait we should chat about the API in #topgg-api
ohk
alright how do i hack R6 for bobux
Get information about who voted the server in the past 12 hours?
There's no API for DSL
so that's not possible
@outer perch the data inside .then() is not available outside
is it possible to make IDE convert JS to TS
you need to use async/await syntax instead of then
There's no API for DSL
but its possible for bots ? dbl
@outer perch the data inside .then() is not available outside
@quartz kindle I did this another way
I can assign values from a then to a variable outside then right?
const ref = db.collection('servidores').doc(message.guild.id);
const prefixes = new Object();
if (!prefixes[message.guild.id]) {
await ref.get().then(doc => { prefixes[message.guild.id] = doc.get('prefix'); });
}
const prefix = prefixes[message.guild.id];
you can, but the outside code will not wait for it
await
now it's getting the prefix I wanted, but it's going undefined right after
I'm just confused
if you're already using await, then just do ```js
if (!prefixes[message.guild.id]) {
let doc = await ref.get();
prefixes[message.guild.id] = doc.get('prefix')
}
AHA THAT WAY
also, if you define prefixes inside the message event, it will be redefined/reset every time
tfw you think you're somewhat of a dumbf*ck
also, if you define prefixes inside the message event, it will be redefined/reset every time
@quartz kindle I'd like to get around that
I thought the if statement would avoid that
like, if not in the object, retrieve from DB and put it in the obj
if it is, use from the obj
yes but the object needs to already be created
it is created
you cant create it again on every single message
const target = message.mentions.users.first() || message.author
const targetID = target.id
const guildId = message.guild.id
const userId = target.id
const coins = await economy.getCoins(guildId, userId)
const BalanceEmbed = new MessageEmbed()
.setTitle(`${target.tag}'s Balance`)
.setDescription(`Crystals: ${coins}\nTokens: 0`)
.setTimestamp()
message.channel.send(BalanceEmbed)```
again I didn't noticed what I did
where
I know javascript lets you program
without semicolons
but a programmer always needs to have that habit
nope
what is economy? how did you define economy?
@quartz kindle const economy = require('../economy') economy/economy.js
and what is economy.js?
the code for getCoins and addCoins
show it
undefined
undefined
undefined
undefined
+
undefined
+
undefined
- is the default prefix
why are the others getting undefined?
these are the prefix logs
@outer perch I know
@quartz kindle
const mongo = require('./mongo')
const profileSchema = require('./schemas/profile-schema')
const coinsCache = { 'guildId-userId': coins }
module.exports = (client) => {}
module.exports.addCoins = async (guildId, userId, coins) => {
return await mongo().then(async (mongoose) => {
try {
console.log('Debug Mode: running find one and update')
const result = await profileSchema.findOneAndUpdate(
{
guildId,
userId,
},
{
guildId,
userId,
$inc: {
coins,
},
},
{
upsert: true,
new: true,
}
)
console.log('Debug Mode: RESULT:', result)
coinsCache[`${guildId}-${userId}`] = result.coins
return result.coins
} finally {
mongoose.connection.close()
}
})
}
module.exports.getCoins = async (guildId, userId) => {
const cachedValue = coinsCache[`${guildId}-${userId}`]
if (cachedValue) {
return cachedValue
}
return await mongo().then(async mongoose => {
try {
console.log('running findone()')
const result = await profileSchema.findOne({
guildId,
userId
})
console.log('[DEBUG] Result:', result)
let coins = 0
if (result) {
coins = result.coins
} else {
console.log('[DEBUG] Inserting docs')
await new profileSchema({
guildId,
userId,
coins
}).save()
return coins
}
} finally {
mongoose.connection.close()
}
})
}```
Iferg is better than bobby
@cinder sandal what do the console.logs in there say?
nothing
you dont return coins if there is a result
just the error that coins is not defined in economy.js
@cinder sandal hello
because you did this lol const coinsCache = { 'guildId-userId': coins }
coins is undefined
???
so
how do i make it so Discord OAuth2 sends a HTTP POST request to the redirect URI instead of adding ?code= in the redirect URI
@quartz kindle u play cod?
no, also wrong channel for that
@quartz kindle it’s boobys channel
@quartz kindle u noob
@earnest phoenix how could you say that bleach
i should define it up0n it
and remove return coins?
@slender thistle NSFW in the channel
@earnest phoenix Keep this channel on topic of programming. Non-English goes to #general-int
No?
how do i make it so Discord OAuth2 sends a HTTP POST request to the redirect URI instead of adding
?code=in the redirect URI
special ping: @quartz kindle
I thought it’s of bobby plays
Isn’t it gaming discord server?
@earnest phoenix definetely no

@earnest phoenix i dont think you can
Ok what will I do there
ty
gg
i made an economy system in my bot now
Keep your off-topic conversation in the proper channel and avoid getting muted for misusing channels
why are people like this
oops i forgot we're humans
@earnest phoenix for eg > why are people like this
oops i forgot we're humans
@earnest phoenix
sigh
Im currently using these to load cogs in my python bot any shorter ways out there?
@earnest phoenix i dont think you can
@quartz kindle what about putting?response_type=smthin the OAuth URL
@slender thistle please feel free to take
What si load cogs
Not hard to move channels bro
ban speedrun?
Client..........???😂
i made an economy system in my bot now
@cinder sandal cool which database you use for storing stuff
@cinder sandal cool which database you use for storing stuff
@earnest phoenix mongo
@remote orbit not really
Tfw my mongodb connection has 6s latency :(
@remote orbit A simple list like ["utility", "fun"] and then a for-loop where you load f"Cogs.{cog}", where cog is each element of the list
@slender thistle mute?
Mainu pata nahi kidar jaana hai
@earnest phoenix #general-int me jaao agar hindi bolna hai kripya karke moderator ka baat sunlo bhai
Man said n word 
no
he didn't
@earnest phoenix main tain Punjabi Bol Rahain hain
god
why can't you understand
mongo is a good db
even more that good
Good for big data
Registered
Thu, Jul 16, 2020 8:37 AM
of course these noobs that take a whole year to understand simple shit
@earnest phoenix who all??
alright now i am going off topic
mongo is a good db
even more that good
@cinder sandal atlas or local mongodb?
which one you use
i go for atlas
Same
my VPS ain't trustable
@cinder sandal atlas or local mongodb?
@earnest phoenix atlas because i host on heroku
ATLAS
@earnest phoenix atlas because i host on heroku
@cinder sandal WHY HEROKU WHY WHY WHY WHY
hey
hi
is there any way to create your vps on your computer?
Relatiomal dbs can be faster in some use cases than non-relational
Wanna play cod cod cod
I wanna play cod cod
@slender thistle pls mute
mute me for 5 minutes i might come off as toxic if this guy won't stop

How about you leave this channel for on-topic discussions now after seeing me just mute someone for off-topic conversations in #development
||
||
should i store OAuth2 access tokens on the user's computer on in my encrypted MongoDB database?
they both have their pros and cons
Now, on to relational DBs. Is MS Access worth a try in production? 🤔
Ehhh
@quartz kindle I fixed some things here and there inside the code, now everything is doing fine
I personally don't like ms Access
@slender thistle
I'd rather draw out the diagrams, then implement them with SQL commands
Or would you consider it only as something to be used in a welcome-to-DB environment?
@slender thistle
@earnest phoenixwhy here
sorry for the ping
Block and carry on, also DM me for this
Atlas does
Lol
the key required to decrypt the files
i wanna store OAuth2 access tokens with encryption cuz storing it on user's PCs sucks
Eh
Encrypt the access token reversed with base64 😂
More of a config file use case
Encrypt the access token reversed with base64 😂
@slender thistle >security through obscurity
How bad is it, though?
Because it isn't real security
I'd be pretty confident that some decryption scripts would include something like that
Base 64 is a pretty recognizable format
not worth hacking
Even reversed
bearer tokens are enough to be stored in just memory
the user can just log back in if it's gone
what about storing it on the user machine
just store them in memory
but it'll eat the server RAM
...
no it wont
those are strings
it is a smol website through which people can manage stuff about the botum
express already takes 60% of CPU, no joke
yes but that is a string
in economy commands i want an random amount of money to be given (1-5), id i put it to say how much you got, it would say like you got 5 coins but you get 4 or less or an onther random number
how do i prevent that?
if you're worried about a string eating your ram you might as well not use node in the first place
apache suck, it takes alots of ram
if you're worried about a string eating your ram you might as well not use node in the first place
@earnest phoenix alright moving to browser-based javascript
but it'll eat the server RAM
@earnest phoenix depends on if the string length is massive or not.
uhhh yeah
snowflakes grow in size as more people start using discord and never delete their accounts before dying
simply hashing the token in memory protects the token from being sniffed from other processes reading the memory, which would be the only way to access something being stored in machine memory
simply hashing the token in memory protects the token from being sniffed from other processes reading the memory, which would be the only way to access something being stored in machine memory
@earnest phoenix if i hash the token how the fuck will i reverse it to get it back
let random = Math.floor(Math.random() * 100 );
how do i return the exact result of it
Hashing is one way
yeah but
you can reverse lookup
you dont even have to hash
hashes can't be reversed
just manipulate the original string to be shuffled so it can't be read from memory
Sounds like obscurity
and not just having a diffrent number
like message.channel.send('random: ${random} ${random2}')
yeah
@earnest phoenix we need our client secret to actually use OAuth tokens right? well then it won't be a problem if the token is leaked unless my client secret is also leaked
random2 would be diffrent from random
you have bigger concerns if you leak your client secret
which is unlikely
anyways
yeah
The client secret is used to ask for tokens, yeah?
i want the random2 be the result of random
how
storing bearer tokens in memory will not eat the memory, they are strings and bearer tokens expire after a week if you don't refresh regardless so just drop it from memory after a week
that's why i'll store the tokens in a temporary MongoDB collection that is deleted every 24 hours (which is what top.gg does)
k
but how will i store the tokens in memory anyways?
make an object where every property name is a user's IP address and the property value is the token?
or discord.js collection jazz?
or localstorage jazz?
or cache jazz?
array/map of the token and unix timestamp of entry
i want the
random2be the result ofrandom
how
@cinder sandal
how do i return the exact result of it
@cinder sandal What do you mean "exact"? Just remove theMath.floor? 🤔
Math.random() * 100 will return a float, and if that's not what you want, I don't know what else
Applying common sense and knowledge from Python, basic JS can be fairly comprehensive
Math.floor(Math.random() * 100)
Will be the code
hey i want to get this image link to just display as image
instead of getting a link
it iss one image
wtf
const coins = Math.floor(Math.random() * 50);
const guildId = message.guild.id
const userId = message.author.id
const NewCoins = await economy.addCoins(guildId, userId, coins)
message.channel.send(`You walked on the streets and picked up ${coins} Crystal.`)
},
};```
they are all the same
You can't add images in any fields other than the image one. You could try to use emotes, which doesn't sound like what you want
uhh wut
my code would add around 50 money in my balance
So you guys are aware....
MAP is slow as hell; don't do it. PLEASE just don't!!!!
Your for-statement beats it ten-folds.
0-50
fun fact
webhooks can use twitter embed's multi image support
So you guys are aware....
MAP is slow as hell; don't do it. PLEASE just don't!!!!
Your for-statement beats it ten-folds.
@unique patio good luck convincing these guys here of that one lol
So you guys are aware....
MAP is slow as hell; don't do it. PLEASE just don't!!!!
Your for-statement beats it ten-folds.
@unique patio discord.js collections & our own methods of doing stuff intensify
673940 OPS/s on for
206931OPS/s on MAP
so how do i give the exact amount in the balance
and not like it says u got 50 but it give you 20
Yeah I modified my discord.JS
Calculations
isn't a map just O(1)
Operations per second
oh
@cinder sandal wtf that code is perfectly correct how the hell is there an error
You can perform more operations in a for-loop in 10 seconds
than a map command
and go more complexed.
@earnest phoenix it's not an error
how is a map so slow in node
hey
It just is...
embed.setThumbnail(`${location.current.imageUrl}`)``` it is saying location is not defined
Map can be fast in some scenarios but not always, it gets outweighed
c# dictionary lookups are O(1) being directly keyed by their hash
with our default iterations
while i am sure this is the actual variable
Cuz ur code is wrong @eternal osprey
@unique patio but still it is our own choice to do stuff
and why so ace
that it wouldn't give the exact amount that the message says to the balance
random amount between 5 and 0
READ CONSOLE
smh
@eternal osprey is location defined AFTER that line of code
console.log()
i have read console
show code
Yup; but if you want to aim for practicality, and efficiency JSBench all code.
yes it is
You intend to use.
think about it @eternal osprey
yes it is
@eternal osprey you can't use a variable if it is defined AFTER the line that is asking for it
If you really care about performance, you might want to go strictly typed and compiled languages :p
}
const title = "**Cities/countries ranked by: ** " +`**${skytext}**`;
let embed = new Discord.MessageEmbed()
.setTitle(title);
locations_found.slice(0, 10).forEach(location =>
{
embed.addField(
`${location.current.observationpoint}`, `${location.location.lat}`, `${location.location.long}`, true
);
});
embed.setThumbnail(`${location.current.imageUrl}`)
embed.setImage('https://media.giphy.com/media/CKsIi206Ntz4k/giphy.gif')
.setColor('#FF0000')
.setFooter("Command hosted for Pokehub`s community!");
message.author.send("<@" + message.author.id + ">")
message.author.send({embed});
}
}
});
const coins = Math.floor(Math.random() * 50);
const guildId = message.guild.id
const userId = message.author.id
const NewCoins = await economy.addCoins(guildId, userId, coins)
message.channel.send(`You walked on the streets and picked up ${coins} Crystal.`)
},
};```
@cinder sandal this would say like you found 1 - 50 coins but it gives you an diffrent amount
If you really care about performance, you might want to go strictly typed and compiled languages :p
@slender thistle this
what math.floor does
Floors it
@eternal osprey location is literally not defined anywhere
is it required for math.random
in ofrEach
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor @cinder sandal
it is defined above
@slender thistle There's that, but the difference here was1/3
back to 4th grade you go
one question: is math.floor required for math.random?
Rounds down
Imagine what a a lower-level language could do
@eternal osprey that's a callback function
It's not required, but do you want decimal numbers as user currency?
variables defined inside callback functions can't be used outside
Which is something with a decimal
how do i make a random number between 1 and 50 without math.floor
Imagine what a a lower-level language could do
@unique patio My brain hurts when it comes to memory pointers. I'm too used to Python's sugarcoating :p
how do i make a random number between 1 and 50 without math.floor
@cinder sandal it will but the number would have upto 10 decimal places
you floor it because Math.random() returns a decimal from 0 to 1 which you multiply based on what range you want
lol 😛
Math.random(1 * 50);
I try to avoid python, for Js/C++/C# or Java
should it be like that
Used it a lot tho during early bot days
3 years, still using it for my numerical methods assignments 😂
lol
please stop being a help vampire and read what you're being told
I try to avoid python, for Js/C++/C# or Java
@unique patio how the hell would you use python inside those languages
this
i gave up on python after 3 whole hours
I like the python a lot, but it's not syntax appropriate for me
@unique patio English is a giant meme boy
bracket style languages are my togo
i gave up on python after 3 whole hours
@earnest phoenix I gave up when it told me not to mix spaces and tabs
I can do it but that is ugly as hell
Time to make a bracket-styled Python interpreter in Python...
sin.....

Do it shivaco I'd probably use the language more
For me, I need to visually see errors GG with that
otherwise
I'll probably fail if I do it now but maybe someday™️
Think someone has done it though with a linter.
I use PyCharm and it helps a lot
An IDE?
Yup
Never heard of it, I usually used one of them all in ones
visual studios, eclipse
you know.... lol
Sometimes just running flake8 on my projects to spot stuff I can improve
Light-weight and correcting on the go; or auto-formatting. That's all I need.
😂 especially with stuff running in background
how do i generate a number between 1 and 5 or any other number
i forgot it
https://www.w3schools.com/js/js_random.asp @cinder sandal
Heh, simple stuff gang
Make a function for it
i use the node editor from the terminal
any questions
nano ftw
i use nano for git commits
I only really chase the big-boy IDE's for project management when I got like 5-20+ files on the go for one project.
Same
Helps pointing the fi nger to imports/requires better
How can I get the dominant color and color palettes from a url?
Which module or api should I use?
Could you simplify on what you mean?
You want to take CSS attributes from another domain?
my balance command shows Crystals: undefined
after i et some coins it returns the normal amount that i have.
how do i prevent the undefined to appear
bruh nobody gonna make ur bot for u
google it read docs
read console
console.log()
debug it by ur self
Value needs setting ahead of time
Possibly starts out undefined and called in that state
then when it's set; you no longer see it. Simple issue, make sure you set correctly before first call.
or check if value is undefined to not return on state.
Yeah console.log (keep that on ctrl+s) for checking all your work/calcs.
const economy = require('../economy');
const { MessageEmbed } = require('discord.js');
module.exports = {
name: 'balance',
description: 'shows ur balance',
cooldown: 5,
async execute(message, args) {
const target = message.mentions.users.first() || message.author
const targetID = target.id
const guildId = message.guild.id
const userId = target.id
const coins = await economy.getCoins(guildId, userId)
const BalanceEmbed = new MessageEmbed()
.setTitle(`${target.tag}'s Balance`)
.setDescription(`Crystals: ${coins}\nTokens: 0`)
.setTimestamp()
message.channel.send(BalanceEmbed)
},
};```
any errors?
What is this "economy"
Better not be json
did you fix the non-returned result i told you about? @cinder sandal
So you ran an await
oh it is a module.exports ?
You're in async vs sync....
You're going to return undefined cause the balance embed is not sent in promise
to the await
AKA wait for the coins to get value, and send it to
not send it before.
did you fix what i told you to fix?
in the code you showed before, you were not returning anything if the user had coins
no didn't fix
don't want to fill the chat with code but ok
use a bin
const mongo = require('./mongo')
const profileSchema = require('./schemas/profile-schema')
const coinsCache = {}
module.exports = (client) => {}
module.exports.addCoins = async (guildId, userId, coins) => {
return await mongo().then(async (mongoose) => {
try {
console.log('Debug Mode: running find one and update')
const result = await profileSchema.findOneAndUpdate(
{
guildId,
userId,
},
{
guildId,
userId,
$inc: {
coins,
},
},
{
upsert: true,
new: true,
}
)
console.log('Debug Mode: RESULT:', result)
coinsCache[`${guildId}-${userId}`] = result.coins
return result.coins
} finally {
mongoose.connection.close()
}
})
}
module.exports.getCoins = async (guildId, userId) => {
const cachedValue = coinsCache[`${guildId}-${userId}`]
if (cachedValue) {
return cachedValue
}
return await mongo().then(async mongoose => {
try {
console.log('running findone()')
const result = await profileSchema.findOne({
guildId,
userId
})
console.log('[DEBUG] Result:', result)
let coins = 0
if (result) {
coins = result.coins
} else {
console.log('[DEBUG] Inserting docs')
await new profileSchema({
guildId,
userId,
coins
}).save()
return coins
}
} finally {
mongoose.connection.close()
}
})
}```
uh
hastebin/pastebin/sourcebin
:3
see
huh
Yup^
if result, coins = result.coins
but you dont return it
so it returns undefined
you only return coins if there is no result
const mongodbpass = process.env.MONGODBPASS;
const uri = `mongodb+srv://replit:${mongodbpass}@codeco-cluster.3pscq.mongodb.net/userData?retryWrites=true&w=majority`;
const MongoClient = require('mongodb').MongoClient;
const client = new MongoClient(uri,{useUnifiedTopology: true, useNewUrlParser: true});
client.connect(err => {
if (err) throw err;
});
This throws the error: https://hastebin.com/uqifovemip.php
Why does this happen?
Nailed @quartz kindle
so i should remove return coins?
^
please don't be a help vampire
be a help cow
const mongodbpass = process.env.MONGODBPASS; const uri = `mongodb+srv://replit:${mongodbpass}@codeco-cluster.3pscq.mongodb.net/userData?retryWrites=true&w=majority`; const MongoClient = require('mongodb').MongoClient; const client = new MongoClient(uri,{useUnifiedTopology: true, useNewUrlParser: true}); client.connect(err => { if (err) throw err; });This throws the error: https://hastebin.com/uqifovemip.php
Why does this happen?
special ping: @quartz kindle
or with single |
if(result) {
coins = result.coins
} else {
save coins
coins = 0
}
return coins
not double*
@hasty hedge
what
the bot is muted anyways lol
I'd simplify that a bit, on the single return on any if they return true or with vals
@earnest phoenix idk i dont use mongo
try googling the error: connection monitor closed
conditional statements are fun
Search the world's information, including webpages, images, videos and more. Google has many special features to help you find exactly what you're looking for.
Tim said the thing. Aww edit
Lgtm
https://google.it/search?q=mongodb+connection+error+monitor+closed
typed it all out
italian google
Lol
No
:))
Been here for like 5 mins, does that make me mod?
😛
google.it sounds cool
@cinder sandal it's really cool, especially when you realize it's all in Italian
Search the world's information, including webpages, images, videos and more. Google has many special features to help you find exactly what you're looking for.
yes
no
Oml
@earnest phoenix you'll get muted role if you ping devs for no reason
no
god stop
Well bye
stop
adding return coins to the if (result) fixed the Crystals: undefined
@slender thistle
We gottem
yeah
There was an admin in the chat, why mention multiple mods, derp
now we're getting off topic
const title = "**Cities/countries ranked by: ** " +`**${skytext}**`;
let embed = new Discord.MessageEmbed()
.setThumbnail(`${location.current.imageUrl}`)
.setTitle(title);
locations_found.slice(0, 10).forEach(location =>
{
embed.addField(```
still undefinned location
can someone help me with suggestions on where to set the thumbnail so it stays defined.
You can put it in the forEach
since there is only 1 thumbnail, putting it in the forEach will give you the thumbnail of the last location
Or you can get the first location and set the thimbnail to that
or you can just not add a thunbnail
random.randint?
between
I don't remember if it's inclusive or exclusive
inclusive - randint(1, 10) can return 1 or 10
exclusive - randint(1, 10) cannot return 1 or 10
o ok
well i need it to return those
well
not really
im ok
its fine regardless
Oh yeah it's inclusive
even better
in CanvasGradient.addColorStop() can i pass a percentage instead of a decimal?
I want to make a antiswear bot in discord.js but theres one issue, i need to do a trigger command, So none of the anti swear features can be used or deleted until someone with admin permissions type %trigger, and they can disable the anti swear again with %trigger command, Is there any guides or things i can use like a package to do this?
A global Map object where key is guild ID and value is a boolean
or even a damn array that includes guild IDs where antiswear is on
alright ty
why not, code
how can i combine 2 args?
Define "combine"
Curious if any of you guys tried hosting off a phone before and noticed idling properties, but once kicked in, no issues?
Running several bots off my samsung and it works great till it goes idle for 20-30 mins 😐
Never tried hosting on a phone, personally. Seems like a pain in the ass to do to an extent 
^
My hardware tho is giving issues tho, not ideal for it cause of its power-savers/etc.
plz
Trust me if you don't got enough ram or good enough CPU it's gonna be horrible
@pale vessel can you use HEX colors in CanvasGradient.addColorStop()
My projects are always low-ram usage/high calc; generally get away with an arm cpu
1-2GB ram
my bot only uses 30mb ram
gradient.addColorStop((1 / 7) * 2,"#4B0082");
have like a bunch of args be one
@drifting wedge
https://discordapp.com/channels/264445053596991498/272764566411149314/753883938304294962
any helppppppppppppppppppppppppppppppppppppppp?
@vale garden god stop being a help vampire
@unique patio as well, the more servers your bot is in the more ram it might use
how can i combine args without quotes
@white drum I haven't noticed that at all, stable ram usage varies on my active memory allocations per server
cuz i do?
@unique patio understandable
So if I have 60 servers I allocate ahead the space for them, then it stays fixed entire time, no leaks
My issue mostly is my phone goes idle on me, it stays connected but it takes 2-3 seconds extra to get back into the game
and post again
I run my bot on my server pc
I leave my PC on all the time
That'd work 😛
If you have issues with that, heroku is a decent free option to consider
at Client.<anonymous> (/home/container/server.js:93:11)
(node:25) 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(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)```
If you have issues with that, heroku is a decent free option to consider
@white drum
I generally don't over-kill, so by that I'll run server bare-minimal why run top-end for a low-resource app
it worked before btw
So in my case, 2.5-5watts to power the bot 24/7
let channel = client.channels.cache.find((x) => (x.id === "709450453699526707"))
let data = await canva.welcome(member, { link: "https://cdn.discordapp.com/attachments/702477981570039939/739160066862612631/PicsArt_08-01-10.07.56.png" })
let wembed = new discord.MessageEmbed()
.attachFiles([{
attachment: data,
name: "hello.png"
}])
.setColor("RANDOM")
.setImage("attachment://hello.png")
.setThumbnail(member.user.avatarURL())
.setDescription(`** Welcome <@${member.user.id}> To our Server**
▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
**Make sure to**
▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
** #🌆╎rules Read and Follow our Rules.**
** #🌃╎announcement Be upto date with our Server Updates.**
** #💭╎general-chat Make new friends in the chat and be active.**
▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
**We hope that u have fun in the server!**
▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
**User Join Position - ${member.guild.memberCount}**
**User Joined Discord - ${member.user.createdAt}**`);
channel.send(wembed)
});```
@weak rain channel is undefined
^
true true
lol

why here

