#development
1 messages · Page 939 of 1
or just remove (
so they expect to be spoonfed
what I meant was the way I've put the addRole INSIDE the promise
so it'll only run AFTER the promise gets the role
that wasn't clear enough ay
compare both codes
where, why and what?
remember that promises run in parallel, so most of the time you'll not be able to get the promise value directly
so you gotta put the code that'll use the returned value inside a .then() clause
anyone know why I'm getting a error
@still merlin maybe tell us the error
remove one of the two ( in the .setThumbnail line
it wants to see another ) somewhere, but in this case there was a ( too much
this warning pops up when running a command, how can i fix???
isnt it need to work https://ta.is-inside.me/cphkuhjR.png
is a global chat api abuse.
How do I make it so "on_ready()" is only called once in discord.py?
no
yes its not api abuse
ok thanks
@earnest phoenix can you tell me how to make the code im about to put not be on a loop. v11.5.1
no
helium.on("message", async(msg) => {
let chatmoderators = ['539195184357965833', '550170362248429568', '437019658374348801', '641795527444529152']
if (msg.author.bot)return;
if(msg.channel.name !== 'helium-global-chat')return;
msg.delete()
let e = new Discord.RichEmbed()
.setTitle("Helium Global Chat")
.setAuthor(msg.guild.name, msg.guild.iconURL)
.addField("Message content", msg.content)
.setColor("RANDOM")
.setThumbnail(msg.author.avatarURL)
.setTimestamp()
.setFooter(`Helium Global Chat System || SECURITY | Guild id: ${msg.guild.id} | msg author id: ${msg.author.id} | code by Airbus A350-1000#0001. thanks to him, this bot will have a functioning global chat.`);
if(chatmoderators.includes(msg.author.id)){
e.addField("Sent By", `🛠️ Chat Moderator | **__${msg.author.tag}__**`)
}else{
e.addField("Sent By", `**__${msg.author.tag}__**`)
}
await Promise.all(helium.channels.filter(c => c.name === 'helium-global-chat').map(c => c.send(e)))
await Promise.all(helium.channels.filter(c => c.name === 'helium-global-chat').map(c => c.setTopic(`Last message is sent by <@${msg.author.id}>`)))
})
crap
btw, stop using v11
why?
else your bot will have about 5 months of life left
How do I make it so "on_ready()" is only called once in discord.py?
@sullen salmon in discord js that's called likeclient.once('ready', so maybe try once instead of on.
cool name
i dont have exprience in discord.js
@sullen salmon idk if it works though
time to attempt to update
it's easier now than later
oh the js docs also don't show that, it's not a very popular thing or something
now to figure out what in my code i need to edit
so you can still try it haha
Doesn't work sadl
client.on('ready') will only be called when your bot has booted up
so only once per restart
that's not true I understood
No that calls whenever it's ready which can be multiple times
Only client.once('ready') ensures it's called only once
it will also get called when your client reconnects or something
But it doesn't seem like this feature exists in discord.py
yes but you can always try. It's not in the js docs too
client.on('ready') will only be called when your bot has booted up
so only once per restart
false
I tried and it didn't work
oh okay that's sad
ready can be fired multiple times during the lifespan of your app
i need help with adding a bulkdelete command and i have been trying alot any help me out
@earnest phoenix nasıl düzelteceğim
Is there a function that fires only once though
onu biliyorum
Or is there a way to simulate such a thing
why would you need that
With like global variables
literally have a bool in your app
@earnest phoenix bilmiyorum javasciptle aram iyi değil
i need help with adding a bulkdelete command and i have been trying alot any help me out
It considers it a different variable if it's outside of the function though @earnest phoenix
@white sentinel tell us what language you're using and what kind of database
then keep it... outside of the function lol?
@white sentinel nvm ignore my message
Dude @earnest phoenix
but still tell us what language
It says in the function that the variable gets used before init
That's why I said it considers it a different variable
some bool in a file
ready ->
if bool is true
ready already fired once
else
first time firing ready
bool = true
@nocturne grove im using .js
okay
what's your code and what's the error
I literally put a screenshot above
oh python
nice
@white sentinel okay so you know you want to bulkdelete messages from a text channel
I said I was using python
@nocturne grove yes
Honestly coders are fucking losers in general
did you smash your head on your keyboard
i have been trying for 3 hours now
just go to the docs and find something like that: https://discord.js.org/#/docs/main/stable/class/TextChannel?scrollTo=bulkDelete 😉
Always looking to smash some newbie who is so much dumber
Instead of trying to actually HELP
omg where does that come from
This is so characteristic of coders
victim andy
you could've done that before having a breakdown in the chat
@nocturne grove im confused
You could've read back before assuming I was braindead @earnest phoenix
Coders do this all the time
I'm tired of it
i, nor anyone else, assumed or said you were braindead
The coding community is not a community of genuinely helpful people
he literally just helped you
I can't find any docs about this,
Anyone know how I can force clear my bots cache?
He didn't though @pale vessel
Ah, ty @pale vessel
He wouldn't stop acting like I was stupid and offered the same solution multiple times when I told him it didn't work and he didn't even know what library I used
This is so typical of coding help forums
shut up karen
huge chad energy
Everyone acts like you're a 12 year old that has stolen his dad's keyboard
I'm tired of it
you're being a keyboard warrior right now, you're voiding the point you're trying to get across lol
I suggest this ends here
I guess I will listen to the will of the almighty janny
you'll end up corrupting it
Code:
["command"].forEach(handler => require(`./handlers/${handler}`)(bot));```
Code:
["command"].forEach(handler => require(`./handlers/${handler}`)(bot));```
@earnest phoenix
are you sure that is where the error is coming from
yes
there's literally no way 
unless that isn't the code you're using
check the stack trace
did you save the file?
yes
save it again
What do you need help with? 🙂 @earnest phoenix
@quartz kindle i saved again, still same error
uh, no.
The error is probably coming from within one of the handler files
If you want someone else to write a bot for you I don't think you will have much success
But you could describe what kind of things you want? You never know, maybe someone has already made a bot with the features you want
@white sentinel it was about the ( right?
@earnest phoenix try expanding the forEach method with braces and log the handler before requiring it.
const { readdirSync } = require("fs");
const ascii = require("ascii-table");
let table = new ascii("Commands");
table.setHeading("Command", "Load status");
module.exports = bot => {
readdirSync("./commands/").forEach(dir => {
const commands = readdirSync(`../commands/${dir}`).filter(file =>
file.endsWith(".js")
);
for (let file of commands) {
let pull = require(`../commands/${dir}/${file}`);
if (pull.name) {
bot.commands.set(pull.name, pull);
table.addRow(file, "✅");
} else {
table.addRow(file, "🚫 Error");
continue;
}
if (pull.aliases && Array.isArray(pull.aliases))
pull.aliases.forEach(alias => bot.aliases.set(alias, pull.name));
}
});
console.log(table.toString());
};
this is the code from the handler
ok, i'll try
whats the full error?
/app/index.js:9
["command"].forEach(handler => require(`./handlers/${handler}`)(bot));
^
TypeError: Cannot read property 'forEach' of undefined
at Object.<anonymous> (/app/index.js:9:13)
at Module._compile (internal/modules/cjs/loader.js:759:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:770:10)
at Module.load (internal/modules/cjs/loader.js:628:32)
at Function.Module._load (internal/modules/cjs/loader.js:555:12)
at Function.Module.runMain (internal/modules/cjs/loader.js:826:10)
at internal/main/run_main_module.js:17:11```
that's wack
try for looping instead of using forEach 🤷♂️
that makes 0 sense
forEach is slow as fuck anyways
const prefix = botconfig.prefix```
;
add a ;
It's optional
now that error is solved, but i have one more question
this is why i always use ;
That's the most cringe part about js tbh
it isn't when you're defining something like an array or an object
fuck js's autocompleting
i will got that error at every command?
Error: Cannot find module './commands/admins/arrole.js'
even
if the command
is in that dir?
oh nvm
i forgot a .
tyvm guys
If deliver is an async function, should this loop call the function, wait, then move on and do it again etc? Or do I need to specifically make deliver return a promise?
if its an async function, it automatically returns a promise
Yeah that's what I read on mdn but it appears they all called at once last time that code ran
does your deliver function have any async logic in it? such as loading stuff from a website
No but it relies on some other functions, one of which does
All other functions it uses return promises though
And they are handled with then blocks
they have to be awaited as well
once you use then, that part of the code will not be considered anymore for the waiting
Oh that would make sense based on the output I got
in nodejs v14 u can await outside of an asynchronous function
Thank you very much
u mean deno? kek
oh, i've only been looking at it for like 2 minutes cuz i just saw it
its kinda cool tbh
idk if i prefer it or not doe
(node:12415) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'startsWith' of undefined
code:
bot.on('message', async message => {
const botconfig = require("./botconfig.json");
const prefix = botconfig.prefix;
if(message.author.bot) return;
if(!message.conent.startsWith(prefix)) return;```
conent
Can I use my bot's dblapi token in another bot, and use it for bot statistics? (dblapi.js package.)
I am trying to cache stuff to take load off the database.
When a new guild is seen, the bot should cache the relevant properties of each sql table. I also want to load into cache the info i have on every guildmember, when loading the guild.
Now it would be nice to add to my client objects guild/channel/role/member items a new property AppData where i cache my stuff, so i have my own and discords cache at one place. But as guildmembers should never all be cached by discord.js on guild load, i cannot do this for those. Is there any workaround for this, without discord.js caching all guildmembers on startup?
The alternative would be make my own Collection of guilds for caching, would this be a good idea?
bot.on('message', async message => {
const botconfig = require("./botconfig.json");
const prefix = botconfig.prefix;
if(message.author.bot) return;
if(!message.content.startsWith(prefix)) return;
if(!message.guild) return;
if(!message.member) message.member = await message.guild.fetchMember(message);
const args = message.content.slice(prefix.lenght).trim().split(/ +/g);
const cmd = args.shift().toLowerCase();
if(cmd.lenght == 0) return;
const command = bot.commands.get(cmd)
if(!command) command = bot.commands.get(bot.aliases.get(cmd)); //here
if(command) command.run(bot, message, args)
})
Assignment to constant variable.
@viral spade why not create some sort of a service class where calling methods to it e.g. get looks the cache up first, if the user is not found in the cache, fetch from the db
you shouldn't cache all of your db data
once you use const, you cant change it @earnest phoenix
use let instead
Now when i use a command nothing happens, no errors, nothing, why ?
anyone know why this is happening. I have setcolour defiend in another embed
@earnest phoenix its not all my db data, its one int per guildmember. The db is many times that big.
Amazri console.log() returns nothing.
ok so do i remove console.log then
u shouldn't console.log within the embed
ohk
if u want to still console.log do it after the embed is sent
ok ty
np
last question lmao how do i remove the undefined part-
.addField(Title, Descrip)
true but u still got it
I cant thank u enough-
np bro
just to be sure-
.addField("<ban @User#0000, *this will ban a user from the guild*") is the correct way of doing it
u forgot the "
oof ok
addField("<ban @User#0000", "*this will ban a user from the guild*") @still merlin like this
Would it be ok for a mysql remote database to handle 1 connection (opening + closing) per guildmember cache miss for sent textmessages?
My bot sending 2 message in one commands
i regenerated the bot but it still sending 2 messages
pls help
Error: Could not locate the bindings file. Tried:
first, check if your bot has 2 of the same commands
if not close down the program and open again
@earnest phoenix
no
no to what-
I have no clue then.
you have node processes still running in the background
i used killall node
but nothing
/f as well
and killall forever
killall pm2
but . . . .
/f ??
so now i have a free hosting
wtf
wait i will restart the vps
so the vps shuted down
and the bot is not working
ok
done
Fixed
I tried making a new command handler but now none of my commands work, here is the message event
const Timeout = new Set();
const ms = require("ms")
module.exports = async (bot, message) => {
const botconfig = require("../../botconfig.json");
let prefix = botconfig.prefix;
if(message.author.bot) return;
if(!message.content.startsWith(prefix)) return;
if(!message.guild) return;
if(!message.member) message.member = await message.guild.fetchMember(message);
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const cmd = args.shift().toLowerCase();
if(cmd.length == 0) return;
let command = bot.commands.get(cmd)
if(!command) command = bot.commands.get(bot.aliases.get(cmd)); //here
if(command) command.run(bot, message, args)
}
and here is the handler
const {readdirSync} = require("fs");
const ascii = require('ascii-table');
let table = new ascii("Commands");
table.setHeading('Command', 'Load status');
module.exports = bot => {
readdirSync('./commands/').forEach(dir => {
const commands = readdirSync(`./commands/${dir}`).filter(file => file.endsWith('.js'));
for(let file of commands){
let pull = require(`../commands/${dir}/${file}`);
if(pull.name){
bot.commands.set(pull.name, pull);
table.addRow(file, '✅')
} else {
table.addRow(file, '🚫' )
continue;
}if(pull.aliases && Array.isArray(pull.aliases)) pull.aliases.forEach(alias => bot.aliases.set(alias, pull.name))
}
});
console.log(table.toString());
}
how come i have this const { channel } = message.member.voiceChannel I have if(!channel) return message.reply("join a channel)" but im already in a channel and it tells me to join one, so if i leave it then try it, it says (node:19126) UnhandledPromiseRejectionWarning: TypeError: Cannot destructure property `channel` of 'undefined' or 'null'.
assuming you are on v11
mhm
{ channel } = voiceChannel
is the same as
channel = voiceChannel.channel
there is no voiceChannel.channel
as voiceChannel is already a channel
OHH ty
My bot relies on an image attached to a command message for one of it's functions, and I'm encountering an issue where the image seems to have only partially uploaded to discord when my bot starts trying to download it, resulting in the image appearing invalid
Is there a way to "wait" for discord to receive the full image before I start downloading?
Actually scrap that
anyone know any good bot stat websites?
wdym @earnest phoenix
where you can see bot growth etc
View the historical performance of over 7600 bots listed on Discord Bot List (top.gg). Updates every hour.
.tk is a decent free domain
people still use tk? thats so old school
I wonder if I get a free ferrari upon purchase
@lyric mountain freenom
@lyric mountain freenom
@knotty steeple always unavailable despite me writing random characters
hmm maybe off topic would be better for this convo lol
ngl i thought this was off topic
UnhandledPromiseRejectionWarning: RangeError [BITFIELD_INVALID]: Invalid bitfield flag or number. confused why i keep getting this
my flags are all correct
you sure?
yeah manage server isnt a thing
well boys
you would of thought it was but nop
mhmm
i just went from pro to amateur
true
anyway is manage server v11
it's aight
its still manage guild in v11
imma go over the flags to double check every command i have
thanks for the handy image
its in the guide too
its okay discord themselves flip flop btwn guild n server lol
anybody can help with this
(node:9068) UnhandledPromiseRejectionWarning: RangeError: RichEmbed field values may not exceed 1024 characters.
Its my server info cmd
self explanatory
aka you put more letters than 1024 and it isn't allowed
Ok thx
I want to make it so my bot blocks users from the specified command so I have this
instead of it being the id of the user i want it to take the ids from the file config.json bannedusers
its coded in JS
the code is quite old
Store an array in config.json like blacklisted: [id1, id2, ...]
Require the file with require()
const discord = require("discord.js")
const botconfig = require("../botconfig.json");
module.exports.run = async (bot, message, args, color) => {
let prefix = botconfig.prefix;
if (!message.content.startsWith(prefix)) return
if (message.author.id !== '519861424017768451' && message.author.id !== '519861424017768451') return;
if(args <=0) return msg.reply(`Say what ?`);
let content = args.join(" ");
let embed = new discord.RichEmbed().setTitle(content).setColor("0x3d3d29");
msg.channel.send(embed)
}
exports.help = {
name:"say"
}
and check the blacklisted property like blacklisted.includes()
that would be my code for a file
Are you doing that for every command file? Why not in the single message event?
It may be two years old but as long as you have knowledge on JS it should be straight forward. Simply check if the user is blacklisted in your message on event.
okie
as well i just got a error saying this is undefined
${message.author.username}
what do you mean by? can you show the actual error message? do you still have good knowledge on JS?
2020-05-22T21:02:03.113957+00:00 app[worker.1]: [LightBenefits 💎][BAN] Brandonn_01#8690
2020-05-22T21:02:03.117457+00:00 app[worker.1]: /app/index.js:120
2020-05-22T21:02:03.117458+00:00 app[worker.1]: console.log(` Banned By ${message.author.username}`);
2020-05-22T21:02:03.117459+00:00 app[worker.1]: ^
2020-05-22T21:02:03.117460+00:00 app[worker.1]:
2020-05-22T21:02:03.117460+00:00 app[worker.1]: ReferenceError: message is not defined
2020-05-22T21:02:03.117460+00:00 app[worker.1]: at Client.<anonymous> (/app/index.js:120:31)
2020-05-22T21:02:03.117461+00:00 app[worker.1]: at Client.emit (events.js:310:20)
2020-05-22T21:02:03.117461+00:00 app[worker.1]: at GuildBanAddHandler.handle (/app/node_modules/discord.js/src/client/websocket/packets/handlers/GuildBanAdd.js:12:31)
2020-05-22T21:02:03.117462+00:00 app[worker.1]: at WebSocketPacketManager.handle (/app/node_modules/discord.js/src/client/websocket/packets/WebSocketPacketManager.js:103:65)
2020-05-22T21:02:03.117463+00:00 app[worker.1]: at WebSocketConnection.onPacket (/app/node_modules/discord.js/src/client/websocket/WebSocketConnection.js:333:35)
2020-05-22T21:02:03.117463+00:00 app[worker.1]: at WebSocketConnection.onMessage (/app/node_modules/discord.js/src/client/websocket/WebSocketConnection.js:296:17)
2020-05-22T21:02:03.117464+00:00 app[worker.1]: at WebSocket.onMessage (/app/node_modules/ws/lib/event-target.js:120:16)
2020-05-22T21:02:03.117464+00:00 app[worker.1]: at WebSocket.emit (events.js:310:20)
2020-05-22T21:02:03.117464+00:00 app[worker.1]: at Receiver._receiver.onmessage (/app/node_modules/ws/lib/websocket.js:137:47)
2020-05-22T21:02:03.117465+00:00 app[worker.1]: at Receiver.dataMessage (/app/node_modules/ws/lib/receiver.js:409:14)
i use to be good at it but i took a 2 year break
im not sure if I need to change the message.author to a newer one
but it shows no errors in VSC when i load it up
The error is self-explanatory: message is not defined. I don't know what "the new one" means but it may help to try learning more about JS again.
ok
bot.on('guildBanAdd', function(guild, user) {
//log to console
console.log('[' + guild.name + '][BAN] ' + user.username + '#' + user.discriminator);
console.log(` Banned By ${message.author.username}`);
//post in the guild's log channel
var log = guild.channels.find(ch => ch.name === 'mod-log');
if (log != null)
log.sendMessage('**[Banned]** ' + user);
});
``` thats my code i load it up in VSC but no error of it being undefined
its still undefined
does anyone know how to stub the discord api
Context being to test bot under specific circumstances that are painful to do in actual discord (eg people spamming messages or thousands of reactions etc)
been suggested litecord although not 100%
Are you sure unknownCommandResponse is a option for CommandoClient? (https://discord.js.org/#/docs/commando/master/typedef/CommandoClientOptions)
There's a registerDefaultCommands method allowing you to change it under CommandoRegistry class.
not in titles, but you can in the author field
const Discord = require("discord.js");
const colours = require("../../colours.json");
const db = require("quick.db");
module.exports = async (client, message, channel) => {
const logs = db.fetch(`logs_${message.guild.id}`);
let logChannel = client.channels.cache.get(logs);
if (!logs) return;
if (!logChannel) return;
const channelCreated = new Discord.MessageEmbed()
.setColor(colours.auxcrd)
.setAuthor(`${message.guild.name} Modlogs`, message.guild.iconURL())
.setDescription(`**Channel Created:** ${channel}`)
.setTimestamp()
if (logChannel) logChannel.send(channelCreated);
};``` how would i get the channel name?
i've tried channel.name
is there any property to change the name of a channel ?
i haven't seen anything about this in the docs
*using discord.js
v11
the only method i see in the doc is delete :/
.setName()
https://discord.js.org/#/docs/main/stable/class/TextChannel?scrollTo=setName
@steel drum this is for v12
i'm on v11
exists in v11 too
npnp
^^
exists for voicechannel too jsyk https://discord.js.org/#/docs/main/v11/class/VoiceChannel?scrollTo=setName
lol
import discord
import json
from discord.ext import commands
import random
players = {}
def get_prefix(client, message):
with open('prefixes.json', 'r') as prefixesjson:
prefixes = json.load(prefixesjson)
return prefixes[str(message.guild.id)]
client = commands.Bot(command_prefix = get_prefix)
@client.event #onready
async def on_ready():
await client.change_presence(status=discord.Status.dnd, activity=discord.Game("with Python"))
print('Webhookisback Loaded.')
@client.event #addprefix
async def on_guild_join(guild):
with open('prefixes.json', 'r') as prefixesjson:
prefixes = json.load(prefixesjson)
prefixes[str(guild.id)] = 'web.' # web. is the default prefix for custom prefixes
with open('prefixes.json', 'w') as prefixesjson:
json.dump(prefixes, prefixesjson, indent=4)
@client.event #deleteprefix
async def on_guild_remove(guild):
with open('prefixes.json', 'r') as prefixesjson:
prefixes = json.load(prefixesjson)
prefixes.pop(str(guild.id))
with open('prefixes.json', 'w') as prefixesjson:
json.dump(prefixes, prefixesjson, indent=4)
@client.command() #prefixchange
async def changeprefix(ctx, prefix):
with open('prefixes.json,', 'r') as prefixesjson:
prefixes = json.load(prefixesjson)
prefixes[str(ctx.guild.id)] = prefix
with open('prefixes.json', 'w') as prefixesjson:
json.dump(prefixes, prefixesjson, indent=4)
espasmo
spasm
@quartz kindle - Sorry to ping you again. Any idea how to send a message embed using eval? Lol
build the embed on the destination, ie: inside the eval code
Right, but how do I access discord.MessageEmbed in the eval?
or define a function in the shards, and call the function from the eval
you need to either have discord defined in the shards, or require it inside the eval code
https://oliy.is-just-a.dev/y3da4y_4004.png I mean you can just do it like you would in any other time
I'll have to require it - stupid me was attempting to import( )
if you have something like this let prefix = bot.db.fetch(`prefix_${message.guild.id}`) ? bot.db.fetch(`prefix_${message.guild.id}`) : config.prefix; how do you make it so that you can also ping the bot for the prefix
anyone help me with this it says message is not defined
client.on('guildMemberAdd', member => {
console.log('User ' + member.user.username + ' has joined the server!')
let role = message.guild.roles.cache.find('name', 'Community');
member.addrole(role)
});
@astral yoke
dont ping people because they are a recent message
okay sorry i just need help
wait
anyone know how to retrieve the number of users on all of the guilds that my bot is in?
message.client.users.size.toLocaleString() @graceful dock
ty
make sure all of the peoples are cached though
oh, cant i use something with the ctx.bot.guilds?T
like members in ctx.bot.guilds.members
or anything like that
for this
const client = new Client()
add
({ fetchAllMembers: true })
so its like this
const client = new Client({ fetchAllMembers: true })
you will be missed
lmao agree
should just iterate the memberCount property of each guild (in d.js)
^
the fact they use ctx indicates probably python
im using python ye
oh then
yes
Iterate your guilds and add up the member_count of each guild
it returns the count of members regardless of cache
it'll be the most accurate
({ fetchAllMembers: true })
@astral yoke - That won't work come October unless you're verified
anyone help me with this it says message is not defined
client.on('guildMemberAdd', member => {
console.log('User ' + member.user.username + ' has joined the server!')
let role = member.guild.roles.cache.find('name', 'Community');
member.addrole(role)
});
whats the thing in disocrdjs v12 that chekcs if someone has a role or not
Creo que esta es una discordia inglesa así que no muchas son guerreras españolas.
@earnest phoenix
@white sentinel ok, pera sabes js?
ci
@white sentinel espar saber como hago un cmd asi tipo inviter manager
ejemplo pongo -invites
@paper phoenix it will work for bots in less than 100 guilds also
no se mucho sobre js
@amber fractal ctx.bot.guilds.member_count ?
anyone help me with this it says message is not defined
client.on('guildMemberAdd', member => {
console.log('User ' + member.user.username + ' has joined the server!')
let role = member.guild.roles.cache.find('name', 'Community');
member.addrole(role)
});
and essentially every bot in more than 100 will verify
@paper phoenix it will work for bots in less than 100 guilds also
@white anvil Bots don't stay in less than 100 for long when on DBL. 😛
i beg to differ
It double my server count in 2 days
it always does when it just got added
once its down and deep on the front page you get one server a week
since it appears in the new list
yeah lol
@white sentinel that error wont be thrown in that code
u havent referenced message anywhere there
how tdo i reference it in that way
There's not much competition for mine though:
https://top.gg/tag/rocket-league
(Rocket Planet)
@white anvil how would i reference it
@graceful dock Each guild has the property member_count, you should loop over each guild and add up that property
^ That won't get you unique users, though. Could have someone in multiple mutual servers
well if you want to cache all users and kill your ram usage for a more accurate member count be my guest
this also wont work if you dont request all members
@white anvil - You can still access member count without having all cached/requesting all
Im still kinda of new to coding, does anyone know how to get the bot to respond when you mention it using discord.js?
You could check if the message contains <@[id]> or <!@[id]>
help pls
Do you know how to make a fetchinvite (serverid) command, and the bot makes an invite and give to u, bot owner only
Why would you want to have something like that?
because it sounds quite malicious and might seem like a privacy breach in some cases
Lol why does everyone ask for help with backdoor commands 😂
@indigo flax thats a privacy breach and is against ToS
People just want some kind of Control
@delicate zephyr unless described on the bot page and can be opt-in/out
yes
Just don't give the bot create instant invite or administrator
can i have help, i try doing custom prefix cmd but when i change it ut lets any prefix work
https://hastebin.com/maxexejuvo.js the whole index.js file
my whole prefix.js file
Because you don't have a check
Whaaat
under the prefix line you should have something like if !message.content.startsWith
On which file??
index
if(!message.content.startsWith);
let prefix = prefixes[messageg.guild.id].prefixes;
if (message.content.startsWith(prefix)) {
// Put command running stuff in here
}```
You need to put the if (!prefixes[]) bit above let prefix
Yes like that. Take a look at the link I sent.
is mine right tho
Yeah it is.
Look for a missing } or )
Remove the ! before message.content
Otherwise the stuff inside that if statement won't work.
still doesn't work
Same error?
Send what you have in index.js file now
Put everything from line 53 to 79 into the if statement
53 - 79 into the if (message.content.startsWith(prefix)) { // here }
what?
Everything from line 53 to 79 put where the //here is
Yes where that // here is replace it with everything from line 53 to 79
so put everything in that bracket
Or you can just require the json file and tell it to require the text inside the bracket instead of doing it so confusingly
What you just said makes less sense.
Why exactly
Tell a JSON file to require another file.
yes
like that
Yeah
do you know stuff about custom log channel cmd @warm marsh ?
I've done it in the past.
Like logging certain actions?
https://gyazo.com/6cf8620c9576f4e3e3826bf098f121a8 i have this and idk what to do next and basically what i'm trying to do is imagine you have to have a channel called aciton logs to have logs working, well i'm trying to do as you can change the location of logs to another channel
How can i get it to tag the role?
Just setting the default logs channel?
@clear wraith Language and Lib?
Rami you should probably look into using a sqlite3 database or something
JSON is very bad.
It's not made for being constantly edited.
Roman <@id>
not @<id>
well, idrc about that tbh, i'm just tryna make a custom log channel cmd, i'vebeen using json for a while and it works fine
Alright.
It's kinda the same as your prefix one.
Just make sure they mention a channel
then store it.
idrk what to do next:(
Idk what you're trying to do and yeah learning a bit more might help with the "how" side.
You can always go on stackflow as well
They have some really useful threads on discord.js
Might be out-dated now though.
basically imagine you need a channel names staff logs to have logs working but i want to make it as you can change thta location to another channel like staff logs to admin chat
Some concepts might still work but the methods and properties, etc.. might have changed.
I know how logging works.
Yeah but atleast it gives a basic idea
Just listen to the events
check if the guild has a logs channel
if so send the message
Do you have a log feature setup or not?
yes i have logs feature ste up
The changing of the channel is really easy to do, Literally almost the same way as your prefix changer.
Yeah
?
Why !args = false
because !![] = true
@warm marsh so what do i do next after this https://gyazo.com/6b27eb1d62ad4c91d8a65701f6cf6f2c
I saw.
Ok
where do i do that
Only one of which are defined
Duck wrong one
ffs
I’m on my phone lmao
Websites not supporting www in 2020 rip
Lmao
This is my args message.content.split(" ").slice(2);
Oof
let args = message.content.substring(message.content.indexOf(prefix) + prefix.length).trim().split(/\s+/)```
That's how I did args when I used JS.
let cmd = (args.shift()).toLowerCase();
and cmd
Ok
Yeah figured that out last second
ah lol
Anyways ima head to bed before my brain kills me any more
Alright, Have a good one!
You too
Hello, I have just updated to djs v12.2 and get this error.
const errorembed = new Discord.RichEmbed()
TypeError: Discord.RichEmbed is not a constructor
at Client.<anonymous> (/home/container/bot/bot.js:370:24)
Any fix?
@silent berry https://discord.js.org/#/docs/main/12.2.0/examples/embed
It's MessageEmbed in v12
Oh thank you@hoary elm
i just add api to one of my testing bot before adding it to my main bot. I wanna test if the coding is working as a intend but how do i test?
i mean i am sure if i add my bot to the site it will get rejected
cuz it has noting
its just to test my code
anyone? how do you test it?
If the API is setup correctly you can catch an error and console log the response 🤷🏻♂️@lime torrent
The language you use would obviously differ how you would go about achieving this but just a suggestion
i mean i want to test by having a member of my team vote and then seeing if my bot rewards it or not.
Oh 🤔 idk about that
Is it possible to run these without .map
await Promise.all(helium.channels.cache.filter(c => c.name === 'helium-global-chat').map(c => c.send(e)))
await Promise.all(helium.channels.cache.filter(c => c.name === 'helium-global-chat').map(c => c.setTopic(`Last message is sent by <@${msg.author.id}>`)))
I keep getting this error randomly I tried handling it with on('error') but with no avail
Error: This socket has been ended by the other party
at Socket.writeAfterFIN [as write] (net.js:453:14)
at JSStreamSocket.doWrite (internal/js_stream_socket.js:170:19)
at JSStream.onwrite (internal/js_stream_socket.js:28:57)
at TLSSocket.Socket._final (net.js:416:28)
at callFinal (_stream_writable.js:599:10)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
code: 'EPIPE',
source: 'socket'
}
It crashes the bot every time it occurs so it's quite a nuisance
anyone who know what was the djs version in september 2018 ?
why?
I need it
Bc I need to help a friend who is using a code on an older version that he dont remember. I just have the file creation date
they should upgrade instead
He don't want to lmao
he needs to
sure
it'll stop working
thanks @pale vessel his code seems to be working now
How do i get something like this "div.game-calls-to-action > div.game-title-container > h2" in edge?
It should be} catch {
@tight plinth } catch (error) {
SyntaxError: missing ) after argument list
Show full code
Ok
youre missing a right paren somewhere where you are calling a function
Damn 2000 limit
Hatsebin
I'ma create txt file
ye hastebin
The section would've probably be enough, like the try catch section
But txt file will be okay too
Solution: use your brain. Try to guess where else you can put the missing ) by looking at where it starts and where it needs to be closed
There are a few missing return statements as well
@vivid crescent half the bot like that, still ran
Do you know Javascript in general?
I'm new
Yeah but your code will bleed into other things
That's why
Learning
Don't learn js by making a bot
That's the worst idea ever
Except if you're smart enough to read errors and solve them by urself
You have } and ) that are unnecessary and aint closing anything
They are just there
To break your code
Like the last }); isnt closing anything
Soooo, you have an editor no? Go through all your statements and look if they're closed correctly
What is the fastest time your bot is allowed to change its status on discord without it being considered API absue
5s
ok
I suggest doing at least 10 seconds
whenever i try to my mongo db database
connect ECONNREFUSED 127.0.0.1:27017
this error appears
ok cause I always change the status withing 1 minute intervals
that's good
pls someone help me
whenever i try to my mongo db database
connect ECONNREFUSED 127.0.0.1:27017
make sure you actually setup your db correctly
@pale vessel this happens when my bot tries to connect
it has some economy commands so i used a database for it
but whenever i try to connect
this appers
@pale vessel
https://stackoverflow.com/questions/46523321/mongoerror-connect-econnrefused-127-0-0-127017 this can help you probably
Hey. In the following code, the concerned user has voted and it's week-end. The console confirms that it has detected that indeed the user has voted and it's weekend. But the embed isn't modified. Did I make a mistake?
dbl.hasVoted(msg.author.id).then(voted => {
dbl.isWeekend().then(weekend => {
// \/\/\/\/
if (weekend && voted) { console.log(`voted & weekend`); topggEmbed.addField(`🎉 Yaay, it's weekend! Earn bonuses by voting!`, `✅ You have already voted in the past 12 hours`) }
// /\/\/\/\
if (weekend && voted === false) { topggEmbed.addField(`🎉 Yaay, it's weekend! Earn bonuses by voting!`, `⚠️ You haven't voted in the past 12 hours`) }
if (weekend === false && voted) { topggEmbed.addField(`❎ It isn't week-end yet. Wait for friday!`, `✅ You have already voted in the past 12 hours`) }
if (weekend === false && voted === false ){ topggEmbed.addField(`❎ It isn't week-end yet. Wait for friday!`, `⚠️ You haven't voted in the past 12 hours`) }
});
});```
I have already tried to use `topggEmbed = new Discord.MessageEmbed(topggEmbed).addField('...')`
btw, topggEmbed is declared and used above this part of code
I think i've found why it doesn't work
The API takes time to get the values
When I got the values, the embed is already sent. But I can't use await here... How could I do this ?
no need to answer thx
i've found
:)
I used this: js let voted = await dbl.hasVoted(msg.author.id) let weekend = await dbl.isWeekend()
random question:
how long do you guys normally spend on designing elements? like, changing placement or format of text in embeds etc.
Since embeds are prety simple (author, title, color, description, fields, footer), I don't spend much time on them. But recently I've found bots that send very strange embeds (I couldn't define what is a field or a description), so these times I'm trying to figure out their secret xD
embeds are only as simple as you want to make them 😛
bonuses
random question:
how long do you guys normally spend on designing elements? like, changing placement or format of text in embeds etc.
@neat ingot sometimes I just use the .setDescription one for the embeds cause it looks nicer than doing the .addFields, depends on what it is though
yea i've tried that out as well 😛
sometimes I just use the .setDescription one for the embeds cause it looks nicer than doing the .addFields, depends on what it is though
@zenith terrace About replacing fields by description : i've tried this, but the space between lines is too big. Do you have any trick to avoir this?
I have a question- I'm trying to have a "Join Support Server:", "click here." but where would I add a .setURL(url)
on a embed
with .setURL, you'll add a URL on the Title. Not very practical. If you want to set a link in a field or the description, you can do this: js '[click here!](http://this.is.the/url "this is the text when you hover the link")'
alright ty
np
const channels = guild.channels.cache.filter(c => c.type == 'text' && c.permissionsFor(guild.me).has(['SEND_MESSAGES', 'VIEW_CHANNEL', 'READ_MESSAGE_HISTORY'])).array();
for (const channel of channels) {
const message = await channel.messages.fetch({ limit: 1 });
...
}```
How can that give this? ```json
DiscordAPIError: Missing Access
at RequestHandler.execute (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:170:25)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (internal/process/task_queues.js:97:5) {
name: 'DiscordAPIError',
message: 'Missing Access',
method: 'get',
path: '/channels/xxx/messages?limit=1',
code: 50001,
httpStatus: 403
}```
that's the only spot in my whole code where it's fetching one message
What are you trying to do
The error code is 403. Your code seems right, but you just can't do that apparently
oh this is weird. That code is executed in a guildCreate event, but no guild was joined before that error
heya guys so i'm trying to verify my bot and i wanna remove anything that might make it look suspicious, how could i remove my bot from all the servers with 3 members or less
but what I'm doing is just normal, it normally works
heya guys so i'm trying to verify my bot and i wanna remove anything that might make it look suspicious, how could i remove my bot from all the servers with 3 members or less
@slender wagon loop through all guilds and doguild.leave()when its membercount is less than 3
oh alrightys
Well you can catch the error at the loop
but this only happened once, so next time it will probably not happen again
bot.guilds.cache.forEach(guild => {
console.log(" - " + guild.name, +guild.memberCount);
could i add it here
I have an element <button onclick="click()">Calculate</button> in my HTML file and my click function doesn't get fired
Script tag right below the button:
<script rel="script">
function click() {
console.log(resultstr);
}
</script>
yeah ik that just logs the servers
@slender thistle idk how that works but is resultstr defined somewhere?
To add more details to my issue, I can run click() from browser console just fine
resultstr will just be undefined
okay so you'd just like to log undefined 😁
or an error, I don't exactly care which one. I just want it to run 😂
well idk, I'm sorry
you cant use the function name click on a button
buttons already have a click method that has higher priority than your function
ye
https://discordapp.com/channels/264445053596991498/272764566411149314/713686845665312808 but how could that happen? Or did Discord have an outage around 12am UTC? As it gave that error 7 minutes after my bot joined a server
if the bot joined a guild with 500 channels, it could happen that someone edited or deleted a channel while your bot was fetching them lol
you could change the logic to check for permissions inside the for loop
its a missing access error
can happen because you dont have view channel permission
oh i see yeah someone could've changed permissions for the channel
while looping
for(let [id,channel] of guild.channels.cache) {
if(channel.permissionsFor(guild.me).has([a,b,c])) {
await channel.messages.fetch()
}
}
hmm okay thanks
but could that really take 7 minutes? Also, I don't think it had a lot of channels
but I will try that instead 👍
i don't know if node has something like that, but in mutlithreaded langs you can just offload the async tasks to another thread, so the for loop just queues the task and forgets about it without blocking itself from continuing
ok a quick google search it does
look up the fire and forget pattern if you're interested
isn't that just a foreach?
if you mean the forEach method
kind of
forEach is super slow compared to a native for loop though
but I can just do what Tim said right?
yeah
yeah I hear that often from you haha I transferred some
i was just noting if you don't want the for loop to block you can follow the fire and forget pattern
oh okay. Well I can read about it. Thanks
I don't understand why show error .
In node.js discord.js, whats the easiest way to let all shards share the same db (mysql) connection pool (possibly in the sharding managers process) ?
@robust moth try adding if (!commandFile) return
does anyone know how i can make an image like this bigger? https://gyazo.com/bc1af7efd99ea777abe4a08a7785b4ca
@rain jacinth wat?
Oh ok..
@zenith terrace About replacing fields by description : i've tried this, but the space between lines is too big. Do you have any trick to avoir this?
@spice smelt wdym by lines being too big
@zenith terrace wait 1min i'll create an exemple
Mkay
@earnest phoenix An error occurred while the command matched
whats the easiest way to let all shards share the same db (mysql) connection pool (possibly in the sharding managers process) ?
@zenith terrace well it looks like my issue is gone 😓
Lol what did you use
simply .setDescription('description \nto the line \n to the line')
Fun
See with description I can make stuff like this
Ok
It looks a whole lot better than .addField(). And no that looks good
bot is not defined
const { MessageEmbed } = require("discord.js");
module.exports = {
name: "ping",
category: "info",
description: "Returns latency and API ping",
run: async (client, message, args) => {
let msg = await message.channel.send('🏓 Pinging... 🏓')
const p = new MessageEmbed()
.setTitle("🏓 Pong! 🏓")
.setColor("#ff9900")
.addField("Letancy", `${Math.floor(msg.createdTimestamp - message.createdTimestamp)}ms`)
.addField("API letancy", `${Math.round(bot.ws.ping)}ms`);
msg.edit(p);
}
}
Help ?
I love the amoled theme
oh right
Thats why it aint defined
ty
Are you copying it from somewhere
how can i make it as when you level up on the amount of xp you need to level up adds like 70 per new level to the amount that you need to level up
the handler yes, because i tried so many times making one good and i didn't made it 😅
I'm trying to wait for an async function to finish and then call it again with different arguments, but it finishes but my code keeps waiting
The function I'm waiting for only uses awaits for async stuff and I return true at the end just to be sure
But nothing happens once it finishes the first time
what's your code
async function cycleStart(oids){
for(i=0;i<oids.length;i++){
console.log(i)
res = await deliver(oids[i])
}
}
cycleStart(oids);
deliver is the async function I'm waiting for
I fixed it and thanks
these people are rare xD
@spice smelt I think any major phone that was created recently has amoled :o
Well I used my phone to take that ss
In node.js discord.js, whats the easiest way to let all shards share the same db (mysql) connection pool (possibly in the sharding managers process) ?
how do i make it as every level you earn it adds like 70 to the amount you need to level up?
It definitley retuns because I can log what the function returns, I guess it just gives up because it isn't able to socially distance from the function
I also have a problem with DB when sharding
where is tim? 😭
Hibernating
You're asking for the exceedingly rare thing 
i don't get it.
are you really trying to use "this" in js?
Yes
is "this" a thing in js?
Yes
understandable

Is client users attached to this?
xignotic can you help me
Maybe
In node.js discord.js, is there an easy way to let all shards share the same db (mysql) connection pool (possibly in the sharding managers process) ?
ahhh okay i get it.
I thought of redirecting queries via ipc. but i did not manage to "await" return values from messages i send from a shard to the sharding manager using the libraries own functions / using node-ipc.
thanks for the solution xd.
:)
how to make send a dms to person to notice that they got kick/ban from a server ?
my level.js file
@viral spade If all shards share the same connection pool, then you could end up with one shard could starving all others
@earnest phoenix what do i do and on which file
mines look like this on kick and ban to.
so just add toBan.Send like that ?
the reason not string doesn't work.
@hasty sparrow True, but on the other hand this way it can balnce in a way that one shard that needs more get more from those who dont at that time.
Make sure to send the DM before the user is kicked/banned
yes i mean how i tried my friend code but it instead sending error.
@hasty sparrow more importantly, i dont need one connection per shard per database
How many databases do you have?
only two for testing purposes, but i want to design it in a way that i can have multiple.
for the long term
Are we talking multiple databases on one or multiple servers?
multiple servers, one db per server
Odd design choice
Depends on your use case, but a single (no)sql server can easily manage multiple databases
i mean its the same scheme, the guild data is sharded accross these databases
You might not even need multiple databases (like 1 per shard/guild is wasteful)
So that's like 100 idle connections to each db server, no big deal and much faster than having to create new connections cause the shared pool is empty
Not to mention the fact that you can't really share the pool to start with
Get to a 1000 shards and then worry about these kind of things, chances are other parts of your bot will fail before then
wait is member.user.tag mean to tag the person or it's user.tag to tag the person i'm a little bit confused because member.user.tag only shown the name and the tag but not pinged them.
What db are you using?
mysql
i know it can handle that many connections. its just too much ram, when say 10 bot servers à 100 shard exist, and each shard connects to all 10 databases.
@fickle arch the docs are your saviours during difficult moments
Why would each shard connect to all databases though?
@earnest phoenix
for example it's
`${member.user.tag} Has been muted.${
reason ? ` Reason ${reason}` : ""```
so i changed it to this ?
```return msg.sendMessage(
`${member.user} Has been muted.${
reason ? ` Reason ${reason}` : ""```
because what guild is on what shard changes when increasing shards
it's sure to ping the person right ?
so possibly, most likely each shard of 1000 guild will have at least one guild on each db server
The only way to share the connection between shards that I can think of right now would be to have all querying be done by a separate/parent process
tag is same with id or it's different ?
Right but as i said, i cannot find a way (node-ipc, d.js build in sharding messaging) to send a message and wait for the results
How would you even determine which server has which guild, if the shard a guild is in changes when the bot grows?
first time a guild is seen it caches the location
@earnest phoenix shown this xd.
it caches location from coordinator server
return msg.sendMessage(
`@${member.user.id} Has been kicked.${
reason ? ` Reason : ${reason}` : ""```
before i write member.user.tag instead of id.
let me replace tag with id
oh wait there's none.
like this ?
if (member.id === msg.author.id) throw "You cannot kick yourself.";
if (member.id === this.client.user.id) throw "I cannot kick myself.";
if (member.roles.highest.position >= msg.member.roles.highest.position)
throw "You cannot kick this user.";
if (!member.kickable) throw "I cannot kick this user.";
await member.kick(reason);
return msg.sendMessage(
`@${member.user.tag} Has been kicked.${
reason ? ` Reason : ${reason}` : ""```
@viral spade You could send your payload along with a unique identifier to the other process, register a callback with this identifier in your sharded process and when the shard receives a message/the result, check the identifier and call the registered callback with the returned payload/query result
interesting, but i would need to transfer guild, client etc. objects
to be able to keep on working after the callback has returned
@earnest phoenix i already make it into level 6 (people who have kick perm)
define i already tag the person it works before but it doesn't ping them only shown their name and tag but not ping
third the user is below mods.
As an alternative, what would you say about making one connection per query. The most critical part is that i need to cache the guildmember info i have (not much, a few properties) to the clients guildmember object, when that user first writes a message or talks in a voicechannel.

