#development

1 messages · Page 697 of 1

earnest phoenix
#

if you lurk around this channel you'll often see that the stupidest of questions are mostly asked by python and javascript users

marsh frost
#

Oh no lol

mossy vine
#

all*

marsh frost
#

Thank both of y'all for the chat. I love communities that can bounce ideas/techniques off of each other.

mossy vine
#

lol you were just lucky and asked the question at the right time so you didnt get responses like "ew java"

marsh frost
#

Imagine saying 'ew java' Kek

#

That surely sounds like something, someone would say who doesn't know java 😛

earnest phoenix
#

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);
    }
}
modern elm
#

@earnest phoenix i might be wrong, but it could be member.addRole

earnest phoenix
#

thats on stable

modern elm
#

like member.addRole(role)

#

oh

#

:3

earnest phoenix
#

make sure the role id is valid

small latch
#

@everytwo

#

Is that not a default role?

#

@everythree

earnest phoenix
#

@everyone

slim heart
#

Don’t shitpost in development

unkempt ocean
#

is client.users.size shows all users that bot can see?

earnest phoenix
#

it shows cached users

#

if you want a total member count, go through each guild and sum up their memberCount property

unkempt ocean
#

oh ok. Thanks

earnest phoenix
#

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

vivid mortar
#

Is this where I can ask for help about discord.js

twilit rapids
#

Yes

#

But for better support I would advise to go to their official server

slim heart
#

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

earnest phoenix
slim heart
#

Log in the code

earnest phoenix
#

alright

slim heart
#

The role object

#

Or did you just log the name?

earnest phoenix
vivid mortar
#

Someone suggested something in my bot and I’d like to reply

#

I have the message command

#

But I can’t find the channel

slim heart
#

Try and do .add(roleid) to see if it could be that

earnest phoenix
#

^

#

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

slim heart
#

You have latest version of master right?

earnest phoenix
#

yeah freshly installed yesterday

#

discordjs/discord.js

slim heart
#

Strange

wet kite
#

member.roles.add(role); -> member.roles.add(role.id); - you didn't do .id for the one you sent above @earnest phoenix

slim heart
#

No he just typed in the role id I think?

earnest phoenix
#

i did do .id

slim heart
#

No

#

Type in the I’d

#

Like .roles.add("1235")

earnest phoenix
slim heart
#

In the code

earnest phoenix
#

worked again

slim heart
#

Cuz we’ve proven that it works in eval

earnest phoenix
#

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);
    }
}
slim heart
#

Hm

earnest phoenix
#

its weird asf

slim heart
#

Ask in djs server

earnest phoenix
quartz kindle
#

await it or catch it

#

see if it generates an error

slim heart
#

It was solved

quartz kindle
#

lmao i checked the djs server to see what was the problem, pretty funny

livid rivet
#

hey quick question again

#

anyone knows the rate limit on editing roles?

west spoke
#

big

slender thistle
#

edit the role itself or assign to/remove from a member?

livid rivet
#

edit the role itself

slender thistle
#

50/1s by default

#

Ratelimits aren't static

livid rivet
#

so that means 50 requests per second are allowed 🤔

#

sry im dumb

slender thistle
#

By default, yes. 50 requests per 1 second, but I don't see why you would need a role that much

livid rivet
#

rainbow role

grim aspen
#

that's against the tos for discord

livid rivet
#

really? but why? if i keep it slow? thats why I asked here

livid rivet
#

lmao

#

okay i see

slender thistle
#

Meh, even if it's slow, I still wouldn't suggest doing it

livid rivet
#

hmm.. dommage

#

anyways thank you guys for your quick response

slender thistle
#

👍

livid rivet
#

tbh i really wasn't keen to do it, only when it would be okay anyhow

shut crow
#

I dont see an issue if the bots does some backend work on a timer though

#

ie. Updating databases

quartz kindle
#

updating databases usually does not affect the discord api

#

unless you're doing something like fetch messages or fetch users regularly

earnest phoenix
#

Yep fetching stuff calls api

spark kelp
sage bobcat
#

One message removed from a suspended account.

#

One message removed from a suspended account.

spark kelp
#

Sorry where i could ask

slender thistle
#

Do you need help with making a bot for that?

sage bobcat
#

One message removed from a suspended account.

amber fractal
#

Dv m8

#

What the fuck

sage bobcat
#

One message removed from a suspended account.

amber fractal
#

Rule 1 jesus

sage bobcat
#

One message removed from a suspended account.

spark kelp
#

Nope i just need an idea for solution

sage bobcat
#

One message removed from a suspended account.

spark kelp
#

But this channel name is development right ?

amber fractal
#

And that could be a question about development.

slender thistle
#

I mean

spark kelp
#

I want to use that soliton in my bots

amber fractal
#

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.

spark kelp
#

Can we catch user updates with discord js ?

#

I know there is an memberupdate but its belong guild collection

smoky spire
#

userUpdate event

amber fractal
spark kelp
#

Thanks i should check docs again

tight forum
#

@spark kelp

hollow prawn
#

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"

quartz kindle
#

show code?

spark kelp
#

@tight forum _?

tight forum
hollow prawn
#

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
    }```
spark kelp
#

sorry i cant actually understand whats wrong and what do u want to do

hollow prawn
#

just ignore it, you end up filling this channel with extra off-topic talk

spark kelp
#

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.

hollow prawn
#

oh ye, that was because I was trying to pass it on from the index.js, so ignore that part

grave pilot
#

logYN is undefined becuase u are not defining it outside the scope

hollow prawn
#

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?

stuck ravine
twilit rapids
#

It would help a lot if you send the code that created that error

stuck ravine
twilit rapids
#

Are you sure that member is define correctly

spark kelp
#

use find instead of has | ^ check that too

delicate zephyr
#

Its not the function

#

but yea

#

find and has should work

stuck ravine
#

I already use Find and if it's a function

twilit rapids
#

Guys, has of undefined, so he is calling has on something that doesn't exist

delicate zephyr
#

Timo I said that

#

Member isnt defined properly

twilit rapids
#

@stuck ravine are you sure rMember is defined as the member object and not e.g. as the user object

high lava
#

@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

hollow prawn
#

ohh that does seem like a good idea it will indeed save me trouble since bot is already binded to the events

high lava
#

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) => {});

hollow prawn
#

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

high lava
#

I think you may still need bot, but that's just what I do, but if not then yeah. Go ahead

hollow prawn
#

well in any case i'll keep it in mind if it ends up being undefined or something

dusky marsh
#

What is the ratelimit on changing a bot's display avatar, I cant find any information on it somehow

amber fractal
#

you cant find any info on it because almost all rate limits are dynamic

dusky marsh
#

yeah i just want a general sense of how often is a good idea

amber fractal
#

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

loud salmon
#

@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

amber fractal
#

No I thought you were going to say something because maybe I was giving him wrong information

loud salmon
#

that have no real value

#

kk

amber fractal
#

I know you probably know that stuff better than I do

sly parcel
#

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

hollow prawn
#

you would want to tie those keywords to the role id's I think

warm marsh
#

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.

marsh frost
#

I wish there was different development channels for different languages 😛

warm marsh
#

Its easier to have one.

marsh frost
#

Easier for you guys who use the more popular languages

warm marsh
#

More popular langauges lmao

#

I use java.

marsh frost
#

Same, been trolling all day, seen no java haha

twilit rapids
#

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

marsh frost
#

oof was half-way joking.

warm marsh
#

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*

loud salmon
#

java gang

twilit rapids
#

smh Java /s

warm marsh
#

I watched your stream spider and it made me want to code in a more opp, strict language.

loud salmon
#

lol

marsh frost
loud salmon
#

strict lang best lang ryukoSip

warm marsh
#

Yeah javascript seems so shit looking back to it.

marsh frost
#

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.

loud salmon
#

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

marsh frost
#

🥄

#

I have not looked into catnip. Used JDA, JavaCord and D4J though.

loud salmon
#

blobspoonfeed yes

marsh frost
#

yoink

#

thanks for the emote

scarlet phoenix
#

kotlin gang

loud salmon
#

never used catnip but i heard its alright

marsh frost
#

gang gang

loud salmon
#

@scarlet phoenix kotlin more like javascript under the jvm

scarlet phoenix
#

Im mostly a java dev but have been loving me some kotlin

marsh frost
#

how so?

scarlet phoenix
#

more like java with better syntax lol

marsh frost
#

Same, I have been converting some code using IntelliJ and it's interesting

scarlet phoenix
#

Most of my projects now are like half and half

marsh frost
#

BETTER SYNTAX? Lol to me it's like lazy, shorthand, yet more efficient

scarlet phoenix
#

so nice that you can use both

#

Data classes are so much easier

#

super nice

marsh frost
#

err more productive I should say

loud salmon
#

yea kotlin meshes well with standard java code

marsh frost
#

That's very true

loud salmon
#

i need to code in scala and kotlin a bit

#

actually have some fun with it

marsh frost
#

I haven't yet touched scala

loud salmon
#

the logo sure looks snazzy thats for sure 👀

scarlet phoenix
#

Ive been meaning to try scala, but still working out how to pronounce it

marsh frost
#

lmao

loud salmon
#

skay-la

#

like

#

gay-la

marsh frost
#

thought it was sca-la

loud salmon
#

lol maybe

scarlet phoenix
#

i say sca - la

marsh frost
#

although scay-la makes sense

#

scalability Kek

loud salmon
#

scalable blobowo

marsh frost
#

its a meme lol, haven't heard of scala being scalable at all

#

could be dead wrong.

west spoke
#

bruh

#

hey spider

loud salmon
#

hi

#

hows u

west spoke
#

Gud

loud salmon
#

thats nice

west spoke
#

u ok?

earnest phoenix
#

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}`);
});
eternal mesa
#

@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

valid frigate
#

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

eternal mesa
#

@valid frigate i assume djs

valid frigate
#

yes

#

e.g. ["SEND_MESSAGES", "ADMINISTRATOR"] would return true even without the client having administrator

#

.has is funny

eternal mesa
#

what are you currently using

#

o

#

i would try the following

valid frigate
#

oh hasPermission?

eternal mesa
#

ye

#

it accepts a PermissionResolvable which can be an array of permissions

valid frigate
#

yea same with .has but

#

this might be different

#

let me test it out

eternal mesa
#

i mean reading the docs .has() should work

#

but im not too sure

valid frigate
#

.has doesnt work if one of those permissions returns true

#

but .hasPermission worked

#

👌

eternal mesa
#

thats awfully strange

#

but ok

valid frigate
#

id agree but

#

the description was "Checks if any of this member's roles have a permission"

eternal mesa
#

Checks whether the bitfield has a permission, or multiple permissions.

valid frigate
#

maybe because it was multiple permissions

eternal mesa
#

idk

valid frigate
#

if one was true it overrode the result

eternal mesa
#

glad it worked

valid frigate
#

yeah js is weird edition 2

#

thx

eternal mesa
#

are you checking perms on the bot?

valid frigate
#

yeah

#

the bot as a user of the guild

#

member*

#

just saying though, dont need any additional help mmulu

eternal mesa
#

just saying think

valid frigate
#

oh fuck

#

didnt know this existed

#

lmao thanks mmLol

earnest phoenix
#

hey

#

do you guys know how to set permissions for a channel when created

#

like only a certain group can view

eternal mesa
#

@earnest phoenix what lib

earnest phoenix
#

discord.js stable

eternal mesa
#

take a look at the ChannelData typedef

earnest phoenix
#

so how would you change it for one specific role

#

nvm

eternal mesa
#

i think you got it from there

fallow quiver
#

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.

hushed berry
#

its pretty standard to use some kind of database to store that kind of data

fallow quiver
#

Is there a way for the bot to auto organize it using discord.js, like stringify for JSONs

hushed berry
#

discord.js is a discord lib

#

not a database

fallow quiver
#

I know

#

I just saying what my bot is based in

hushed berry
#

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

fallow quiver
#

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

quartz kindle
#

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

fallow quiver
#

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

quartz kindle
#

the problem is not about that

#

is that if you dont know what you're doing, you risk data loss

west spoke
#

^

hushed berry
#

and just generally reinventing the wheel

quartz kindle
#

json files are prone to corruption if not handled correctly

west spoke
#

^

hushed berry
#

people have been storing data for decades

fallow quiver
#

Would there be a simpler way to store the data when the bot goes offline

#

rather than using sqlite or node's fs

quartz kindle
#

node's fs is the simplest there is

quartz kindle
#

you cant get any simpler than that

fallow quiver
#

Let me do some reading

potent ivy
#

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

fallow quiver
#

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!');
            });
    }
potent ivy
#

why are you unlinking

#

thats removing the rifle, isnt it

fallow quiver
#

To clear the data easily

potent ivy
#

huh

#

you remove the whole file to clear the data?

fallow quiver
#

Yeah

potent ivy
#

thats... a weird approach

#

and you have separate files for separate guilds? also weird apprach

fallow quiver
#

That way if a new event starts, the users get cleared and only people who are given a score will be included

potent ivy
#

why not one file with different guild ids as keys

#

i mean its gonna work probably but its weird af

fallow quiver
#

Idk

#

Seemed simpler at the time

#

Just to write the files as server IDs + score.json

#

And store the data under the user

potent ivy
#

as long as you handle it and dont try to read a file that doesnt exist i guess

fallow quiver
#

Yeah

potent ivy
#

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

fallow quiver
#

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

quartz kindle
#

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

potent ivy
#

basically

#

you never want to actually read the file

#

except

#
let stats = require('../stats.json')
#

at the very start the the bot

fallow quiver
#

Ok

potent ivy
#

but i didnt see any file reading on your code anyways so /shrug

fallow quiver
#

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

quartz kindle
#

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

potent ivy
#

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

fallow quiver
#

Send the error

west spoke
#

I think you may need a compiler

potent ivy
#

@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

fallow quiver
#

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]

potent ivy
#

you will probably run into tons of problems

fallow quiver
#

I might have to let the score reset when the bot goes offline

potent ivy
#

hard to tell without actually doing it since this apprach is not really normal

fallow quiver
#

But that would be a problem I decide to run a long term event

quartz kindle
#

its not a problem

potent ivy
#

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

quartz kindle
#

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

fallow quiver
#

If I decide to go for something like score = X can I do something like message.guild.id + message.author.id + "score" = X

potent ivy
#

wtf

#

why

#

you can, but why

fallow quiver
#

It might be an alternative to making files

potent ivy
#

its a json, you can nest objects and stuff

#

ah you want to make up name of a variable?

#

thats... a no

fallow quiver
#

But if I just need to store numeric data for now

quartz kindle
#

you can make a dynamically named variable

fallow quiver
#

There isn't any way to name a variable by something like that

quartz kindle
#

but its not really a good idea, it can get messy

potent ivy
#

especially with snowflakes tbh

fallow quiver
#

But since I'm just doing numeric values that should be easy right?

#

Then it can call on the data without reading a file

quartz kindle
#

make it a key in an object

#

dont make it a global variable

fallow quiver
#

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

potent ivy
#

mate

#

objects

quartz kindle
#
const database = {};

database[message.guild.id + message.author.id + "score"] = x```
potent ivy
#

^ 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

fallow quiver
#

I just started this a few days ago and I think I picked an overambitious project

potent ivy
#

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

fallow quiver
#

So would I replace my +eventstart command with that

#

I feel overly dumb

potent ivy
#
// 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
  }
}```
quartz kindle
#

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

fallow quiver
#

Every time I think I have it worked out I over think it or rethink it and I just try a different approch

quartz kindle
#

tell that to all projects ive rewritten countless times lol

potent ivy
#

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

quartz kindle
#

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

fallow quiver
#

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

potent ivy
fallow quiver
#

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

potent ivy
#

you want to store stats variable though

#

not initialize it everytime you start the command

fallow quiver
#

Ah

potent ivy
#

and you want to initialize the guild only if it wasnt initialized already

#

cause if you do it, its gonna wipe the scores

fallow quiver
#

I am pretty dumb at the moment

potent ivy
#

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

fallow quiver
#

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

potent ivy
#

and actually let stats = require('stats.json')

#

so it reads it when it starts

fallow quiver
#

That way it won’t work unless stats.json exists

potent ivy
#

why wouldnt it exist?

fallow quiver
#

I don’t know

potent ivy
#

make stats.json file and put {} inside

fallow quiver
#

I have

potent ivy
#

its gonna have all your guilds, members and their scores

#

and just never delete that file lol

fallow quiver
#

So I shouldn’t need any other files because everything will be in the JSON

potent ivy
#

if some event ends or whatever you can just do stats[message.channel.guild.id] = {} again to "soft wipe" the guild's data

#

yeah

fallow quiver
#

Cool, this is much easier than whatever I thought up

stray garnet
#

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?

lusty dew
#
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

coral trellis
#
<script>
    function fixImage() {
        document.getElementById("serverIcon").src ='https://cdn.discordapp.com/icons/493015512960204802/1a13b87b1966721a201015dcac032930.png'
    }
</script>```
low wasp
#
<img id="serverIcon" class="server_icon" src="<%= `https://cdn.discordapp.com/icons/${serverData.id}/${serverData.icon}.png`%>" onerror="return fixImage()">```
coral trellis
#

Is that

idle basalt
#

@stray garnet change createdTimestap to createdTimestamp

#

undefined - undefined = NaN

#

which is why youre getting NaNms

low wasp
#

@coral trellis can u hop in general

coral trellis
#

I can't speak nor hear

#

So not really

low wasp
#

ok

#

was just going to show without any audio

low wasp
#

Xig's problem has been solved

spark kelp
#

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

loud salmon
#

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 this

young forge
#
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?
grim aspen
lament meteor
#

use change dir before running node mybot

young forge
#

change dir?

eternal mesa
#

cd

lament meteor
#

change diaper if i say so myself

grim aspen
#

@young forge cd is create directory

lament meteor
#

no?

#

its change

eternal mesa
lament meteor
#

cd command also know as chdir**(change directory)**

grim aspen
#

I'm thinking of mkdir

lament meteor
#

lol

spark kelp
#

what is the best profanity filter way by yourselves ?

lament meteor
#

what do u mean?

grim aspen
#

I don't have a profanity filter

young forge
#

It says no command found.

spark kelp
#

idk actually i mean i search some google about profanity filtering and i found regex way, string include way etc.

lament meteor
#

i mean regex is fast so it works nicely

#

rather than doing .include in a loop of an array of a profanity list

grim aspen
#

Hm what's this name

#

@glacial beacon

glacial beacon
#

Yes?

grim aspen
#

I saw you typing

glacial beacon
#

And the command to make a directory is mkdir

lament meteor
#

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

dusky marsh
#

That's how it is for pretty much every lang

lament meteor
#

no?

dusky marsh
#

yes?

broken shale
#

no

glacial beacon
#

no

lament meteor
#

i mean random number generator is built into js and java

#

regex also

dusky marsh
#

Java and.js

broken shale
#

in py you have to import every little shit GWcorbinHolyFuck

glacial beacon
#

pip is terrible too; it doesnt even come with python

dusky marsh
#

Are just two langs out of hundreds

broken shale
#

npm comes with node :^)

lament meteor
#

swift and others also have

broken shale
#

py you gotta import the even builtin functions but ok

lament meteor
#

ye...

loud salmon
lament meteor
#

hi spider

loud salmon
#

keep rule 3 in mind yall

lament meteor
#

i aint bullying py just saying u have to import every small function

#

next probs is py have to import py itself

broken shale
#

actually now I'm wondering

lament meteor
#

wut?

broken shale
#

is it easier to make the function than import it

lament meteor
#

rarely tbh

young forge
#

I think my Bot is broken :/

ionic compass
#

also rip nickname

#

oof

lament meteor
#

no? what are u using to play

ionic compass
#

believe it's nAudio

#

been a while since i messed with it

tight mountain
#

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

lavish shuttle
#

put `` around it?

tight mountain
young forge
#

Can someone help me out with my bot tomorrow?

#

I'm having problems setting it up.

lusty dew
#
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

lament meteor
#

what db?

#

also if there is the error then just do if (res === null) return

lusty dew
#

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

grizzled valley
#

@young forge u are using js or py?

grizzled valley
#

Link because it contains more than 2000 char

unkempt ocean
#
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

quartz kindle
#

do you call that function in a loop?

unkempt ocean
#

no

#

Addition is the word I'm looking for tho

quartz kindle
#

but do you want to add all of them, or only some of them?

unkempt ocean
#

all

#

for total users

quartz kindle
#

then its easier to do that without a function

#

using client.guilds.reduce()

unkempt ocean
#

oh I see

#

thanks

#

no wait. its for server count?

#

cause I'm using function for each server's memberCount

quartz kindle
#

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?

unkempt ocean
#

no xd

#

wait yes

#

but not much. I have serious problems about explain myself

grizzled valley
#

just google it

#

or just read through the documentation

#

that helps alot

quartz kindle
#

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)

unkempt ocean
#

its bit much for me. Going to research . Thanks for help again

quartz kindle
#

👍

weary lark
slender thistle
#

How is a bot going to use a gif avatar

twilit rapids
#

Yeah, bot's cannot use GIF avatars

weary lark
twilit rapids
#

There was a exploit a a while ago

weary lark
#

oh

twilit rapids
#

But it isn't allowed to do it anway

weary lark
#

ok

twilit rapids
#

so I recommend not doing it

weary lark
#

i wont

#

cause i understand

bronze urchin
#

If i buy a BC will it converted to PREMIUM?

earnest phoenix
#

Is it possible to connect discord webhooks with an application on vb.net?

mossy vine
#

i think so

weary lark
#

try it

earnest phoenix
#

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?

grizzled valley
#

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

unique nimbus
#

Its searching for "r/memes", "r/FilthyFrank", "r/dankmemes"

grizzled valley
#

yep

unique nimbus
#

oh yes you don't need to do r/

#

remove it

grizzled valley
#

ah lmao thanks

#

reddit docs should have explained tho

unique nimbus
#

Examples does say

#

yeet

earnest phoenix
grizzled valley
#

still no good ffs

unique nimbus
#

just put memes

#

it should work

grizzled valley
#

k

earnest phoenix
#

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?

grizzled valley
#

ez

earnest phoenix
#

e.e

mossy vine
#

just send the request directly to the webhook?

earnest phoenix
#

my app will send text, it won't make a request

#

mm ok

grizzled valley
#

@mossy vine can ya tell me why my code passes doing nothing tho i have made respective changes to it

mossy vine
#

no

late hill
#

@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

grizzled valley
#

umm...any better way to make it work then?

late hill
#

Well

#

There's a bunch of solutions

#
  • Send only 1 post
  • Combine multiple posts into one message
grizzled valley
#

u mean embedding the whole thing into one?

late hill
#

Yeh

grizzled valley
#

k thanks

late hill
#

You could also show 1 but have the user make a selection through reactions or by adding a number

grizzled valley
#

umm...nah xD im too lazy to code than rn...so will leave it to 10 msgs in one embed

late hill
#

Whatever works for you meguyes

slim heart
#

Reaction menus are dying sad

#

With the new ratelimit stuff

amber fractal
#

What?

grizzled valley
#

^+1

late hill
#

It's not an easy limit to reach lol

slim heart
#

Yeah but for larger bots at least

amber fractal
#

spam next page mmulu

slim heart
#

A lot of them had to remove them it’s sad

quartz kindle
#

new rate limits?

slim heart
#

Old by now but the 25k thing

quartz kindle
#

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.)

copper cradle
#

lmfao

weary lark
#

lmao

mossy vine
#

lmaooo

earnest phoenix
#

@flat pelican

grizzled valley
#

lmfaooooo

unreal junco
#

are there any links to know how to use the dbl voting?

mossy vine
#

the documentation

unreal junco
#

where?

mossy vine
earnest phoenix
#

Is their is any bot which auto kicks the users who are not logging in Discord for longer than 30D?

mossy vine
#

isnt that possible with member pruning

west spoke
#

^

#

and bots dont have the ability to mass-kick, do they?

mossy vine
#

they can kick users one by one

west spoke
#

Ye

mossy vine
#

or use the prune feature

earnest phoenix
#

But that is only possible if a user has not got any role.

west spoke
#

^ discord should change that

earnest phoenix
#

Yes

west spoke
#

Ok no

#

that's a server link... oops mmulu

#

@earnest phoenix

earnest phoenix
#

??

#

Can You Please Put The Request Instead Of Me?

#

@west spoke

west spoke
#

no

ornate shoal
#

is 500gb monthly bandwith for ~2500 servers normal?

west spoke
#

I have more concern about that avatar

ornate shoal
#

I'm not sure if the logging is even right but it seems pretty high

west spoke
#

than your bandwidth

#

but yeah

#

for that many post/get requests its gonna be a lot

ornate shoal
#

I guess so, it has to process every message

west spoke
#

A lot

trail trout
#

there was an array. the array would be like this. ['a', 'b', 'c']

#

how we can turn it to:

  1. a
  2. b
  3. c
scarlet phoenix
quartz kindle
#

@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

young forge
#

@grizzled valley js

ornate shoal
#

Thanks, I'll look into disabling those

quartz kindle
#

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

amber fractal
#

Easy, just delete the source code mmulu

ornate shoal
#

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

earnest phoenix
#

how do I bulk delete added emoji (discord.js)

hollow saddle
earnest phoenix
flint trellis
#

??

#

clearReactions is used on a message

#

not a TextChannel

earnest phoenix
#

How do I do it on the text channel

slim heart
#

You don’t

flint trellis
#

You don't

earnest phoenix
#

Tatsumaki also had such a feature 🤔

amber fractal
#

Dont is one word. You cant

#

Fetch messages, clear reactions

slim heart
#

You mean like removes reactions from all the messages in the channel?

amber fractal
#

You cant clear reactions on a channel

flint trellis
#

why the hell would you want to do that

slim heart
#

I’m asking

earnest phoenix
#

ex !clear reactions 10

slim heart
#

Explain what it does

#

Not its name

amber fractal
#

Berry I wasnt talking to you lol

quartz kindle
#

@flint trellis that does not disable the event from being sent by discord, it only doesnt process it when it arrives

flint trellis
#

is there even a way to disable the event from being sent?

quartz kindle
#

yes

amber fractal
#

Unsubscribe from the event mmulu

#

I actually dont know excatly how to with a lib

quartz kindle
inner jewel
#

disabling events like that changes almost nothing

quartz kindle
#

guild_subscriptions = false

inner jewel
#

it's still parsed and processed

modest musk
#

hi

copper cradle
grizzled valley
#
                     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?
unique nimbus
#

wdym as more accurate

grizzled valley
#

like whenever i say !meme it replies with 1 meme and then stops for 1-2 hrs

unique nimbus
#

@grizzled valley wdym as stops

#

also new memes doesnt go up to host straight away

slender thistle
#

@sour sandal Custom emoji or?

#

So, <:name:id>

grizzled valley
#

like whenever i say !meme it wont work after sending one meme no matter how much more !meme commands i type

slender thistle
#

Sounds like blocking

#

why would there be backticks

#

I only used them to format the emoji

grizzled valley
eternal mesa
#

@grizzled valley maybe try to add some debug logging statements

drowsy sentinel
#

When you use discord dark mode but not chrome dark theme 😩

earnest phoenix
#

what are you even talking about

#

you want to send it?

wheat jolt
#

how I can get the amount of sent messages by an user in a guild

#

d.js lib

earnest phoenix
#

you can't without spamming the api

#

which will practically get you banned from the api

wheat jolt
#

the clients can show the amount

#

:(

earnest phoenix
#

a user account is not equivalent to a bot account

wheat jolt
#

of course

grizzled valley
#

@eternal mesa did but no good

#

ffs

split hazel
#

I keep getting ECONNREFUSED when connecting with mongoose with a url that starts with mongodb+srv://

grizzled valley
#

aah sry nvm it worked

#

i got the spellings wrong

#

thanks development team

tough rock
grizzled valley
#

use the rewrite version

#

there has been a lot of change

tough rock
#

@grizzled valley Thanks!

grizzled valley
#

nvm

opaque trail
#

does any one know how discord scrapes the content of a website? is it via the twitter meta tags?

earnest phoenix
#

not twitter meta tags, opengraph meta tags yes

opaque trail
#

alright, thx

indigo geyser
earnest phoenix
west spoke
#

just use datetimemmulu

slender thistle
#

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

slim heart
#

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

eternal mesa
#

@slim heart that is awful delete it

#

Jk, what is the purpose

slim heart
#

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

indigo geyser
#

Thanks

#

@earnest phoenix that is awesome

earnest phoenix
#
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?

sudden geyser
#

you're comparing a guildmember object to a user object

#

compare the user ids maybe

idle basalt
#

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

earnest phoenix
#

oh ok

#

ah i see

sudden geyser
#

<GuildMember>.id does not exist in discord.js to my knowledge

earnest phoenix
#

let me check

drowsy sentinel
#

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.

idle basalt
#

it does exist

earnest phoenix
#

It does work

west spoke
#

that's why python is better (keeping rule 3c in mind)

earnest phoenix
#

thankyou very much @idle basalt

idle basalt
#

np

sudden geyser
#

it does work. Didn't work for me in the past HyperAI

earnest phoenix
#

@west spoke How VERY TRUE 😉

west spoke
#

Guild member, message author, and client user are all put under <user>

earnest phoenix
#

how do you chat in js format in

idle basalt
#

```js
code here
```

earnest phoenix
#

oh

west spoke
#

U tried

idle basalt
#

you can put any language there

west spoke
idle basalt
#

like cpp py or whatever you want

earnest phoenix
#

nice

#

well, thankyou all 🙂

west spoke
#

```js
```

idle basalt
#

sure

earnest phoenix
#

I did have one more question but it's quite a big one/noobish question

idle basalt
#

thats fine

earnest phoenix
#

basically, at the moment I have the bot write in a seprate channel who voted for who

west spoke
#

^

earnest phoenix
#

how would i have the bot store that information in a json file?

west spoke
#

just write values to it

idle basalt
#

json as db isnt preferable

earnest phoenix
#

what would be?

idle basalt
#

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

earnest phoenix
#

oh i dont mind i dont store much

idle basalt
#

its not really about the size

#

but you can use fs

earnest phoenix
#

how woul.d i go about that?

earnest phoenix
#

ah thankyou

#

dont know how to implement that but ill try 🤷

idle basalt
#
const fs = require('fs');

fs.writeFile('yourfilename.json', 'stufftowrite', console.log)```
earnest phoenix
#

let me try'

idle basalt
#

if you plan on making multiple writes, it will be easier to use writeFileSync

earnest phoenix
#

yes i do

idle basalt
#
const fs = require('fs');

fs.writeFileSync('file.json', 'anything you want');
fs.writeFileSync('file.json', 'more stuff you want');```
earnest phoenix
#

hmm let me see

#

give m eone second

idle basalt
#

fileSync will block the execution of further code until it finishes (i think)

#

basically everything you need for file interaction will be in here

earnest phoenix
#

im really having trouble with this ...

#

how would i have it log js message.mentions.users.first() + " has been voted by " + message.author

idle basalt
#

need to newline

#

also no spaces before js

#

lol'

#

right now youre writing two huge objects

earnest phoenix
#

yea

idle basalt
#

no newline before js

earnest phoenix
#

who cares lol

idle basalt
#

just for next time

earnest phoenix
#

ok

#

so how would i have it save that

idle basalt
#

do you just want their names or do you want their entire object

#

make that the second argument

earnest phoenix
#

i kinda want it so like

#

{"472510930949767197":{"votes: 1}}

#

or like the vote count

idle basalt
#

fs.writeFileSync('file.json', JSON.stringify({ [message.author.id]: { votes: 1 } });

earnest phoenix
#

let me see one sec

idle basalt
#

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

earnest phoenix
#

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?

idle basalt
#

im not gonna write the whole program for you 🌚

earnest phoenix
#

haha okay 🙂

idle basalt
#

first you read the file, then you change the part you need, then you write that new change

lusty dew
#
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

idle basalt
#

again, a database would make this significantly easier (harder to set up if youre a beginner but definitely easier once youre going)

lusty dew
#

My db is being a bitch

idle basalt
#

what is Guild

lusty dew
#

Returning null when it isn’t supposed to

#

const { Guild } = require('../library/seq_db.js')

#

I’m using sequelize btw

#

Not mongodb

quartz kindle
#

where is guildBanAdd fired from?

#

is it protected from dms?

lusty dew
#

Idk what you mean by the last one but give me a sec and I’ll show you the whole file

quartz kindle
#

if you prevent it from possibly being triggered by a dm

lusty dew
#

That is possible with guildBanAdd?

quartz kindle
#

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

lusty dew
#

What command?

#

Ban command?

quartz kindle
#

something like that yes

lusty dew
#

Pretty sure I restrict commands to guild only

quartz kindle
#

then the only other possibility is that the guild is not in the database

#

is it a known guild or a recently added guild?

lusty dew
#

The guild is in the database though

#

Known guild

#

It’s been in the db for 3-5 weeks

fervent pilot
#

Hello how would I make a command that changes the prefix and stores the prefix I am making a public bot

lusty dew
#

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

idle basalt
#

use a database to store the prefix values for each guild

earnest phoenix
#

ahhh, it can't write more than one message in a json file for some reason

idle basalt
#

and then in your command, find the correct guilds prefix and change it

fervent pilot
#

Would mongo db work

idle basalt
#

sure

quartz kindle
#

@lusty dew try to log guild along with res

earnest phoenix
#

@idle basalt how come it won't write more than one message in the json file?

lusty dew
#

If you want my opinion sequelize and sqlite3 are my favorite to use

#

Okay

drowsy sentinel
#

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.

lusty dew
#

Mine does a lot of writing/reading data

#

Or it is about to

idle basalt
#

i cant tell you that without seeing your code

lusty dew
#

Mongodb was becoming too slow

earnest phoenix
#

me?

#

or him

amber fractal
#

uh

idle basalt
#

you

amber fractal
#

I've never had issues with mongo

earnest phoenix
#

its the code you sent

amber fractal
#

I never really timed it's responses tho

earnest phoenix
#

fs.writeFileSync('votes.json', JSON.stringify({ [vUser]: { votes: 1 } }));

amber fractal
#

I dont actually do a lot of discord bot coding anymore

drowsy sentinel
#

I hope you're not reading/writing in megabytes a day. zoomeyes @lusty dew

idle basalt
#

well it only writes that one line because thats all youre putting in

earnest phoenix
#

but i need it to send multiple... ohhhh

#

i see i think

idle basalt
#

its just a normal js object

quartz kindle
#

@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

idle basalt
#

you can add as much as you need

earnest phoenix
#

but its worked with tther bots

#

im getting really frustrated with this lol

#

i dont know how to do it

quartz kindle
#

do you understand how json works?

earnest phoenix
#

no

#

i never used json before

quartz kindle
#

json stands for Javascript Object Notation

#

do you know what an object is?

earnest phoenix
#

yes

lusty dew
#

I didn’t even know that

quartz kindle
#

so json is an object in text format

lusty dew
#

I just knew how Json worked

quartz kindle
#
object = {key:value}
json = "{key:value}"
earnest phoenix
#

i just dont know how to be able to save it on there

quartz kindle
#

json is an object represented as plain text

earnest phoenix
#

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?

idle basalt
#

there is appendFile

quartz kindle
#

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

earnest phoenix
#

yes

lusty dew
#

Tim I logged guild and got the guild object

quartz kindle
#
  1. read the json file
  2. convert the json text into an object
  3. edit the object, add/remove/modify values
  4. convert the object to json again
  5. write the json data to file
lusty dew
#

It didn’t even touch the res console log

#

Okay nvm moved the console log up

quartz kindle
#

nothing works after you defined res?