discord-vatron
Version:
Módulo para facilitar la interacción con la API de Discord
239 lines (215 loc) • 13.1 kB
JavaScript
const EventEmmiter = require('events');
const ManagerServidores = require('../clases/ManagerServidores.js');
const ManagerCanales = require('../clases/ManagerCanales.js');
const ManagerUsuarios = require('../clases/ManagerUsuarios.js');
const ManagerRoles = require('../clases/ManagerRoles.js');
const Mensaje = require('../clases/Mensaje.js');
const Miembro = require('../clases/Miembro.js');
const EstadoVoz = require('../clases/EstadoVoz.js');
const iniciar = require('./metodos/iniciar.js');
const request = require('request-promise-native');
const { errores } = require('../../props.js');
const BotUsuario = require('./BotUsuario.js');
const Presencia = require('../clases/Presencia.js');
const Coleccion = require('../clases/Coleccion.js');
const ManagerEmojis = require('../clases/ManagerEmojis.js');
const Boton = require('../clases/Boton.js');
const Reaccion = require('../clases/Reaccion.js');
const Interaccion = require('../clases/Interaccion.js');
const pUsuarios = {};
module.exports = class Bot extends EventEmmiter {
constructor(opciones = {}) {
super();
//if(!opciones) throw new Error('No hay nada en opciones.');
//if(!opciones.intents) throw new Error('Debes específicar los intents a usar en las opciones del bot.');
this.intents = 32767;
this.servidores = new ManagerServidores(this);
this.canales = new ManagerCanales(this);
this.usuarios = new ManagerUsuarios(this);
this.roles = new ManagerRoles(this);
this.emojis = new ManagerEmojis(this);
this.presencias = new Coleccion();
this.canalesMD = new Coleccion();
}
iniciar(token) {
if(!token) throw new Error('Debes específicar el token del bot.');
iniciar(this, token)
.catch(err => {
console.error('[DISCORD-VATRON] ' + errores[err.statusCode] || err.message);
})
}
async obtenerCanal(id) {
const c = await request.get({ url: `https://discord.com/api/v9/channels/${id}`, headers: { Authorization: 'Bot ' + this.token } })
.catch(err => {
//const json = JSON.parse(err.message.slice(err.message.indexOf('"')+1, -1).replace(/\\([aA-zZ]){1,}/g, ''));
console.error('[DISCORD-VATRON] ' + errores[err.statusCode] || err.message);
});
if(!c) return null;
this.canales._setCanal(JSON.parse(c), this, this.servidores.get(JSON.parse(c).guild_id));
return this.canales.has(id) ? this.canales.get(id) : null;
}
async _evento(datos, socket) {
switch(datos.t) {
case "READY":
this.usuario = new BotUsuario(datos.d.user, this, socket);
setTimeout(() => {
this._botid = datos.d.user.id;
this.emit('listo', this.usuario);
}, 1250);
break;
case "GUILD_CREATE":
GUILD_CREATE(datos, this, socket);
break;
case "MESSAGE_CREATE":
const msg = new Mensaje(datos.d, this);
if(this.canales.has(datos.d.channel_id)) this.canales.get(datos.d.channel_id).mensajes.set(msg.id, msg);
this.emit('mensaje', msg);
break;
case "MESSAGE_UPDATE":
const msgu = new Mensaje(datos.d, this);
const antiguom = this.canales.get(datos.d.channel_id).mensajes.has(msgu.id) ? this.canales.get(datos.d.channel_id).mensajes.get(msgu.id) : await this.canales.get(datos.d.channel_id).obtenerMensaje(datos.d.id);
if(this.canales.has(datos.d.channel_id)) this.canales.get(datos.d.channel_id).mensajes.set(msgu.id, msgu);
this.emit('mensajeEditado', antiguom, this.canales.get(datos.d.channel_id).mensajes.has(msgu.id) ? this.canales.get(datos.d.channel_id).mensajes.get(msgu.id) : null);
break;
case "MESSAGE_DELETE":
const msge = this.canales.get(datos.d.channel_id).mensajes.has(datos.d.id) ? this.canales.get(datos.d.channel_id).mensajes.get(datos.d.id) : null;
this.canales.get(datos.d.channel_id).mensajes.delete(datos.d.id);
this.emit('mensajeEliminado', msge);
break;
case "GUILD_UPDATE":
const servidorAntiguo = this.servidores.has(datos.d.id) ? this.servidores.get(datos.d.id) : null;
this.servidores._setServidor(datos.d, this);
this.emit('servidorActualizado', servidorAntiguo, this.servidores.has(datos.d.id) ? this.servidores.get(datos.d.id) : null);
break;
case "GUILD_MEMBER_ADD":
const miembroA = new Miembro(datos.d, this);
this.servidores.get(datos.d.guild_id).miembros.set(miembroA.id, miembroA);
this.usuarios._setUsuario(datos.d.user, this);
this.emit('servidorEntrandoMiembro', miembroA);
break;
case "GUILD_MEMBER_UPDATE":
if(datos.d.user && datos.d.user.id == this.usuario.id) canalesSV(datos.d.guild_id, this);
const antiguoM = this.servidores.has(datos.d.guild_id) ? this.servidores.get(datos.d.guild_id).miembros.has(datos.d.user.id) ? this.servidores.get(datos.d.guild_id).miembros.get(datos.d.user.id) : null : null;
const miembroU = new Miembro(datos.d, this, this.servidores.get(datos.d.guild_id));
this.servidores.get(datos.d.guild_id).miembros.set(miembroU.id, miembroU);
this.emit('servidorMiembroActualizado', antiguoM, miembroU);
break;
case "GUILD_MEMBER_REMOVE":
this.emit('servidorSaliendoMiembro', this.servidores.get(datos.d.guild_id).miembros.get(datos.d.user.id));
this.servidores.get(datos.d.guild_id).miembros.delete(datos.d.user.id);
break;
case "CHANNEL_UPDATE":
const canalAntiguo = this.canales.has(datos.d.id) ? this.canales.get(datos.d.id) : null;
this.canales._setCanal(datos.d, this, this.servidores.get(datos.d.guild_id));
this.emit('canalActualizado', canalAntiguo, this.canales.has(datos.d.id) ? this.canales.get(datos.d.id) : null);
break;
case "CHANNEL_DELETE":
this.emit('canalEliminado', this.canales.has(datos.d.id) ? this.canales.get(datos.d.id) : null);
this.canales.delete(datos.d.id);
break;
case "GUILD_DELETE":
this.emit('servidorEliminado', this.servidores.has(datos.d.id) ? this.servidores.get(datos.d.id) : null);
this.servidores.delete(datos.d.id);
break;
case "USER_UPDATE":
const uantiguo = this.usuarios.has(datos.d.id) ? this.usuarios.get(datos.d.id) : null;
this.usuarios._setUsuario(datos.d, this);
this.emit('usuarioActualizado', uantiguo, this.usuarios.has(datos.d.id) ? this.usuarios.get(datos.d.id) : null);
break;
case "PRESENCE_UPDATE":
if(!pUsuarios[datos.d.user.id]) pUsuarios[datos.d.user.id] = 1; else pUsuarios[datos.d.user.id]++;
const pantigua = this.presencias.has(datos.d.user.id) ? this.presencias.get(datos.d.user.id) : null;
this.presencias.set(datos.d.user.id, new Presencia(datos.d, this));
if(pUsuarios[datos.d.user.id] > 1) return;
this.emit('presenciaActualizada', pantigua, this.presencias.has(datos.d.user.id) ? this.presencias.get(datos.d.user.id) : null);
setTimeout(() => {
pUsuarios[datos.d.user.id] = 0;
}, 2000);
break;
case "GUILD_ROLE_CREATE":
this.roles._setRole(datos.d, this, this.servidores.get(datos.d.guild_id));
this.emit('servidorRoleCreado', this.roles.has(datos.d.id) ? this.roles.get(datos.d.id) : null);
break;
case "GUILD_ROLE_DELETE":
this.emit('servidorRoleEliminado', this.roles.has(datos.d.id) ? this.roles.get(datos.d.id) : null);
this.roles.delete(datos.d.id);
break;
case "GUILD_ROLE_UPDATE":
const rantiguo = this.roles.has(datos.d.id) ? this.roles.get(datos.d.id) : null;
this.roles._setRole(datos.d.role, this, this.servidores.get(datos.d.guild_id));
this.emit('servidorRoleActualizado', rantiguo, this.roles.has(datos.d.id) ? this.roles.get(datos.d.id) : null);
break;
case "VOICE_STATE_UPDATE":
const eantiguo = this.servidores.get(datos.d.guild_id).estadosVoz.has(datos.d.user_id) ? this.servidores.get(datos.d.guild_id).estadosVoz.get(datos.d.user_id) : null;
if(datos.d.channel_id) {
const estado = new EstadoVoz(datos.d, this, this.servidores.get(datos.d.guild_id));
this.servidores.get(datos.d.guild_id).estadosVoz.set(datos.d.user_id, estado);
} else {
this.servidores.get(datos.d.guild_id).estadosVoz.delete(datos.d.user_id);
}
this.emit('estadoVozActualizado', eantiguo, this.servidores.get(datos.d.guild_id).estadosVoz.has(datos.d.user_id) ? this.servidores.get(datos.d.guild_id).estadosVoz.get(datos.d.user_id) : null);
break;
case "GUILD_EMOJIS_UPDATE":
let servidore = this.servidores.get(datos.d.guild_id);
const emojisEliminados = servidore.emojis.filtrar(e => !datos.d.emojis.some(em => e.id == em.id));
for(var em of datos.d.emojis) {
this.emojis._setEmoji(em, this, servidore);
}
for(var em of emojisEliminados.array()) {
this.emojis.delete(em.id);
}
servidore = this.servidores.get(datos.d.guild_id);
this.emit('servidorEmojisActualizados', servidore, servidore.emojis);
break;
case "MESSAGE_REACTION_ADD":
if(!this.canales.has(datos.d.channel_id)) return;
if(datos.d.channel_id) {
await this.canales.get(datos.d.channel_id).obtenerMensaje(datos.d.message_id);
//this.canales.get(datos.d.channel_id).mensajes.get(datos.d.message_id).reacciones.set(datos.d.emoji.id || datos.d.emoji.name, new Reaccion(datos.d, this));
}
this.emit('mensajeReaccionAnadida', (new Mensaje(this.canales.get(datos.d.channel_id).mensajes.get(datos.d.message_id)._datos, this, this.servidores.get(datos.d.guild_id), this.usuarios.get(datos.d.user_id)) ).reacciones.get(datos.d.emoji.id || datos.d.emoji.name));
break;
case "MESSAGE_REACTION_REMOVE":
if(!this.canales.has(datos.d.channel_id)) return;
if(datos.d.channel_id) {
await this.canales.get(datos.d.channel_id).obtenerMensaje(datos.d.message_id);
//this.canales.get(datos.d.channel_id).mensajes.get(datos.d.message_id).reacciones.set(datos.d.emoji.id || datos.d.emoji.name, new Reaccion(datos.d, this));
}
this.emit('mensajeReaccionEliminada', (new Mensaje(this.canales.get(datos.d.channel_id).mensajes.get(datos.d.message_id)._datos, this, this.servidores.get(datos.d.guild_id), this.usuarios.get(datos.d.user_id)) ));
break;
case "INTERACTION_CREATE":
this.emit('interaccionCreada', new Interaccion(datos.d, this));
break;
}
}
}
function GUILD_CREATE(datos, bot, socket) {
for(const c of datos.d.channels) {
bot.canales._setCanal(c, bot, datos.d);
}
for(const u of datos.d.members) {
if(u && u.user) bot.usuarios._setUsuario(u.user, bot);
}
for(const r of datos.d.roles) {
bot.roles._setRole(r, bot, datos.d);
}
for(var p of datos.d.presences) {
const pr = new Presencia(p, bot);
bot.presencias.set(p.user.id, pr);
}
for(var e of datos.d.emojis) {
bot.emojis._setEmoji(e, bot, datos.d);
}
bot.servidores._setServidor(datos.d, bot);
}
function canalesSV(idsv, bot) {
if(!idsv) return;
request.get({ url: `https://discord.com/api/v9/guilds/${idsv}`, headers: { Authorization: 'Bot ' + bot.token } }).then(servidor => {
request.get({ url: `https://discord.com/api/v9/guilds/${idsv}/channels`, headers: { Authorization: 'Bot ' + bot.token } })
.then(canales => {
canales.forEach((c) => {
bot.canales._setCanal(c, bot, servidor);
});
}).catch(() => {});
}).catch(() => {});
}