#development
1 messages · Page 914 of 1
those gifs look bad on mobile btw
Sorry :/ Am kind of on a rush
yea on mobile they strenthed af :/
so const member = with what
@high geode where is this code used? show full code
Hi so I'm getting the error that it can't read sell_summary of undefined any idea why? Am I doing something wrong?
data.products[miniontype].sell_summary[0].pricePerUnit(This is an API btw)+
@tulip ledge do console.log(data.products)
i think on guild member add event
how can I get urls from a string as an array (I did use a node module for that but it doesn't detect urls like discord attachment urls)
see if that entry exists
link i answered that already lol
@high geode full code
"im a string https://dekbot.com".match(/(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[-A-Z0-9+&@#\/%=~_|$?!:,.])*(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[A-Z0-9+&@#\/%=~_|$])/igm)
do String(miniontype) then @tulip ledge
hm
wait
@tulip ledge console.log(miniontype)
:))))))))
The api stores it as CLAY_BALL not CLAY srry xd
@high geode just use hastebin goddamm
at least use hastebin or something
also why is your dbl token in the picture
omg

lol hardcoded token
@high geode you're trying to use member in the top level, you cant do that, there is no member there
you dont even need member
i need user
if you want a guild, just do client.guilds.cache.get()
right?
what do you want?
does anyone know how to allow iframes with nginx? I'm having issues with that
lulz
then you need to use the memberAdd event
you're putting that code in top level, outside of any event
the way i showed earlier worked for me hector, idk why it wouldnt for you 😦
yeah it's weird
you could just allow iframes for all sites
how
current one: add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline' frame-ancestors 'self' https://top.gg/bot/534632914445664267;" always;
bot.on("guildMemberAdd", member => { // here is your member
member.guild.channels...
})
``` @high geode
now you have a proper context to get a member from
thanks
whats your domain that your trying to iframe hector?
whats the const for message?
http cannot iframe https iirc
what message?
cant I use bot.on("guildMemberAdd", member, => { // here is your member
message.channel.send('message')
})
?
there is no message in guildMemberAdd
guildMemberAdd gives you a member
you get a guild from the member
you get a channel from the guild
i need when someone joines that guild id
then you send to that channel
https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_iframe is a useful site for testing your iframes.
why not just make a .html file and test it yourself?
shows that for my domain, which is correct as i only allow my site and top.gg bot page to iframe
@quartz kindle
bot.on('guildMemberAdd', async member => {
bot.guilds.get("699189120945094757").channels.get("706161523155796058").send(`message`);
}```
why are you mixing client with bot
whats your domain that your trying to iframe hector?
@neat ingot its https://deltabot.tech
yes, its good if you want to send a welcome message always to the same guild
even if the member joins a different guild
@neat ingot it could be because of the html tag? I just have <iframe src='https://deltabot.tech></iframe>
oh
I think I'll just put a screenshot of the site if I can't put an iframe
then what must i edit like when a member joines my server, that guild to send a message in a channel?
when a member joins
you get the guild from the member
is it good?
yes
member.guild.channels.find("name", "welcome")
but change find to a function
but where must i insert that
.find(channel => channel.name === "welcome")
omg
/app/events/message.js:8 let perms = client.elevation(message); ^ TypeError: client.elevation is not a function at Client.module.exports.message (/app/events/message.js:8:22) at emitOne (events.js:121:20) at Client.emit (events.js:211:7) at MessageCreateHandler.handle (/rbd/pnpm-volume/13b65e33-103e-4d0a-8ef1-675f018a70c7/node_modules/.registry.npmjs.org/discord.js/11.6.4/node_modules/discord.js/src/client/websocket/packets/handlers/MessageCreate.js:9:34) at WebSocketPacketManager.handle (/rbd/pnpm-volume/13b65e33-103e-4d0a-8ef1-675f018a70c7/node_modules/.registry.npmjs.org/discord.js/11.6.4/node_modules/discord.js/src/client/websocket/packets/WebSocketPacketManager.js:108:65) at WebSocketConnection.onPacket (/rbd/pnpm-volume/13b65e33-103e-4d0a-8ef1-675f018a70c7/node_modules/.registry.npmjs.org/discord.js/11.6.4/node_modules/discord.js/src/client/websocket/WebSocketConnection.js:336:35) at WebSocketConnection.onMessage (/rbd/pnpm-volume/13b65e33-103e-4d0a-8ef1-675f018a70c7/node_modules/.registry.npmjs.org/discord.js/11.6.4/node_modules/discord.js/src/client/websocket/WebSocketConnection.js:299:17) at WebSocket.onMessage (/rbd/pnpm-volume/13b65e33-103e-4d0a-8ef1-675f018a70c7/node_modules/.registry.npmjs.org/ws/6.2.1/node_modules/ws/lib/event-target.js:120:16) at emitOne (events.js:116:13) at WebSocket.emit (events.js:211:7)
.-. welp
verified bot dev
const member = "";
i sue SAMEORIGIN too though inn my setup, so idk why thats disallowing it
@neat ingot uh I don't have that option
@copper cradle shut up, i really dedicate my self to learn.
you don't need much to become verified bot dev @copper cradle
message.author.id can't be null
if(!msg.author.id == "492506057814310923") {return;}
afaik
doesn't work
@high geode no
i removed quotes
i'd try adding the x-frame option for sameorigin then, just to see how it responds.
still not working
@topaz fjord I know lol
add_header X-Frame-Options "SAMEORIGIN" always;
also: remember to reload nginx conf. ive forgott hat a few times and wondered why changes werent working lol
doesn't work
if (message.author.id === 'the id')
don't use !message.author.if
easy
don't use ! if you don't know what it means
@neat ingot
it shouldn't have worked with !message.author.id
! is a negation operator
aha fml
ye
then why are you using it?
if(!msg.author.id == "492506057814310923") {return;}
@elder garnet take out the ! in front and replace the == with !==
ima try again
@neat ingot do I have to replace SAMEORIGIN by my bot's page?
ok
proxy_hide_header X-Powered-By;
#proxy_hide_header X-Frame-Options;
add_header X-Powered-By "DekitaRPG" always;
#add_header X-Frame-Options "" always;
#add_header X-Frame-Options "ALLOW-FROM (https://top.gg/bot/652216670370398231)" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Content-Type-Options "nosniff" always;
# enable strict transport security only if you understand the implications
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
add_header Content-Security-Policy "default-src * data: 'unsafe-eval' 'unsafe-inline'; frame-ancestors 'self' https://top.gg/bot/652216670370398231" always;
#add_header Content-Security-Policy "script-src 'self' 'nonce-ZGVrYm90UkQ'" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Feature-Policy "accelerometer 'none'; camera 'none'; geolocation 'none'; gyroscope 'none'; magnetometer 'none'; microphone 'none'; payment 'none'; usb 'none'" always;```
is all the headers i use in my nginx
rip formatting lol
going to try
ummm help ?
@sweet spade client doesn't have an elevation method
where did you copy that code from
still doesn't work
if(msg.author.id !== "492506057814310923") {return;}
where did you put that if statement at
ima console log
var args = msg.content.split(/[ ]+/)
if(msg.content.startsWith(config.prefix + "eval")) {
if(msg.author.id !== "492506057814310923") {return;}
eval(args[2])
}
in the
client.on('message', async msg => {
what does happen
you what
@elder garnet not an answer to your question, but if your doing a single line if statement, you can drop the {}. for example:
if(msg.author.id !== "492506057814310923") return;```
ima try with a console
now I take error from event loader
show
@weak parrot is @707618473966043227 approved?
{return;} is really ugly coding, no offense
@sweet spade the error isn't coming from that file
duh
read the error
the fact that it says eventLoader.js doesn't mean the file has an error, if you try to read the rest of the error it says 'cannot find module eventLoader.js'
which means that in your main file
where you're requiring eventLoader js you're getting an error
index requiring eventloader so... I need to delete it or change it ?
oml
show the code in your index file
did you make your bot asking should I delete or change
hector, can you try adding
https://www.w3schools.com/to the csp for frame-ancestors
@neat ingot still getting the same error
@copper cradle nope just I want solve that problem quick :p
you require quick.db twice 👀
weird
tbh csp is a dick. i had a bunch of trouble getting all mine working as well. havent touched it since incase it breaks again lol
the file is where it should be
and you're requiring it correctly
do you require it anywhere else?
Seems it's still in queue @earnest phoenix
@weak parrot Ok Thx
hmm Im going to take code in my another bot It can be solve problem I think
I will try that
https://content-security-policy.com/ is a site i got most of* my reference information from for csp's
@neat ingot I changed the header to yours (mine wasn't exactly similar), now its not giving any log at all
also do you think it could be blocked by cloudflare?
it's working tho
uh but its not showing for me
lmao
I made a custom prefix command with quick.db and now i want to ask, if i want to pun in another command ${prefix} i should define prefix like that?
let prefix = db.fetch(`prefix_${message.guild.id}`)
but remove that white shit from dbl
@earnest phoenix yes.
but its still not showing for me
lol
did discordmessage.delete get changed?
@earnest phoenix i did this but when i use a command with ${prefix} in it it doesn't work
oh, you have your support page directly on your site, thats neat, ill have to pinch that idea 😄
all of the sudden I'm getting errors on code that I didn't touch
also: gotta love those font awesome icons 😄
thanks lol
@earnest phoenix do you defined prefix in (message.js)?
I need help I’m trying to make a basic private bot for shits n giggles type but I want it so where if a command is entered it’s deleted and replaced by the outcome I can’t see anything on google that answers my question
@earnest phoenix i have defined once when i made the custom prefix in index.js, and then if i want in a command.js it doesn't work
my bot
yikes
what the
wow, dbl blocks a ton of things on your page
@neat ingot maybe because its a sandbox iframe
anyone have any idea why my msg isn't a valid object?
@earnest phoenix interesting..
@earnest phoenix oh nevermind, i solved it
@maiden mauve message.delete()'s options are an object now
@maiden mauve do {timeout: 5000}
@maiden mauve I’m having that exact same issue 😂 with deleting message
ahhh
lulz, f
very recent change?
no
hmm
weird, I just started getting the error today
did you just update d.js?
ofc
updated a week ago
its possible I just didn't wait for the event to occur for some time
thanks for heads up
@earnest phoenix any idea why after i changed the prefix from a server the commands don't work with the changed prefix but with the old one ?
another reason to switch
[ERR_INVALID_ARG_TYPE]: The "id" argument must be of type string. Received undefined trying to switch from command.execute to module.exports.run
lol usually its firefox blocking things that chrome doesn't
Someone who know quick.db can help me ?
fml, now i too need to deal with this crap lol
step 1, fetch message,
step 2, call delete on message.
lmao
ok :v
there's no way to bypass that?
dont use chrome?
LOLLLLLLLLLLLLLLLLLLLL
thats not a solution
but true
it's built into google
thats not a solution
@strange mango agreed
mixed content has been deprecated for ages no? it always showed the warning that it would be blocked in the future
this suggests its from loading resources via http, im certain my site doesnt do that though :/
do resources you load also load resources?
the only external resource is google analytics :/
everything else is hosted on site
and i guess paypal too, but thats on a different route that isnt the one being framed.
(node:4384) UnhandledPromiseRejectionWarning: DiscordAPIError: Unknown Message
at C:\Users\Usuario Estandar\node_modules\discord.js\src\client\rest\RequestHandlers\Sequential.js:85:15
at C:\Users\Usuario Estandar\node_modules\snekfetch\src\index.js:215:21
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(node:4384) 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:4384) [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.
(node:4384) UnhandledPromiseRejectionWarning: #<Collection>
(node:4384) 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: 3)
oooooookk
if (command === 'deletemessage') {
// Await !vote messages
const filter = m => m.content.startsWith(`yes`);
// Errors: ['time'] treats ending because of the time limit as an error
message.channel.awaitMessages(filter, { max: 2, time: 60000, errors: ['time'] })
message.channel.fetchMessage(args[0])
.then(message => message.delete())
.catch(message.channel.send('Error al no poder eliminar el mensaje'));
}
@neat ingot actually I think it was just missing a colon, but now its saying Refused to display 'https://deltabot.tech/' in a frame because it set 'X-Frame-Options' to 'sameorigin'. again. Can you tell me if it works on firefox?
nah blocked again
need help with a let commands argmunet
let commands = {}
does something go in the parenthesis
@strange mango i think thats because of your site
why
k lemme remove that header
Is anyone familiar with Heroku and might be able to help me figure out how why my branch won't deploy?
I removed the header but its still giving the error
Hey. I'm a bit confused as to why I keep getting a null error in my code. All I do is talk (although that does trigger the client.on('message', message =>) and don't know how to fix it. Can anyone help me out here?
Code: https://srcb.in/31c26308f8
Error: https://srcb.in/4289777473
member is null. Was the command used in a guild? Is the guild member cached?
Hey there! I'm having a problem.
Guess I don't full understand discord.js but I can't figure out how to listen for new reactions on a message after the bot restarts.
Currently I'm listening for the messageReactionAdd even on the client.
I want to make the bot give out a role to users who react in #rules (when they accept rules)
the event doesn't emit on messages that aren't cached
you should try using partials
I tried fetching messages in the channel but I guess that doesn't cache them?
const channel = this.guild.channels.cache.get(
"chan_id",
) as Discord.TextChannel;
channel.messages.fetch({ limit: 100 });
If the message is old then that won't work, using partials is the only way to do it
or you can save the message ID in a database and fetch it when the bot starts up
don't you need to resolve the promise first
it resolves itself
He's not using the returned messages from the fetch so no
Since I don't need the value(s) then I don't need to use await or .then
My idea was to fetch the messages so that it puts them in the cache so they'd work with messageReactionsAdd.
oh yeah nvm thought it took an api action.
Not necessarily everywhere though. In this case I should await the promise but I wouldn't necessarily agree that it's better practice in general.
Also, thanks @cinder patio. Forgot to respond!
I'll take a look at partials 
yeah but if it fails for whatever reason u cant handle it and you'll just get an unhandled promise rejection error
better to await and wrap in try catch
Hey can someone help
if you ask...
Im trying to make a bot but when I do some commands it send 2 repones
-ask2ask
EDIT: forgot it's for mods only
show us the code too lmao
Im trying to make a bot but when I do some commands it send 2 repons
@merry portal see if you're not creating two clients
?
also naming your self mee6 isnt the best idea. Showing the code will make it easier for us to find the error
const Discord = require('Discord.js');
const bot = new Discord.Client();
const token = ';
const PREFIX = '?';
bot.on('ready', () =>{
console.log('this bot it online')
})
bot.on('message', message=>{
let args = message.content.substring(PREFIX.length).split(" ");
switch(args[0]){
case 'ping':
message.reply('your mom')
break;
case 'website':
message.channel.send('')
break;
case 'info':
if(args[1] === 'Version'){
message.channel.send('Version 1.0.1');
}else{
message.channel.send('Invalid Args')
}
break;
case 'clear':
if(!args[1]) return message.reply('Error please Define secound arg')
message.channel.bulkDelete(args[1]);
break;
case 'embed':
const embed = new Discord.MessageEmbed()
.setTitle('User Info')
.addField('Player Name', message.author.username)
.addField('Version', '1.0.1')
.addField('Current Sever', message.guild.name)
.setColor(0x89FFA6)
message.channel.send(embed);
break;
}
const Discord = require('Discord.js');
const bot = new Discord.Client();
const token = '';
const PREFIX = '?';
bot.on('ready', () =>{
console.log('this bot it online')
})
bot.on('message', message=>{
let args = message.content.substring(PREFIX.length).split(" ");
switch(args[0]){
case 'ping':
message.reply('your mom')
break;
case 'website':
message.channel.send('')
break;
case 'info':
if(args[1] === 'Version'){
message.channel.send('Version 1.0.1');
}else{
message.channel.send('Invalid Args')
}
break;
case 'clear':
if(!args[1]) return message.reply('Error please Define secound arg')
message.channel.bulkDelete(args[1]);
break;
case 'embed':
const embed = new Discord.MessageEmbed()
.setTitle('User Info')
.addField('Player Name', message.author.username)
.addField('Version', '1.0.1')
.addField('Current Sever', message.guild.name)
.setColor(0x89FFA6)
message.channel.send(embed);
break;
}
fixed
now we can see it lmao
why is everything blue?
do you have two instances running
cuz he forgot to terminate a string
const token = ';
?
- const token = ';
+ const token = '';
thank u mr. git
why is everything blue?
discord birthday soon
misly terminate that string plz
show where you login
bot.login(token);
also i know its offtopic but please check your spelling
it's either you have more than one instance running or you login some where weird in your code. can you upload your entire file to a site like https://hastebin.com as what you previously showed us is not the entire thing.
Ok
also would recommend making a command handler
It could listen to the event twice as well.
That was my first thought, don't know if this is the full code or not.
And could you provide screenshot of the problem?
What command you're sending and what you're receiving.
also @merry portal how old are you?
you know instead of calling out publicly you can report to a mod right

good point
But can someone help
smh, underage
Well hey, at least he's interested in development 
shouldn't be on discord anyway.
how i upload a pip of python?
Hey! I had success with the partials but now I'm wondering about the "raw events" solution.
https://github.com/AnIdiotsGuide/discordjs-bot-guide/blob/master/coding-guides/raw-events.md
Any opinions?
Hi quick question, how do you host images under custom domain?
Like https://conner.something/gghhhh
And the image would pop up?
image uploader & sharex
Well there are many approaches but the one that comes to mind instantly is that you can use .htaccess rewrite and php on a webhost.
So can I host the images on a same website host?
Sure but it really depends on the project.
If the images are going to be accessed a lot and if you need performance then you should think about a cdn.
You can still use the webhost to display the images under that custom path.
I'm just thinking of uploading screenshots.
Cannot read property 'get' of undefined
at
let commandfile = bot.commands.get(cmd.slice(prefix.length));```
code :
```js
let prefix = botconfig.prefix
let messageArray = message.content.split(" ");
let cmd = messageArray[0];
let args = messageArray.slice(1);
let commandfile = bot.commands.get(cmd.slice(prefix.length));
if(commandfile) commandfile.run(bot, message, args);
if(commandfile) db.add(`commandran_${message.guild.id}`, 1);```
Add if (!commandfile) return to your code @earnest phoenix
Oky
wdym?
then no queue :d?
yea
why is that not changing the background color?
from the mozilla mdn docs on Date() I get error Date.prototype is not a constructor
what i'm trying to do is, have my date created differently when my bot comes online
so instead of using Date().toString() I build my own showcase of current day, month, year --- current time
on the docs it's showing that Date.prototype.getDate() is the usage, and I do this code:
bot.on('ready', async function() {
const tn = new Date.prototype;
console.log(`${bot.user.username} is online.\n${tn.getDate()}/${tn.getMonth()+1}/${tn.getFullYear()} --- ${tn.getHours()}:${tn.getMinutes()}:${tn.getSeconds()}`);
const status = await bot.db.query(`SELECT * FROM botStats`).catch(console.error);
if (status[0].motd.length > 1) {
await bot.user.setActivity(`${bot.guilds.size} servers // fl.help / MOTD: ${status[0].motd}`, { type: "WATCHING" }).catch(console.error);
}
let gIDs = bot.guilds.map(g => g.id);
for (const g of gIDs) {
let gInDB = await bot.db.query(`SELECT * FROM serverInfo WHERE serverID = ${g}`).catch(console.error);
if (gInDB[0].serverID.length < 1) {
await bot.db.query(`INSERT INTO serverInfo (serverID) VALUES ('${g}')`);
console.log(`Added ${g} to database as it was not in it`);
}
}
const mainBotChannel = bot.channels.get('618929645173342210');
const botRunning = new Discord.RichEmbed()
.setColor('#63ff48')
.setDescription('Started and running')
.setFooter(`${tn.getDate()}/${tn.getMonth()+1}/${tn.getFullYear()} --- ${tn.getHours()}:${tn.getMinutes()}:${tn.getSeconds()}`)
mainBotChannel.send(botRunning);
});```
mby I shouldn't use new before Date.prototype 
hector you got your iframeworking?
or is that just an image of what the iframe should show?
for chrome too?
yea, when you visit your top gg bot page using google chrome, does your iframe show? mine only shows in firefox cause of changes chrome made late last year/this year that i cannot fix for some reason :/
whats your site ip/domain that the iframe points to if u dun mind sharing? i want to see what security headers its using
ty 🙂
lol, no security headers at all. f rating. 😄
even why i try do that for the one route im trying to frame it doesnt allow it :/
@strange mango thats not how u css
fk it, imma just show an image. this is now worth all the hasstle, nor worth reducing my site security. ill figure a fix in future if needed lol
dekbot.com but its going on and offline like mad atm cause im changing and trying things 😛
hello that i can check for sql, a
THIS? (PHP) URL: phpactiovation.php?email=****&vkey=*** ```php
if (!isset($_GET['email']) || !isset($_GET['vkey'])) {
header('Location: reg.php');
exit();
} else {
$email = $_GET['email'];
$vkey = $_GET['vkey'];
$sql = mysqli_query($con, "SELECT * FROM users WHERE email=$email AND vkey=$vkey AND verify=0");
if ($sql->num_rows > 0) {
$sql2 = mysqli_query("UPDATE users SET verify=1 WHERE email=$email");
refirect();
} else
echo "asd";
}```
ughhhhh
hector you got your iframeworking?
@neat ingot unfortunately I didn't, so I'll just put a screenshot of the site
yea i checked source and seen that, i was gonna do the same, but its itching my brain now
so, i'd like to thank you for raising it to my attention and ruining my day ❤️
im determined to figure out how to allow the iframe on chrome but only for that specific route im showing in the iframe (/mini)
How would I add a role when I'm using client.on('message', message=> and not client.on('guildMemberAdd', member =>?
Ex. I want to add the 'Shield' role to an user here:
// Shield
if (message.content.startsWith(`${prefix}shield`)) {
con.query(`SELECT * FROM energy WHERE id = '${message.author.id}'`, (err, rows) => {
if (err) throw err;
let xp = rows[0].xp;
if (xp < 10000) {
message.reply("You don't have enough energy!");
} else {
// Add shield role
}
console.log(xp);
})
}
How would I do that?
You get the guild member with message.member and then add the roles like you would
there's no guaranteed the member will be cached or exist.
if you wanna make sure the member is cached you can fetch it
I want to make my bot status change like every 30 seconds, and I'll need loop on a timer. how do I make a loop so the code keeps repeating?
Oh yeah sorry python
Okay, thanks!
Sorry for the ping @sudden geyser I'm still a bit confused. I tried using this method:
var role = message.member.guild.roles.find(role => role.name === "Shielded");
message.member.roles.add(role);
But I got the error message.member.guild.roles.find is not a function. I assume I'm doing the role variable wrong?
Yeah in v12 it's a manager, so you should be using the .find function on the cache collection.
cache.find
Alright. Cool. So it would be:
message.member.cache.find
```?
noop
roles.cache.find
should be .roles.cache.find
ohhh i see
okay thx! ill try that out
Oh no I got a deprecation warning:
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.
And than the fact that the role supplied is not a role/snowflake/array/collection. I already have the role created (which the bot creates if it doesn't exist).
// Shield
if (message.content.startsWith(`${prefix}shield`)) {
con.query(`SELECT * FROM energy WHERE id = '${message.author.id}'`, (err, rows) => {
if (err) throw err;
let xp = rows[0].xp;
if (xp < 1000) {
message.reply("You don't have enough energy!");
} else {
// Add shield role
var role = message.member.roles.cache.find(role => role.name === "Shielded");
message.member.roles.add(role);
}
console.log(xp);
})
}
make sure it's properly getting the role
use like console.log(role) after var role = ...
Hmm it says undefined 
*after logging it
var role = message.member.roles.cache.find(role => role.name === "Shielded");
message.member.roles.add(role);
console.log(role);
you're searching for the role in the member roles
Wdym?
if you have roles A B C D, and member has roles A and B added to them, and you search for role C, member will not have it
Oh I see.
you have to search it from the guild
role is undefined, which means it wasnt found
Yay it works. Thanks 🙂 This might've caused another issue however. I keep getting this null error:
if (!message.member.hasPermission("ADMINISTRATOR")) {
^
TypeError: Cannot read property 'hasPermission' of null
Which is always this similar line:
if (!message.member.hasPermission("ADMINISTRATOR")) {
Anyone mind giving me their opinion on something?
did the message come from a DM?
no (if ur talking to me)
@earnest phoenix just ask lol, dont ask to ask
^
@simple stump the only way message.member would be null is if the message came from a dm, or if for some reason the member isnt cached
oh sorry lol, well i'm working on a dashboard for my bot, and im making a page to manage punishments, and I need someone to critique my punishment card, cause it looks weird and idk what to do with it
That's weird. Well I'll have to look into it than. Thanks
@earnest phoenix work on the font spacing, make it smaller and make each area more distinct and separated
my terminal is spamming TypeError [ERR_INVALID_ARG_TYPE]: The "id" argument must be of type string. Received undefined at validateString (internal/validators.js:117:11) at Module.require (internal/modules/cjs/loader.js:1035:3) at require (internal/modules/cjs/helpers.js:77:18) at Client.<anonymous> (C:\Users\jjpla\OneDrive\Documents\GitHub\disc-bot-rep\bot.js:48:27) at Client.emit (events.js:310:20) at MessageCreateAction.handle (C:\Users\jjpla\OneDrive\Documents\GitHub\disc-bot-rep\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14) at Object.module.exports [as MESSAGE_CREATE] (C:\Users\jjpla\OneDrive\Documents\GitHub\disc-bot-rep\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32) at WebSocketManager.handlePacket (C:\Users\jjpla\OneDrive\Documents\GitHub\disc-bot-rep\node_modules\discord.js\src\client\websocket\WebSocketManager.js:386:31) at WebSocketShard.onPacket (C:\Users\jjpla\OneDrive\Documents\GitHub\disc-bot-rep\node_modules\discord.js\src\client\websocket\WebSocketShard.js:436:22) at WebSocketShard.onMessage (C:\Users\jjpla\OneDrive\Documents\GitHub\disc-bot-rep\node_modules\discord.js\src\client\websocket\WebSocketShard.js:293:10) (node:47720) 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: 150)
How would I check whether an user's ID has been inputted? For example I have this snippet of code:
if (message.content.startsWith(`${prefix}shield`)) {
let ts = Date.now();
con.query(`SELECT * FROM energy WHERE id = '${message.author.id}'`, (err, rows) => {
if (err) throw err;
let xp = rows[0].xp;
if (xp < 1000) {
message.reply("You don't have enough energy!");
} else {
// Add shield role
var role = message.guild.roles.cache.find(role => role.name === "Shielded");
message.member.roles.add(role);
message.channel.send("Inserting data for " + message.author.id + "... Please wait.");
con.query(`INSERT INTO shielded (id, time) VALUES ('${message.author.id}', '${ts}')`, (err, rows) => {
if (err) throw err;
message.reply("You have been shielded for 12 hours.");
})
}
})
}
Which inserts the user's ID into the database. I'm slightly familiar with MySQL (I've used in PHP a LOT) but always been stumped on how to check if something exists. Can someone give me an example? Thanks for the help!
No I mean in MySQL... In PHP I would use:
if (mysqli_num_rows($check) > 0) {
But in Node it's different
so i'm just wondering what the way to do this is in node
it depends on the library/driver you're using, not node
each library has their own way of interacting with sql
you have to check the docs for the one you're using
if (!(channel.permissionOverwrites.get(rows[0].muteRoleID).deny & new Discord.Permissions('SEND_MESSAGES', 'SEND_TTS_MESSAGES', 'ADD_REACTIONS', 'EMBED_LINKS', 'ATTACH_FILES', 'SPEAK', 'USE_VAD').bitfield)) {
channel.overwritePermissions(channel.guild.roles.find(r => r.id === rows[0].muteRoleID), { SEND_MESSAGES: false, SEND_TTS_MESSAGES: false, ADD_REACTIONS: false, EMBED_LINKS: false, ATTACH_FILES: false, SPEAK: false, USE_VAD: false }, 'Updating perms for the mute role').catch(console.error);
console.log(`Denying perms for ${rows[0].muteRoleID} in channel ${channel.id} of server ${channel.guild.id}`);
}```
am I able to do this compare in the `IF` statement?
I've tried to do such before, but I've had troubles, for example ones that are promises and require awaiting to actually do it
so I want to know, if something doesn't need an awaiting/callback function and etc, can I work with it in a `IF`?
tim im just using MySQL; node.js and using phpMyAdmin. i dont think it rlly depends...
i mean
How can I get status instead of Custom Status? DiscordJS 11.6.4
i just need to check whether a row exists
mysql is not built in into node
you use mysql in node through a driver/library/package
just like you use mysqli in php
oh i see.
the way you posted is mysqli's specific way of doing it, you need to see whats the way for the package you're using
would saying that i use the MysQL library than?
seems like you're using d.js library
after you get the row and if nothing is found on user ID/serverID etc you can do if (row.length < 1) { code to run here }
i honestly have no clue how to find an existing row
if you did npm install mysql, yes
^ thats what i did
Anyone got any tips on how to decide if updates are major, minor or patches (using semantic versioning)?
I mean are there weirdos that are gonna get mad if I don't do it right?
if you fixed a bug or renamed something
patch
if you added new stuff removed stuff but it doesn't break any existing code
minor
and if you literally changed a big part of the project and it breaks existing code or you literally removed lots or features
major
or you can read that too
Thank you very much, that kinda explains it better than the site imo
how to get my status instead of Custom Status? DiscordJS 11.6.4
Pls ready webhook thanks vote code ❤️
Yeah @true ravine
interesting
well saying pls ready webhook thanks vote code ❤️ doesn't say anything
I've seen some engrish here
await channel.send(f'Antes: {before.content}, Despues:
{after.content}')
AttributeError: 'NoneType' object has no attribute 'send'
channel is None
@client.event
async def on_message_edit(before, after):
channel = client.get_channel(f'{int(get_channelID(after))}')
await channel.send(f'Antes: {before.content}, Despues: {after.content}')
what?
Uhh
get_channel takes an int
i have lag ;vvvvvvvvvvv
get_channel returns a Channel object if your bot could find a channel under given ID
oh
What is get_channelID anyway
[str(message.guild.id)]
[int(message.guild.id)]?
def get_channelID(ctx):
with open("logs.json", 'r') as f:
logs = json.load(f)
return logs[str(ctx.guild.id)]
And what type will be returned from that function
which must be the case
I legit just got $50 for inviting a bot to someone's server
dude
what the hell
omg
how to get my status instead of
Custom Status? DiscordJS 11.6.4
@open flicker https://img.ichigo.uk/Pfvy7jIPtTJ4.mp4 Also you shouldnt be using Discord.JS to automate user account as this is against TOS
@amber fractal on freelancer?
fiverr
omg
@delicate zephyr, I want to get it in userinfo
so? @copper cradle
You need to give get_channel an integer
oh
that's only in spanish thoñ
im spanish xd
I know
oh
i dont understand(my english is bad xd)
we only use ? and ! in english
and we don't use ¿ nor ¡
let's move this convo to #memes-and-media
the request took too long to receive a respond so it just dipped
and it probably is.
I don't know which library you're using but for discord.js you can pass a retry limit into the client constructor
https://discord.js.org/#/docs/main/stable/typedef/ClientOptions -> retryLimit
I am legit so confused. If I do console.log(rows[0].time), I get no errors and get printed a nice string of numbers. But if I do if (ts = rows[0].time + 1000), I get this error:
throw err; // Rethrow non-MySQL errors
^
TypeError: Cannot read property 'time' of undefined
This legit makes NO SENSE.
Code:
con.query(`SELECT * FROM shielded WHERE id = '${message.author.id}'`, (err, rows) => {
if (err) throw err;
if (ts = rows[0].time + 1000) {
var role = message.guild.roles.cache.find(role => role.name === "Shielded");
message.member.roles.remove(role);
message.reply("Shielded role removed.");
}
//console.log(rows[0].time);
})
I have my ts variable defined which is Date.now. What the heck???? How do I fix this?
I'm assuming that rows can be an empty array. If true, then rows[0] will be undefined. This will probably occur when shielded does not include a row with the user's ID
?
what did i do wrong than? and @woeful sphinx it is defined. i have a row in my db where id is equal to my id
if it isnt i could see why that could be an issue
and yes cry i prob am not comparing ts and rows[0].time
but im still a bit stumped on how to fix the error itself
cause when console.loging its fine
but when comparing the two variables it isnt
print out rows[0] right after if (err) throw err;. at some point itll be undefined
alright
i get the same thing
1588884916929
which is what i want
sry its prob not clear what my goal is
so rows[0] is 1588884916929?
i basically want to check if rows[0].time plus <some_number> is equal to ts, or the current date
yes
because rows[0] is the time stamp
it should look something like
{
time: 1588884916929
}```
yes
but its not stored in a json file its stored in a mysql db 😛 but yes same premise
right. but the mysql library will return the data in an object
oh? i dont believe ive seen that...
when you select, it'll return an array of objects where each object has a key of the column along with its value
does anyone know if this is possible
client.on('ready', () => {
console.log("Successfully logged in.")
setInterval(() => {
process.exit()
}, 1800000)
});
setInterval?
it'll close off so no point in making that an interval
GoogleSites hmm true. so do u think my MySQL query is incorrect?
@woeful sphinx
use setTimeout and a package like pm2 to restart it
then yeah go for it
@simple stump your query is good. you're just handling it incorrectly. here's an example in node14
con.query(`SELECT * FROM shielded WHERE id = '${message.author.id}'`, (err, rows) => {
if (err) throw err;
const [ row ] = rows;
if (row?.time + 1000 === ts) {
const role = message.guild.roles.cache.find(role => role.name === "Shielded");
message.member.roles.remove(role);
message.reply("Shielded role removed.");
}
});```
or <14
```js
con.query(`SELECT * FROM shielded WHERE id = '${message.author.id}'`, (err, rows) => {
if (err) throw err;
const [ row ] = rows;
if (row && row.time + 1000 === ts) {
const role = message.guild.roles.cache.find(role => role.name === "Shielded");
message.member.roles.remove(role);
message.reply("Shielded role removed.");
}
});```
alright. cool thansk for the help 🙂 ill try it out
I'm not sure what you're trying to achieve though. I'm assuming row.time + 1000 will return a timestamp and you're making sure it's been at least a second (cooldown maybe). but this will not work
at Function.normalizeFields (/home/container/node_modules/discord.js/src/structures/MessageEmbed.js:443:8)
at MessageEmbed.setup (/home/container/node_modules/discord.js/src/structures/MessageEmbed.js:77:91)
at new MessageEmbed (/home/container/node_modules/discord.js/src/structures/MessageEmbed.js:18:10)
at embedLikes.map.e (/home/container/node_modules/discord.js/src/structures/APIMessage.js:164:40)
at Array.map (<anonymous>)
at APIMessage.resolveData (/home/container/node_modules/discord.js/src/structures/APIMessage.js:164:31)
at TextChannel.send (/home/container/node_modules/discord.js/src/structures/interfaces/TextBasedChannel.js:166:62)
at Object.exports.run (/home/container/commands/verify.js:24:14)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:16) 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: 1)
(node:16) [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.
anyone know how to fix this?
GoogleSites thats correct.
dont spoonfeed wew
not spoonfeeding - he's already got it I'm just showing him how the structure looks
@simple stump currently you're checking if row.time + 1000 is equal to ts (is that the current time in UNIX?). anyway, if you want it to make sure it has been at least a second you need to make sure that row.time + 1000 is less than ts
okay. thx googlesites
top gg is down?
uh there seems to be an error
i tried logging row and row.time
but it says that its undefined?
console.log(row.time);
console.log(row);
throw err; // Rethrow non-MySQL errors
^
TypeError: Cannot read property 'time' of undefined
@woeful sphinx
Edit: Fixed
classes
you cant extend an initialized class, you need to extend it before initializing it
so u have to do it in the other file
welp
yea u dont extend it when u initialize
i didnt understand for a sec
so just export client
yea, or extend it before creating instance
For some reason my custom status isn't working. I don't get ANY errors, yet my bot has no status whatsoever.
client.once('ready', () => {
console.log('Ready!');
client.user.setPresence({
status: "online", // Change 'online' to online, idle, etc.
game: {
name: "the Endran Empires.", // The message shown in status
type: "WATCHING" // PLAYING: WATCHING: LISTENING: STREAMING:
}
});
});
pretty sure its activity, not game
^
alright. thanks
also if you're keeping status to online then you can set the activity with client.user.setActivity('the Endran Empires.', { type: 'WATCHING' })
It's a common issue with the website.
I'd simply ignore it.
what are these profile pictures pls explain
@pale vessel ?
flazepe it's an evolution.
how
isn't it discords birthday or smth
can I join
Use a site like https://projectblurple.com/paint/
thank you
How do I get an user's nickname/name by their ID? I don't want to do it in my client.on('ready' but rather in client.on('message'.
Ex.
if (message.content.startsWith(`${prefix}energy`)) {
let target = message.mentions.users.first() || message.author;
if (!target) {
message.reply("Please either mention an user!")
}
con.query(`SELECT * FROM energy WHERE id = '${target.id}'`, (err, rows) => {
if (err) throw err;
if (!rows[0]) return message.channel.send("This user has no XP on record.");
let xp = rows[0].xp;
if (target != " ") {
const user = <something>.fetchUser(target.id);
message.channel.send(user + " has " + xp + " xp.");
} else {
message.channel.send("You have " + xp + " xp.")
}
});
}
I know it's client.fetchUser but that becomes a problem if I want to get it in a client.on('message'
client.fetchUser() in v11
client.users.fetch() in v12
How would I get "client" though?
i dont believe u can if its not inside a client.on('ready'
How do servers with a few hundred shards manage their database connection? i guess not every shard will have its own connection? (nodejs, mysql)
client is a global variable, since you define it in top level
you just need to await it
lol im using v12 not v11
because fetching returns a promise
okay. thx tim!
@viral spade remote database probably
each client will have its own connection yes
but that multiple hundrets of connections to the remote database then?
F
yes, databases are capable of handling that many connections
Sorry for coming back so soon but how would I use an await if I don't put my client.ons inside an async?
okay i read that mysql default is 150
^ you could amp that up
for the callback put async
you just need to make the parent function async, or use .fetch().then() if you prefer callbacks
client.on("event", async (variable) => {})
whats the documentation page for the .fetch().then()? i dont want to change my code up too much
example
promises are native javascript
or make some kind of empty async function
Okey tim please check my plan of implementation. my goal is that the setup could theoratically handle 1.000.000 servers.
So lets say i have multiple nodes with shards and multiple nodes with databases and 1 manager node that has info of which guild data is in which database (this info gets cached in the client's guild object).
Lets say the bot is in 1.000.000 servers and there is 10 database nodes they are separated on. Each shard/client will be connected to each database, and use the right connection for the right guild. This means every of the 10 databases will have 1000 connections, altough data will be spread pretty thin accross the connections.
Would this be a good or bad way to do it?
it wont work
because if/when you change your total shard count, all guilds will be re-shuffled across shards, so a single shard can contain guilds from databases A B C and more all mixed in
unless you plan to have each shard connect to all databases
Each shard/client will be connected to each database
its also possible to shard databases, for example mongodb
That should work i guess, but only its so many connections
so if you have 1000 shards, with 1000 guilds each, each database will have 1000 connections
which is doable, but not ideal
yes
you can pool connections and use them when they're needed -- you dont need to stay connected all of the time
also, you dont need to have one process per shard, you should mix internal sharding in
i was thinking of letting the db query go though the shardingmanager, so its sent from one place per node
each shard is already a new process, no?
since anyway you need the sharding manager to keep an index of what guild is in what database
with the sharding manager yes
no i cache it from the manager node into the shard
first time i see a not cached guild
discord.js in general is not recommended for large scale bots
yeah. until they limit the user cache size it takes up way too much memory
lets say you have 100 processes, each process has 10 shards
i thought the sharding manager spawns 1 client within 1 process? Can i explicitly tell it to spawn multiple shards per process?
thanks!
you can give the manager a a totalShard and which shards to spawn
so for example give it 50 total shards, and spawn 10 shards
i do that
and inside each shard, you have to tell it to spawn a specific set of shard ids
i dont think the manager will do that for you
a shard is the process - I don't think you can spawn more shards in a shard
thats what i was thinking
technically a "shard" is a websocket connection
which discord limits to 2500 guilds per connection
Im getting this error while adding my bot
because the mods closed it, so people stop spamming the same question
about the crash?
yes
How can i get a bot developer role?
by adding a bot to the website
wait until they fix it
https://discord.js.org/#/docs/main/11.5.1/class/TextChannel?scrollTo=permissionsFor doesnt return null when i serialize it
Thought its as the guild's role perms are taken into account to
is there any to to ignore role perms just the channel perms
Get it?
but someone in the voice channel told me i was coding in a wrong way
Can I get another help?
how can i tackle latency issues?
but in principle do you agree with my plan tim?
So for handling a huge amount of servers, let each shard connect to each database, possibly having 1000 connections on a single db?
@small prairie you need to use permissionOverwrites
and its related functions/methods
Ah
i can get the required role from there
Thanks tim
@viral spade at such large scale, database connections are usually not kept open, the shards should connect, do a thing, and disconnect
which makes using transactions and eventual consistency more important
i see, that sounds legit.
Yes i want to reassamble my bot to reflect your tips you gave me! That means (for now, but i am planing ahead as you see) use only a remote, no local database and in turn add perfect caching of the most important parts so like you said, only a) user actions or b) periodic batch updates cause database actions.
yup
also look into using internal sharding in combination with the sharding manager
Tim at what point would you say you need to switch from djs or start horizontal scaling?
having one process per shard is not a good idea at scale
So opening new connections > Keeping one connection open 😅
as soon as you want to stop wasting resources lmao

f
oh but then the databse connection problem also resolves. i guess each shard from the same process would use the same static module and connection?
yes, all shards in the same process share everything from the process
they even share the same discord client and events
interested in this tim.lib mentioned 👀
lmao
uh top secret project
idk, i havent worked on it much the past few days
but i'll push something to github soon
😮 your actually writing a library? lol
is the repo private?
for which language might it be for?
there is no repo yet lul
for js
already installed
oohhh nice
but i get such error
are you requiring the right path?
what prompted you to write your own? not happywith the current offerings?
Will anyone help if I throw my project
@neat ingot yeah there is a market gap that remains unfilled
'market gap' 😄
lmao
@quartz kindle help me pls
sounds like this lib gonna cost me many bucks 😛
@rustic veldt make sure you install the latest version. if it still doesnt work, run enable pnpm in your glitch console
I want to learn how to write something like a lib, I just dont know websocket stuff heartbeating etc
I've worked with tcp sockets before though 
what is the latest version @quartz kindle
@rustic veldt lol
I mean I've been developing for many years now, just never had a real reason to look into it
??
oof
did you copy and paste someone's package.json?
looks like it lmao
Tim do you use ws or is there another package/built in node thing you use
no

then how did you install ytdl?
@amber fractal im using ws
i looked into uws, but i remember discord.js had issues with it
my own project
Yeah I heard uws was stink
how to install the latest version
How do I use message.channel.type? I'm trying to check if the message an user sent was in a channel or a DM.
did you write it in package.json? did you install it from the console, using npm install? did you use the add package button in glitch?
It was deprecated tho wasnt it?
I put this in the main file
const m3u8stream = require ('m3u8stream');
const parseTime = require ('m3u8stream / dist / parse-time');
the one in npm was, but they are still in development
If I throw my project, do you have a chance to see what the problem is?
ive tried taking a look at taht @pale vessel. tbh it doesnt rlly make sense to me i just need an example
actually im gonna give uws a try
@quartz kindle ?
the latter
they boast being 2x more efficient than ws
and it's == or === btw
okay. thx
for comparison
@rustic veldt i still dont understand what you're doing, why did you require them separately?
main on the internet wrote that this file should be discarded
they kinda pioneered websockets on browsers
ws is the new and good stuff
uws is a port from c++
I have difficulty understanding you because I am Turkish
not heard of this uws thing, still using socket.io where needed. its worth learning more on uws to repalce the sockets?
@quartz kindle
stop pinging random users
if it's 5x more efficient, probably
👀
its native code, so yes its more efficient than js
uws is theoretically the fastest open source websocket atm
If I throw my project, would you look at the problem @quartz kindle
and by a lot
@rustic veldt i can try
its similar to use to socket io, or a hugely different structure?
@quartz kindle thanks
intersting, gotta look into that more i think 🙂
Cant seem to find docs on uws tho, besides docs directory in the repo, but I don't know if they host that somewhere
wait
Tim do you know you're an angel in this otherwise mostly stupid and unhelpful world
I'm just dumb
i know
lmao
oh neat, so this would entirely replace express as well
@rustic veldt
Just feels different
wonder if templating engines are supported. like ejs etc.
thanks
"Add Package 22"
can you load the module @quartz kindle
i guess i could always use ejs and just render the content before sending it
https://discord.js.org/#/docs/main/11.5.1/class/PermissionOverwrites either has allow or deny
doesnt has null

