#development
1 messages ยท Page 686 of 1
ah ok
i use quick.db
similar concept across all databases
gonna ask again, where would i set the authorization?
if you do need any additional help Google is also a thing
oh
this might be a better question to ask in #topgg-api 
uhh
this uses that concept
But does that rly help you

On each update I get the current time and compare it with the previously saved time
(lastupdate)
nothing shows up on console :/
You put a timeout in the foreach
While you probably meant to put a foreach in an interval
index.js is fine
Just follow your code in your head
You posted
client.users.forEach(user => {
setTimeout(function(){
db.add(`currency_${user.id}` , 100)
console.log('GIVEN 100 COINS')
}, 10000)
});```
What does that do
For each user you're setting a timeout
What's a timeout
It means you're waiting x before doing y
For each user you're setting a timeout to give them some money
Meaning you have hundreds/thousands of timeouts running
That will only trigger once
client.users.forEach(user => {
let timestamp = new Date());
let auto = timestamp-client.lastUpdate / 60000
client.lastUpdate = timestamp
setInterval(function(){
db.add(`currency_${user.id}` , 100)
console.log('GIVEN 100 COINS')
}, 1 * 1000)
});
Well
The point of our timestamp mechanism is avoiding the loops
It's one or another
๐
On top of that
should i remove
You're still setting an interval for each user
setInterval
Meaning if more users get added
and forEach?
let timestamp = new Date());
let auto = timestamp-client.lastUpdate / 60000
client.lastUpdate = timestamp
db.add(`currency_${user.id}` , 100)
console.log('GIVEN 100 COINS')
now what ๐
im a noob
:/
hm
So client.lastUpdate doesn't make much sense there
idk what your code is like
You'd need some place, some action on which you'd want to update their stats
That's where you'll put your timestamps code
I got a feeling that's quick.db
hm
it is
quick.db
const request = require('request')
request('https://discordbots.org/api/bots/BOTIDHERE', async function (error, response, body) {
var veri = JSON.parse(body);
message.channel.send(new Discord.RichEmbed()
.setDescription(veri.monthlyPoints)
.setColor('#bf1818'))
})
Answer; undefined
what is the problem
unauthorized?
So how can I pull this data @sudden geyser
add the authorization header
which part should I add? @sudden geyser
have you ever done a post req?
request ('https://discordbots.org/api/bots/botidhere', 'dbltoken', async function (error, response, body)
will it be? @sudden geyser
The docs for request tells how to add headers
botidhere 

how can i edit/replace console.logs
||(example when i m installing somthing like npm i discord.js)||
you cant
because npm is a cli program like any other
@peak quail u mean the install msg when installing a pkg?
Any1 know if you can just send a msg to every guild a bot is in (d.js) ?
Why
Anonymous chatting
Thatโs called api spam bro
^ ๐
Lol
that would possibly be the worst anonymous chat ever having to switch between discords ๐
!anonymouschat discord dot gg slash my server
Pseudo anonymous ๐
Just thought it be fun to chat through a discord bot with ppl you don't share a server with

For fun
You're already making one ?
Didn't you just call the idea "meh" and reccomend against it ?
yep
the cross srv is MEH
to much effort to switch between discords to read a msg ๐
What do you mean by switching server ?
going inbetween 2 discords to read a msg
when u could do in 1 srv
its not effeciant imagine switching apps on phone to have a conversation ๐
its not that bad i lied but its still bad ๐
That's not how I imagine it either
Like the bot would repeat everything said to it from all the servers it's in,
Serv 1: msg 1, serv 2: msg 2
that would be aids
Bot: msg 1, msg 2
i mean its a thing but y 2 dif srvs?
imagine some kid on one side spamming NAUGHTY words what would the other side do?
if they cant ban or mute him
Idunno, maybe the bot would support multiple " rooms"
still not a fix
Of connected servers
he would switch ๐
then do again ๐
but in the same srv they can look at mod log and ban
k
Ppl can join and read but not write
w.h.y?
Everyone has to write through the bot lol
Like in the dm channel between the user and the bot
yeah
i see were ur goin
for half a sec it was like ok avoid making a million channels but they would still have to switch pages
I'd think it would be an interesting experiment at the very least
That too
same thing im doing but thru dms instead of channels
but its inconvenient
for the user
The lines of code to interesting ratio is dank
lol
anyone know /recommend some free localisation management services?
like bot hosting?
no more like localisation management eg i18n translations
I'm getting "Error: Cannot find module '/app/js/Main.js'
at Function.Module._resolveFilename (module.js:548:15)
at Function.Module._load (module.js:475:25)
at Module.require (module.js:597:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/app/bot.js:7:15)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)"
On glitch
I have installed node.js
ANd have a bot.js (my bot from discord bot maker)
Can someone help me
please
you have a require Main.js somewhere that leads to a non existent location
without your code, we can't say...
post the relevant code here
/*
- Discord Bot Builder Bot
- Version 1.2.0
- Robert Borghese
*/
const Files = require(require('path').join(__dirname, 'js', 'Main.js')).Files;
if(!process.send) {
Files.initStandalone();
} else {
process.on('message', function(content) {
Files.initBotTest(content);
});
}
One message removed from a suspended account.
That is bot.js
One message removed from a suspended account.
One message removed from a suspended account.
I don't know how to code all of it lmao
One message removed from a suspended account.
There's nothing on what I need
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
Oh okay
One message removed from a suspended account.
Really?
mood
One message removed from a suspended account.
One message removed from a suspended account.
as the error says
there's no file named Main.js in /app/js
That would be great.
One message removed from a suspended account.
One message removed from a suspended account.
the require you have at the top is calling a non existant file
One message removed from a suspended account.
as said at start
so to fix you need to update the require or make the file
the code asks for Main.js
okay]
the problem is he used discord bot maker
Yeah, so I need Main.js
One message removed from a suspended account.
Yeah
One message removed from a suspended account.
All I need is it to be on 24/7
One message removed from a suspended account.
i don't think anyone here offers support with bot makers ๐คท
np
if you have an issue with the bot maker, go complain to the app creator
discord bot maker specifically
ye
every green name is a bot maker
that's a bot developer ๐
who has made a bot
Okay
i know, that's why i put the upside down emoji
Well if someone wants to help me out when I'm on tomorrow and guide me through the basics, only if you want to and have time. Feel free to pm me. I'll respond to it tomorrow if I see you online.
All I need it to do is stay online 24/7 and display a status.
Thanks
glitch auto sleeps btw
there's no free hosting that'll stay up 24/7 and allow hosting a discord bot
Okay
if you want constant uptime, pay for it
I'll use my pc then lmao
that's what i used to do when i was smaller -- i had an extra PC in my room that i'd keep on 24/7
Glitch doesnโt auto sleep if you use uptimerobot
I have one that is really small and uses no power tbh.
19V == 3.42A Rating.
So really low.
Just google how to configure uptimerobot with glitch
Yeah
It pings your bot every 5 mins to keep it online
I love the friendly community ๐
Which is why you use uptimerobot which pings it every 5 minutes. I have a bot that has been online for 5 months on glitch 24:7
uptime will wake it up but its still being forced sleep and can result in downtime
glitches docs say right there any project is forced sleep if its been running 12 hours
uptime can wake it back up but its still downtime
Well maybe thatโs new because I donโt remember my bot ever sleeping
been there since day 1
:/
yeah
no one will allow you to spend their power and machine resources for free 24/7
if they do then its either a free trial or a scam
amazon ec2 ๐
that costs
i mean, aws is one year free trial
and even that plan is limited to what you can do
its also worth noting that uptime isnt always reliable on ping times https://oh-mah.ga/LXzybKzZ.png
thoughout the last period it only got 3 points in a row right
if it done all on time then all points would be clustered like that
so in terms of monitoring its good
but if you depend on it for uptime like anti sleep then your gonna have potential issues
Google cloud free tier too
gotta pay for data though
you get a f2 micro i think thats its name but yeah data costs
they're generally overpriced
azure is the overpriced one lol
google's 1-2 gb vm machine with a virtual cpu will last you through the entire trial though
true that
they wasted all of my student credits within a week
things like vultr are more popular
and a few other gem providers if you can find them
@earnest phoenix reffering to https://oh-mah.ga/iqpxdThU.png
you actually get to keep it
ah
but its a potato and network costs
what are the specs of the free one
i had no problems running 1500 guilds on it with djs
but your mileage may vary
now i use it to host my api
Python on its own is retarded as it wants so much ram
How would I make a viewer for e621 for my bot?
You can get an api if it's available or use addons to grab the images
There might be however idfk
Hmm
probably best to ask elsewhere though since it's an nsfw website and dbl doesn't allow nsfw
isn't it fine as long as nsfw is restricted behind nsfw channels
i remember when my bot was accepted, it had a notable category of nsfw commands
but it didn't list nsfw commands nor allowed the usage of nsfw outside of nsfw channels
bots on dbl can have nsfw features, just cant be listed, unless you're dank memer because you drive too much traffic for the rules to apply

ads ๐ค
are dbl ads using google's adsense
because that's even worse
cause trackers and tailored content
idk the thing in the top right says adchoices
I prefer tailored ads though because then I might find a product I actually like, even though I rarely click ads anyways

i dont care what type of ad it is because i'm blocking it anyway 
This fucking video has taken me over 5 hours https://vinniehat.is-inside.me/ag3991Wu.png
You want to know what the pos does?
Every time he imports a group thing, he just says ok let me import this and bam 15 things are imported
Every time he adds multiple styles "looks at second monitor" cuts video to after
WHY DO YOU PURPOSELY CUT EVERY 3 SECONDS
link the video this seems like quality content
Aw the poor YT guy got back to me when I mentioned it
Now I feel like a dipshit
Learn how to add OAuth2 login authentication to your app with some of your favorite socials including Facebook, Instagram, Google, Twitch, Github, and Amazon...
nvm deleted it instead of editing -_-
Maybe a dumb question, but with discordjs, will client.users.size get a count of all the members the bot is helping?
@abstract crow passport is cool
There's a discord passport module
@earnest phoenix no
it will get the cached users
to get all users you need to filter through all guilds and get their member count
ohhh, that's what I thought was happening, thanks :)
When getting member count, it currently would count the same member for each time they happen to be in a guild, is there a better way to get member count, where it doesn't end up counting the same member multiple times. Currently I have client.guilds.map(g => g.memberCount).reduce((a, b) => a + b);.
you'll have to download all users from your guilds and then you can use client.users.size, with filtering applied
https://discord.js.org/#/docs/main/stable/class/Guild?scrollTo=fetchMembers - do this on every guild in your client to have every member in cache
it can hang for a while though if the guild has a lot of members
that seems like it would be a bit inefficient
but it would work
its the only way if you want to filter users
you need to have a reference to the user if you want to filter them out of other guilds
and to have a reference to the user you have to download all members (because it's a collection, if it wasn't you could just use fetchMember)
Even though it's a bit inefficient, i'm still gonna use it, thanks for your assistance ๐
Hey, I was wondering if there would be anyway on making and extended audit log bot?
you can't really make extended audit logs
the api doesn't provide enough info for you to extend on anything
They should update it to discordjs.guide now since AnIdiotsGuide is spoonfeed heaven.
Is there anybots that notify me when somone is banned or kicked
Lots, those are called mod logs
Search for bots on the website and youโll find one that does it... most likely, one of the bots you already have in your server might already do it.
However, weโre not a bot curation discord, so please refrain from asking such questions from now pls
Oh sorry, is there any channels where i can ask them?
Nope.
This server primarily serves as a community hangout for programmers who create Discord bots, so such conversations often turn into devs just advertising their own bots.
Any one help me pls invite mannager is not working
Go to their support server
Has anyone tried out this logDNA thing before? it showed up in the github dev pack list and it seems to do the same thing as sentry
Redis isn't a database
You're comparing it to a database?
Also personally I like KeyDB over Redis. It's a multi-threaded fork of Redis.
Website: https://keydb.dev
Repo: https://github.com/JohnSully/KeyDB
Docker: https://hub.docker.com/r/eqalpha/keydb
Does anyone have any automatic bot notifications when the new episode anime is released?

DISCORD BOT LIST, AKA THIS SERVER
What We Are
The Official Discord Server for https://discordbots.org
A community hangout for programmers who create Discord bots.
Place to post stale memes.
Admire Crazy Rich Asians in #bids.
What We're Not
Place to shitpost, spam, or have heated discussions.
Place to complain about the bot approval queue.
Bot curation service to recommend Discord bots.
Server curation service to recommend servers.
Support server for random bots you find online.
I wonder if there is a Netflix API
for what
Welcome to the Netflix Partner Help Center. Have a question or need help with an issue? Send us a ticket and we'll help you to a resolution.
Netflix?
Come on no one appreciates the time and effort I put into my message
i thought it was cool
ay ty fam
pffft
netflix api sucked even when it was not deprecated
To send something to someone in a ban cmd wouldnโt I do it before I actually ban em?
I remember using it before
Yes
After u ban, that user is unavailable to ur bot, unless u share another guild with them
Okay
Also does anyone know anything about better-sqlite3
Iโm trying to make a function to pull data from a specific table
But I canโt figure out what other param I need to pass.
db.prepare(`CREATE TABLE IF NOT EXISTS promo (
id TEXT PRIMARY KEY,
credits SMALLINT NOT NULL DEFAULT 0,
guild_premium BOOL NOT NULL DEFAULT FALSE,
expiration BIGINT NOT NULL DEFAULT 0,
uses SMALLINT NOT NULL DEFAULT 0
)`).run()
Db table
get(table, cond = {}, sel = "*", id = "id") {
if (Array.isArray(sel))
sel = sel.join`, `
let p = Object.keys(cond)
let ins = db.prepare(`
INSERT OR IGNORE INTO ${table}
(${p.join`, `})
VALUES (${p.map(k => "@"+k).join`, `})
`);
let sQ = db.prepare(`
SELECT ${sel} FROM ${table}
WHERE ${p.map(k => k+" = @"+k).join` AND `}
`)
//return (...a) => (ins.run(a), sel.run(a))
return (ins.run(cond), sQ.get(cond))
}```
Get func
```js
getPromoCode(something, sel = "*"){
this.get("promo", {something}, sel)
}
Func Iโm trying to create
Ik this won't help you but normally i prefer using an ORM
Like Sequelize or TypeORM
Oh
It abstracts the SQL queries for u
Ehhh
useful in a large project
Like js // SELECT modLogChannel FROM guild WHERE id = 'ID_HERE' LIMIT 1; Guild.findOne({ select: ["modLogChannel"], where: { id: "ID_HERE" } });
Kinda easier to look at
or ```js
/*
- equivalent to: CREATE TABLE tags(
- name VARCHAR(255),
- description TEXT,
- username VARCHAR(255),
- usage INT
- );
*/
const Tags = sequelize.define('tags', {
name: {
type: Sequelize.STRING,
unique: true,
},
description: Sequelize.TEXT,
username: Sequelize.STRING,
usage_count: {
type: Sequelize.INTEGER,
defaultValue: 0,
allowNull: false,
},
});```
Mongo*
That first example was TypeORM
This second one is Sequelize
idk ur call, just saying... i like ORMs in large projects
The TypeORM looks like Mongo
Defining structures in TypeORM (using TypeScript, JavaScript has similar syntax with some differences)```js
import {Entity, PrimaryGeneratedColumn, Column, BaseEntity} from "typeorm";
@Entity()
export class User extends BaseEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
firstName: string;
@Column()
lastName: string;
@Column()
age: number;
}```
Thatโs Typescript?
Strong typing
Everything has types
function add(x: number, y: number): number {
return x + y;
}``````ts
class MessageUtils {
static async getPrefix(message: Message): Promise<string> {
if (message.channel instanceof TextChannel) {
return Guild.findOne({
where: { id: message.channel.guild.id }
}).then(g => g!.prefix);
} else {
return settings.prefix;
}
}
}```
I may use Sequelize
Yeah
Sequelize is a good fit
Sequelize Real-life Example using Discord.js: https://discordjs.guide/sequelize/
Whatโs the benefit of making your own classes?
Classes are just abstractions of how classes are made with prototypes
So they just make it easier
Ah mk
I was wondering what the point of classes are and how they can help you
I saw someone making a class that extended onto Client
^
1 sec
function Apple(type) {
this.type = type;
this.color = "red";
}
Apple.prototype.getInfo = function() {
return this.color + " " + this.type + " apple";
};``````js
class Apple {
constructor(type) {
this.type = type;
this.color = "red";
}
getInfo() {
return this.color + " " + this.type + " apple";
}
}```
The only class Iโve made is a LavalinkQueue class that extended into Lavalink
Those two codeblocks do the same thing
Sequelize just makes queries look easier to the eye
it uses sqlite3/pg/any-relevant-db-pkg in the background
About the classes stuff... Here's my Discord bot that makes rather extensive use of classes.
It's actually in TypeScript, but TypeScript is just JavaScript with the extra Map<K, V> etc, just ignore those.
https://github.com/SinistreCyborg/Penelope
Ah mk
hey guise my code is br0ke can i get some help plz
const __=Symbol,___=Object.assign,_____=Array.isArray,____=Object.keys,_=(_=[])=>___({},...(_____(_)?_:____(_)).map(_=>({[_]:__(_)})))
seriously
Uhm
i mean its kinda boring now
Walks away Nope

find and replace does the trick @languid dragon
still fun to do
ok
I donโt even know what that is so
function foo(arr = []) {
let thing_to_assign;
if (Array.isArray(arr)) {
thing_to_assign = arr;
} else {
thing_to_assign = Object.keys(arr).map(makeSymbol);
}
return Object.assign({}, ...thing_to_assign);
}
function makeSymbol(e) {
return { [e]: Symbol(e) }
}```
@languid dragon
pog
Hm
ppl made fun of my old commands all the time... if only u showed these functions then lmao @languid dragon
Would I put localhost if itโs on a server?
Very old ban command for the memes:js member.bannable ? await member.ban(days ? {days, reason: `[${message.author.tag}] ${reason}`} : `[${message.author.tag}] ${reason}`).then(()=>message.say(`${this.client.emojis.get("508827649229979648")} ${member} has been ${this.command.name}ed${reason !== "No reason provided." ? ` for reason: \`${reason}\`` : "."}`)) : message.reply(`${this.client.emojis.get("508827674110590998")} I can't ${this.command.name} that person!`);
That looks...messy
Very old ping command:js module.exports = { description: "Check my connection to the Discord server.", execute: message => message.channel.send("Pinging...").then(m => m.edit(`Pong! (Roundtrip took: ${ping.createdAt - message.createdAt}ms. Heartbeat: ${message.client.ws.ping}.)`)) };
Would I put localhost if itโs on a server?
Talking about memes, I memed my whole bot. This was the ready event:
var a=['guilds','size','\x20servers\x20|\x20','users','\x20users','PLAYING','ready','user','setActivity','mwr\x20help\x20|\x20'];(function(c,d){var e=function(f){while(--f){c['push'](c['shift']());}};e(++d);}(a,0x128));var b=function(c,d){c=c-0x0;var e=a[c];return e;};mwr['on'](b('0x0'),async()=>{mwr[b('0x1')][b('0x2')](b('0x3')+mwr[b('0x4')][b('0x5')]+b('0x6')+mwr[b('0x7')][b('0x5')]+b('0x8'),{'type':b('0x9')});});
@opaque eagle
wow
My commands have tons of spacing now: ```ts
import { Command, Penelope } from "../..";
import { Message, PrivateChannel } from "eris";
import { oneLine } from "common-tags";
export default class extends Command {
constructor(client: Penelope) {
super(client, {
name: "ping",
description: "Check my connection to Discord.",
category: "๐ Utility"
});
}
async exec(message: Message) {
const ping = await message.channel.createMessage("Pinging...");
const round_trip = ping.timestamp - message.timestamp;
return ping.edit(oneLine`
๐ Pong!
Round-trip took: ${round_trip}ms.
Latency: ${this.latency(message)}ms.
`);
}
private latency(message: Message): number {
if (message.channel instanceof PrivateChannel) {
return [...this.client.shards.values()][0].latency;
} else {
return message.channel.guild.shard.latency;
}
}
}```
Would I put localhost if itโs on a server
Yes
Okay
Yeah, this is my ping command now
const ShinkaCommand = require('../abstract/ShinkaCommand.js');
const { MessageEmbed } = require('discord.js');
class Ping extends ShinkaCommand {
get name() {
return 'ping';
}
get usage() {
return 'ping';
}
get description() {
return 'Basic ping and pong command';
}
async run(msg) {
const embed = new MessageEmbed()
.setColor(this.client.embedColor)
.setDescription(`Pinging...`)
const sent = await msg.channel.send(embed);
const embed2 = new MessageEmbed()
.setColor(this.client.embedColor)
.setTitle('Pings')
.setDescription(`Command Delay: **${Math.round(sent.createdTimestamp - msg.createdTimestamp)}ms**\nGateway Ping: **${Math.round(msg.guild.shard.ping)}ms**`)
await sent.edit(embed2);
}
}
module.exports = Ping;
My ping cmd is like 20 lines
localhost is usually just fancy-talk for 127.0.0.0/8 (v4) or ::1 (v6) so I don't see why not
Name, description and usage
Okay
no u Ari
what's the /8 at the end of 127.0.0.1?
The port
๐
Awww. TIL. Interesting
So Iโm guessing storage is the file where all the database stuff will be saved?
@glad shell Subnet mask of the ip
uwu
Do I have to create the storage file? @opaque eagle
no u
Or will it create it for me
Okay I know better-sqlite3 creates the file for you not sure about sqlite3
Whoever asked the question about the slash, idk if I answered it in detail. Idk if you have a CS background or not, so I'll keep it short. The number to the right of the slash indicates the number of contiguous 1 bits in the netmask.
Example: 192.168.0.1/24 has a subnet mask containing 24 contiguous bits, which is 255.255.255.0.
Going to that specific IP I mentioned, 127.0.0.0/8 would have a subnet mask with 8 contiguous bits, which is 255.0.0.0
That was me. Outside a Udemy Golang course for beginner programmers I have no CS background. I just recognized 127.0.0.0 as being off from the typical localhost ip of 127.0.0.1
Yeah that's reasonable
Iโm assuming in Sequelize there is no primary key?
Anyways having that subnet mask makes sense for localhost b/c that would allow for roughly 16.7M IPs/applications, while Class A networks (medium-sized networks) have a default subnet mask of 255.0.0.0, which allows for only 256 connections
Sequelize assumes a primary key of id iirc
You can define your own, too: ```js
class Collection extends Model {}
Collection.init({
uid: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true // Automatically gets converted to SERIAL for postgres
}
}, { sequelize });
class Collection extends Model {}
Collection.init({
uuid: {
type: Sequelize.UUID,
primaryKey: true
}
}, { sequelize });```
@lusty dew Reading the documentation comes in handy:
https://sequelize.org/master/manual/legacy.html#primary-keys
np
Thanks
there's a search button for future reference if you'd like
it's useful to have the docs open while you're following along with Discord.js's guide
I hope it doesnโt matter that Iโm using sequelize.define
Nope doesn't matter
Ah mk
This is what I have so far:
const Sequelize = require("sequelize")
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: 'sqlite',
logging: false,
operatorsAliases: false,
storage: 'clap.sqlite'
})
module.exports = new class DB {
constructor(){
Object.defineProperty(this, "sequelize", {
value: sequelize
})
this.define('users', {
id: {
type: this.text,
primaryKey: true
}
})
}
}
Hopefully Iโm doing it right.
Iโm copying the same format as my old db.js file
Whatโs postgres
forked version of mysql/mariadb with a few more features
I donโt even know how to get a Postgres URI
Don't worry about Postgres, I just copy-pasted that code from the docs
^
also the module.exports part isnt in the docs @lusty dew
Ik
forget what I said about the connection URI stuff, it's just gonna make the learning curve harder
But yeah the syntax is a bit off
Iโm not following the docs to the exact letter
That's not how classes are made
new doesn't belong there```js
class ClassName {
// all the other stuff
}```
Isnโt it just class ClassName or smth
But tbh I don't see why classes are necessary in that case
You can just make that connection a property in ur bot
Wdym?
wait a min
Okay
Huh?
You're using discordjs?
const db = new Sequelize('stuff here');
const Tags = db.define('more stuff');
const Guilds = db.define('more stuff too');
let client = new Discord.Client();
client = { ...client, db: { Tags, Guilds } };
// so now, you can do this anywhere, even if it's in a separate file:
client.db.Tags.findOne('stuff');```
No need to make a class
Even if you're using a command handler and the command is in a separate file, you could do: js // commands/some-cmd.js module.exports = { name: "some-cmd", run(message, args) { message.client.db.Guilds.findOne('stuff'); } };
how does that set property work? Are you instantiating all instances by calliing ...client?
I was just gonna do const db = require('../library/seq_db.js')
Then I was gonna make functions for each thing I needed
Yeah that works
Like getGuild, writeGuid, etc
getGuild() would just be calling Guilds.findOne()
Yea ik
you don't really need to write your own functions when using smth like sequelize
True.
The point of sequelize is that you don't need to write your own functions
But I donโt feel like writing blah.findOne all the time kek
Thatโs my lazy side though
ok ur call, I guess
In your class above, this.text and this.define are undefined btw
Huh?
module.exports = new class DB {
constructor(){
Object.defineProperty(this, "sequelize", {
this.define('users', {
id: {
type: this.text,
primaryKey: true
}
})
}
}
mysql, rethinkdb
An actual database
this.define implies that class DB or its parent(s) has a method named define()
const configf did you mean to have the extra f there?
Ah okay
So wait how should I setup the file instead?
I think you meant to do sequelize.define() and Sequelize.TEXT @lusty dew
Didnโt you say not to use a class?
Yeah
That it was pointless?
I just wanna get this working kek
lmao
Itโs 1am and I am supposed to have been pushing the new update hours before now
just if you read/write like every 5 seconds to json can easily make it corrupt lol
oof
Most times, developers like to define their models in separate files, kinda like commandss
Yea. I donโt wanna do everything in my main file
Itโd get messy
So I split stuff up into separate files
ye
Yeah...
modulate it
Wait a min, I'll get some boilerplate code going
// main file
const db = new Sequelize('define ur db connection here');
module.exports.db = db;``````js
// modules/Guild.js (for example)
const db = require("../path/to/that/main/file.js");
const Guild = db.define(
/* define that model here */
);
module.exports = Guild;```
Then you can write a command handler-type thing to get all ur models into one object
So I can do this instead:
const Sequelize = require('sequelize')
const sequelize = new Sequelize(blah blah blah)
module.exports = (client) => {
sequelize.define('users', {
name: {
type: sequelize.text
}
})
}
don't do new Sequelize() in every file, that'll make a new connection each time
oh ok
Yea
then what did u mean by splitting stuff up into multiple files
Like my cmd handler
lmao
ok
event handler?
client.on, client.error.... etc
I couldn't initialize a lot of functionality cuz I wasn't calling the event handler
edit: you guys aren't even talking about the discordjs api. I'm tired..
Then maybe just a db.js that looks like: ```js
const db = new Sequelize();
module.exports.Tag = db.define();
module.exports.Guild = db.define();
// etc etc etc``````js
// so in every file you need the db in, you can do:
const { Guild } = require("../path/to/db.js");
Guild.findOne();```
Lol... this channel isn't supposed to be about just Discord**.js** @glad shell
It can be about anything related to development
I know I know. I've been at it for like 18 hours. I'm exhausted and I'm not being helpful.
Hm
I can be talking about pointers in C++ and no one can say a thing
Well that would be against Discord ToS
Unless I was working with real-life stats of some deadly virus in MATLAB
Oh yea one more question
I donโt wanna make a new column for each event there is like guildMemberAdd, guildMemberRemove, messageUpdate, etc
Is there a way I can condense it down
Some people where talking about arrays and such
What would you want to store in each column
logging events like sending it to a channel in a guild?
or logging it as in logging it to the console
So people can do like -settings guildMemAdd true
Ye guild channel
It's not as many DB entries as you think.
- Member Join/Leave Messages use two events but they both go to the same channel, so you only need a single
memberLogsentry. - Moderation Logs use three events but they all go to the same channel, so you only need a single
moderationLogsentry. - Message Logs use three events but they all go to the same channel, so you only need a single
messageLogsentry.
And to see if those logs are enabled or not, just check if the entry is null
This is the Guild model for my Discord bot (it's in TypeORM not Sequelize, but you can understand what it means)```ts
import { Entity, BaseEntity, Column, PrimaryColumn } from "typeorm";
import { settings } from "../..";
@Entity()
export class Guild extends BaseEntity {
@PrimaryColumn({ type: "varchar", length: 20 })
id!: string;
@Column({ default: settings.prefix }) prefix!: string;
@Column({ type: "varchar", length: 20, nullable: true })
modLogs!: string;
@Column({ type: "varchar", length: 20, nullable: true })
memberLogs!: string;
@Column({ type: "varchar", length: 20, nullable: true })
messageLogs!: string;
@Column({ type: "varchar", length: 20, nullable: true })
autorole!: string;
}```
Uhm I kinda understand it but kinda not at the same time.
How does that allow the, to individually turn off or on the events they want?
Like say they want guildMemberAdd but not guildMemberRemove active
Well turning on and off individual events is really rare
Most bots don't offer that feature (besides welcome/goodbye messages)
I know a few bots that do
Dyno and logger does iirc
I just want to have it as an option in case people want it
In that case, I'd just suggest having separate entries
It's good to make use of what's already provided, instead of trying to devise some home-brewed, half-baked solution
Okay
People who work on large libraries or open source software take their time with optimizing all their code for performance/efficiency, etc. Using what's already provided for you in such scenarios is usually really beneficial. Well that first part isn't so true of JavaScript libraries these days, but it still holds for large OSS projects like SQLite or Apache
So basically:
sequelize.define('guilds', {
guildMemAdd: {
type: sequelize.boolean,
defaultValue: false,
allowNull: false
},
//etc
})```
Why
string so u can store the channel ID
Huh
and if the string is null, that means the owner didn't enable the feature
Why have two entries for the same feature, ya know
๐คท
I see how it can be beneficial
Allows them to if they want to have specific channels for the events
And what not
Yeah, that's already possible
Make it a nullable string:
- if it's null, it's not enabled
- if it's not null, it is enabled, and the value is the channel id
Two "features" with the same entry
Actually
No I wonโt have to change my settings cmd at all
Except for fixing the db thing
But everything else should work
Could I set the default value of it to a string
No, I'd set the default value to null, cuz it wouldn't be enabled by default
Like ''
Mk
Iโll be back if I have anymore questions
Also sequelize looks so much cleaner then the db.prepare('CREATE TABLE IF NOT EXISTS guilds') thing
Yep
Also gonna go on one small rant
Also just as a heads up/life advice type thing... making sense out of languages/libraries you don't understand is a valuable skill.
You don't need to know the syntax, but you should still understand what that code does just by using context clues. For example, about that TypeORM code I showed earlier. You don't need to know everything about TypeORM and TypeScript to understand that that said, because there are tons of context clues there to help you. There was:
varchar(a common data type in SQL databases)nullable("able to be null")modLogs/memberLogs/messageLogswhich are common words in Discord Bot devColumnwhich means what it says.
Here's the code again if you want to take another look at it:
https://github.com/SinistreCyborg/Penelope/blob/master/Internals/Models/Guild.ts
But anyways, that skill comes in really really handy... Real-life example:
Tons upon tons of devs look to Discord's official docs in their own code, but Discord's game SDK docs give code in C#... not all devs, however, use C#.
Here's an example from the Discord docs: https://discordapp.com/developers/docs/game-sdk/applications#getticket-example
Even in code as seemingly complex as that, you can see several context clues, like:
Discord.Userwhich is a Discord Usertimestampwonder what could that beticket.Split('.')use what you know aboutString.split()in javascriptparts[0] == "2"woahhh isn't that just like js code??Console.WriteLine("some string")sounds just likeconsole.log()in js
Just like Kevin says: https://www.youtube.com/watch?v=_K-L9uhsBLM
Kevin decides that talking normally takes up too much time so he starts abbreviating all his words and sentences much to the confusion of the rest of the off...
Okay I remember seeing it just forgot what it did
Gn everyone
Just for the record, I didn't know a thing about Sequelize except for the fact that it existed. I answered all those questions just by reading the documentation + google.
How can I run two bot applications on the same code and same database? This is my config file:{ "prefix": "*", "token": "secret", "dbl": "secret" }
Would it be possible to have two different tokens to run two instances of the bot with the exact same code and database? (If anyone replies, please mention me in the response.)
token1, token2 keys containing different values
@earnest phoenix yes its perfectly possible
Thanks, would I do it as shivaco mentioned above?
you can do it in a million different ways
Well, I suggested the way I use, at least 
we cant give you an answer just from you config file, we dont know how your code accesses your config file and how it logs into discord
and do you want to run two bots in the same process or in two separate processes?
also which library
"prefix": "*",
"token1": "secret",
"token2": "secret",
"dbl": "secret"
}```~~This gives me an error: "No token was provided." ~~ I see why.
two separate processes, discord.js master
if its two separate process, just make two config files
but if you're running two instances of exactly the same code, then you need to detect which process was currently fired
for example, when running node, you can add arguments
node myfile.js argument here
then inside the code you can get the argument from process.argv
so basically when you run your bot you have to do node myfile.js bot1 then node myfile.js bot2 or something like that, and from inside the code you check which bot was run, and load the correct config file
this is my sharding file```const { ShardingManager } = require('kurasuta');
const { join } = require('path');
const { token } = require("./config.json")
const { isMaster } = require('cluster');
const sharder = new ShardingManager(join(__dirname, 'index'), {
"token": token
"timeout": 240000
});
sharder.on('debug', message => {
console.log(message);
});
sharder.spawn();
i created `config1.json` and `config2.json`. how would i declare the constant here? `const { token } = require("./config.json")`
assuming you run your bot like this node myfile.js bot1 this is one of the possible ways ```js
const { token } = process.argv[2] === "bot1" ? require("./config1.json") : require("./config2.json")```
process.argv gives you an array of all arguments, like this ["node","myfile.js","bot1"]
so get the 3rd argument (index 2), and check if it contains "bot1" and load config one, else load config 2. this will always load config2 if you put anything else that is not "bot1" in the args
you can also make it like this
const { token } = require(`./${process.argv[2]}.json`)```
then you launch it using the config file as the arg: node myfile.js config1
this is probably a better way to do it than what i said before
~~i see you mentioned index 2 but the file name is index - i want to use the same already existing files for both bot applications.
i also have no idea what i should put into the config files for the second method.~~
ah, i see, thank you
for (let member of message.guild.voiceChannel.members) {
console.log("Hmmm")
}
TypeError: Cannot read property 'members' of undefined
i want to loop something for the voice Channels members in the guild
so for all members that are in a voice channel
Guys tiny Question, how can i do for Example !play creeper awww man
so how to search with Words?
i already got an Play command
@peak quail are you using stable or master
oh wait
yeah guild.voiceChannel isnt a thing
Mmmmm
you need to specify which voice channel
503 - service unavailable
basically discord dead
With a richembed, how do you change the setColor?
It wonโt let me change it of 0x00bfff
rich embed is deprecated in v12
One message removed from a suspended account.
One message removed from a suspended account.
it's not actually that stupid
just with a different name
ok im probably dumb
on a side note the methods in richembed wee moved into messageembed
Thank
hey, im trying to make a blacklist system and i want to do that if the user have the permission manage messages the bot will not trigger and im always getting this error
how can i do an play command that uses tags and links?
code, mind byoe?
the second line is the error line
is this inside a DM?
no
i blocked DMs in the bot
and the block DMs code is before the blacklist system
message.member can be null in stable
try fetching the author as a member in the server, then calling hasPermision
like message.guild.members.get(message.author.id)?
preferably <guild>.fetchMember()
as .get() relies on cache
so fetch member is better?
you could say that
ok
thank you ill try that
the fetch member takes a id?
UserResolvable
so it could be just message.author
ok
thx
i need to do await message.guild.fetchmember?
yeah, you need to resolve the promise fetchMember() creates
ok
You should rather read the error by yourself. It directly states the problem
ok its now working thanks
meh, not really
now its giving me that error
ok i think i fixed it
use a database
cache the blacklisted members on bot start
if the message author is in the blacklist, return
I use a database
So I would have to make another table for blacklisted users. Then Every Time Someone runs a command it checks there message.author.id .
Mainly requires more resources
please don't use a json
also prone to corruption
Yes
i just use it for storing custom prefixes
it works lol
Its bad tho
no err ever
please stop trying to promote the use of json as a db
i only just db for coin sytem
one concurrent read/write and you have lost all your prefixes/coins/blacklist
json != db
no
Yes
no
can we stop arguing about json and get back to support 
shard 0 and 1 are logged in but all shards from 2 do not want to log in. shard 2 logs in but restarts itself every few seconds.
(if image doesn't load - https://cdn.discordapp.com/attachments/272764566411149314/618129484544999427/unknown.png )
how can that be the case though if shard 0 and 1 is logged in without issues
3300
Hmm
Is your bot using auto sharding?
Hmm
Idk
I dont need to shard yet Idk much about sharding yet still learning
i use kurasuta with sharding manager
I would wait for a response by someone smarter than me heh
https://i-was-scammed-by.dabbot.org/5m9rCpr.png fix your code
@inner jewel as they said it only occurs on shard 2, not 0 and 1
how is that possible
just because it happens to work on two shards, doesn't mean it's correct
have you tried reading the error
posting the exact same wall of images 1 minute after posting them the first time won't make you get help faster
also, copy the text and send it in a codeblock
it clearly says that incorrect login details were provided
also that code is literally a mass dm command
surely no shards should work then?
it's easier to debug if you send the code in question
well i dont know which code it is in the file, the error just tells me that it is in ready
send the code in your sharding manager, and send the code of the file the sharding manager runs
its probably a problem during process spawning
the error says more than just "it's in ready"
it says the line and column number of where it happened
how can i let my bot leave the voice channel when a song finishes
your library probably has an event for when a stream ends
i reverted to my normal method (which hosts one instance) when i started getting this error @quartz kindle
sharding file```const { ShardingManager } = require('kurasuta');
const { join } = require('path');
const { token } = require("./config.json")
const { isMaster } = require('cluster');
const sharder = new ShardingManager(join(__dirname, 'index'), {
"token": token,
"timeout": 300000
});
sharder.on('debug', message => {
console.log(message);
});
sharder.spawn();
config file```{
"prefix": "*",
"token": "secret",
"dbl": "secret"
}
question
why exactly are you using the cluster module?
doesnt the manager handle that for you?
sharding manager wasnt working alone on discord.js master
which is why i am using kurasuta
which is why i need the clusters
your code looks nothing like kurasuta examples on github and npm
it broken because either kurasuta has issues, or you are not using it correctly
the second option is more plausible
(although their docs are also not helping)
probably an issue with kurasuta because it was working for a long while, surely it cant just break out of nowhere
it can, and many times it happens because the coder did not foresee a possibility
from what i understand from their docs, you dont need cluster unless you have some code that specifically needs to be run in the master process
how i can get shards size?
can i see your index and ready files?
you can, though it would be too large to put here
Does anyone know if it's possible to make dynamic command loader in java?
yes
I tried a few things but nothing seems to work.
but it's somewhat complicated and very easy to backfire
someone can explain me what is sharding
could i just send you the files in dm? hastebin is refusing to save @quartz kindle
Could you give me a little tip on how to do dynamic commands?
a messagechannel can't have permissionsFor
you can only use that method on a user iirc
Hmmm
ClassLoader and reflection
someone can explain me what is sharding and how can setup it
sharding is having multiple connections to discord, each one handling part of your bots' guilds
setting up sharding depends on your library
you should read it's docs for that
the js docs have?
yes, most libraries have sharding
Vysion, that's incorrect, guild channels do have the permissionsFor method
sharding is recommended at 1500 guilds and required at 2500
no?
personally, i'd recommend having sharding setup from the beginning
because rewriting most of your code to work with sharding when you're approaching 2500 guilds is a bad experience
@earnest phoenix your problem is probably this
shards are loaded sequentially, meaning more shards take more time for the bot to completely load. you cant wait a fixed amount of time, because you risk the bot not being completely ready by that point, which is probably what happened as your bot grew
as you have access to client in that file, all the code that requires the bot to be ready should be placed inside a client.on("ready") event
oh wait this applies to guildchannel
a message channel (TextChannel) extends GuildChannel, so it will have that method
@earnest phoenix actually the problem is not exactly that, but its related to that
when you cluster your bot, clusters are also loaded sequentially, so one cluster become ready and fires the ready event before other clusters are ready
and you try to access data from clusters that are not ready yet
so removing the delay and clusters would possibly fix the issue?
@inner jewel overexaggerating a little? you dont really need to rewrite the whole code for sharding
unless you create the library yourself
depends on how the code is structured
@earnest phoenix to fix the issue you should remove fetchClientValues and use broadcastEval instead, with a check if the target process is ready
give me an example




