#development
1 messages · Page 697 of 1
Oh no lol
all*
Thank both of y'all for the chat. I love communities that can bounce ideas/techniques off of each other.
lol you were just lucky and asked the question at the right time so you didnt get responses like "ew java"
Imagine saying 'ew java' 
That surely sounds like something, someone would say who doesn't know java 😛
Hello, my guildMemberAdd event (on d.js master) is not adding this role to the member.. it changes their nickname just fine meaning it has returned some data, but it completely skips the role adding part and gives no errors
module.exports = async (client, member) => {
const role = member.guild.roles.get("622954748148187138");
const data = await client.db.models.verify.findOne({
where: {
discord: member.id
}
});
if (data) {
member.roles.add(role);
const username = await client.rbx.getUsernameFromId(data.account);
member.setNickname(username);
} else {
member.send(`${member}, welcome to **RBX Trust**! To get started, you should verify your ROBLOX account with your Discord account... To do this, run the \`r.verify\` command! You can do this right here if you like!`).catch(() => null);
}
}
@earnest phoenix i might be wrong, but it could be member.addRole
thats on stable
make sure the role id is valid
@everyone
Don’t shitpost in development
is client.users.size shows all users that bot can see?
it shows cached users
if you want a total member count, go through each guild and sum up their memberCount property
oh ok. Thanks
the role ID is valid for sure, it works when I eval that code, but not on the guildMemberAdd event for some reason
but it executes everything else in that event
its weird
Is this where I can ask for help about discord.js
Adding a role that doesn’t exist is the only thing that silently fails in that situation @earnest phoenix
Try and log the role to make sure
Log in the code
Someone suggested something in my bot and I’d like to reply
I have the message command
But I can’t find the channel
Try and do .add(roleid) to see if it could be that
^
that did nothing, i logged the object this time too
can you try to eval adding the role to the member
the only other thing that comes to my mind is that it's erroring out due to permission/hierarchy errors but you aren't handling it properly
worked in eval
its not perms either
You have latest version of master right?
Strange
member.roles.add(role); -> member.roles.add(role.id); - you didn't do .id for the one you sent above @earnest phoenix
No he just typed in the role id I think?
In the code
worked again
Cuz we’ve proven that it works in eval
didnt work, but it still nicknames me without any issues, which is after the role add part
new code just to catch you up:
module.exports = async (client, member) => {
const data = await client.db.models.verify.findOne({
where: {
discord: member.id
}
});
if (data) {
member.roles.add("622954748148187138");
const username = await client.rbx.getUsernameFromId(data.account);
member.setNickname(username);
} else {
member.send(`${member}, welcome to **RBX Trust**! To get started, you should verify your ROBLOX account with your Discord account... To do this, run the \`r.verify\` command! You can do this right here if you like!`).catch(() => null);
}
}
Hm
its weird asf
Ask in djs server
defo master too
It was solved
lmao i checked the djs server to see what was the problem, pretty funny
big
edit the role itself or assign to/remove from a member?
edit the role itself
By default, yes. 50 requests per 1 second, but I don't see why you would need a role that much
rainbow role
that's against the tos for discord
really? but why? if i keep it slow? thats why I asked here
Meh, even if it's slow, I still wouldn't suggest doing it
👍
tbh i really wasn't keen to do it, only when it would be okay anyhow
I dont see an issue if the bots does some backend work on a timer though
ie. Updating databases
updating databases usually does not affect the discord api
unless you're doing something like fetch messages or fetch users regularly
Yep fetching stuff calls api
One message removed from a suspended account.
One message removed from a suspended account.
Sorry where i could ask
Do you need help with making a bot for that?
One message removed from a suspended account.
One message removed from a suspended account.
Rule 1 jesus
One message removed from a suspended account.
Nope i just need an idea for solution
One message removed from a suspended account.
But this channel name is development right ?
And that could be a question about development.
I mean
I want to use that soliton in my bots
You can use a basic filter, which would suck if they changed messages or some type of machine learning that is too complicated to teach for me.
Can we catch user updates with discord js ?
I know there is an memberupdate but its belong guild collection
userUpdate event
Thanks i should check docs again
i'm having trouble passing my database mysql connection to my event handlers
tried to follow arguments based on numeric input (e.,g. [1, 2, 3] and pass the same to the event [1, 2, 3]) yet my supposed database ends up "undefined"
show code?
@tight forum _?
alright tim, 1 sec yet again
// the "index.js"
let db = mysql.createConnection({
host: "localhost",
user: "root",
password: "hydrabolt-is-bae",
database: "flserv"
});
bot.on("emojiUpdate", async (bot, oldEmoji, newEmoji, db) => {});
// the "event handler.js"
module.exports = async (bot, oldEmoji, newEmoji, db) =>
{
db.query(`SELECT serverLog FROM serverInfo WHERE serverID = '${oldEmoji.guild.id}'`, async (err, rows) => {
if (err) throw err;
let logYN = rows[0].serverLog;
});
console.log(logYN);
if (logYN == 'Y') {
//sum code here
}```
sorry i cant actually understand whats wrong and what do u want to do
just ignore it, you end up filling this channel with extra off-topic talk
Okay than let me tell u something you cant console.log(logYN) cause logYN is defined as let it means you cant use that variable out of defined scope.
oh ye, that was because I was trying to pass it on from the index.js, so ignore that part
logYN is undefined becuase u are not defining it outside the scope
that isn't the issue, the issue is my 'db' isn't being passed down by the arguments from the index.js file to the event handler file
@quartz kindle sorry for ping, something popped into mind, my "bot" is being binded to each event by the event handler with bot.on(eventName, event.bind(null, bot)); would binding the db thru that work? if yes, how should I proceed to use it?
Hello ^^
It would help a lot if you send the code that created that error
Are you sure that member is define correctly
use find instead of has | ^ check that too
I already use Find and if it's a function
Guys, has of undefined, so he is calling has on something that doesn't exist
@stuck ravine are you sure rMember is defined as the member object and not e.g. as the user object
@hollow prawn I have something else for you to try
instead of js let db = mysql.createConnection({ host: "localhost", user: "root", password: "hydrabolt-is-bae", database: "flserv" });
do js bot.db = mysql.createConnection({ host: "localhost", user: "root", password: "hydrabolt-is-bae", database: "flserv" });
Then you don't need to pass db as it's own parameter
ohh that does seem like a good idea it will indeed save me trouble since bot is already binded to the events
You'd simply do bot.db intead of db
Yeah
It'd be easier
Then all you need is js bot.on("emojiUpdate", async (bot, oldEmoji, newEmoji) => {});
i'd have to change some other things here and there but that'll be alright
well i dont need bot there since its already binded as i said by the event handler
I think you may still need bot, but that's just what I do, but if not then yeah. Go ahead
well in any case i'll keep it in mind if it ends up being undefined or something
What is the ratelimit on changing a bot's display avatar, I cant find any information on it somehow
you cant find any info on it because almost all rate limits are dynamic
yeah i just want a general sense of how often is a good idea
there's not really a hard set number you'll find. You need to use the x-rate-limit-remaining header that it returns
which most libs dont provide and apply automatically
but
avatar changing might be one of the hard set ones
@loud salmon I saw you typing what you gonna say
@amber fractal just because you see me typing does not mean I actually have anything to say. Its nothing against you but I personally fucking hate the fact that people meme typing notifications so much. I would turn them off in an instant if I could.
I also hate unwarranted pings
No I thought you were going to say something because maybe I was giving him wrong information
I know you probably know that stuff better than I do
I am trying to make my bot work with AutoRole so it will assign roles by keywords, but I just can't figure it out
so it will add role based on role like "Member" "Joinee" "User" etc
you would want to tie those keywords to the role id's I think
Depending on the language could do a few things.
For instance djs, <Member>.guild.roles.find(r => /(member|join|user)/I.test(r.name));
Although no doubt going to get told otherwise by someone to not use regex because of some mad bullshit code injection or someshit.
I wish there was different development channels for different languages 😛
Its easier to have one.
Easier for you guys who use the more popular languages
Same, been trolling all day, seen no java haha
There's no need for more, you can ask all questions here and if you need more detailed support you can go to the library's official server
oof was half-way joking.
Java is and some other languages seem to be rare in here, although people still use them just not really beginners therefore don't often need help.
Java and*
smh Java /s
I watched your stream spider and it made me want to code in a more opp, strict language.
lol

strict lang best lang 
Yeah javascript seems so shit looking back to it.
I'm not near as proficient in js as I am in Java but the libraries like JDA are so robust, I don't see any reason to try another language for this use case
robust and well documented, half the questions I've seen here today just seem to be lack of documentation or how to find it, with a Java IDE you can just right click for documentation.
use catnip if you want to manage the cache and every other small thing in a java bot, use jda if you just want to make something that werks™
also you can do that in other ide's iirc
its just that more beginners use JS here
so they don't know where to find documentation
and go here for help
yes
kotlin gang
never used catnip but i heard its alright
gang gang
@scarlet phoenix kotlin more like javascript under the jvm
Im mostly a java dev but have been loving me some kotlin
how so?
more like java with better syntax lol
Same, I have been converting some code using IntelliJ and it's interesting
Most of my projects now are like half and half
BETTER SYNTAX? Lol to me it's like lazy, shorthand, yet more efficient
err more productive I should say
yea kotlin meshes well with standard java code
That's very true
I haven't yet touched scala
the logo sure looks snazzy thats for sure 👀
Ive been meaning to try scala, but still working out how to pronounce it
lmao
thought it was sca-la
lol maybe
i say sca - la
scalable 
Gud
thats nice
u ok?
I am a bit new to express, but the res.redirect() is not actually redirecting but is refreshing the webpage instead and adding a question mark to the end
app.post("/search", async (req, res) => {
if (!req.body.username) return;
const id = await client.rbx.getIdFromUsername(req.body.username).catch(() => null);
if (!id) res.status(404).send({ message: "user does not exist on ROBLOX" });
return res.redirect(`/profile/${id}`);
});
@earnest phoenix if i had to guess, it has something to do with the relative path you are currently on. what is the full endpoint for /search and the full endpoint for /profile/:id
how do i check for if a user is missing all permissions in a PermissionResolvable array?
right now it only checks if one is missing
@valid frigate i assume djs
yes
e.g. ["SEND_MESSAGES", "ADMINISTRATOR"] would return true even without the client having administrator
.has is funny
what are you currently using
o
i would try the following
oh hasPermission?
.has doesnt work if one of those permissions returns true
but .hasPermission worked
👌
id agree but
the description was "Checks if any of this member's roles have a permission"
Checks whether the bitfield has a permission, or multiple permissions.
maybe because it was multiple permissions
idk
if one was true it overrode the result
glad it worked
are you checking perms on the bot?
yeah
the bot as a user of the guild
member*
just saying though, dont need any additional help 
just saying 
hey
do you guys know how to set permissions for a channel when created
like only a certain group can view
@earnest phoenix what lib
discord.js stable
take a look at the ChannelData typedef
i think you got it from there
I've done a bit of research, but I couldn't find a good answer. How would I be able to use a database file to read and write variables per user? I have a command that can create and delete those files using the server ID to organize them, but I'm not sure how to go about writing the data to a file.
its pretty standard to use some kind of database to store that kind of data
Is there a way for the bot to auto organize it using discord.js, like stringify for JSONs
If you were gonna go that route
youd probably just want to convert the object into a json string and write that string to the file
but again
this is just reinventing the wheel
The idea is to have the bot create a file for each server that can store the score of each user during an event, even if the bot goes offline, the data is stored. When the event is ended, it will delete the file until a new event starts
it is recommended to use a proper database for that
something like sqlite
if you absolutely wanna go the file storage route, then look at node's fs functions
I'll look into it
It's going to be a small mostly private bot so I'm not concerned with having to many files and what not
the problem is not about that
is that if you dont know what you're doing, you risk data loss
^
and just generally reinventing the wheel
json files are prone to corruption if not handled correctly
^
people have been storing data for decades
Would there be a simpler way to store the data when the bot goes offline
rather than using sqlite or node's fs
node's fs is the simplest there is
you cant get any simpler than that
Let me do some reading
json files are prone to corruption if not handled correctly
speaking of which
const writeFileAtomic = require('write-file-atomically')
await writeFileAtomic('stats.json', JSON.stringify(stats, null, 2))```
Would there be a simpler way to store the data when the bot goes offline
rather than using sqlite or node's fs
yeah... cant be simplier than node's fs man
This is what I'm doing right now
if (message.content.startsWith (prefix + "startevent") || message.content.startsWith (prefix + "eventstart")) {
if (message.member.permissions.has('MANAGE_CHANNELS')) {
embed = new discord.RichEmbed ()
.setDescription ("**Begining an Event!**")
.setFooter ("*Please Wait A Moment Before Begining*")
.addField ("Server: " + message.guild.name, ":LoadBuffer:")
.setThumbnail (message.guild.iconURL)
.setColor ("#0086ff")
message.channel.send (embed)
var fs = require('fs')
fs.writeFile(message.guild.id + 'score.json', '', function (err) {
if (err) throw err;
console.log('Started Event!');
});
}
}
if (message.content.startsWith (prefix + "endevent") || message.content.startsWith (prefix + "eventend")) {
if (message.member.permissions.has('MANAGE_CHANNELS'))
embed = new discord.RichEmbed ()
.setDescription ("**Ending the Event**")
.setFooter ("Thanks for Using Robonics Bot!")
.addField ("Event Ended For: " + message.guild.name, ":white_check_mark:")
.setThumbnail (message.guild.iconURL)
.setColor ("#0086ff")
message.channel.send (embed)
var fs = require('fs')
fs.unlink(message.guild.id + 'score.json', function (err) {
if (err) throw err;
console.log('Event Ended!');
});
}
To clear the data easily
Yeah
thats... a weird approach
and you have separate files for separate guilds? also weird apprach
That way if a new event starts, the users get cleared and only people who are given a score will be included
why not one file with different guild ids as keys
i mean its gonna work probably but its weird af
Idk
Seemed simpler at the time
Just to write the files as server IDs + score.json
And store the data under the user
as long as you handle it and dont try to read a file that doesnt exist i guess
Yeah
in a way, if you are not gonna make use of any atomic write file fs modifications, this might actually be better, so it wont fuck up the entire "database", just one file
lol
I might use variables or something so the bot knows if an event is going on for that ID and doesn't try to read nonexistant files
This is why I like coding, problem solving
the most efficient way to use json files is to keep a copy of them in memory at all times
so instead of reading and writing all the time, you do one big read, then you only write
basically
you never want to actually read the file
except
let stats = require('../stats.json')
at the very start the the bot
Ok
but i didnt see any file reading on your code anyways so /shrug
Not yet
I need a way to read the file, turn it into a variable, and write the variable to the file under the user
With changes
if you do the method we are proposing, you wont need to read the file at runtime
because you already have the variable in memory
you still gotta write it tho, but i guess if hes gonna keep the "as many files as guilds" approach, the corruption problem risk is whatever
Send the error
I think you may need a compiler
@fallow quiver
you probably want to put them all into some separate directory and read them at bot booting via something like this
glob.sync('./scores/*.json').forEach( file => {
let json = require( path.resolve( file ) )
scores[json.guild_id] = json
})
// assuming the guildidscore.json looks like this
{
"guild_id" : "406969205661892608",
"scores" : ...
}```
wel dunno never did separate files that can get removed during bot uptime actually
So are you saying when the bot starts to read the JSON and set a variable like score = message.channel.author + [data read from JSON]
you will probably run into tons of problems
I might have to let the score reset when the bot goes offline
hard to tell without actually doing it since this apprach is not really normal
But that would be a problem I decide to run a long term event
its not a problem
I might have to let the score reset when the bot goes offline
correct mindset would be "reset when the bot goes online" actually, you can put some flag for long term events
everytime your event is updated, you will write the update to those files
as a backup
then if your bot restarts, he will re-read them all
and continue from where it left
so your main data is always in memory, the files are just a backup
this is also known as caching
If I decide to go for something like score = X can I do something like message.guild.id + message.author.id + "score" = X
It might be an alternative to making files
its a json, you can nest objects and stuff
ah you want to make up name of a variable?
thats... a no
But if I just need to store numeric data for now
you can make a dynamically named variable
There isn't any way to name a variable by something like that
but its not really a good idea, it can get messy
especially with snowflakes tbh
But since I'm just doing numeric values that should be easy right?
Then it can call on the data without reading a file
So how would I write that
var message.guild.id + message.author.id + "score" = X
or
message.guild.id + message.author.id = X
Or are neither correct and I'm just dumb trying to look for over simplified solutions
const database = {};
database[message.guild.id + message.author.id + "score"] = x```
^ or this, assuming theres some real reason you want such keys
and this will fuck you up
when you want to list top user scores in a guild etc
and shit
so just do it like on my screenshot
I just started this a few days ago and I think I picked an overambitious project
with my approach you can just loop through keys in certainGuildStats[guild_id] and have a list of top users
assuming thats something you'd want to have
// start of the document
let stats = {} // or let stats = require('stats.json')
// initialize guild (only once)
stats[message.channel.guild.id] = {}
// ...
let certainGuildStats = stats[message.channel.guild.id]
// add some members' score to the guild
certainGuildStats[message.author.id] = 5
certainGuildStats["292867854464843781"] = 15
certainGuildStats["146935827119865856"] = 15
this would produce a stats object (that can be saved to stats.json):
{
"246333358987018250": {
"153942038138585088": 5,
"292867854464843781": 15,
"146935827119865856": 15
}
}```
its not overambitious, its just logistics, think about how you want your data structure to look like, and code accordingly
you just need to learn how to think in a logistical way
its a great learning experience
Every time I think I have it worked out I over think it or rethink it and I just try a different approch
tell that to all projects ive rewritten countless times lol
i do have some old code that "works" but i could rewrite it in like 10 different ways and each one of them would be 10x better
that just happens when you javascript at first
everyone goes through that, you do something, rethink it, and figure out things you havent thought about before, and you redesign it, and improve it
Yeah when I first started my bot I used some example code but I restarted because I didn't like the way it was done
improving old code be like
Ok @potent ivy I put in your code using a test command
if (message.content.startsWith (prefix + prefix + "test")) {
// start of the document
let stats = {}
// initialize guild (only once)
stats[message.channel.guild.id] = {}
// ...
let certainGuildStats = stats[message.channel.guild.id]
// add some members' score to the guild
certainGuildStats[message.author.id] = 5
certainGuildStats["292867854464843781"] = 15
certainGuildStats["146935827119865856"] = 15
}
and got this error when I typed it in chat
}
^
SyntaxError: missing ) after argument list
Wait
Am I Stupid
I thought it said missing } after augment list and I read it several times
But where does it go
you want to store stats variable though
not initialize it everytime you start the command
Ah
and you want to initialize the guild only if it wasnt initialized already
cause if you do it, its gonna wipe the scores
I am pretty dumb at the moment
something like
// this initializes the guild object only if it doesnt exist in the stats obj
if (!stats[message.channel.guild.id]) stats[message.channel.guild.id] = {}```
should be enough tbh
but yeah if you put the let stats ={} somewhere else, out of any bot events etc, and replace your initialization line with the one i wrote just now, you should have yourself already a working database of member's scores per guild
just save the stats to some file at the end and there u go
I’ll work on it, I have to do something right now but thanks for the help. I’ll save this all to notes or something
That way it won’t work unless stats.json exists
why wouldnt it exist?
I don’t know
make stats.json file and put {} inside
I have
its gonna have all your guilds, members and their scores
and just never delete that file lol
So I shouldn’t need any other files because everything will be in the JSON
if some event ends or whatever you can just do stats[message.channel.guild.id] = {} again to "soft wipe" the guild's data
yeah
Cool, this is much easier than whatever I thought up
Code: ```const re = require ("discord.js")
exports.run = async (client, message, args) => {
let embed = new re.RichEmbed()
.setAuthor("🏓 Pinging.....")
const msg = await message.channel.send(embed);
let embed2 = new re.RichEmbed()
.setAuthor("🏓 Pong!")
.setDescription(📡**Latency**: ${Math.floor(msg.createdTimestap - message.createdTimestap)}ms\n💻**API Latency**: ${Math.round(client.ping)} ms)
msg.edit(embed2);
}
module.exports.help = {
name: "ping",
aliases: []
}```
Output:
But why?
async function guildBanAdd(guild, user) {
const res = await Guild.findOne({ where: { id: guild.id } })
console.log(res)
const logChannel = res.get('guildBanAdd')
const gBanEmbed = new Discord.MessageEmbed()
.setAuthor(user.username, user.displayAvatarURL({ format: "png" }))
.setDescription(`${user.username} was just banned`)
.setThumbnail(user.displayAvatarURL({ format: "png" }))
.addField('Time ', moment.duration(Date.now()).format("MM/DD/YY | HH:mm:ss"))
.setColor("BLURPLE")
.setTimestamp()
.setFooter(client.user.username, client.user.displayAvatarURL({ format: "png" }))
if (logChannel === null) {
return;
} else {
client.channels.get(logChannel).send(gBanEmbed)
}
}
This is still causing problems res is returning null I have that I just don't know why it is returning null the way I am getting the info using the guildID looks correct
<script>
function fixImage() {
document.getElementById("serverIcon").src ='https://cdn.discordapp.com/icons/493015512960204802/1a13b87b1966721a201015dcac032930.png'
}
</script>```
<img id="serverIcon" class="server_icon" src="<%= `https://cdn.discordapp.com/icons/${serverData.id}/${serverData.icon}.png`%>" onerror="return fixImage()">```
Is that
@stray garnet change createdTimestap to createdTimestamp
undefined - undefined = NaN
which is why youre getting NaNms
@coral trellis can u hop in general
Xig's problem has been solved
is there any way or tool to calculate regex match time ? | i mean i have an badword list and i want to know all how much take compare all words
uh
probably very small
but what you can do is create a variable that stores the epoc time when the badword finder starts checking
and then create a variable of another epoc time
then compare the 2
epoch1 = system.getEpoch()
//put code checker stuff here
epoch2 = system.getEpoch()
result = epoch2 - epoch1
probably wont be more than a few ms difference
unless your bad word list is unfathomably large
@spark kelp 
internal/modules/cjs/loader.js:638
throw err;
^
Error: Cannot find module '/Users/student/mybot.js'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
at Function.Module._load (internal/modules/cjs/loader.js:562:25)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)``` Can someone help me figure out what this means?
I followed the instructions on https://anidiots.guide/getting-started/getting-started-long-version
use change dir before running node mybot
change dir?
cd
change diaper if i say so myself
@young forge cd is create directory

cd command also know as chdir**(change directory)**
I'm thinking of mkdir
lol
what is the best profanity filter way by yourselves ?
what do u mean?
I don't have a profanity filter
It says no command found.
idk actually i mean i search some google about profanity filtering and i found regex way, string include way etc.
i mean regex is fast so it works nicely
rather than doing .include in a loop of an array of a profanity list
Yes?
I saw you typing
I was going to say something about the profanity filter but https://discordapp.com/channels/264445053596991498/272764566411149314/623338477785710611 this answered it
And the command to make a directory is mkdir
btw is it me or legit... u need to download a package for every simple fing function in py
like regex... u need a package, a random num generator, also a package
That's how it is for pretty much every lang
no?
yes?
no
no
Java and.js
in py you have to import every little shit 
pip is terrible too; it doesnt even come with python
Are just two langs out of hundreds
npm comes with node :^)
swift and others also have
py you gotta import the even builtin functions but ok
ye...

hi spider
keep rule 3 in mind yall
i aint bullying py just saying u have to import every small function
next probs is py have to import py itself
actually now I'm wondering
wut?
is it easier to make the function than import it
rarely tbh
I think my Bot is broken :/
m'boy's music module is broken... it plays fine but looks like garbage after the second song... is this api abuse? https://gyazo.com/6ab520d094485c792a58fb62baa30441
also rip nickname
oof
no? what are u using to play
believe it's nAudio
been a while since i messed with it
it's been doing that since discord.NET v2.1.0
If I am doing client.guilds.size for instance, how would i format the text on that?
like
I want to have something like clients.guilds.size
just want to put barticks on the number
put `` around it?
async function guildBanAdd(guild, user) {
const res = await Guild.findOne({ where: { id: guild.id } })
console.log(res)
const logChannel = res.get('guildBanAdd')
const gBanEmbed = new Discord.MessageEmbed()
.setAuthor(user.username, user.displayAvatarURL({ format: "png" }))
.setDescription(`${user.username} was just banned`)
.setThumbnail(user.displayAvatarURL({ format: "png" }))
.addField('Time ', moment.duration(Date.now()).format("MM/DD/YY | HH:mm:ss"))
.setColor("BLURPLE")
.setTimestamp()
.setFooter(client.user.username, client.user.displayAvatarURL({ format: "png" }))
if (logChannel === null) {
return;
} else {
client.channels.get(logChannel).send(gBanEmbed)
}
}
I have found res to be null that is why it is erroring the big question is why is it null
The guild matching the ID when using guild.id is in the table
and existing
and logChannel is also been set so it has no problems getting the log channel from the table either
I don't know why I have been getting this error, all my other events fire perfectly fine using this same method of getting info from the db
But res shouldn’t be null
It isn’t null
But it’s returning as null
And idk why
And I thought table would be enough to know I’m talking about SQLite
Or sql in general
@young forge u are using js or py?
okay so i developed a multi purpose bot and for some reasons the translator wont just work no matter what i do...anyone knows the solution?
pastebin code link :- https://pastebin.com/J1VJpWzm
Link because it contains more than 2000 char
function membercount(item, index) {
let a = client.guilds.get(item).memberCount;
console.log(a)
}
this is my code. I don't know how to say umm
has output like this
67869
60
12
306
4
I want to combine? these
do you call that function in a loop?
but do you want to add all of them, or only some of them?
oh I see
thanks
no wait. its for server count?
cause I'm using function for each server's memberCount
Yes, a reducer is the best way to do it, but reducer functions are a bit hard to understand for beginners
Do you know how array.reduce() works?
Reduce loops over all items and combines them into a single value
You need to specify how the reducer should process it, by giving it a function and an initial value
For example .reduce(function(result,item) {}, initial result)
Or using arrow functions .reduce((result,item) => {},initial result)
its bit much for me. Going to research . Thanks for help again
👍
how would you set a gif avatar in discord.js? i tried with client.user.setAvatar but it only sets it to a png, the gif is here: https://media.giphy.com/media/13gvXfEVlxQjDO/giphy.gif cause why not
How is a bot going to use a gif avatar
Yeah, bot's cannot use GIF avatars
There was a exploit a a while ago
oh
But it isn't allowed to do it anway
ok
so I recommend not doing it
If i buy a BC will it converted to PREMIUM?
i think so
try it
I am new in development of discord, for that reason I ask it xd.
As I don't know much about discord.js it occurred to me to create a web api and connect my bot with that api and also with the application. Is there a simpler way to do it?
umm...it is weird but idk for some reason this just wont work
client_secret = "my client secret",
user_agent="my user agent")
@client.command()
async def meme(ctx):
memes_submissions = reddit.subreddit("r/memes", "r/FilthyFrank", "r/dankmemes").hot()
post = random.randint(1, 10)
for i in range(0, post):
submissions = next(x for x in memes_submissions if not x.stickied)
await ctx.send(submission.url)```
any idea what i did wrong?
cuz i have checked thrice nothing is wrong in it nor any syntax error
the code is just passing doing nothing
AETERNUS read the documentation properly before developing a bot
Its searching for "r/memes", "r/FilthyFrank", "r/dankmemes"
yep

still no good ffs
k
I want to connect my app in vb.net with a discord webhook, it occurred to me to create a web api and connect my bot with that api and also with the app. Is there an easier way to do it?
e.e
just send the request directly to the webhook?
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
@mossy vine can ya tell me why my code passes doing nothing tho i have made respective changes to it
no
@grizzled valley You're using submission to send but you defined it as submissions
Also, in the worst case scenario your code will send 10 messages at once
Which will get you ratelimited
umm...any better way to make it work then?
Well
There's a bunch of solutions
- Send only 1 post
- Combine multiple posts into one message
u mean embedding the whole thing into one?
Yeh
k thanks
You could also show 1 but have the user make a selection through reactions or by adding a number
umm...nah xD im too lazy to code than rn...so will leave it to 10 msgs in one embed
Whatever works for you 
What?
^+1
It's not an easy limit to reach lol
Yeah but for larger bots at least
spam next page 
A lot of them had to remove them it’s sad
new rate limits?
Old by now but the 25k thing
For 403s, we've noticed bots not respecting the forbidden access response, and retrying requests ad-infinitum (one popular bot that got hit by the system was sending ~300,000 requests/hour to an endpoint they did not have permission to access.)
lmfao
lmao
lmaooo
@flat pelican
lmfaooooo
are there any links to know how to use the dbl voting?
the documentation
where?
Is their is any bot which auto kicks the users who are not logging in Discord for longer than 30D?
isnt that possible with member pruning
they can kick users one by one
Ye
or use the prune feature
But that is only possible if a user has not got any role.
^ discord should change that
Yes
no
is 500gb monthly bandwith for ~2500 servers normal?
I have more concern about that avatar
I'm not sure if the logging is even right but it seems pretty high
I guess so, it has to process every message
I wonder how much bandwidth was saved by shutting down #265156361791209475 lol
there was an array. the array would be like this. ['a', 'b', 'c']
how we can turn it to:
- a
- b
- c
For all those people who find it more convenient to bother you with their question rather than search it for themselves.
@ornate shoal 90% of a bot's bandwidth is caused by typing and presence updates
there is a way to completely disable them, but doing so also disables member-related updates
such as member join, member update and member delete
if your bot doesnt have welcome messages or other member-related events, you can disable it and save ~90% of your bandwidth costs
@grizzled valley js
Thanks, I'll look into disabling those
i dont know which libraries already support disabling it, discord.js does not at the moment (because it may cause other problems)
you need to disable it at the ws level, using guild_subscriptions = false in the ws options
Easy, just delete the source code 
I'm using discord.net
and the code is still pretty bad but I'm refactoring most of it, so I'll look into it
there's probably a ton more optimizations I can make
how do I bulk delete added emoji (discord.js)
??
clearReactions is used on a message
not a TextChannel
@quartz kindle you can disable events in the client constructor https://github.com/sycer-dev/giveaways/blob/a69e16b296ee94af5cbf2dbc6636614a8b90fab8/src/classes/GiveawayClient.ts#L31
How do I do it on the text channel
You don’t
You don't
Tatsumaki also had such a feature 🤔
You mean like removes reactions from all the messages in the channel?
You cant clear reactions on a channel
why the hell would you want to do that
I’m asking
ex !clear reactions 10
Berry I wasnt talking to you lol
@flint trellis that does not disable the event from being sent by discord, it only doesnt process it when it arrives
is there even a way to disable the event from being sent?
yes
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
disabling events like that changes almost nothing
guild_subscriptions = false
it's still parsed and processed
hi
client_secret = "eJdhbSuqx2iTuVidz1FeADXEV-Y",
user_agent="Pink_Guy (by /u/Som_S_Som")
@client.command()
async def meme(ctx):
memes_submissions = reddit.subreddit('memes').new()
post_to_pick = random.randint(0 , 1)
for i in range(0, post_to_pick):
submissions = next(x for x in memes_submissions if not x.stickied)
await ctx.send(submissions.url)```
is there any better ways to make the code work more accurately?
wdym as more accurate
like whenever i say !meme it replies with 1 meme and then stops for 1-2 hrs
like whenever i say !meme it wont work after sending one meme no matter how much more !meme commands i type
Sounds like blocking
why would there be backticks
I only used them to format the emoji
this is whats happening
@grizzled valley maybe try to add some debug logging statements
When you use discord dark mode but not chrome dark theme 😩
you can't without spamming the api
which will practically get you banned from the api
a user account is not equivalent to a bot account
of course
I keep getting ECONNREFUSED when connecting with mongoose with a url that starts with mongodb+srv://
I'm trying to make a bot that has a level function, but I can't get it to work... I watched https://youtu.be/pKkrCHnun0M but it didn't work for me... Any ideas?
In this video, we create a level system that allows users to level up based on how many messages they send in the server. Join here: https://discord.gg/4Fy88...
use the rewrite version
there has been a lot of change
@tough rock go through this https://discordpy.readthedocs.io/en/latest/
@grizzled valley Thanks!
nvm
does any one know how discord scrapes the content of a website? is it via the twitter meta tags?
not twitter meta tags, opengraph meta tags yes
alright, thx
[discord.py] how to see uptime?
just use datetime
right after declaring bot/client, add another property to the bot variable (e.g bot.uptime)
then, when needed, you would subtract current time from the time when the bot variable was declared
is this a good way of doing it?
const Client = require("discord-tag");
let client = new Client()
// Add a prefix
.addPrefix("!")
// Set a log function
.setLog(console.log)
// Add a command
.addCommand("commandname", "command response")
// Add a command using a function
.addCommand("commandname2", (message, send) => {
send("Yada");
})
// Add a command that deletes the invoking message
.addCommand("commandname3", "command response", true)
// Log in and start the bot
.login(YOUR_BOT_TOKEN);```
fine ill ask here im scared tho

its a tag bot library im making
instead of people using bulky libraries just for some tags it uses the discord-no-cache lib i made a few days ago to make it super lightweight just for command response bots
if(!vUser) return message.channel.send(embed41);
if (vUser === message.author) return;```
im trying to make it so the person that uses the command can't be voted
how can i make it so vUser can't be the author of the message?
compare ids, not objects
let vUser = message.mentions.members.first() || message.guild.members.get(args[0]);
if (!vUser) return message.channel.send(embed41);
if (vUser.id === message.author.id) return;```
rewrote it a bit
<GuildMember>.id does not exist in discord.js to my knowledge
let me check
I'd suggest using an alternative method like using regex and grabbing ids/ids from mentions then checking if the member or user is fetched for cache purposes.
it does exist
It does work
that's why python is better (keeping rule 3c in mind)
thankyou very much @idle basalt
np
it does work. Didn't work for me in the past 
@west spoke How VERY TRUE 😉
how do you chat in js format in
```js
code here
```
oh
U tried
you can put any language there

like cpp py or whatever you want
```js
```
sure
I did have one more question but it's quite a big one/noobish question
thats fine
basically, at the moment I have the bot write in a seprate channel who voted for who
^
how would i have the bot store that information in a json file?
just write values to it
json as db isnt preferable
what would be?
but if you want to do that, use the built in fs module to write to a file
a db lol
writing to files can get very messy so for any type of non-static storage its typically recommended to use a database
theyre designed specifically to store dynamic data
oh i dont mind i dont store much
how woul.d i go about that?
const fs = require('fs');
fs.writeFile('yourfilename.json', 'stufftowrite', console.log)```
let me try'
if you plan on making multiple writes, it will be easier to use writeFileSync
yes i do
const fs = require('fs');
fs.writeFileSync('file.json', 'anything you want');
fs.writeFileSync('file.json', 'more stuff you want');```
fileSync will block the execution of further code until it finishes (i think)
https://nodejs.org/api/fs.html these are the docs for fs (native file system module)
basically everything you need for file interaction will be in here
im really having trouble with this ...
how would i have it log js message.mentions.users.first() + " has been voted by " + message.author
need to newline
also no spaces before js
lol'
right now youre writing two huge objects
yea
no newline before js
who cares lol
just for next time
do you just want their names or do you want their entire object
make that the second argument
i kinda want it so like
{"472510930949767197":{"votes: 1}}
or like the vote count
fs.writeFileSync('file.json', JSON.stringify({ [message.author.id]: { votes: 1 } });
let me see one sec
you can concatenate strings if you like but personally id just use JSON.stringify() on a normal object
you can build the object before you put it into the function if you want it to look a bit cleaner (especially when you get more data)
youll have to append the file every time though, which will be more difficult
honestly you want a database
yea but i only need to have it store for like 1 day
and then it gets reset
if this doesnt work ill get one
@idle basalt how do i make the votes increase if you get voted again?
im not gonna write the whole program for you 🌚
haha okay 🙂
first you read the file, then you change the part you need, then you write that new change
async function guildBanAdd(guild, user) {
const res = await Guild.findOne({ where: { id: guild.id } })
console.log(res)
const logChannel = res.get('guildBanAdd')
const gBanEmbed = new Discord.MessageEmbed()
.setAuthor(user.username, user.displayAvatarURL({ format: "png" }))
.setDescription(`${user.username} was just banned`)
.setThumbnail(user.displayAvatarURL({ format: "png" }))
.addField('Time ', moment.duration(Date.now()).format("MM/DD/YY | HH:mm:ss"))
.setColor("BLURPLE")
.setTimestamp()
.setFooter(client.user.username, client.user.displayAvatarURL({ format: "png" }))
if (logChannel === null) {
return;
} else {
client.channels.get(logChannel).send(gBanEmbed)
}
}
I have found res to be null that is why it is erroring the big question is why is it null. Though it shouldn’t be because the guild is in the table it exists so the question is why is it returning null
again, a database would make this significantly easier (harder to set up if youre a beginner but definitely easier once youre going)
My db is being a bitch
what is Guild
Returning null when it isn’t supposed to
const { Guild } = require('../library/seq_db.js')
I’m using sequelize btw
Not mongodb
Idk what you mean by the last one but give me a sec and I’ll show you the whole file
if you prevent it from possibly being triggered by a dm
That is possible with guildBanAdd?
not from the event, but if you run that function on a manual ban command and some weirdo tries to run the command in dms
something like that yes
Pretty sure I restrict commands to guild only
then the only other possibility is that the guild is not in the database
is it a known guild or a recently added guild?
Hello how would I make a command that changes the prefix and stores the prefix I am making a public bot
Other events run fine using the same method of retrieving info from the db
const { Guild } = require('../library/seq_db.js')
const Discord = require('discord.js')
const moment = require('moment')
module.exports.load = client => {
client.on('guildBanAdd', guildBanAdd)
}
module.exports.unload = client => {
client.removeListener('guildBanAdd', guildBanAdd)
}
async function guildBanAdd(guild, user) {
const res = await Guild.findOne({ where: { id: guild.id } })
const logChannel = res.get('guildBanAdd')
console.log(logChannel)
const gBanEmbed = new Discord.MessageEmbed()
.setAuthor(user.username, user.displayAvatarURL({ format: "png" }))
.setDescription(`${user.username} was just banned`)
.setThumbnail(user.displayAvatarURL({ format: "png" }))
.addField('Time ', moment.duration(Date.now()).format("MM/DD/YY | HH:mm:ss"))
.setColor("BLURPLE")
.setTimestamp()
.setFooter(client.user.username, client.user.displayAvatarURL({ format: "png" }))
if (logChannel === null) {
return;
} else {
client.channels.get(logChannel).send(gBanEmbed)
}
}
That is my whole file
use a database to store the prefix values for each guild
ahhh, it can't write more than one message in a json file for some reason
and then in your command, find the correct guilds prefix and change it
Would mongo db work
sure
@lusty dew try to log guild along with res
@idle basalt how come it won't write more than one message in the json file?
mongo db is a little slow compared to other databases, but it works just fine for 90% of the time. You only really need SQL in high-end bots, or in bots that do a lot of writing/reading data.
i cant tell you that without seeing your code
Mongodb was becoming too slow
uh
you
I've never had issues with mongo
its the code you sent
I never really timed it's responses tho
fs.writeFileSync('votes.json', JSON.stringify({ [vUser]: { votes: 1 } }));
I dont actually do a lot of discord bot coding anymore
I hope you're not reading/writing in megabytes a day.
@lusty dew
well it only writes that one line because thats all youre putting in
its just a normal js object
@earnest phoenix fs writes whole files at once, so you need to read the file, edit it and write the whole file back at once
you can add as much as you need
but its worked with tther bots
im getting really frustrated with this lol
i dont know how to do it
do you understand how json works?
yes
I didn’t even know that
so json is an object in text format
I just knew how Json worked
object = {key:value}
json = "{key:value}"
i just dont know how to be able to save it on there
json is an object represented as plain text
because, if i need to rewrite the whole file,
how would i have it sync from what was in there before
to be in too?
there is appendFile
once you understand how json works
you understand what you need to do
you need to do the following
assuming you already have a json file
yes
Tim I logged guild and got the guild object
- read the json file
- convert the json text into an object
- edit the object, add/remove/modify values
- convert the object to json again
- write the json data to file
nothing works after you defined res?





